在ANTLR解析器中跳过whitespases

时间:2014-04-25 14:38:58

标签: java parsing antlr antlr4

我有一些语法,以下列方式忽略空格

WS : [ \r\t\n]+ -> channel(HIDDEN) ;

没关系,' cos空白不是我语法的一部分。但在解析器中,我需要知道空格在哪里。现在我无法找到任何直接的方法。

我使用的是ANTLR4的最新版本

提前致谢。

2 个答案:

答案 0 :(得分:1)

请参阅Token stream API

您必须习惯于查看API和源代码。你也可以便宜地买这本书。页面206:访问隐藏的频道。

答案 1 :(得分:1)

如果您在解析树时正在寻找令牌,那么在v3中您会做类似的事情:

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
}