我有一个组合的 ANTLR 语法,它应该寻找特定的标记/标记组合。有些 token 可以使用 0 次或 1 次。
我想将“找到”或“未找到”值存储到这些 token 的 HashMap 中。我已经知道,在 token 可用的情况下如何执行此操作。但是对于尚未找到的 token 我该如何做。
以下示例显示它非常简化:
grammar Expr;
@header {
import java.util.HashMap;
}
@members {
HashMap<String,String> memory = new HashMap<String,String>();
}
statements: ONE
(WS TWO {memory.put("two","found");})?
WS THREE EOF;
ONE: 'one';
TWO: 'two';
THREE: 'three';
WS: ' ';
是否有可能直接在此语法中找出“TWO”未找到,因此将不同的值放入 HashMap 中?
memory.put("two","not found");
最佳答案
Is there a possibility to find out directly within this grammar, that "TWO" was not found and therefore put a different value to the HashMap?
当然,像这样:
statements
: ONE WS ( TWO WS THREE EOF {memory.put("two","found");}
| THREE EOF {memory.put("two","not found");}
)
;
编辑
或者,如果您有更多可选 token (TWO
、THREE
和 4
是可选的),请执行以下操作:
statements
: ONE (WS TWO memory.put("two","found"); | memory.put("two","not found");)
(WS THREE memory.put("three","found"); | memory.put("three","not found");)
(WS FOUR memory.put("four","found"); | memory.put("four","not found");)
EOF
;
或者类似的东西也应该有效:
statements
: ONE (WS TWO)? (WS THREE)? (WS FOUR)?
{
memory.put("two", $TWO.text == null ? "not found" : "found");
memory.put("three", $THREE.text == null ? "not found" : "found");
memory.put("four", $FOUR.text == null ? "not found" : "found");
}
;
关于标记的 ANTLR 语法表达式求值,可以使用 0 次或 1 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15163846/