I'm creating eclipse plugin to format/inject code.
One of the requirements is to add blocks (if not exist) for if-else statements.
In case of nested if-else, my code works well for outer if-else, but doesn't add block for inner if-else statements.
e.g.
if (i == 0)
if (i == 1)
System.out.println("A");
else
System.out.println("B");
else if (i == 2)
if (i == 3)
System.out.println("C");
else
System.out.println("D");
else if (i == 4)
System.out.println("E");
else
System.out.println("F");
output after injecting blocks
if (i == 0){
if (i == 1)
System.out.println("A");
else
System.out.println("B");
}
else { if (i == 2)
if (i == 3)
System.out.println("C");
else
System.out.println("D");
else if (i == 4)
System.out.println("E");
else
System.out.println("F");
}
Here is my code:
for (TypeDeclaration typeDeclaration : allTypes) {
typeDeclaration.accept(new ASTVisitor() {
@Override
public boolean visit(TypeDeclaration node) {
node.accept(new ASTVisitor() {
@Override
public boolean visit(IfStatement ifStatement) {
if (ifStatement != null) {
Statement thenStatement = ifStatement.getThenStatement();
Statement elseStatement = ifStatement.getElseStatement();
String codeToReplace = "if(" + ifStatement.getExpression() + ")";
if (thenStatement instanceof Block)
codeToReplace += "" + thenStatement + "";
else
codeToReplace += "{\n" + thenStatement + "\n}";
if (elseStatement != null) {
if (elseStatement instanceof Block)
codeToReplace += "else" + elseStatement + "";
else
codeToReplace += "else{\n" + elseStatement + "\n}";
}
replaceStatment(rewriter, getBlockInstence(ifStatement), codeToReplace, ifStatement);
}
return super.visit(ifStatement);
}
});
return super.visit(node);
}
});
}
iCompilationUnit.applyTextEdit(rewriter.rewriteAST(), new NullProgressMonitor());
iCompilationUnit.commitWorkingCopy(true, new NullProgressMonitor());
I also tried committing document on AST node visit
IDocument document = new org.eclipse.jface.text.Document(
iCompilationUnit.getSource());
TextEdit edits = cu.rewrite(document, null);
document.replace(ifStatement.getStartPosition(),ifStatement.getLength(),
codeToReplace);
edits.apply(document);
iCompilationUnit.getBuffer().setContents(document.get());
iCompilationUnit.commitWorkingCopy(true, new NullProgressMonitor());
}
For replacing the document, I get right offset [ifStatement.getStartPosition();] for first IfStatement, & modified code [block added] gets replaced successfully. But for next nodes in this AST, I get the older offset & hence modified code for that gets placed at wrong place! How can I get updated startPosition for nodes?
Any sort of solution/suggestion is welcome.
Thanks for your time!