初学者:ANTLR 确实行为不端?
Beginner: ANTLR does misbehave?
我有一个非常简单的语法来解析骰子表达式。
grammar Dice;
function : ( dice | binaryOp | DIGIT );
binaryOp: dice OPERATOR function | DIGIT OPERATOR function;
dice : DIGIT DSEPERATOR DIGIT EXPLODING?;
DSEPERATOR : ( 'd' | 'D' | 'w' | 'W' );
EXPLODING : ( '*' );
OPERATOR : ( ADD | SUB );
ADD : '+';
SUB : '-';
DIGIT : ('0'..'9')+;
WS : [ \t\r\n]+ -> skip ; // skip spaces, tabs, newlines
它应该解析类似 3D6+2D10
的东西,但它没有。我得到一个 no viable alternative at input '2d10'
的部分结果:
(function (binaryOp (dice 3 W 6) + (function 2 d 10)))
我不明白为什么。你能帮我理解这个吗?
由于 function
规则是递归的(最终),您需要为顶层显式添加规则,以便 ANTLR 可以推断 "oh, this top level rule should be the one that implicitly can accept an EOF at the end of input",然后从中进行解析。
我加了一行:
start : function ;
你的语法,现在可以解析了:
$ echo "3D6+2D10" | java -cp antlr-4.7.1-complete.jar:. org.antlr.v4.gui.TestRig Dice start -tree
(start (function (binaryOp (dice 3 D 6) + (function (dice 2 D 10)))))
我有一个非常简单的语法来解析骰子表达式。
grammar Dice;
function : ( dice | binaryOp | DIGIT );
binaryOp: dice OPERATOR function | DIGIT OPERATOR function;
dice : DIGIT DSEPERATOR DIGIT EXPLODING?;
DSEPERATOR : ( 'd' | 'D' | 'w' | 'W' );
EXPLODING : ( '*' );
OPERATOR : ( ADD | SUB );
ADD : '+';
SUB : '-';
DIGIT : ('0'..'9')+;
WS : [ \t\r\n]+ -> skip ; // skip spaces, tabs, newlines
它应该解析类似 3D6+2D10
的东西,但它没有。我得到一个 no viable alternative at input '2d10'
的部分结果:
(function (binaryOp (dice 3 W 6) + (function 2 d 10)))
我不明白为什么。你能帮我理解这个吗?
由于 function
规则是递归的(最终),您需要为顶层显式添加规则,以便 ANTLR 可以推断 "oh, this top level rule should be the one that implicitly can accept an EOF at the end of input",然后从中进行解析。
我加了一行:
start : function ;
你的语法,现在可以解析了:
$ echo "3D6+2D10" | java -cp antlr-4.7.1-complete.jar:. org.antlr.v4.gui.TestRig Dice start -tree
(start (function (binaryOp (dice 3 D 6) + (function (dice 2 D 10)))))