context.getText() excludes spaces in ANTLR4

后端 未结 1 593
挽巷
挽巷 2021-01-26 01:12

The getText() returns the complete statement excluding the spaces between the words. One way of considering the spaces is to include them in grammar. But, is there any other way

相关标签:
1条回答
  • 2021-01-26 02:04

    Yes, there is (assuming here you are using ParserRuleContext.getText(). The idea is to ask the input char stream for a range of characters. The position values are stored in the start and stop tokens of the context.

    Here's some code (converted from C++, so it might not be 100% correct):

    string sourceTextForContext(ParseTree context) {
      Token startToken = (context.start instanceof TerminalNode) ? (TerminalNode)(start).getSymbol() : (ParserRuleContext)(start).start;
      Token stopToken = (context.stop instanceof TerminalNode) ? (TerminalNode)(stop).getSymbol() : (ParserRuleContext)(stop).start;
    
      CharStream cs = start.getTokenSource().getInputStream();
      int stopIndex = stop != null ? stop.getStopIndex() : -1;
      return cs.getText(new Interval(start.getStartIndex(), stopIndex));
    }
    

    Since this retrieval function uses the absolute char indexes, it doesn't count in any possible whitespace rule.

    0 讨论(0)
提交回复
热议问题