0

I am using JavaParser to parse Java applications. I need a function to return the number of cases that a variable in a method body is read or modified. As an example, the function should determines variable x in the below code is read two times and one time is modified.

private int foo(){
  int x;
  System.out.println(x); //Read
  x = 10; //modify
  bar(x); //read
}

so far I wrote this code.

for (ClassOrInterfaceDeclaration cd : cu.findAll(ClassOrInterfaceDeclaration.class)) {
                
    for (MethodDeclaration method : cd.getMethods()) {
                    
        method.getBody().ifPresent(blockStatement -> {
                    
            for( VariableDeclarator variable : blockStatement.findAll(VariableDeclarator.class)) {

                for (NameExpr nameExp : blockStatement.findAll(NameExpr.class)) {
                            
                    if (nameExp.getNameAsString().equals(variable.getNameAsString())) {
                        System.out.println(nameExp.getNameAsString());
                    }
                }
            }
        });
    }
}

Using this code I can know the variable x is used three times in the method body, but I can not distinguish between read and write. Let me know what is the best way to do this using JavaParser.

Iman
  • 91
  • 7
  • You are looking inside `VariableDeclarator`. If you call `getName()` on that and compare it to the variable, shouldn't that be the assingment (the write)? – f1sh Sep 01 '20 at 13:22
  • How should I know it is an assignment? could you post a sample code. `isAssignExpr()` method is not working on `NameExpr`. – Iman Sep 01 '20 at 13:44

1 Answers1

0

I was able to solve the question using the code below:

for (NameExpr nameExpr : callingMethod.findAll(NameExpr.class)) {

    ResolvedValueDeclaration calledVariable = nameExpr.resolve();

    String variableName = calledVariable.getName();
    String variableType = calledVariable.getType().describe();
                
    String type = "Read";

    Node parentNode = nameExpr.getParentNode().get();
    if (parentNode instanceof AssignExpr) {
                    
        Expression target = ((AssignExpr)parentNode).getTarget();
                    
        //Note that arrayAccessExp is not covered in this code
        if (target.isNameExpr()) {
            if (target.asNameExpr().getNameAsString().equals(variableName)) 
                    type = "Write";
        }
    }
}
Spectric
  • 30,714
  • 6
  • 20
  • 43
Iman
  • 91
  • 7