Default throws
Some checks failed
Build and Test with Maven / Build-and-test-with-Maven (push) Has been cancelled

This commit is contained in:
Daniel Holle 2024-09-12 14:36:26 +02:00
parent 114de0b236
commit 54f258e333
3 changed files with 17 additions and 12 deletions

View File

@ -11,7 +11,7 @@ public class Switch {
case Rec(Integer a, Float b) -> a + 10;
case Rec(Integer a, Rec(Integer b, Integer c)) -> a + b + c;
case Integer i -> i;
default -> 0;
//default -> 0;
};
}
}

View File

@ -1339,11 +1339,7 @@ public class Codegen {
}
}
var defaultLabel = end;
if (aSwitch.default_() != null) {
defaultLabel = new Label();
}
var defaultLabel = new Label();
mv.visitTableSwitchInsn(0, labels.length - 1, defaultLabel, labels);
for (var i = 0; i < aSwitch.cases().size(); i++) {
@ -1378,11 +1374,18 @@ public class Codegen {
if (aSwitch.isExpression()) mv.visitJumpInsn(GOTO, end);
}
mv.visitLabel(defaultLabel);
if (aSwitch.default_() != null) {
mv.visitLabel(defaultLabel);
generate(state, aSwitch.default_().body());
if (aSwitch.default_().isSingleExpression() && aSwitch.isExpression())
yieldValue(state, aSwitch.default_().body().statements().get(0).type());
} else {
// throw illegal argument exception on missing default case
mv.visitTypeInsn(NEW, "java/lang/IllegalArgumentException");
mv.visitInsn(DUP);
mv.visitLdcInsn("Unhandled case value");
mv.visitMethodInsn(INVOKESPECIAL, "java/lang/IllegalArgumentException", "<init>", "(Ljava/lang/String;)V", false);
mv.visitInsn(ATHROW);
}
mv.visitLabel(end);

View File

@ -3,15 +3,11 @@ import de.dhbwstuttgart.environment.ByteArrayClassLoader;
import org.junit.Ignore;
import org.junit.Test;
import java.io.*;
import java.lang.reflect.*;
import java.util.AbstractList;
import java.util.Arrays;
import java.util.List;
import java.util.Vector;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import targetast.TestCodegen;
import static org.junit.Assert.*;
@ -684,7 +680,13 @@ public class TestComplete {
assertEquals(swtch.invoke(instance, r2), 20);
assertEquals(swtch.invoke(instance, r3), 40);
assertEquals(swtch.invoke(instance, 50), 50);
assertEquals(swtch.invoke(instance, "Some string"), 0);
try {
assertEquals(swtch.invoke(instance, "Some string"), 0);
fail("No assertion thrown!");
} catch (InvocationTargetException exception) {
assertTrue(exception.getCause() instanceof IllegalArgumentException);
assertEquals(exception.getCause().getMessage(), "Unhandled case value");
}
}
@Test