javajavaparser

How know a variable is read or modified using JavaParser


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.


Solution

  • 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";
            }
        }
    }