簡體   English   中英

如何獲取antlr4規則匹配的原文?

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

使用 Java 7 語法https://github.com/antlr/grammars-v4/blob/master/java7/Java7.g4我想找到具有特定名稱的方法,然后打印出該方法。 我看到我可以在匹配時使用methodDeclaration規則。 所以我Java7BaseListener並覆蓋了這個監聽器方法:

@Override public void enterMethodDeclaration(Java7Parser.MethodDeclarationContext ctx) { }

怎么把原文拿出來? ctx.getText()給了我一個去掉所有空格的字符串。 我想要評論和原始格式。

ANTLR 的CharStream類有一個getText(Interval interval)方法,它將返回給定范圍內的原始源。 Context對象具有獲取開始和結束的方法。 假設您的偵聽器中有一個名為input的字段,其中正在解析 CharStream,您可以這樣做:

    int a = ctx.start.getStartIndex();
    int b = ctx.stop.getStopIndex();
    Interval interval = new Interval(a,b);
    input.getText(interval);

演示:

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);

Python實現:

def extract_original_text(self, ctx):
    token_source = ctx.start.getTokenSource()
    input_stream = token_source.inputStream
    start, stop  = ctx.start.start, ctx.stop.stop
    return input_stream.getText(start, stop)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM