我有一些语法,可以通过以下方式忽略空格
WS : [ \r\t\n]+ -> channel(HIDDEN) ;
没关系,因为空格不是我语法的一部分。但在解析器中我需要知道空格在哪里。目前我无法找到任何直接的方法来做到这一点。
我使用最新版本的 ANTLR4
提前致谢。
最佳答案
在 v3 中,如果您在解析树时寻找 token ,您会执行类似的操作:
getPreviousTokenInHiddenChannel(retval, input);
public String getPreviousTokenInHiddenChannel(TreeRuleReturnScope retval, TreeNodeStream input) {
try {
TokenStream tstream = input.getTokenStream();
CommonTree node = (CommonTree) retval.start;
int boundary = node.getTokenStopIndex();
if (boundary <= 0) { // fix for antlr 3.3 bug, from 3.5 getTokenStartIndex should itself resolve parent's boundaries if <= 0
while (node.getTokenStartIndex() == -1) { // if node is imaginary
node = (CommonTree) node.getParent();
if (node == null) return ""; // means we are root
boundary = node.getTokenStopIndex();
if (boundary > 0) break;
}
}
int i = boundary;
while (true) {
i--;
Token tok = tstream.get(i);
if (tok.getChannel() == HIDDEN) {
// do what you want to do https://www.youtube.com/watch?v=JgRBkjgXHro
}
}
} catch (Exception e) {
// handle e
}
}
您可以使用类似的内容(伪代码)轻松地将这段代码改编为 v4:
BufferedTokenStream bts;
// retrieve bts
List<Token> hiddenTokens = bts.getHiddenTokensToLeft(bts.index(), HIDDEN);
// loop backwards over the list
for (int i = hiddenTokens.size(); i--; i >= 0) {
Token t = hiddenTokens.get(i)
// process your hidden token
}
关于java - 在 ANTLR 解析器中跳过空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23296173/