如何在没有繁琐的繁琐任务的情况下编写以下代码?
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.
};
答案 0 :(得分: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;}
;
更具可读性,恕我直言。