2

如何在没有多个繁琐的分配的情况下编写以下代码?

statement returns [Leaf node]
    :  assignment     {node = $assignment.node;}
    |  write          {node = $write.node;}
    |  writeln        {node = $writeln.node;}
    |  readBool       {node = $readBool.node;}
    |  readInt        {node = $readInt.node;}
    ;

像下面这样的东西就足够了。

statement returns [Leaf node]
    :  a=(assignment | write | writeln | ...) { //all statements returns `Leaf`
        node = $a.node; //but 'a' is just a `Tokien`, so we get compile error.
    };
4

1 回答 1

3

不,这是不可能的:

statement returns [Leaf node]
    :  a=(assignment | write | writeln | ...) { //all statements returns `Leaf`
        node = $a.node; //but 'a' is just a `Tokien`, so we get compile error.
    };

因为括号可能匹配多个规则:

a=(a b | c d e | ...) 

或者解析器和词法分析器规则可以混合使用:

a=(A b | C | d | ...) 

可以做这样的事情:

statement returns [Leaf node]
    :  (a=assignment | a=write | a=writeln | ...) 
       {
         $node = $a.node;
       };

但就个人而言,我更喜欢您首先发布的内容:

statement returns [Leaf node]
    :  assignment     {node = $assignment.node;}
    |  write          {node = $write.node;}
    |  writeln        {node = $writeln.node;}
    |  readBool       {node = $readBool.node;}
    |  readInt        {node = $readInt.node;}
    ;

恕我直言,更具可读性。

于 2012-11-11T15:56:39.610 回答