[antlr-interest] Generate an AST with virtual nodes and conditions

Loïc Habermacher loic.habermacher at insa-lyon.fr
Mon Apr 26 10:58:42 PDT 2010


Hello everybody,

I am new to ANTLR but as I have to do a quite big project with it, I have
already read a lot of docs (includig the definitive guide) and played with
my first grammars.

I need
- to parse an input like this one : table_name(elem1 blue opt, elem2 blue ,
elem3 red, elem4 red opt);

- to produce an AST like this one : (table_name (WITH_OPT (elem1 blue)
(elem4 red)) (WITHOUT_OPT (elem2 blue) (elem3 red)))
// I want to regroup under the same branch all the elements with opt at the
end and on another branch the elements without opt at the end

- to process the AST

I am stucked with the rewrite rule
table_def
 :
 table_name LEFT_PAREN elem_list RIGHT_PAREN SEMICOLON
 -> ^(table_name ^(WITH_OPT elem_list) ^(WITHOUT_OPT elem_list));

How can I communicate with the other rules to have the right content in each
list ?


Thanks
Loïc

*Code*
*
*
*FirstGram.g (to parse and generate the AST)*
grammar FirstGram;

options {
  language = Java;
  output       = AST;
  ASTLabelType = CommonTree;
}
tokens{
WITH_OPT;
WITHOUT_OPT;
}
@header {
  package toy.draft;
}
@lexer::header {
  package toy.draft;
}

table_def
 :
 table_name LEFT_PAREN elem_list RIGHT_PAREN SEMICOLON
 -> ^(table_name ^(WITH_OPT elem_list) ^(WITHOUT_OPT elem_list));

elem_list:
elem (COMMA elem)* -> elem+;

elem :
elem_name elem_color option?
-> ^(elem_name elem_color);

table_name :ID ;
elem_name : ID ;
elem_color : ('blue'|'red');
option : 'opt'  ;

/*------------------------------------------------------------------
 * LEXER RULES
 *------------------------------------------------------------------*/

LEFT_PAREN : '(';
RIGHT_PAREN : ')';
COMMA : ',';
SEMICOLON : ';';
DOT :  '.';
NUMBER  : (DIGIT)+;
ID  : (('a'..'z'|'A'..'Z' | '_') ((DIGIT)*))+ ;
NEWLINE:'\r'? '\n' { $channel = HIDDEN; };
WS : ( '\t' | ' ' | '\r' | '\n' | '\u000C' )+   { $channel = HIDDEN; } ;
fragment DIGIT :   '0'..'9' ;

*Walker.g (to process the AST)*
tree grammar Walker;

options {
  language = Java;
  tokenVocab = FirstGram;
  ASTLabelType = CommonTree;
  output = template;
  rewrite = true;
}
@header {
  package toy.draft;
}

table_def
  :^(table_name list_with_opt list_without_opt)
  ;

list_with_opt
  : ^(WITH_OPT elem_list)
  ;

 list_without_opt
  : ^(WITHOUT_OPT elem_list)
  ;

table_name :ID ;
elem_list: elem+ ;
elem : elem_name;
elem_name : ID ;


More information about the antlr-interest mailing list