开发者

Tree of variable definitions with and without initializations

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----------
        /             开发者_C百科  |              \
    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.


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:

Tree of variable definitions with and without initializations

for the input:

public var a, b = 42, c;

And produces:

Tree of variable definitions with and without initializations

for the input:

var a, b = 42, c;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜