我有一个组合的ANTLR语法,它将寻找特定的令牌/令牌组合。一些tokes可以零或一次。 我想将“找到”或“未找到”值存储到这些令牌的哈希映射中。我已经知道,在令牌可用的情况下如何做到这一点。但是如何才能找到尚未找到的令牌呢 以下示例显示了它非常简化:
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");
答案 0 :(得分:2)
是否有可能直接在这个语法中找到“TWO”,因此找不到HashMap的不同值?
当然,像这样:
statements
: ONE WS ( TWO WS THREE EOF {memory.put("two","found");}
| THREE EOF {memory.put("two","not found");}
)
;
如果您有更多可选令牌(TWO
,THREE
和FOUR
是可选的),请执行以下操作:
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");
}
;