csviri
csviri

Reputation: 1229

Antlr grammar multiplicity problem of tree in tree grammar

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?

Upvotes: 3

Views: 302

Answers (1)

Bart Kiers
Bart Kiers

Reputation: 170178

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)
  ;

Upvotes: 3

Related Questions