Rewriting a node swallows a comment line [message #987419] |
Mon, 26 November 2012 09:31  |
Eclipse User |
|
|
|
I was writing simple refactoring and noticed a strange thing. The comment line before the node I am rewriting disappears after refactoring. Also comments after the node in question are transferred inside the node and break the indentation in the new place. This is very strange and I want to ask if it is a bug in jdt or I did something wrong and oblivious.
For example my code suppose to refactor if-else statements in a way that the shortest branch would appear first.
when I try to refactor this:
// pre
if(a==6) {
a = 5;
return false;
} else {
a++;
}
//post
I get this:
if (!(a==6)) {
a++;
}
//post
else {
a = 5;
return false;
}
The relevant snippet where the refactoring is done:
protected ASTRewrite createRewrite(CompilationUnit cu, SubProgressMonitor pm) {
pm.beginTask("Creating rewrite operation...", 1);
final AST ast = cu.getAST();
final ASTRewrite rewrite = ASTRewrite.create(ast);
cu.accept(new ASTVisitor() {
public boolean visit(IfStatement node) {
if (node.getStartPosition() > selection.getOffset() + selection.getLength() || node.getStartPosition() < selection.getOffset())
return true;
if (node.getElseStatement() == null)
return true;
int thenCount = countNodes(node.getThenStatement());
int elseCount = countNodes(node.getElseStatement());
if(thenCount <= elseCount)
return true;
IfStatement newnode = ast.newIfStatement();
PrefixExpression neg = negateExpression(ast, rewrite, node.getExpression());
newnode.setExpression(neg);
newnode.setThenStatement((org.eclipse.jdt.core.dom.Statement) rewrite.createMoveTarget(node.getElseStatement()));
newnode.setElseStatement((org.eclipse.jdt.core.dom.Statement) rewrite.createMoveTarget(node.getThenStatement()));
rewrite.replace(node, newnode, null);
return true;
}
});
pm.done();
return rewrite;
}
|
|
|
Re: Rewriting a node swallows a comment line [message #997325 is a reply to message #987419] |
Sat, 05 January 2013 18:15  |
Eclipse User |
|
|
|
You mave have figured this out meanwhile, the behavior can easily be explained if we just assume:
- "//pre" is associated to the if statement as a leading comment; since the if statement has been replaced with a new one (which has no leading comment) this comment is lost.
- "//post" is associated as a trailing comment to the else statement, by moving up the else statement also this comment is moved up.
I didn't check the code, but I believe the above comes close to the truth.
cheers,
Stephan
|
|
|
Powered by
FUDForum. Page generated in 0.05088 seconds