包含和不包含初始化的变量定义树

时间:2011-08-29 21:08:25

标签: antlr antlr3

我要解析的语言包含

之类的语句
public var a, b = 42, c;

即。 .g文件看起来像:

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

生成这样的树很容易,但对我来说几乎没用(

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

我希望'='位于中间节点之上:

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

但我无法找到重写规则。

1 个答案:

答案 0 :(得分:1)

使用您设置规则的方式并不容易。

这是 可能的方式:

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

产生以下AST:

enter image description here

输入:

public var a, b = 42, c;

并产生:

enter image description here

输入:

var a, b = 42, c;
相关问题