Pav Lo
Pav Lo

Reputation: 25

Extracting all variable names from Variable declarations using Eclipse JDT

I have been working on analyzing source code using Eclipse JDT. Currently, I have a program that is able to get some code, convert it to an AST and then make some annotations.

Now, what I want to do is, for each variable declaration, get all the variables involved. For example:

int  a = 10;

Its easy, just variable a

But in the following case :

int a = b +c ;

I need to analyze the right part and extract each variable. What I have until now is this :

For each variable declaration:

//get the fragment                                   
List<VariableDeclarationFragment> ff = vds_p.fragments();

//foreach fragment, get the name of the variable and the value associated
for(VariableDeclarationFragment f_p : ff){
   SimpleName name = f_p.getName();
   Expression exp  =  f_p.getInitializer();
   ChildPropertyDescriptor exp_prop = f_p.getInitializerProperty();

   System.out.println("name: "+name);
   System.out.println("expression: "+exp);
}                                                                       

So, Im able to get the name of the variable and the expression which is assigned to it. Now, here is my question:

How can I analyze using JDT the expression being assigned to the variable, For example in

int a = b + c ;

I want to get b and c. I know that I can get the "b+c" string and apply a manual parsing based on the operator, but Im wondering if there is a more automated way using JDT

Thanks!

Upvotes: 1

Views: 3062

Answers (1)

Deepak Azad
Deepak Azad

Reputation: 7923

Essentially you are looking for 'org.eclipse.jdt.core.dom.SimpleName' nodes which have an 'org.eclipse.jdt.core.dom.IVariableBinding'. You should create an 'org.eclipse.jdt.core.dom.ASTVisitor' and override 'org.eclipse.jdt.core.dom.ASTVisitor.visit(SimpleName)'. Using the ASTVisitor you should then analyse the right hand side expression of a variable declaration.

You may find the 'How to find an AST Node' section of this article useful. You may also find the AST View plugin useful.

Upvotes: 3

Related Questions