IDEA-182526 Move assignment to field declaration swallows comments

This commit is contained in:
Tagir Valeev
2017-11-24 11:17:26 +07:00
parent e71ffcdb58
commit cb4f3f1a89
4 changed files with 29 additions and 10 deletions
@@ -23,10 +23,7 @@ import one.util.streamex.StreamEx;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.*;
/**
* @author cdr
@@ -220,8 +217,10 @@ public class MoveFieldAssignmentToInitializerInspection extends AbstractBaseJava
PsiElement prev = PsiTreeUtil.skipWhitespacesAndCommentsBackward(assignment.getParent());
String comments = prev == null ? null : CommentTracker.commentsBetween(prev, assignment);
PsiExpression initializer = assignment.getRExpression();
field.setInitializer(initializer);
CommentTracker ct = new CommentTracker();
// Should not reach here if getRExpression is null: isInitializedWithSameExpression would return false
PsiExpression initializer = Objects.requireNonNull(assignment.getRExpression());
field.setInitializer(ct.markUnchanged(initializer));
PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
if (comments != null) {
@@ -242,12 +241,13 @@ public class MoveFieldAssignmentToInitializerInspection extends AbstractBaseJava
parent instanceof PsiWhileStatement ||
parent instanceof PsiForStatement ||
parent instanceof PsiForeachStatement) {
PsiStatement emptyStatement = factory.createStatementFromText(";", statement);
statement.replace(emptyStatement);
ct.replaceAndRestoreComments(statement, ";");
}
else {
statement.delete();
ct.deleteAndRestoreComments(statement);
}
// if we replace/delete several assignments we want to restore comments at each place separately
ct = new CommentTracker();
}
// Delete empty initializer left after fix
@@ -3,10 +3,11 @@
class X {
int f = 0;
X() {
<caret>}
}
X(int i) {
if (1==1) ;
else {
//sds
}
}
}
@@ -0,0 +1,9 @@
// "Move assignment to field declaration" "true"
class X {
String ff = "";
void f() {
//comment
}
}
@@ -0,0 +1,9 @@
// "Move assignment to field declaration" "true"
class X {
String ff;
void f() {
ff <caret>= ""; //comment
}
}