所以我的原則是令牌空當匹配語法規則,雖然符合
/* Addition and subtraction have the lowest precedence. */
additionExp returns [double value]
: m1=multiplyExp {$value = $m1.value;}
(op=AddOp m2=multiplyExp)* {
if($op != null){ // test if matched
if($op.text == "+"){
$value += $m2.value;
}else{
$value -= $m2.value;
}
}
}
;
AddOp : '+' | '-' ;
我的測試IST 3 + 4
但op.text總是返回NULL,從來沒有一個字符。
有誰知道我如何測試AddOp的價值?
在從ANTLR4 Actions and Attributes的例子它應該工作:
stat: ID '=' INT ';'
{
if (!$block::symbols.contains($ID.text)) {
System.err.println("undefined variable: "+$ID.text);
}
}
| block
;
有相當多的事情不正確,據我所知。 ANTLR工具是否接受你的語法?我認爲它應該會產生'additionExp'工具的錯誤,因爲actions/embedded-code必須放在替代的末尾。另外,'$ op!= null'也會觸發一個錯誤,不是?最後,你使用'=='比較字符串('$ op.text ==「+」'),這是不正確的(參見:http://stackoverflow.com/questions/767372/java-string-equals-與)。 –
@BartKiers它可以正常工作,你可以從發佈的例子中看到。但是你在字符串比較上是正確的。我需要'.equals'而不是'=='。 – RedX
你會驚訝有多少人發佈一些不反映他們實際代碼的代碼片段。 B.t.w.,我只是注意到你把嵌入式代碼放在'(...)*'之外。這應該在裏面。 –