1

my language to parse contains statements like

public var a, b = 42, c;

I.e. the .g file looks something like:

statements
    : (introduction | expression ';'! | ... )+
    ;
introduction
    : head single+ -> ^(head single)+
    ;
single
    : Name ('='^ expression)?
    ;
head
    : modifiers* v='var' -> ^(VARIABLE[$v] modifiers*)
    ;

Generating a tree like that would be easy, but mostly useless (for me):

         ----------statements----------
        /               |              \
    variable         variable       variable
    /      \         /      \       /      \
'public'   'a'   'public'  '='   'public'  'c'
                          /   \
                         'b'  expr

I would like to have the the '=' on top of the middle node:

         ----------statements----------
        /               |              \
    variable           '='          variable
    /      \          /   \         /      \
'public'   'a'  variable  expr   'public'  'c'
                 /     \
             'public'  'b'

but I can't find the rewrite rule to do that.

Kijewski
  • 25,517
  • 12
  • 101
  • 143

1 Answers1

1

That is not easly done with the way you've set up your rules.

Here's a way it is possible:

grammar T;

options { 
  output=AST;
  ASTLabelType=CommonTree; 
}

tokens {
  STATEMENTS;
  VARIABLE;
  DEFAULT_MODIFIER;
}

declaration
  :  modifier 'var' name[$modifier.tree] (',' name[$modifier.tree])* ';' -> ^(STATEMENTS name+)
  ;

modifier
  :  'public'
  |  'private'
  |  /* nothing */ -> DEFAULT_MODIFIER
  ;

name [CommonTree mod]
  :  ID '=' expression -> ^('=' ^(VARIABLE {new CommonTree(mod)} ID) expression)
  |  ID                -> ^(VARIABLE {new CommonTree(mod)} ID)
  ;

// other parser & lexer rules

which produces the following AST:

enter image description here

for the input:

public var a, b = 42, c;

And produces:

enter image description here

for the input:

var a, b = 42, c;
Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
  • Wow, that was fast, thank you! I did not know you could "generate" nodes in rewrite rules. Great answer! – Kijewski Aug 29 '11 at 21:59