Skip to content
Advertisement

Find if the current statement in an If/Else block is the last statement of the THEN branch

I am using JavaParser to parse through the contents of the following code and identify the sequence of statements:

JavaScript

The code I am using to parse the above example:

JavaScript

What I would also like to do is to identify if the current statement is an expression statement (i.e., assignment), and if yes, find if it is the last statement contained in the THEN block of an If/Else statement. In the example above that would be statement x=3;. However, I am not sure how to achieve this.

So far my thinking was along these lines:

JavaScript

which works for if statements but not for assignments. Any recommendations on how to approach this?

Advertisement

Answer

This answer is probably to late but this is how you can solve your issue.

If the result of n.getThenStmt() is a BlockStmt you can call getStatements on it that returns a NodeList and then call getLast on the list.

It’s more safety to use equals method to compare to nodes.

The visitor needs to call super.visit method to fully visit the node (expression or statement).

Below a simplified example.

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement