[antlr-interest] Suggestion about refactoring a rule

Loïc Habermacher loic.habermacher at gmail.com
Sat May 1 08:44:09 PDT 2010


Hello everyone,

I have a rule that works fine but I would like to factor it for better
readibility.
I am processing the INSERT SQL request which looks like :
*insert into table1 (col1,col2,col3) values (1,foo,bar);*
I want to create an AST with table1 as root and with ^(col1 1)  ^(col2
foo)  ^(col3 bar) as child of table1.

It works fine with the grammar below but I find the *insert_def* rule
difficult to read
------extract from grammar.g ------
insert_def:
  'insert' 'into' table_name
  LEFT_PAREN a=column_name (COMMA cls+=column_name)* RIGHT_PAREN
  'values' LEFT_PAREN b=atom (COMMA ats+=atom)* RIGHT_PAREN
  SEMICOLON
   -> ^(INSERT ^(table_name ^($a $b) ^($cls $ats)*))
  ;

colum_name: ID;
table_name : ID;
atom: ID | NUMBER;
----------------------------
I would prefer to have a grammar like the one below :
--------------------------------------------
insert_def:
  'insert' 'into' table_name
  column_list
  value_list
  SEMICOLON
   -> ^(INSERT ^(table_name ^(column_list value_list)+))
  ;

column_list:
  LEFT_PAREN column_name (COMMA column_name)* RIGHT_PAREN
  -> column_name+
  ;
value_list:
  values' LEFT_PAREN atom (COMMA atom)* RIGHT_PAREN
  -> atom+
  ;
---------------------------------------
but at runtime with the second grammar I get a "more than one node as root"
exception. However, the first grammar works and ANTLR construct multiple
trees on the base of two lists (cls and ats) ....
Any help is very welcome.

Thanks


More information about the antlr-interest mailing list