3
votes

I have a simple grammar

options {
  language = Java;
  output = AST;
  ASTLabelType=CommonTree;
}

tokens {
  DEF;
}

root
  : ID '=' NUM (',' ID '=' NUM)* -> ^(DEF ID NUM)+     
  ;

and the corresponding tree grammar:

options {
  tokenVocab=SimpleGrammar;
  ASTLabelType=CommonTree;
}

root
  : ^(DEF ID NUM)+
;

However antlr (v3.3) cannot compile this tree grammar I'm getting:

syntax error: antlr: unexpected token: +
|---> : ^(DEF ID NUM)+

Also it don't works if I want to create it as ^(ROOT ^(DEF ID NUM)+)

I want a tree that is corresponds to this (as parse creates it as well) :

(ROOT (DEF aa 11) (DEF bb 22) (DEF cc 33))

Thus antlr is capable to generate the tree in parser but not capable to parse it with tree grammar?!

Why this happens?

1
I just found this: stackoverflow.com/questions/5844012/… its ok, that there is a workaround but, what if I want to walk a tree that looks exactly as defined above?csviri
Well, your tree ^(DEF ID NUM)+ repeats its root DEF as well. So you have a tree with potentially more than 1 root, which is not possible. Could you edit your question and explain what tree you want to create?Bart Kiers
Ok i edited it, result should be something like: (ROOT (DEF aa 11) (DEF bb 22) (DEF cc 33))csviri

1 Answers

3
votes

In order to get (ROOT (DEF aa 11) (DEF bb 22) (DEF cc 33)) you can define the following parser rules:

tokens {
  ROOT;
  DEF;
}

root
  : def (',' def)* -> ^(ROOT def+)
  ;

def
  :  ID '=' NUM -> ^(DEF ID NUM)
  ;

and then your tree grammar would contain:

root
  :  ^(ROOT def+)
  ;

def
  :  ^(DEF ID NUM)
  ;