开发者

Tree of variable definitions with and without initializations

开发者 https://www.devze.com 2023-04-01 10:10 出处:网络
my language to parse contains statements like public var a, b = 42, c; I.e. the .g file looks something like:

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

精彩评论

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