How do I get the original text that an antlr4 rule matched?

前端 未结 2 2061
闹比i
闹比i 2020-12-05 01:58

Using the Java 7 grammar https://github.com/antlr/grammars-v4/blob/master/java7/Java7.g4 I want to find methods with a specific name and then just print out that method. I

相关标签:
2条回答
  • 2020-12-05 02:42

    ANTLR's CharStream class has a method getText(Interval interval) which will return the original source in the give range. The Context object has methods to get the beginning and end. Assuming you have a field in your listener called input which has the CharStream being parsed, you can do this:

        int a = ctx.start.getStartIndex();
        int b = ctx.stop.getStopIndex();
        Interval interval = new Interval(a,b);
        input.getText(interval);
    
    0 讨论(0)
  • 2020-12-05 02:44

    demo:

    SqlBaseParser.QueryContext queryContext = context.query();
    int a = queryContext.start.getStartIndex();
    int b = queryContext.stop.getStopIndex();
    Interval interval = new Interval(a,b);
    String viewSql = context.start.getInputStream().getText(interval);
    
    0 讨论(0)
提交回复
热议问题