5

I know that JavaParser operates on the AST, yet I was curious if it was possible to add new statements on the same line as another one. Let me give an example on what I would like to achieve.

Example input X.java (do not mind the "logic"):

public class X {
    public static void main(String[] args) {
        int a = 1;
        while(a < 100) {
            a *= 2;
        }
    }
}

What I would like to achieve is to add the statement System.out.println("End of loop reached"); at the end of every loop body - yet, if possible, I would like to add this new statement next to the last statement in the body. Thus, the result should look something like this:

public class X {
    public static void main(String[] args) {
        int a = 1;
        while(a < 100) {
            a *= 2; System.out.println("End of loop reached");
        }
    }
}

Currently I use the following visitor (written in Kotlin), just to get to know JavaParser. Yet this results in new lines being added for the print statements. Any idea on how to instruct JavaParser to add new nodes on the same line?

class WhileVisitor : VoidVisitorAdapter<Void>() {
    override fun visit(whileStatement: WhileStmt, arg: Void?) {
        super.visit(whileStatement, arg)
        val oldBody = whileStatement.body
        if (oldBody.isBlockStmt) {
            (oldBody as BlockStmt).addStatement("System.out.println(\"End of loop reached\");")
        } else {
            whileStatement
                .createBlockStatementAsBody()
                .addStatement(oldBody)
                .addStatement("System.out.println(\"End of loop reached\");")
        }
    }
}
Markus Weninger
  • 11,931
  • 7
  • 64
  • 137
  • You're currently using the `addStatement(String)` method. Have you tried using the `Statement` overload and adjusting the tokens in a `Statement` you create to be at the positions you want? – Pezo Dec 18 '20 at 07:44
  • @Pezo not yet, since the constructor `Statement(TokenRange tokenRange)` has the following documentation in the JavaDoc: This constructor is used by the parser and is considered private. Thus, I did not yet try to use it. But you may be right that I could probably achieve something by manully manipulating certain token ranges, I will have a look into this. – Markus Weninger Dec 18 '20 at 08:53

0 Answers0