Patrick
Patrick

Reputation: 33

Locating method/variable declaration in Java with Rascal

I am looking for a library or tools which offer functionality to build up a data structure which I can use to find variable or method declarations that are used in a class in another scope.

example code:

class A
{
    public void methodA()
    {
         B external = new B();
         external.methodB();    // I would like to know the name/location where this method is declared. something like: classB.java ... line 3
    }
}

class B
{
    public void methodB()
    {

    }
}`

Would Rascal be a good candidate to retrieve this kind of information? I have been using the tool before. As far as I know, I can create an AST but this will not have enough information to determine the scope of where certain variables/methods are declared. If this would not be the right candidate, any ideas on alternatives? My list of candidates I am currently looking into are: Antlr/symtab; JavaParser/JavaSymbolSolver; Spoon; Rascal; JDT

Upvotes: 2

Views: 640

Answers (1)

Jurgen Vinju
Jurgen Vinju

Reputation: 6696

Yes, there are certainly several options to find out where something is declared.

The first answer is to retrieve the decl information from any node in the AST like so, for example:

 rascal>myTree.decl
 loc: |java+parameter:///myClass/fac(int)/n|

From the location value you see that this is the parameter named n in the method named fac in the class myClass.

Now you can disect the location to go find the parent, using the access fields and function for locations, like myTree.decl.path etc, or you can find your information further in an M3 model which the AST builder can also construct:

 model = createM3FromEclipseProject(|project://myProject);

This model contains relations like this: rel[loc, loc] containment, all defined here:

To find the parents in the containment relation you could try this:

model.containment[myTree.decl]

or this for the reverse lookup:

invert(model.containment)[myTree.decl]

For your particular question the rel[loc src, loc name] uses relation is also quite interesting which maps fully qualified declaration names to the source location uses, and rel[loc name, loc src] declarations which maps the qualified names to where they are declared.

Upvotes: 0

Related Questions