I have read the JavaParser manual and started to build my own examples. What I intend to achieve, is to read Java code and insert new lines of code on it. Specifically, I want to initialise a counter before every if
and while
statement, and inside the body of the statement to increment the counter. My purpose for doing this, is to run the new code for a specified set of runs and observe how many times each branch is executed. I am using JavaParser to parse and add code, because I want to generate and run everything automatically.
For example, we have the following simple piece of code:
if (x>4) {
x=4;
}
else {
x=4;
}
while (i<x) {
i++;
}
And after the parsing I would like to have something like the following:
int countA=0;
int countB=0;
if (x>4) {
x=4;
countA++;
}
else {
x=4;
countB++;
}
int countC=0;
while (i<x) {
i++;
countC++;
}
My code so far:
public static void main (String[] args) throws Exception {
CompilationUnit cu = StaticJavaParser.parse("class X{void x(){" +
" if (x>4) { " +
" x=4; " +
" } " +
" else { " +
" x=4; " +
" } " +
" while (i<x) { " +
" i++; " +
" } " +
" }}");
cu.findAll(Statement.class).forEach(statement -> {
if (statement.isIfStmt()) {
//System.out.println(statement.getChildNodes().get(0));
// System.out.println(statement.getParentNodeForChildren().toString());
// statement.getChildNodes().add(statement.getChildNodes().get(0));
// System.out.println(statement.toString());
}
if (statement.isWhileStmt()) {
// System.out.println();
}
});
System.out.println(cu);
}
}
I have tried some things (the commended out lines) but unsuccessfully. My main problem is that I cannot find a way to inject any line of code at the end of the childNodes
of the given statement
which supposedly would be the increment of the counter or at the end of the parentNode
which would be the initialisation. Is there any way to achieve what I am describing?