java - 在 ANTLR 解析器中跳过空格

标签 java parsing antlr antlr4

我有一些语法,可以通过以下方式忽略空格

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/

相关文章:

perl - 解析文本时是否有一个好的 CPAN 模块来实现状态机?

antlr - 将 ANTLR 语法翻译成 XText 语法 : how to remove syntactic predicates

java - spring mvc Controller 报错java.lang.IllegalStateException : No suitable resolver for argument [0]

java - 使用数组按姓名和分数对学生进行排序

angularjs - 在 GoLang 中解析嵌入式结构形式的值

android - org.json.jsonarray 无法转换为 jsonobject 错误

java - 将字符串与词法分析器匹配 : 'expecting' error

java - 从 Java 源代码生成 AST 报告而不实际运行它

Java NIO 套接字 : the server doesn't receive the second message over the same socket

java - 从 Factory 重构中提取 lambda(使用 IDE)?