Anand
Anand

Reputation: 853

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?

Upvotes: 1

Views: 703

Answers (1)

Bart Kiers
Bart Kiers

Reputation: 170227

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

Upvotes: 1

Related Questions