1

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!

1
  • I would post this question on the JDT forum at eclipse.org. The JDT committers are there and will answer it. Feb 15, 2012 at 16:15

1 Answer 1

3

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.