Convert to single return: fix for incorrect code

This commit is contained in:
Tagir Valeev
2019-03-20 10:47:52 +07:00
parent b115bc03d8
commit a26ebd6de8
4 changed files with 23 additions and 5 deletions
@@ -81,7 +81,7 @@ class ExitContext {
myReturnVariableDefaultValue = (PsiExpression)value.copy();
}
else {
replacements.add(myReturnVariable + "=" + value.getText() + ";");
replacements.add(0, myReturnVariable + "=" + value.getText() + ";");
}
}
@@ -30,7 +30,7 @@ class ReturnReplacementContext {
private final PsiCodeBlock myBlock;
private final ExitContext myExitContext;
private PsiReturnStatement myReturnStatement;
private final List<String> myReplacements = new ArrayList<>();
private final List<String> myReplacements = new ArrayList<>(3);
private ReturnReplacementContext(Project project,
PsiCodeBlock block,
@@ -45,17 +45,18 @@ class ReturnReplacementContext {
private void process() {
PsiExpression value = myReturnStatement.getReturnValue();
PsiStatement currentContext = goUp();
if (currentContext == null) return;
if (value != null) {
myExitContext.registerReturnValue(value, myReplacements);
}
PsiStatement currentContext = goUp();
while (currentContext != null) {
currentContext = advance(currentContext);
}
replace();
}
@NotNull
@Nullable
private PsiStatement goUp() {
PsiElement parent = myReturnStatement.getParent();
while (parent instanceof PsiCodeBlock) {
@@ -84,7 +85,11 @@ class ReturnReplacementContext {
if (grandParent instanceof PsiStatement) {
parent = grandParent;
}
else if (parent != myBlock) {
else if (parent == myBlock) {
// May happen for incorrect code
return null;
}
else {
throw new RuntimeExceptionWithAttachments("Unexpected structure: " + grandParent.getClass(),
new Attachment("body.txt", myBlock.getText()),
new Attachment("context.txt", grandParent.getText()));
@@ -0,0 +1,6 @@
// "Transform body to single exit-point form" "true"
class Test {
String test(String s) {
return "foo";
}
}
@@ -0,0 +1,7 @@
// "Transform body to single exit-point form" "true"
class Test {
String <caret>test(String s) {
return "foo";
return "bar";
}
}