Find variable usage / reference in Java source code using ANTLR?

Variable usage is basically every occurrence of a variable after it is declared in the same scope, in which some operations can be applied to it Some ides such as IntelliJ and eclipse even support variable usage highlighting

I wonder if there is a way to find variable usage using ANTLR? I have passed in Java 8 Running ANTLR on G4 generates lexer, parser and baselistener classes I can find variable declarations, but I can't find variable usage in the given 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 use the listener class to capture the declaration, but I can't use it I parse the Java source code here

Solution

I suppose you only consider local variables

You need scope and solve the problem

The scope will represent the variable scope of Java It holds information about which variables are declared within a given scope When you enter a Java scope (start of block, method,...), you must create it and delete it when you leave the scope You will keep a pile of scopes to represent nested blocks / scopes (Java does not allow hiding local variables in nested scopes, but you still need to track when variables exceed the scope at the end of nested scopes)

Then, you need to resolve each name encountered in the resolved input - determine whether the name refers to a variable (scope of use) Basically, it refers to a local variable. As long as it is the first part of the name (before any). It will not follow (and match the name of the local variable)

The parser cannot do this for you because whether the name refers to a variable depends on the available variables:

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

If you also consider instances and static fields rather than just local variables, the parsing part becomes much more complex because you need to consider all classes in the current class hierarchy, their instances and static fields, visibility, and so on Determines whether a variable with a given name exists and is visible

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>