I have made a small program that uses JavaParser [1] to parse Java code and identify the types of statements that appear in the code. This has been implemented successfully. What I want to do next, and is a bit tricky, is to find the parent node for an if-statement
, and check whether the first statement of the parent node is a while-loop
. After confirming that the above statement is true, I also want to find if this if-statement
is the last child of the parent node.
Following you can find an example of the above description:
void example() {
int x = 1;
int y = 1;
while (y < 3) {
while (x < 4) {
x++;
}
if (y < 5) {
y++;
}
}
x = 0;
}
The main question I have with parsing the above code, is how to obtain that the parent node of if (y < 5 )
is a while-loop
(while (y < 3)
) and secondly, which might be even trickier, is how to identify that the if-statement
of this example is the last statement before we skip back to the parent loop
. There is also y++;
inside the if
but it might be skipped if the condition of the if
is not true, so I do not want to consider it as the last child of the parent node. I believe what I should do is to check for the last "neighbour"? What I mean by neighbour is the relationship between the second while
and the if
of this example, i.e. they are at the same level.
My thoughts so far implemented:
//find if the if-statement has a parent node
if (currIf.getParentNode().isPresent()) {
//find if the parent Node is a While loop
Optional<Node> parent = currIf.getParentNode();
parent.get().getBegin();
}
With the above code I am able to check if the if-statement
has a parent node and I can find the location of the first while
but I do not know how to confirm that it is a while statement
and also implement the second described part.
UPDATE:
I managed to find how to check if the parent is a while-loop
and currently trying to find a solution on how to identify that the if-statement
is the last statement
of its level (or hierarchy if you prefer).
Optional<WhileStmt> ifParent = currIf.findAncestor(WhileStmt.class);
//find if the if-statement has a parent node
if (ifParent.isPresent()) {
//find if the parent Node is a While loop
Optional<Node> sameNode = ifParent.get().findFirst(Node.class, n -> n == currIf);
if (sameNode.isPresent()) {
System.out.println(sameNode);
}
}