views:

233

answers:

1

I am writing a Eclipse ASTVisitor. How to tell if a field is read or written in a method?

The idea provided was "You need to vist Assignment node. Field on the LHS is written, while fields on the RHS expression is read."

After I visit the assignment and get the LHS and RHS which are both of Expression, how do I tell if the Expression contains the field?

A: 

If you are doing AST work, I suggest working with the AST View plugin. It is a very handy tool for understanding the JDT AST.

Your approach will work. I use a variable inside the visitor to indicate I'm in an assignment.

    public boolean visit(final Assignment node) {
 inVariableAssignment = true;
 node.getLeftHandSide().accept(this);
 inVariableAssignment = false;
 node.getRightHandSide().accept(this);
 return false;
}

Now, when visiting a SimpleName or a QualifiedName I do something like:

    public boolean visit(final SimpleName node) {
 if (!node.isDeclaration()) {
  final IBinding nodeBinding = node.resolveBinding();
  if (nodeBinding instanceof IVariableBinding) {
   ...
  }
 }
 return false;
}

The ellipsis (...) will be replaced by a code which handles the field access according to the value of your inVariableAssignment. This will get you started.

Oh, don't forget PostfixExpression and PrefixExpression...

zvikico
Thank you! What do u mean by "Oh, don't forget PostfixExpression and PrefixExpression"? And what to do with fields that are not declared in my project? I don't want them to be detected. For eg. field "out" in System.out.println is detected as a field read.
yeeen
The reason why field like "out" in System.out.println is detected as a field read, cos I used a boolean (ie. ur inVariableAssignment). Now I changed to int, initialize to -1. If appear on LHS, set to 0; if appear on RHS set, to 1. When endVisit of the Assignment node, I reset it to -1, the problem is solved.
yeeen
May I know ur reason for doing "(!node.isDeclaration())"? It seems to me that I can be removed. But whether removing it or not, there is still another problem. It cannot detect the field when it is part of the intialization. Eg int y = x + 15, where x is a field.
yeeen
Another thing is what if the field is read in the case when it is not part of the assignment? Eg. System.out.println("field x: " + x). Sorry ask so many qns at once...
yeeen
I can show you the door, you will have to walk through it yourself. I really recommend you download the entire JDT code and check it as an example. It will also take some trial and error, so prepare yourself some sample code, add some printouts and see what comes out. No answer that I will provide will be sufficient, you need to understand and experience it yourself. As for the postfix/prefix, these refer to expressions like "x++" or "--y".
zvikico
One more thing... The visit to the SimpleName will cover cases where the field is accessed outside assignments.
zvikico