Add instanceof

This commit is contained in:
Daniel Holle 2024-01-31 17:27:18 +01:00
parent 700ea125fc
commit 9da763b361
4 changed files with 26 additions and 14 deletions

View File

@ -1,18 +1,18 @@
import java.lang.Number;
import java.lang.Object;
import java.lang.Integer;
import java.lang.Double;
import java.lang.String;
import java.lang.Boolean;
interface Interface {}
class Test implements Interface {
}
class Test2 {
}
public class InstanceOf {
main(n) {
if (n instanceof Integer i) {
takes(i);
return "Integer";
} else if (n instanceof Double d) {
takes(d);
return "Double";
}
}
a = new Test();
takes(i) {} // Should be overloaded
test1() { return this.a instanceof Test; }
test2() { return this.a instanceof Interface; }
test3() { return this.a instanceof Integer; }
}

View File

@ -1078,6 +1078,7 @@ public class Codegen {
var mv = state.mv;
if (instanceOf.right() instanceof TargetTypePattern right && right.name() == null) {
generate(state, instanceOf.left());
mv.visitTypeInsn(INSTANCEOF, right.type().getInternalName());
return;
}

View File

@ -157,7 +157,7 @@ public class TYPEStmt implements StatementVisitor {
@Override
public void visit(InstanceOf instanceOf) {
//throw new NotImplementedException();
instanceOf.getExpression().accept(this);
}
@Override

View File

@ -788,4 +788,15 @@ public class TestComplete {
var clazz = classFiles.get("SuperCall");
var instance = clazz.getDeclaredConstructor().newInstance();
}
@Test
public void testInstanceOf() throws Exception {
var classFiles = generateClassFiles(new ByteArrayClassLoader(), "InstanceOf.jav");
var clazz = classFiles.get("InstanceOf");
var instance = clazz.getDeclaredConstructor().newInstance();
assertTrue((Boolean) clazz.getDeclaredMethod("test1").invoke(instance));
assertTrue((Boolean) clazz.getDeclaredMethod("test2").invoke(instance));
assertFalse((Boolean) clazz.getDeclaredMethod("test3").invoke(instance));
}
}