Use ANTLR to find use / reference Variable in Java source code?

Using a variable is basically every occurrence of a variable after it is declared in the same scope, where some operation can be applied to it. Highlighting variables is supported even in some IDEs such as IntelliJ and Eclipse.

I was wondering if there is a way to find variable usage using ANTLR? I have already created the Lexer, Parser, and BaseListener classes by running ANTLR in Java8.g4. I can find variable declarations, but I can not find variables in this Java source code. How can i do this?

Example:

int i;    // Variable declaration
i++;      // Variable usage
i = 2;    // Variable usage
foo(i);   // Variable 'i' usage

I can capture the declaration, but not use it using the Listener class. Here I am parsing the Java source code.

+4
source share
1 answer

I assume that you are considering only local variables.

To do this, you will need areas and solutions.

The scope will be the scope of Java variables. It will contain information about which variables are declared in this area. You will need to create it when you enter the Java scope (block start, method, ...) and get rid of it by leaving the scope. You will keep a stack of scopes for representing nested blocks / scopes (Java doesn't allow you to hide a local variable in a nested scope, but you still need to keep track of when the variable goes out of scope at the end of the nested scope).

, , - , ( ). , ( .), ( .

Parser , , :

private static class A {
    B out = new B();
}

private static class B {
    void println(String foo) {
        System.out.println("ha");
    }
}

public static void main(String[] args) {
    {
        A System = new A();
        System.out.println("a");
    }
    System.out.println("b");
}



, , , , .., , .

0

Source: https://habr.com/ru/post/1678755/


All Articles