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:

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.


  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;

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

ID     : [a-zA-Z]+;
SPACES : [ trn] -> 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 {

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

will print: