简体   繁体   中英

How to get line number from ANTLR listener context in Java

I am using ANTLR listener context to get the starting line number of any method using the below Java code:

@Override
public void enterFunctionDeclaration(KotlinParser.FunctionDeclarationContext ctx) {
  Token t = ctx.getStart();
  int lineno = t.getLine();
}

The above code works fine if there is no leading \\n or \\r in the code, but fails otherwise.

Example:

  Line 1 
  Line 2
  Line 3   func test(){
  Line 4  }

The above code returns 1 for this case, but I am expecting value 3, as this is the starting line number of the function "test". How can I achieve this?

I could not reproduce that. Btw, it's not getLineNo() but getLine() .

Test grammar:

grammar T;

functionDeclaration
 : 'func' ID '(' ')' '{' '}'
 ;

ID     : [a-zA-Z]+;
SPACES : [ \t\r\n] -> skip;

and the Java test class:

import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.ParseTreeWalker;

public class Main {

    private static void test(String source) {
        TLexer lexer = new TLexer(CharStreams.fromString(source));
        TParser parser = new TParser(new CommonTokenStream(lexer));
        ParseTreeWalker.DEFAULT.walk(new TestListener(), parser.functionDeclaration());
    }

    public static void main(String[] args) throws Exception {

        test("func test() {\n" +
             "}");

        test("\n" +
             "\n" +
             "func test() {\n" +
             "}");
    }
}

class TestListener extends TBaseListener {

    @Override
    public void enterFunctionDeclaration(TParser.FunctionDeclarationContext ctx) {
        Token t = ctx.getStart();
        int lineno = t.getLine();
        System.out.println("lineno=" + lineno);
    }
}

will print:

lineno=1
lineno=3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM