separate compiler and plugin tests

This commit is contained in:
Dmitry Jemerov
2011-10-20 16:19:02 +02:00
parent a80398098b
commit ec6dec0d37
586 changed files with 69 additions and 42 deletions
@@ -0,0 +1,99 @@
package org.jetbrains.jet.codegen;
import java.lang.reflect.Method;
public class ArrayGenTest extends CodegenTestCase {
public void testKt238 () throws Exception {
blackBoxFile("regressions/kt238.jet");
}
public void testKt326 () throws Exception {
blackBoxFile("regressions/kt326.jet");
System.out.println(generateToText());
}
public void testCreateMultiInt () throws Exception {
loadText("fun foo() = Array<Array<Int>> (5, { Array<Int>(it, {239}) })");
Method foo = generateFunction();
Integer[][] invoke = (Integer[][]) foo.invoke(null);
assertEquals(invoke[2].length, 2);
assertEquals(invoke[4].length, 4);
assertEquals(invoke[4][2].intValue(), 239);
}
public void testCreateMultiIntNullable () throws Exception {
loadText("fun foo() = Array<Array<Int?>> (5, { Array<Int?>(it) })");
Method foo = generateFunction();
Integer[][] invoke = (Integer[][]) foo.invoke(null);
assertEquals(invoke[2].length, 2);
assertEquals(invoke[4].length, 4);
}
public void testCreateMultiString () throws Exception {
loadText("fun foo() = Array<Array<String>> (5, { Array<String>(0,{\"\"}) })");
Method foo = generateFunction();
Object invoke = foo.invoke(null);
System.out.println(invoke.getClass());
assertTrue(invoke instanceof Object[]);
}
public void testCreateMultiGenerics () throws Exception {
loadText("class L<T>() { val a = Array<T>(5) } fun foo() = L<Int>.a");
System.out.println(generateToText());
Method foo = generateFunction();
Object invoke = foo.invoke(null);
System.out.println(invoke.getClass());
assertTrue(invoke instanceof Integer[]);
}
public void testIntGenerics () throws Exception {
loadText("class L<T>(var a : T) {} fun foo() = L<Int>(5).a");
System.out.println(generateToText());
Method foo = generateFunction();
Object invoke = foo.invoke(null);
System.out.println(invoke.getClass());
assertTrue(invoke instanceof Integer);
}
public void testIterator () throws Exception {
loadText("fun box() { val x = Array<Int>(5, { it } ).iterator(); while(x.hasNext()) { java.lang.System.out?.println(x.next()) } }");
System.out.println(generateToText());
Method foo = generateFunction();
foo.invoke(null);
}
public void testPrimitiveIterator () throws Exception {
loadText("fun box() { val x = ByteArray(5).iterator(); while(x.hasNext()) { java.lang.System.out?.println(x.next()) } }");
System.out.println(generateToText());
Method foo = generateFunction();
foo.invoke(null);
}
public void testLongIterator () throws Exception {
loadText("fun box() { val x = LongArray(5).iterator(); while(x.hasNext()) { java.lang.System.out?.println(x.next()) } }");
System.out.println(generateToText());
Method foo = generateFunction();
foo.invoke(null);
}
public void testCharIterator () throws Exception {
loadText("fun box() { val x = CharArray(5).iterator(); while(x.hasNext()) { java.lang.System.out?.println(x.next()) } }");
System.out.println(generateToText());
Method foo = generateFunction();
foo.invoke(null);
}
public void testArrayIndices () throws Exception {
loadText("fun box() { val x = Array<Int>(5, {it}).indices.iterator(); while(x.hasNext()) { java.lang.System.out?.println(x.next()) } }");
System.out.println(generateToText());
Method foo = generateFunction();
foo.invoke(null);
}
public void testCharIndices () throws Exception {
loadText("fun box() { val x = CharArray(5).indices.iterator(); while(x.hasNext()) { java.lang.System.out?.println(x.next()) } }");
System.out.println(generateToText());
Method foo = generateFunction();
foo.invoke(null);
}
}
@@ -0,0 +1,7 @@
package org.jetbrains.jet.codegen;
public class BridgeMethodGenTest extends CodegenTestCase {
public void testBridgeMethod () throws Exception {
blackBoxFile("bridge.jet");
}
}
@@ -0,0 +1,199 @@
package org.jetbrains.jet.codegen;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.List;
/**
* @author yole
*/
public class ClassGenTest extends CodegenTestCase {
public void testPSVMClass() throws Exception {
loadFile("classes/simpleClass.jet");
final Class aClass = loadClass("SimpleClass", generateClassesInFile());
final Method[] methods = aClass.getDeclaredMethods();
// public int SimpleClass.foo()
// public jet.typeinfo.TypeInfo SimpleClass.getTypeInfo()
assertEquals(2, methods.length);
}
public void testArrayListInheritance() throws Exception {
loadFile("classes/inheritingFromArrayList.jet");
final Class aClass = loadClass("Foo", generateClassesInFile());
checkInterface(aClass, List.class);
}
public void testInheritanceAndDelegation_DelegatingDefaultConstructorProperties() throws Exception {
blackBoxFile("classes/inheritance.jet");
}
public void testFunDelegation() throws Exception {
blackBoxFile("classes/funDelegation.jet");
}
public void testPropertyDelegation() throws Exception {
blackBoxFile("classes/propertyDelegation.jet");
}
public void testDiamondInheritance() throws Exception {
blackBoxFile("classes/diamondInheritance.jet");
}
public void testRightHandOverride() throws Exception {
blackBoxFile("classes/rightHandOverride.jet");
}
private static void checkInterface(Class aClass, Class ifs) {
for (Class anInterface : aClass.getInterfaces()) {
if (anInterface == ifs) return;
}
fail(aClass.getName() + " must have " + ifs.getName() + " in its interfaces");
}
public void testNewInstanceExplicitConstructor() throws Exception {
loadFile("classes/newInstanceDefaultConstructor.jet");
System.out.println(generateToText());
final Method method = generateFunction("test");
final Integer returnValue = (Integer) method.invoke(null);
assertEquals(610, returnValue.intValue());
}
public void testInnerClass() throws Exception {
blackBoxFile("classes/innerClass.jet");
}
public void testInheritedInnerClass() throws Exception {
blackBoxFile("classes/inheritedInnerClass.jet");
}
public void testInitializerBlock() throws Exception {
blackBoxFile("classes/initializerBlock.jet");
}
public void testAbstractMethod() throws Exception {
loadText("abstract class Foo { abstract fun x(): String; fun y(): Int = 0 }");
final ClassFileFactory codegens = generateClassesInFile();
final Class aClass = loadClass("Foo", codegens);
assertNotNull(aClass.getMethod("x"));
assertNotNull(findMethodByName(aClass, "y"));
}
public void testInheritedMethod() throws Exception {
blackBoxFile("classes/inheritedMethod.jet");
}
public void testInitializerBlockDImpl() throws Exception {
blackBoxFile("classes/initializerBlockDImpl.jet");
}
public void testPropertyInInitializer() throws Exception {
blackBoxFile("classes/propertyInInitializer.jet");
}
public void testOuterThis() throws Exception {
blackBoxFile("classes/outerThis.jet");
}
public void testSecondaryConstructors() throws Exception {
blackBoxFile("classes/secondaryConstructors.jet");
}
public void testExceptionConstructor() throws Exception {
blackBoxFile("classes/exceptionConstructor.jet");
}
public void testSimpleBox() throws Exception {
blackBoxFile("classes/simpleBox.jet");
}
public void testAbstractClass() throws Exception {
loadText("abstract class SimpleClass() { }");
final Class aClass = loadAllClasses(generateClassesInFile()).get("SimpleClass");
assertTrue((aClass.getModifiers() & Modifier.ABSTRACT) != 0);
}
public void testClassObject() throws Exception {
blackBoxFile("classes/classObject.jet");
}
public void testClassObjectMethod() throws Exception {
blackBoxFile("classes/classObjectMethod.jet");
}
public void testClassObjectInterface() throws Exception {
loadFile("classes/classObjectInterface.jet");
final Method method = generateFunction();
Object result = method.invoke(null);
assertInstanceOf(result, Runnable.class);
}
public void testOverloadBinaryOperator() throws Exception {
blackBoxFile("classes/overloadBinaryOperator.jet");
}
public void testOverloadUnaryOperator() throws Exception {
blackBoxFile("classes/overloadUnaryOperator.jet");
}
public void testOverloadPlusAssign() throws Exception {
blackBoxFile("classes/overloadPlusAssign.jet");
}
public void testOverloadPlusAssignReturn() throws Exception {
blackBoxFile("classes/overloadPlusAssignReturn.jet");
}
public void testOverloadPlusToPlusAssign() throws Exception {
blackBoxFile("classes/overloadPlusToPlusAssign.jet");
}
public void testEnumClass() throws Exception {
loadText("enum class Direction { NORTH; SOUTH; EAST; WEST }");
final Class direction = loadAllClasses(generateClassesInFile()).get("Direction");
System.out.println(generateToText());
final Field north = direction.getField("NORTH");
assertEquals(direction, north.getType());
assertInstanceOf(north.get(null), direction);
}
public void testEnumConstantConstructors() throws Exception {
loadText("enum class Color(val rgb: Int) { RED: Color(0xFF0000); GREEN: Color(0x00FF00); }");
final Class colorClass = loadAllClasses(generateClassesInFile()).get("Color");
final Field redField = colorClass.getField("RED");
final Object redValue = redField.get(null);
final Method rgbMethod = colorClass.getMethod("getRgb");
assertEquals(0xFF0000, rgbMethod.invoke(redValue));
}
public void testKt249() throws Exception {
blackBoxFile("regressions/kt249.jet");
}
public void testKt48 () throws Exception {
blackBoxFile("regressions/kt48.jet");
System.out.println(generateToText());
}
public void testKt309 () throws Exception {
loadText("fun box() = null");
final Method method = generateFunction("box");
assertEquals(method.getReturnType().getName(), "java.lang.Object");
System.out.println(generateToText());
}
public void testKt343 () throws Exception {
blackBoxFile("regressions/kt343.jet");
System.out.println(generateToText());
}
public void testKt344 () throws Exception {
loadFile("regressions/kt344.jet");
System.out.println(generateToText());
blackBox();
}
}
@@ -0,0 +1,40 @@
package org.jetbrains.jet.codegen;
/**
* @author max
*/
public class ClosuresGenTest extends CodegenTestCase {
public void testSimplestClosure() throws Exception {
blackBoxFile("classes/simplestClosure.jet");
System.out.println(generateToText());
}
public void testSimplestClosureAndBoxing() throws Exception {
blackBoxFile("classes/simplestClosureAndBoxing.jet");
}
public void testClosureWithParameter() throws Exception {
blackBoxFile("classes/closureWithParameter.jet");
}
public void testClosureWithParameterAndBoxing() throws Exception {
blackBoxFile("classes/closureWithParameterAndBoxing.jet");
}
public void testExtensionClosure() throws Exception {
blackBoxFile("classes/extensionClosure.jet");
}
public void testEnclosingLocalVariable() throws Exception {
blackBoxFile("classes/enclosingLocalVariable.jet");
System.out.println(generateToText());
}
public void testDoubleEnclosedLocalVariable() throws Exception {
blackBoxFile("classes/doubleEnclosedLocalVariable.jet");
}
public void testEnclosingThis() throws Exception {
blackBoxFile("classes/enclosingThis.jet");
}
}
@@ -0,0 +1,242 @@
package org.jetbrains.jet.codegen;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.testFramework.LightProjectDescriptor;
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jet.JetLightProjectDescriptor;
import org.jetbrains.jet.lang.psi.JetFile;
import org.jetbrains.jet.lang.psi.JetNamespace;
import org.jetbrains.jet.lang.resolve.AnalyzingUtils;
import org.jetbrains.jet.parsing.JetParsingTest;
import org.jetbrains.jet.plugin.JetFileType;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author yole
*/
public abstract class CodegenTestCase extends LightCodeInsightFixtureTestCase {
private MyClassLoader myClassLoader;
protected static void assertThrows(Method foo, Class<? extends Throwable> exceptionClass, Object instance, Object... args) throws IllegalAccessException {
boolean caught = false;
try {
foo.invoke(instance, args);
}
catch(InvocationTargetException ex) {
caught = exceptionClass.isInstance(ex.getTargetException());
}
assertTrue(caught);
}
@Override
protected void setUp() throws Exception {
super.setUp();
myClassLoader = new MyClassLoader(NamespaceGenTest.class.getClassLoader());
}
@Override
protected void tearDown() throws Exception {
myClassLoader = null;
super.tearDown();
}
protected void loadText(final String text) {
myFixture.configureByText(JetFileType.INSTANCE, text);
}
protected void loadFile(final String name) {
myFixture.configureByFile(JetParsingTest.getTestDataDir() + "/codegen/" + name);
}
protected void loadFile() {
loadFile(getPrefix() + "/" + getTestName(true) + ".jet");
}
protected String getPrefix() {
throw new UnsupportedOperationException();
}
protected void blackBoxFile(String filename) {
loadFile(filename);
String actual;
try {
actual = blackBox();
} catch (NoClassDefFoundError e) {
System.out.println(generateToText());
throw e;
} catch (Throwable e) {
System.out.println(generateToText());
throw new RuntimeException(e);
}
if (!"OK".equals(actual)) {
System.out.println(generateToText());
}
assertEquals("OK", actual);
}
protected String blackBox() throws Exception {
ClassFileFactory codegens = generateClassesInFile();
CodegensClassLoader loader = new CodegensClassLoader(codegens);
JetFile jetFile = (JetFile) myFixture.getFile();
final JetNamespace namespace = jetFile.getRootNamespace();
String fqName = NamespaceCodegen.getJVMClassName(namespace.getFQName()).replace("/", ".");
Class<?> namespaceClass = loader.loadClass(fqName);
Method method = namespaceClass.getMethod("box");
return (String) method.invoke(null);
}
protected String generateToText() {
GenerationState state = new GenerationState(getProject(), true);
JetFile jetFile = (JetFile) myFixture.getFile();
AnalyzingUtils.checkForSyntacticErrors(jetFile);
state.compile(jetFile);
StringBuilder answer = new StringBuilder();
final ClassFileFactory factory = state.getFactory();
List<String> files = factory.files();
for (String file : files) {
answer.append("@").append(file).append('\n');
answer.append(factory.asText(file));
}
return answer.toString();
}
protected Class generateNamespaceClass() {
ClassFileFactory state = generateClassesInFile();
return loadRootNamespaceClass(state);
}
protected Class loadRootNamespaceClass(ClassFileFactory state) {
JetFile jetFile = (JetFile) myFixture.getFile();
final JetNamespace namespace = jetFile.getRootNamespace();
String fqName = NamespaceCodegen.getJVMClassName(namespace.getFQName()).replace("/", ".");
Map<String, Class> classMap = loadAllClasses(state);
return classMap.get(fqName);
}
protected Class loadClass(String fqName, ClassFileFactory state) {
List<String> files = state.files();
for (String file : files) {
if (file.equals(fqName.replace('.', '/') + ".class")) {
final byte[] data = state.asBytes(file);
return myClassLoader.doDefineClass(fqName, data);
}
}
fail("No classfile was generated for: " + fqName);
return null;
}
protected Map<String, Class> loadAllClasses(ClassFileFactory state) {
Map<String, Class> result = new HashMap<String, Class>();
for (String fileName : state.files()) {
String className = StringUtil.trimEnd(fileName, ".class").replace('/', '.');
byte[] data = state.asBytes(fileName);
Class aClass = myClassLoader.doDefineClass(className, data);
result.put(className, aClass);
}
return result;
}
protected ClassFileFactory generateClassesInFile() {
try {
GenerationState state = new GenerationState(getProject(), false);
JetFile jetFile = (JetFile) myFixture.getFile();
AnalyzingUtils.checkForSyntacticErrors(jetFile);
state.compile(jetFile);
return state.getFactory();
} catch (RuntimeException e) {
System.out.println(generateToText());
throw e;
}
}
protected Method generateFunction() {
Class aClass = generateNamespaceClass();
try {
return aClass.getMethods()[0];
} catch (Error e) {
System.out.println(generateToText());
throw e;
}
}
protected Method generateFunction(String name) {
Class aClass = generateNamespaceClass();
final Method method = findMethodByName(aClass, name);
if (method == null) {
throw new IllegalArgumentException("couldn't find method " + name);
}
return method;
}
@Nullable
protected static Method findMethodByName(Class aClass, String name) {
for (Method method : aClass.getDeclaredMethods()) {
if (method.getName().equals(name)) {
return method;
}
}
return null;
}
protected static void assertIsCurrentTime(long returnValue) {
long currentTime = System.currentTimeMillis();
assertTrue(Math.abs(returnValue - currentTime) <= 1L);
}
protected Class loadImplementationClass(ClassFileFactory codegens, final String name) {
return loadClass(name, codegens);
}
private static class MyClassLoader extends ClassLoader {
public MyClassLoader(ClassLoader parent) {
super(parent);
}
public Class doDefineClass(String name, byte[] data) {
return defineClass(name, data, 0, data.length);
}
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
return super.loadClass(name);
}
}
private static class CodegensClassLoader extends ClassLoader {
private final ClassFileFactory state;
public CodegensClassLoader(ClassFileFactory state) {
super(CodegenTestCase.class.getClassLoader());
this.state = state;
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
String file = name.replace('.', '/') + ".class";
if (state.files().contains(file)) {
byte[] bytes = state.asBytes(file);
return defineClass(name, bytes, 0, bytes.length);
}
return super.findClass(name);
}
}
@NotNull
@Override
protected LightProjectDescriptor getProjectDescriptor() {
return JetLightProjectDescriptor.INSTANCE;
}
}
@@ -0,0 +1,210 @@
package org.jetbrains.jet.codegen;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
/**
* @author yole
*/
public class ControlStructuresTest extends CodegenTestCase {
@Override
protected String getPrefix() {
return "controlStructures";
}
public void testIf() throws Exception {
loadFile();
System.out.println(generateToText());
final Method main = generateFunction();
assertEquals(15, main.invoke(null, true));
assertEquals(20, main.invoke(null, false));
}
public void testSingleBranchIf() throws Exception {
loadFile();
System.out.println(generateToText());
final Method main = generateFunction();
assertEquals(15, main.invoke(null, true));
assertEquals(20, main.invoke(null, false));
}
public void testWhile() throws Exception {
factorialTest("controlStructures/while.jet");
}
public void testDoWhile() throws Exception {
factorialTest("controlStructures/doWhile.jet");
}
public void testBreak() throws Exception {
factorialTest("controlStructures/break.jet");
}
private void factorialTest(final String name) throws IllegalAccessException, InvocationTargetException {
loadFile(name);
System.out.println(generateToText());
final Method main = generateFunction();
assertEquals(6, main.invoke(null, 3));
assertEquals(120, main.invoke(null, 5));
}
public void testContinue() throws Exception {
loadFile();
System.out.println(generateToText());
final Method main = generateFunction();
assertEquals(3, main.invoke(null, 4));
assertEquals(7, main.invoke(null, 5));
}
public void testIfNoElse() throws Exception {
loadFile();
System.out.println(generateToText());
final Method main = generateFunction();
assertEquals(5, main.invoke(null, 5, true));
assertEquals(10, main.invoke(null, 5, false));
}
public void testCondJumpOnStack() throws Exception {
loadText("import java.lang.Boolean as jlBoolean; fun foo(a: String): Int = if (jlBoolean.parseBoolean(a)) 5 else 10");
final Method main = generateFunction();
assertEquals(5, main.invoke(null, "true"));
assertEquals(10, main.invoke(null, "false"));
}
public void testFor() throws Exception {
loadFile();
System.out.println(generateToText());
final Method main = generateFunction();
List<String> args = Arrays.asList("IntelliJ", " ", "IDEA");
assertEquals("IntelliJ IDEA", main.invoke(null, args));
}
public void testIfBlock() throws Exception {
loadFile();
System.out.println(generateToText());
final Method main = generateFunction();
List<String> args = Arrays.asList("IntelliJ", " ", "IDEA");
assertEquals("TTT", main.invoke(null, args));
args = Arrays.asList("JetBrains");
assertEquals("F", main.invoke(null, args));
}
public void testForInArray() throws Exception {
loadFile();
System.out.println(generateToText());
final Method main = generateFunction();
String[] args = new String[] { "IntelliJ", " ", "IDEA" };
assertEquals("IntelliJ IDEA", main.invoke(null, new Object[] { args }));
}
public void testForInRange() throws Exception {
loadText("fun foo(sb: StringBuilder) { for(x in 1..4) sb.append(x) }");
final Method main = generateFunction();
StringBuilder stringBuilder = new StringBuilder();
main.invoke(null, stringBuilder);
assertEquals("1234", stringBuilder.toString());
}
public void testThrowCheckedException() throws Exception {
loadText("fun foo() { throw Exception(); }");
final Method main = generateFunction();
boolean caught = false;
try {
main.invoke(null);
} catch (InvocationTargetException e) {
if (e.getTargetException().getClass() == Exception.class) {
caught = true;
}
}
assertTrue(caught);
}
public void testTryCatch() throws Exception {
loadFile();
System.out.println(generateToText());
final Method main = generateFunction();
assertEquals("no message", main.invoke(null, "0"));
assertEquals("For input string: \"a\"", main.invoke(null, "a"));
}
public void testTryFinally() throws Exception {
loadFile();
System.out.println(generateToText());
final Method main = generateFunction();
StringBuilder sb = new StringBuilder();
main.invoke(null, sb, "9");
assertEquals("foo9bar", sb.toString());
sb = new StringBuilder();
boolean caught = false;
try {
main.invoke(null, sb, "x");
}
catch(InvocationTargetException e) {
caught = e.getTargetException() instanceof NumberFormatException;
}
assertTrue(caught);
assertEquals("foobar", sb.toString());
}
public void testForUserType() throws Exception {
blackBoxFile("controlStructures/forUserType.jet");
}
public void testForIntArray() throws Exception {
blackBoxFile("controlStructures/forIntArray.jet");
}
public void testForPrimitiveIntArray() throws Exception {
blackBoxFile("controlStructures/forPrimitiveIntArray.jet");
}
public void testForNullableIntArray() throws Exception {
blackBoxFile("controlStructures/forNullableIntArray.jet");
}
public void testForIntRange() {
blackBoxFile("controlStructures/forIntRange.jet");
}
public void testKt237() throws Exception {
blackBoxFile("regressions/kt237.jet");
}
public void testCompareToNull() throws Exception {
loadText("fun foo(a: String?, b: String?): Boolean = a == null && b !== null && null == a && null !== b");
String text = generateToText();
assertTrue(!text.contains("java/lang/Object.equals"));
System.out.println(text);
final Method main = generateFunction();
assertEquals(true, main.invoke(null, null, "lala"));
assertEquals(false, main.invoke(null, null, null));
}
public void testCompareToNonnullableEq() throws Exception {
loadText("fun foo(a: String?, b: String): Boolean = a == b || b == a");
String text = generateToText();
System.out.println(text);
final Method main = generateFunction();
assertEquals(false, main.invoke(null, null, "lala"));
assertEquals(true, main.invoke(null, "papa", "papa"));
}
public void testCompareToNonnullableNotEq() throws Exception {
loadText("fun foo(a: String?, b: String): Boolean = a != b");
String text = generateToText();
System.out.println(text);
assertTrue(text.contains("IXOR"));
final Method main = generateFunction();
assertEquals(true, main.invoke(null, null, "lala"));
assertEquals(false, main.invoke(null, "papa", "papa"));
}
public void testKt299() throws Exception {
blackBoxFile("regressions/kt299.jet");
}
}
@@ -0,0 +1,30 @@
package org.jetbrains.jet.codegen;
import java.lang.reflect.Method;
/**
* @author yole
*/
public class ExtensionFunctionsTest extends CodegenTestCase {
@Override
protected String getPrefix() {
return "extensionFunctions";
}
public void testSimple() throws Exception {
loadFile();
final Method foo = generateFunction("foo");
final Character c = (Character) foo.invoke(null);
assertEquals('f', c.charValue());
}
public void testWhenFail() throws Exception {
loadFile();
Method foo = generateFunction("foo");
assertThrows(foo, Exception.class, null, new StringBuilder());
}
public void testGeneric() throws Exception {
blackBoxFile("extensionFunctions/generic.jet");
}
}
@@ -0,0 +1,16 @@
package org.jetbrains.jet.codegen;
/**
* @author alex.tkachman
*/
public class FunctionGenTest extends CodegenTestCase {
public void testDefaultArgs() throws Exception {
blackBoxFile("functions/defaultargs.jet");
System.out.println(generateToText());
}
public void testNoThisNoClosure() throws Exception {
blackBoxFile("functions/nothisnoclosure.jet");
System.out.println(generateToText());
}
}
@@ -0,0 +1,562 @@
package org.jetbrains.jet.codegen;
import jet.IntRange;
import jet.Tuple2;
import jet.Tuple3;
import jet.Tuple4;
import jet.typeinfo.TypeInfo;
import org.jetbrains.jet.parsing.JetParsingTest;
import java.awt.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
/**
* @author yole
*/
public class NamespaceGenTest extends CodegenTestCase {
public void testPSVM() throws Exception {
loadFile("PSVM.jet");
final String text = generateToText();
System.out.println(text);
final Method main = generateFunction();
Object[] args = new Object[] { new String[0] };
main.invoke(null, args);
}
public void testReturnOne() throws Exception {
loadText("fun f() : Int { return 42; }");
final String text = generateToText();
System.out.println(text);
final Method main = generateFunction();
final Object returnValue = main.invoke(null, new Object[0]);
assertEquals(new Integer(42), returnValue);
}
public void testReturnA() throws Exception {
loadText("fun foo(a : Int) = a");
final String text = generateToText();
System.out.println(text);
final Method main = generateFunction();
final Object returnValue = main.invoke(null, 50);
assertEquals(new Integer(50), returnValue);
}
public void testLocalProperty() throws Exception {
myFixture.configureByFile(JetParsingTest.getTestDataDir() + "/codegen/localProperty.jet");
final String text = generateToText();
System.out.println(text);
final Method main = generateFunction();
final Object returnValue = main.invoke(null, 76);
assertEquals(new Integer(50), returnValue);
}
public void testCurrentTime() throws Exception {
loadText("fun f() : Long { return System.currentTimeMillis(); }");
System.out.println(generateToText());
final Method main = generateFunction();
final long returnValue = (Long) main.invoke(null);
assertIsCurrentTime(returnValue);
}
public void testIdentityHashCode() throws Exception {
loadText("fun f(o: Any) : Int { return System.identityHashCode(o); }");
System.out.println(generateToText());
final Method main = generateFunction();
Object o = new Object();
final int returnValue = (Integer) main.invoke(null, o);
assertEquals(returnValue, System.identityHashCode(o));
}
public void testSystemOut() throws Exception {
loadFile("systemOut.jet");
final Method main = generateFunction();
final Object returnValue = main.invoke(null);
assertEquals(returnValue, System.out);
}
public void testHelloWorld() throws Exception {
loadFile("helloWorld.jet");
System.out.println(generateToText());
generateFunction(); // assert that it can be verified
}
public void testAssign() throws Exception {
loadFile("assign.jet");
System.out.println(generateToText());
final Method main = generateFunction();
assertEquals(2, main.invoke(null));
}
public void testBoxedInt() throws Exception {
loadText("fun foo(a: Int?) = if (a != null) a else 239");
final Method main = generateFunction();
assertEquals(610, main.invoke(null, 610));
assertEquals(239, main.invoke(null, new Object[]{null}));
}
public void testIntBoxed() throws Exception {
loadText("fun foo(s: String): Int? = Integer.getInteger(s, 239)");
final Method main = generateFunction();
assertEquals(239, main.invoke(null, "no.such.system.property"));
}
public void testBoxConstant() throws Exception {
loadText("fun foo(): Int? = 239");
final Method main = generateFunction();
assertEquals(239, main.invoke(null));
}
public void testBoxVariable() throws Exception {
loadText("fun foo(): Int? { var x = 239; return x; }");
System.out.println(generateToText());
final Method main = generateFunction();
assertEquals(239, main.invoke(null));
}
public void testAugAssign() throws Exception {
loadText("fun foo(a: Int): Int { var x = a; x += 5; return x; }");
final Method main = generateFunction();
assertEquals(10, main.invoke(null, 5));
}
public void testBooleanNot() throws Exception {
loadText("fun foo(b: Boolean): Boolean = !b");
final Method main = generateFunction();
assertEquals(true, main.invoke(null, false));
assertEquals(false, main.invoke(null, true));
}
public void testBooleanNotJump() throws Exception {
loadText("fun foo(a: Int) : Int = if (!(a < 5)) a else 0");
final Method main = generateFunction();
assertEquals(6, main.invoke(null, 6));
assertEquals(0, main.invoke(null, 4));
}
public void testAnd() throws Exception {
loadText("fun foo(a : Int): Boolean = a > 0 && a/0 > 0");
final Method main = generateFunction();
assertEquals(false, main.invoke(null, 0));
boolean hadException = false;
try {
main.invoke(null, 5);
} catch (InvocationTargetException e) {
if (e.getTargetException() instanceof ArithmeticException) {
hadException = true;
}
}
assertTrue(hadException);
}
public void testOr() throws Exception {
loadText("fun foo(a : Int): Boolean = a > 0 || a/0 > 0");
final Method main = generateFunction();
assertEquals(true, main.invoke(null, 5));
boolean hadException = false;
try {
main.invoke(null, 0);
} catch (InvocationTargetException e) {
if (e.getTargetException() instanceof ArithmeticException) {
hadException = true;
}
}
assertTrue(hadException);
}
public void testBottles2() throws Exception {
loadFile("bottles2.jet");
System.out.println(generateToText());
final Method main = generateFunction();
main.invoke(null); // ensure no exception
}
public void testJavaConstructor() throws Exception {
loadText("fun foo(): StringBuilder = StringBuilder()");
System.out.println(generateToText());
final Method main = generateFunction();
final Object result = main.invoke(null);
assertTrue(result instanceof StringBuilder);
}
public void testJavaConstructorWithParameters() throws Exception {
loadText("fun foo(): StringBuilder = StringBuilder(\"beer\")");
final Method main = generateFunction();
final StringBuilder result = (StringBuilder) main.invoke(null);
assertEquals("beer", result.toString());
}
public void testJavaEquals() throws Exception {
loadText("fun foo(s1: String, s2: String) = s1 == s2");
System.out.println(generateToText());
final Method main = generateFunction();
assertEquals(Boolean.TRUE, main.invoke(null, new String("jet"), new String("jet")));
assertEquals(Boolean.FALSE, main.invoke(null, new String("jet"), new String("ceylon")));
}
public void testJavaNotEquals() throws Exception {
loadText("fun foo(s1: String, s2: String) = s1 != s2");
final Method main = generateFunction();
assertEquals(Boolean.FALSE, main.invoke(null, new String("jet"), new String("jet")));
assertEquals(Boolean.TRUE, main.invoke(null, new String("jet"), new String("ceylon")));
}
public void testJavaEqualsNull() throws Exception {
loadText("fun foo(s1: String?, s2: String?) = s1 == s2");
final Method main = generateFunction();
System.out.println(generateToText());
assertEquals(Boolean.TRUE, main.invoke(null, null, null));
assertEquals(Boolean.FALSE, main.invoke(null, "jet", null));
assertEquals(Boolean.FALSE, main.invoke(null, null, "jet"));
}
public void testEqualsNullLiteral() throws Exception {
loadText("fun foo(s: String?) = s == null");
final Method main = generateFunction();
System.out.println(generateToText());
assertEquals(Boolean.TRUE, main.invoke(null, new Object[] { null }));
assertEquals(Boolean.FALSE, main.invoke(null, "jet"));
}
public void testTripleEq() throws Exception {
loadText("fun foo(s1: String?, s2: String?) = s1 === s2");
final Method main = generateFunction();
String s1 = new String("jet");
String s2 = new String("jet");
assertEquals(Boolean.TRUE, main.invoke(null, s1, s1));
assertEquals(Boolean.FALSE, main.invoke(null, s1, s2));
}
public void testTripleNotEq() throws Exception {
loadText("fun foo(s1: String?, s2: String?) = s1 !== s2");
final Method main = generateFunction();
String s1 = new String("jet");
String s2 = new String("jet");
assertEquals(Boolean.FALSE, main.invoke(null, s1, s1));
assertEquals(Boolean.TRUE, main.invoke(null, s1, s2));
}
public void testFunctionCall() throws Exception {
loadFile("functionCall.jet");
System.out.println(generateToText());
final Method main = generateFunction("f");
assertEquals("foo", main.invoke(null));
}
public void testStringPlus() throws Exception {
loadText("fun foo(s1: String, s2: String) = s1 + s2");
final Method main = generateFunction();
assertEquals("jetLang", main.invoke(null, "jet", "Lang"));
}
public void testStringPlusChained() throws Exception {
loadText("fun foo(s1: String, s2: String, s3: String) = s1 + s2 + s3");
final String text = generateToText();
final int firstStringBuilderCreation = text.indexOf("NEW java/lang/StringBuilder");
assertEquals(-1, text.indexOf("NEW java/lang/StringBuilder", firstStringBuilderCreation + 1));
final Method main = generateFunction();
assertEquals("jet Lang", main.invoke(null, "jet", " ", "Lang"));
}
public void testStringPlusEq() throws Exception {
loadText("fun foo(s: String) : String { val result = s; result += s; return result; } ");
System.out.println(generateToText());
final Method main = generateFunction();
assertEquals("JarJar", main.invoke(null, "Jar"));
}
public void testStringCompare() throws Exception {
loadText("fun foo(s1: String, s2: String) = s1 < s2");
System.out.println(generateToText());
final Method main = generateFunction();
assertEquals(Boolean.TRUE, main.invoke(null, "Ceylon", "Java"));
assertEquals(Boolean.FALSE, main.invoke(null, "Jet", "Java"));
}
public void testElvis() throws Exception {
loadText("fun foo(s: String?) = s ?: \"null\"");
final Method main = generateFunction();
assertEquals("jet", main.invoke(null, "jet"));
assertEquals("null", main.invoke(null, new Object[] { null }));
}
public void testElvisInt() throws Exception {
loadText("fun foo(a: Int?): Int = a ?: 239");
final Method main = generateFunction();
assertEquals(610, main.invoke(null, 610));
assertEquals(239, main.invoke(null, new Object[]{null}));
}
public void _testVarargs() throws Exception {
loadText("fun foo() = java.util.Arrays.asList(\"IntelliJ\", \"IDEA\")");
final Method main = generateFunction();
ArrayList arrayList = (ArrayList) main.invoke(null);
}
public void testFieldRead() throws Exception {
loadText("import java.awt.*; fun foo(c: GridBagConstraints) = c.gridx");
System.out.println(generateToText());
final Method main = generateFunction();
GridBagConstraints c = new GridBagConstraints();
c.gridx = 239;
assertEquals(239, main.invoke(null, c));
}
public void testFieldWrite() throws Exception {
loadText("import java.awt.*; fun foo(c: GridBagConstraints) { c.gridx = 239 }");
final Method main = generateFunction();
GridBagConstraints c = new GridBagConstraints();
main.invoke(null, c);
assertEquals(239, c.gridx);
}
public void testFieldIncrement() throws Exception {
loadText("import java.awt.*; fun foo(c: GridBagConstraints) { c.gridx++; return; }");
System.out.println(generateToText());
final Method main = generateFunction();
GridBagConstraints c = new GridBagConstraints();
c.gridx = 609;
main.invoke(null, c);
assertEquals(610, c.gridx);
}
public void testFieldAugAssign() throws Exception {
loadText("import java.awt.*; fun foo(c: GridBagConstraints) { c.gridx *= 2; return; }");
System.out.println(generateToText());
final Method main = generateFunction();
GridBagConstraints c = new GridBagConstraints();
c.gridx = 305;
main.invoke(null, c);
assertEquals(610, c.gridx);
}
public void testIncrementAsLastOperation() throws Exception {
loadText("fun foo() { var a = 0; a++; }");
generateFunction(); // make sure we're not falling off end of code
}
public void testArrayRead() throws Exception {
loadText("fun foo(c: Array<String>) = c[0]");
final Method main = generateFunction();
assertEquals("main", main.invoke(null, new Object[]{new String[]{"main"}}));
}
public void testArrayWrite() throws Exception {
loadText("fun foo(c: Array<String>) { c[0] = \"jet\"; }");
final Method main = generateFunction();
String[] array = new String[] { null };
main.invoke(null, new Object[] { array });
assertEquals("jet", array[0]);
}
public void testArrayAugAssign() throws Exception {
loadText("fun foo(c: Array<Int>) { c[0] *= 2 }");
System.out.println(generateToText());
final Method main = generateFunction();
Integer[] data = new Integer[] { 5 };
main.invoke(null, new Object[] { data });
assertEquals(10, data[0].intValue());
}
public void testArrayAugAssignLong() throws Exception {
loadText("fun foo(c: LongArray) { c[0] *= 2 }");
System.out.println(generateToText());
final Method main = generateFunction();
long[] data = new long[] { 5 };
main.invoke(null, new Object[] { data });
assertEquals(10L, data[0]);
}
public void testArrayNew() throws Exception {
loadText("fun foo() = Array<Int>(4, { it })");
System.out.println(generateToText());
final Method main = generateFunction();
Integer[] result = (Integer[]) main.invoke(null);
assertEquals(4, result.length);
assertEquals(0, result[0].intValue());
assertEquals(1, result[1].intValue());
assertEquals(2, result[2].intValue());
assertEquals(3, result[3].intValue());
}
public void testArrayNewNullable() throws Exception {
loadText("fun foo() = Array<Int?>(4)");
System.out.println(generateToText());
final Method main = generateFunction();
Integer[] result = (Integer[]) main.invoke(null);
assertEquals(4, result.length);
}
public void testFloatArrayNew() throws Exception {
loadText("fun foo() = FloatArray(4)");
System.out.println(generateToText());
final Method main = generateFunction();
float[] result = (float[]) main.invoke(null);
assertEquals(4, result.length);
}
public void testFloatArrayArrayNew() throws Exception {
loadText("fun foo() = Array<FloatArray>(4, { FloatArray(5-it) })");
System.out.println(generateToText());
final Method main = generateFunction();
float[][] result = (float[][]) main.invoke(null);
assertEquals(4, result.length);
assertEquals(2, result[3].length);
}
public void testArraySize() throws Exception {
loadText("fun foo(a: Array<Int>) = a.size");
System.out.println(generateToText());
final Method main = generateFunction();
Object[] args = new Object[] { new Integer[4] };
int result = (Integer) main.invoke(null, args);
System.out.println(result);
assertEquals(4, result);
}
public void testIntArraySize() throws Exception {
loadText("fun foo(a: IntArray) = a.size");
System.out.println(generateToText());
final Method main = generateFunction();
Object[] args = new Object[] { new int[4] };
int result = (Integer) main.invoke(null, args);
assertEquals(4, result);
}
public void testIntRange() throws Exception {
loadText("fun foo() = 1..10");
final Method main = generateFunction();
IntRange result = (IntRange) main.invoke(null);
assertTrue(result.contains(1));
assertTrue(result.contains(10));
assertFalse(result.contains(11));
}
public void testSubstituteJavaMethodTypeParameters() throws Exception {
loadText("import java.util.*; fun foo(l: ArrayList<Int>) { l.add(10) }");
final Method main = generateFunction();
final ArrayList<Integer> l = new ArrayList<Integer>();
main.invoke(null, l);
assertEquals(10, l.get(0).intValue());
}
public void testCallMethodDeclaredInSuperclass() throws Exception {
loadText("fun foo(sb: StringBuilder) = sb.charAt(0)");
final Method main = generateFunction();
final StringBuilder sb = new StringBuilder("x");
assertEquals('x', ((Character) main.invoke(null, sb)).charValue());
}
public void testNamespaceQualifiedMethod() throws Exception {
blackBoxFile("namespaceQualifiedMethod.jet");
}
public void testCheckCast() throws Exception {
blackBoxFile("checkCast.jet");
}
public void testPutBooleanAsVoid() throws Exception {
loadText("class C(val x: Int) { { x > 0 } } fun box() { val c = C(0) } ");
final Method main = generateFunction();
main.invoke(null); // must not fail
}
public void testIncrementProperty() throws Exception {
blackBoxFile("incrementProperty.jet");
}
public void testJavaInterfaceMethod() throws Exception {
loadText("import java.util.*; fun foo(l: List<String>) { l.add(\"foo\") }");
final Method main = generateFunction();
final ArrayList<String> list = new ArrayList<String>();
main.invoke(null, list);
assertEquals("foo", list.get(0));
}
public void testArrayAccessForArrayList() throws Exception {
loadText("import java.util.*; fun foo(l: ArrayList<String>) { l[0] = \"Jet\" + l[0]; }");
final Method main = generateFunction();
final ArrayList<String> list = new ArrayList<String>();
list.add("Language");
main.invoke(null, list);
assertEquals("JetLanguage", list.get(0));
}
public void testTupleLiteral() throws Exception {
loadText("fun foo() = (1, \"foo\")");
System.out.println(generateToText());
final Method main = generateFunction();
Tuple2 tuple2 = (Tuple2) main.invoke(null);
assertEquals(1, tuple2._1);
assertEquals("foo", tuple2._2);
}
public void testParametrizedTupleLiteral() throws Exception {
loadText("fun <E,D> E.foo(extra: java.util.List<D>) = (1, \"foo\", this, extra)");
System.out.println(generateToText());
final Method main = generateFunction();
Tuple4 tuple4 = (Tuple4) main.invoke(null, "aaa", Arrays.asList(10), TypeInfo.STRING_TYPE_INFO, TypeInfo.INT_TYPE_INFO);
assertEquals(1, tuple4._1);
assertEquals("foo", tuple4._2);
assertEquals("aaa", tuple4._3);
}
public void testPredicateOperator() throws Exception {
loadText("fun foo(s: String) = s?startsWith(\"J\")");
final Method main = generateFunction();
try {
assertEquals("JetBrains", main.invoke(null, "JetBrains"));
assertNull(main.invoke(null, "IntelliJ"));
}
catch (Throwable t) {
System.out.println(generateToText());
t.printStackTrace();
}
}
public void testEscapeSequence() throws Exception {
loadText("fun foo() = \"a\\nb\\$\"");
final Method main = generateFunction();
assertEquals("a\nb$", main.invoke(null));
}
public void testStringTemplate() throws Exception {
loadText("fun foo(a: String) = \"IntelliJ $a Rulezzz\"");
final Method main = generateFunction();
assertEquals("IntelliJ IDEA Rulezzz", main.invoke(null, "IDEA"));
}
public void testExplicitCallOfBinaryOpIntrinsic() throws Exception {
loadText("fun foo(a: Int) = a.plus(1)");
final Method main = generateFunction();
assertEquals(2, ((Integer) main.invoke(null, 1)).intValue());
}
public void testExplicitCallOfUnaryMinusIntrinsic() throws Exception {
loadText("fun foo(a: Int) = a.minus()");
final Method main = generateFunction();
assertEquals(-1, ((Integer) main.invoke(null, 1)).intValue());
}
public void testExplicitCallOfBooleanNotIntrinsic() throws Exception {
loadText("fun foo(a: Boolean) = a.not()");
final Method main = generateFunction();
assertEquals(false, ((Boolean) main.invoke(null, true)).booleanValue());
}
public void testAppendArrayToString() throws Exception {
loadText("fun foo(a: String, b: Array<String>) = a + b");
final Method main = generateFunction();
final String[] args = new String[] { "foo", "bar" };
//noinspection ImplicitArrayToString
assertEquals("s" + args.toString(), main.invoke(null, "s", args));
}
}
@@ -0,0 +1,19 @@
package org.jetbrains.jet.codegen;
/**
* @author yole
*/
public class ObjectGenTest extends CodegenTestCase {
public void testSimpleObject() throws Exception {
blackBoxFile("objects/simpleObject.jet");
}
public void testObjectLiteral() throws Exception {
blackBoxFile("objects/objectLiteral.jet");
System.out.println(generateToText());
}
public void testMethodOnObject() throws Exception {
blackBoxFile("objects/methodOnObject.jet");
}
}
@@ -0,0 +1,133 @@
package org.jetbrains.jet.codegen;
import jet.NoPatternMatchedException;
import jet.Tuple2;
import java.lang.reflect.Method;
/**
* @author yole
*/
public class PatternMatchingTest extends CodegenTestCase {
@Override
protected String getPrefix() {
return "patternMatching";
}
public void testConstant() throws Exception {
loadFile();
Method foo = generateFunction();
assertTrue((Boolean) foo.invoke(null, 0));
assertFalse((Boolean) foo.invoke(null, 1));
}
public void testExceptionOnNoMatch() throws Exception {
loadFile();
Method foo = generateFunction();
assertTrue((Boolean) foo.invoke(null, 0));
assertThrows(foo, NoPatternMatchedException.class, null, 1);
}
public void testPattern() throws Exception {
loadFile();
Method foo = generateFunction();
assertEquals("string", foo.invoke(null, ""));
assertEquals("something", foo.invoke(null, new Object()));
}
public void testInrange() throws Exception {
loadFile();
System.out.println(generateToText());
Method foo = generateFunction();
assertEquals("array list", foo.invoke(null, 239));
assertEquals("digit", foo.invoke(null, 0));
assertEquals("digit", foo.invoke(null, 9));
assertEquals("digit", foo.invoke(null, 5));
assertEquals("not small", foo.invoke(null, 190));
assertEquals("something", foo.invoke(null, 19));
}
public void testIs() throws Exception {
loadFile();
System.out.println(generateToText());
blackBox();
}
public void testRange() throws Exception {
loadFile();
System.out.println(generateToText());
Method foo = generateFunction();
assertEquals("array list", foo.invoke(null, 239));
assertEquals("digit", foo.invoke(null, 0));
assertEquals("digit", foo.invoke(null, 9));
assertEquals("digit", foo.invoke(null, 5));
assertEquals("something", foo.invoke(null, 19));
assertEquals("not small", foo.invoke(null, 190));
}
public void testRangeChar() throws Exception {
loadFile();
System.out.println(generateToText());
Method foo = generateFunction();
assertEquals("digit", foo.invoke(null, '0'));
assertEquals("something", foo.invoke(null, 'A'));
}
public void testWildcardPattern() throws Exception {
loadText("fun foo(x: String) = when(x) { is * => \"something\" }");
Method foo = generateFunction();
assertEquals("something", foo.invoke(null, ""));
}
public void testNoReturnType() throws Exception {
loadText("fun foo(x: String) = when(x) { is * => \"x\" }");
Method foo = generateFunction();
assertEquals("x", foo.invoke(null, ""));
}
public void testTuplePattern() throws Exception {
loadText("fun foo(x: (Any, Any)) = when(x) { is (1,2) => \"one,two\"; else => \"something\" }");
Method foo = generateFunction();
final Object result;
try {
result = foo.invoke(null, new Tuple2<Integer, Integer>(null, 1, 2));
} catch (Exception e) {
System.out.println(generateToText());
throw e;
}
assertEquals("one,two", result);
assertEquals("something", foo.invoke(null, new Tuple2<String, String>(null, "not", "tuple")));
}
public void testCall() throws Exception {
loadText("fun foo(s: String) = when(s) { .startsWith(\"J\") => \"JetBrains\"; else => \"something\" }");
Method foo = generateFunction();
try {
assertEquals("JetBrains", foo.invoke(null, "Java"));
assertEquals("something", foo.invoke(null, "C#"));
}
catch (Throwable t) {
System.out.println(generateToText());
t.printStackTrace();
}
}
public void testCallProperty() throws Exception {
blackBoxFile("patternMatching/callProperty.jet");
}
public void testNames() throws Exception {
loadText("fun foo(x: (Any, Any)) = when(x) { is (val a is String, *) => a; else => \"something\" }");
Method foo = generateFunction();
assertEquals("JetBrains", foo.invoke(null, new Tuple2<String, String>(null, "JetBrains", "s.r.o.")));
assertEquals("something", foo.invoke(null, new Tuple2<Integer, Integer>(null, 1, 2)));
}
public void testMultipleConditions() throws Exception {
loadText("fun foo(x: Any) = when(x) { is 0, 1 => \"bit\"; else => \"something\" }");
Method foo = generateFunction();
assertEquals("bit", foo.invoke(null, 0));
assertEquals("bit", foo.invoke(null, 1));
assertEquals("something", foo.invoke(null, 2));
}
}
@@ -0,0 +1,277 @@
package org.jetbrains.jet.codegen;
import java.lang.reflect.Method;
/**
* @author yole
*/
public class PrimitiveTypesTest extends CodegenTestCase {
public void testPlus() throws Exception {
loadText("fun f(a: Int, b: Int): Int { return a + b }");
System.out.println(generateToText());
final Method main = generateFunction();
final int returnValue = (Integer) main.invoke(null, 37, 5);
assertEquals(42, returnValue);
}
public void testGt() throws Exception {
loadText("fun foo(f: Int): Boolean { if (f > 0) return true; return false; }");
System.out.println(generateToText());
final Method main = generateFunction();
assertEquals(true, main.invoke(null, 1));
assertEquals(false, main.invoke(null, 0));
}
public void testDiv() throws Exception {
binOpTest("fun foo(a: Int, b: Int): Int = a / b", 12, 3, 4);
}
public void testMod() throws Exception {
binOpTest("fun foo(a: Int, b: Int): Int = a % b", 14, 3, 2);
}
public void testNE() throws Exception {
loadText("fun foo(a: Int, b: Int): Int = if (a != b) 1 else 0");
final Method main = generateFunction();
assertEquals(0, main.invoke(null, 5, 5));
assertEquals(1, main.invoke(null, 5, 3));
}
public void testGE() throws Exception {
loadText("fun foo(a: Int, b: Int): Int = if (a >= b) 1 else 0");
final Method main = generateFunction();
assertEquals(1, main.invoke(null, 5, 5));
assertEquals(0, main.invoke(null, 3, 5));
}
public void testReturnCmp() throws Exception {
loadText("fun foo(a: Int, b: Int): Boolean = a == b");
final Method main = generateFunction();
assertEquals(true, main.invoke(null, 1, 1));
assertEquals(false, main.invoke(null, 1, 2));
}
public void testLong() throws Exception {
loadText("fun foo(a: Long, b: Long): Long = a + b");
System.out.println(generateToText());
final Method main = generateFunction();
long arg = (long) Integer.MAX_VALUE;
long expected = 2 * (long) Integer.MAX_VALUE;
assertEquals(expected, main.invoke(null, arg, arg));
}
public void testLongCmp() throws Exception {
loadText("fun foo(a: Long, b: Long): Long = if (a == b) 0xffffffff else 0xfffffffe");
System.out.println(generateToText());
final Method main = generateFunction();
assertEquals(0xffffffffL, main.invoke(null, 1, 1));
assertEquals(0xfffffffeL, main.invoke(null, 1, 0));
}
public void testShort() throws Exception {
binOpTest("fun foo(a: Short, b: Short): Int = a + b",
Short.valueOf((short) 32767), Short.valueOf((short) 32767), 65534);
}
public void testShortCmp() throws Exception {
binOpTest("fun foo(a: Short, b: Short): Boolean = a == b",
Short.valueOf((short) 32767), Short.valueOf((short) 32767), true);
}
public void testByte() throws Exception {
binOpTest("fun foo(a: Byte, b: Byte): Int = a + b",
Byte.valueOf((byte) 127), Byte.valueOf((byte) 127), 254);
}
public void testByteCmp() throws Exception {
binOpTest("fun foo(a: Byte, b: Byte): Int = if (a == b) 1 else 0",
Byte.valueOf((byte) 127), Byte.valueOf((byte) 127), 1);
}
public void testByteLess() throws Exception {
binOpTest("fun foo(a: Byte, b: Byte): Boolean = a < b",
Byte.valueOf((byte) 126), Byte.valueOf((byte) 127), true);
}
public void testBooleanConstant() throws Exception {
loadText("fun foo(): Boolean = true");
final Method main = generateFunction();
assertEquals(true, main.invoke(null));
}
public void testChar() throws Exception {
binOpTest("fun foo(a: Char, b: Char): Int = a + b", 'A', (char) 3, (int) 'D');
}
public void testFloat() throws Exception {
binOpTest("fun foo(a: Float, b: Float): Float = a + b", 1.0f, 2.0f, 3.0f);
}
public void testFloatCmp() throws Exception {
binOpTest("fun foo(a: Float, b: Float): Boolean = a == b", 1.0f, 1.0f, true);
}
public void testDouble() throws Exception {
binOpTest("fun foo(a: Double, b: Double): Double = a + b", 1.0, 2.0, 3.0);
}
public void testDoubleCmp() throws Exception {
binOpTest("fun foo(a: Double, b: Double): Boolean = a == b", 1.0, 2.0, false);
}
public void testDoubleToJava() throws Exception {
loadText("import java.lang.Double as jlDouble; fun foo(d: Double): String? = jlDouble.toString(d)");
final Method main = generateFunction();
assertEquals("1.0", main.invoke(null, 1.0));
}
public void testDoubleToInt() throws Exception {
loadText("fun foo(a: Double): Int = a.int");
System.out.println(generateToText());
final Method main = generateFunction();
assertEquals(1, main.invoke(null, 1.0));
}
public void testCastConstant() throws Exception {
loadText("fun foo(): Double = 1.dbl");
final Method main = generateFunction();
assertEquals(1.0, main.invoke(null));
}
public void testCastOnStack() throws Exception {
loadText("fun foo(): Double = System.currentTimeMillis().dbl");
final Method main = generateFunction();
double currentTimeMillis = (double) System.currentTimeMillis();
double result = (Double) main.invoke(null);
double delta = Math.abs(currentTimeMillis - result);
assertTrue(delta <= 1.0);
}
public void testNeg() throws Exception {
loadText("fun foo(a: Int): Int = -a");
final Method main = generateFunction();
assertEquals(-10, main.invoke(null, 10));
}
public void testPreIncrement() throws Exception {
loadText("fun foo(a: Int): Int { var x = a; ++x; return x;}");
final Method main = generateFunction();
assertEquals(11, main.invoke(null, 10));
}
public void testPreIncrementValue() throws Exception {
loadText("fun foo(a: Int): Int { var x = a; return ++x;}");
final Method main = generateFunction();
assertEquals(11, main.invoke(null, 10));
}
public void testPreDecrement() throws Exception {
loadText("fun foo(a: Int): Int { return --a;}");
final Method main = generateFunction();
assertEquals(9, main.invoke(null, 10));
}
public void testPreIncrementLong() throws Exception {
loadText("fun foo(a: Long): Long = ++a");
final Method main = generateFunction();
assertEquals(11L, main.invoke(null, 10L));
}
public void testPreIncrementFloat() throws Exception {
loadText("fun foo(a: Float): Float = ++a");
final Method main = generateFunction();
assertEquals(2.0f, main.invoke(null, 1.0f));
}
public void testPreIncrementDouble() throws Exception {
loadText("fun foo(a: Double): Double = ++a");
final Method main = generateFunction();
assertEquals(2.0, main.invoke(null, 1.0));
}
public void testShl() throws Exception {
binOpTest("fun foo(a: Int, b: Int): Int = a shl b", 1, 3, 8);
}
public void testShr() throws Exception {
binOpTest("fun foo(a: Int, b: Int): Int = a shr b", 8, 3, 1);
}
public void testBitAnd() throws Exception {
binOpTest("fun foo(a: Int, b: Int): Int = a and b", 0x77, 0x1f, 0x17);
}
public void testBitOr() throws Exception {
binOpTest("fun foo(a: Int, b: Int): Int = a or b", 0x77, 0x1f, 0x7f);
}
public void testBitXor() throws Exception {
binOpTest("fun foo(a: Int, b: Int): Int = a xor b", 0x70, 0x1f, 0x6f);
}
public void testBitInv() throws Exception {
loadText("fun foo(a: Int): Int = a.inv()");
System.out.println(generateToText());
final Method main = generateFunction();
assertEquals(0xffff0000, main.invoke(null, 0x0000ffff));
}
public void testMixedTypes() throws Exception {
binOpTest("fun foo(a: Int, b: Long): Long = a + b", 1, 2L, 3L);
}
public void testMixedTypes2() throws Exception {
binOpTest("fun foo(a: Double, b: Int): Double = a + b", 1.0, 2, 3.0);
}
public void testPostIncrementTypeInferenceFail() throws Exception {
loadText("fun foo(a: Int): Int { var x = a; var y = x++; if (y+1 != x) return -1; return x; }");
final Method main = generateFunction();
assertEquals(6, main.invoke(null, 5));
}
public void testPostIncrement() throws Exception {
loadText("fun foo(a: Int): Int { var x = a; var y = x++; return x*y; }");
final Method main = generateFunction();
assertEquals(6, main.invoke(null, 2));
}
public void testPostIncrementLong() throws Exception {
loadText("fun foo(a: Long): Long { var x = a; var y = x++; return x*y; }");
final Method main = generateFunction();
assertEquals(6L, main.invoke(null, 2L));
}
public void testDecrementAsStatement() throws Exception {
loadFile("bottles.jet");
System.out.println(generateToText());
final Method main = generateFunction();
main.invoke(null); // ensure no exception
}
private void binOpTest(final String text, final Object arg1, final Object arg2, final Object expected) throws Exception {
loadText(text);
System.out.println(generateToText());
final Method main = generateFunction();
assertEquals(expected, main.invoke(null, arg1, arg2));
}
public void testKt242 () throws Exception {
blackBoxFile("regressions/kt242.jet");
}
public void testKt239 () throws Exception {
blackBoxFile("regressions/kt242.jet");
}
public void testKt243 () throws Exception {
blackBoxFile("regressions/kt243.jet");
}
public void testKt248 () throws Exception {
blackBoxFile("regressions/kt248.jet");
}
}
@@ -0,0 +1,143 @@
package org.jetbrains.jet.codegen;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
/**
* @author yole
*/
public class PropertyGenTest extends CodegenTestCase {
@Override
protected String getPrefix() {
return "properties";
}
public void testPrivateVal() throws Exception {
loadFile();
final Class aClass = loadImplementationClass(generateClassesInFile(), "PrivateVal");
final Field[] fields = aClass.getDeclaredFields();
assertEquals(2, fields.length); // $typeInfo, prop
final Field field = fields[0];
assertEquals("prop", field.getName());
}
public void testPrivateVar() throws Exception {
loadFile();
final Class aClass = loadImplementationClass(generateClassesInFile(), "PrivateVar");
final Object instance = aClass.newInstance();
Method setter = findMethodByName(aClass, "setValueOfX");
setter.invoke(instance, 239);
Method getter = findMethodByName(aClass, "getValueOfX");
assertEquals(239, ((Integer) getter.invoke(instance)).intValue());
}
public void testPublicVar() throws Exception {
loadText("class PublicVar() { public var foo : Int = 0; }");
final Class aClass = loadImplementationClass(generateClassesInFile(), "PublicVar");
final Object instance = aClass.newInstance();
Method setter = findMethodByName(aClass, "setFoo");
setter.invoke(instance, 239);
Method getter = findMethodByName(aClass, "getFoo");
assertEquals(239, ((Integer) getter.invoke(instance)).intValue());
}
public void testAccessorsInInterface() {
loadText("class AccessorsInInterface() { public var foo : Int = 0; }");
final Class aClass = loadClass("AccessorsInInterface", generateClassesInFile());
assertNotNull(findMethodByName(aClass, "getFoo"));
assertNotNull(findMethodByName(aClass, "setFoo"));
}
public void testPropertyInNamespace() throws Exception {
loadText("private val x = 239");
final Class nsClass = generateNamespaceClass();
final Field[] fields = nsClass.getDeclaredFields();
assertEquals(1, fields.length);
final Field field = fields[0];
field.setAccessible(true);
assertEquals("x", field.getName());
assertEquals(Modifier.PRIVATE | Modifier.STATIC, field.getModifiers());
assertEquals(239, field.get(null));
}
public void testFieldPropertyAccess() throws Exception {
loadFile("properties/fieldPropertyAccess.jet");
final Method method = generateFunction();
assertEquals(1, method.invoke(null));
assertEquals(2, method.invoke(null));
}
public void testFieldGetter() throws Exception {
loadText("val now: Long get() = System.currentTimeMillis(); fun foo() = now");
final Method method = generateFunction("foo");
assertIsCurrentTime((Long) method.invoke(null));
}
public void testFieldSetter() throws Exception {
loadFile();
final Method method = generateFunction("append");
method.invoke(null, "IntelliJ ");
String value = (String) method.invoke(null, "IDEA");
if (!value.equals("IntelliJ IDEA")) {
System.out.println(generateToText());
}
assertEquals("IntelliJ IDEA", value);
}
public void testFieldSetterPlusEq() throws Exception {
loadFile();
final Method method = generateFunction("append");
method.invoke(null, "IntelliJ ");
String value = (String) method.invoke(null, "IDEA");
assertEquals("IntelliJ IDEA", value);
}
public void testAccessorsWithoutBody() throws Exception {
loadText("class AccessorsWithoutBody() { public var foo: Int = 349\n get\n private set\n fun setter() { foo = 610; } } ");
final Class aClass = loadImplementationClass(generateClassesInFile(), "AccessorsWithoutBody");
final Object instance = aClass.newInstance();
final Method getFoo = findMethodByName(aClass, "getFoo");
assertEquals(349, getFoo.invoke(instance));
final Method setFoo = findMethodByName(aClass, "setFoo");
assertTrue((setFoo.getModifiers() & Modifier.PRIVATE) != 0);
final Method setter = findMethodByName(aClass, "setter");
setter.invoke(instance);
assertEquals(610, getFoo.invoke(instance));
}
public void testInitializersForNamespaceProperties() throws Exception {
loadText("val x = System.currentTimeMillis()");
final Method method = generateFunction("getX");
assertIsCurrentTime((Long) method.invoke(null));
}
public void testPropertyReceiverOnStack() throws Exception {
loadFile();
final Class aClass = loadImplementationClass(generateClassesInFile(), "Evaluator");
final Constructor constructor = aClass.getConstructor(StringBuilder.class);
StringBuilder sb = new StringBuilder("xyzzy");
final Object instance = constructor.newInstance(sb);
final Method method = aClass.getMethod("evaluateArg");
Integer result = (Integer) method.invoke(instance);
assertEquals(5, result.intValue());
}
public void testAbstractVal() throws Exception {
loadText("abstract class Foo { public abstract val x: String }");
final ClassFileFactory codegens = generateClassesInFile();
final Class aClass = loadClass("Foo", codegens);
assertNotNull(aClass.getMethod("getX"));
}
public void testKt257 () throws Exception {
blackBoxFile("regressions/kt257.jet");
}
public void testKt160() throws Exception {
loadText("internal val s = java.lang.Double.toString(1.0)");
final Method method = generateFunction("getS");
assertEquals(method.invoke(null), "1.0");
}
}
@@ -0,0 +1,15 @@
package org.jetbrains.jet.codegen;
public class SafeRefTest extends CodegenTestCase {
public void test247 () throws Exception {
blackBoxFile("regressions/kt247.jet");
}
public void test245 () throws Exception {
blackBoxFile("regressions/kt245.jet");
}
public void test232 () throws Exception {
blackBoxFile("regressions/kt232.jet");
}
}
@@ -0,0 +1,26 @@
package org.jetbrains.jet.codegen;
public class TraitsTest extends CodegenTestCase {
@Override
protected String getPrefix() {
return "traits";
}
public void testSimple () throws Exception {
blackBoxFile("traits/simple.jet");
System.out.println(generateToText());
}
public void testWithRequired () throws Exception {
blackBoxFile("traits/withRequired.jet");
System.out.println(generateToText());
}
public void testMultiple () throws Exception {
blackBoxFile("traits/multiple.jet");
}
public void testStdlib () throws Exception {
blackBoxFile("traits/stdlib.jet");
}
}
@@ -0,0 +1,143 @@
package org.jetbrains.jet.codegen;
import jet.JetObject;
import jet.TypeCastException;
import jet.typeinfo.TypeInfo;
import java.lang.reflect.Method;
/**
* @author yole
*/
public class TypeInfoTest extends CodegenTestCase {
@Override
protected String getPrefix() {
return "typeInfo";
}
public void testGetTypeInfo() throws Exception {
loadFile();
Method foo = generateFunction();
JetObject jetObject = (JetObject) foo.invoke(null);
TypeInfo<?> typeInfo = jetObject.getTypeInfo();
assertNotNull(typeInfo);
}
public void testOneArgTypeinfo() throws Exception {
loadFile();
Method foo = generateFunction();
TypeInfo typeInfo = (TypeInfo) foo.invoke(null);
assertNotNull(typeInfo);
}
public void testNoArgTypeinfo() throws Exception {
loadText("fun foo() = typeinfo.typeinfo<Int>()");
Method foo = generateFunction();
TypeInfo typeInfo = (TypeInfo) foo.invoke(null);
assertSame(TypeInfo.INT_TYPE_INFO, typeInfo);
}
public void testAsSafeOperator() throws Exception {
loadText("fun foo(x: Any) = x as? Runnable");
Method foo = generateFunction();
assertNull(foo.invoke(null, new Object()));
Runnable r = newRunnable();
assertSame(r, foo.invoke(null, r));
}
public void testAsOperator() throws Exception {
loadText("fun foo(x: Any) = x as Runnable");
Method foo = generateFunction();
Runnable r = newRunnable();
assertSame(r, foo.invoke(null, r));
assertThrows(foo, TypeCastException.class, null, new Object());
}
public void testIsOperator() throws Exception {
loadText("fun foo(x: Any) = x is Runnable");
Method foo = generateFunction();
assertFalse((Boolean) foo.invoke(null, new Object()));
assertTrue((Boolean) foo.invoke(null, newRunnable()));
}
public void testIsWithGenerics() throws Exception {
loadFile();
System.out.println(generateToText());
Method foo = generateFunction();
assertFalse((Boolean) foo.invoke(null));
}
public void testNotIsOperator() throws Exception {
loadText("fun foo(x: Any) = x !is Runnable");
Method foo = generateFunction();
assertTrue((Boolean) foo.invoke(null, new Object()));
assertFalse((Boolean) foo.invoke(null, newRunnable()));
}
public void testIsWithGenericParameters() throws Exception {
loadFile();
Method foo = generateFunction();
assertFalse((Boolean) foo.invoke(null));
}
public void testIsTypeParameter() throws Exception {
blackBoxFile("typeInfo/isTypeParameter.jet");
}
public void testAsSafeWithGenerics() throws Exception {
loadFile();
Method foo = generateFunction();
assertNull(foo.invoke(null));
}
public void testAsInLoop() throws Exception {
loadFile();
generateFunction(); // assert no exception
}
public void testPrimitiveTypeInfo() throws Exception {
blackBoxFile("typeInfo/primitiveTypeInfo.jet");
}
public void testNullability() throws Exception {
blackBoxFile("typeInfo/nullability.jet");
}
public void testGenericFunction() throws Exception {
blackBoxFile("typeInfo/genericFunction.jet");
}
public void testForwardTypeParameter() throws Exception {
blackBoxFile("typeInfo/forwardTypeParameter.jet");
}
public void testClassObjectInTypeInfo() throws Exception {
loadFile();
System.out.println(generateToText());
Method foo = generateFunction();
JetObject jetObject = (JetObject) foo.invoke(null);
TypeInfo<?> typeInfo = jetObject.getTypeInfo();
final Object object = typeInfo.getClassObject();
final Method classObjFoo = object.getClass().getMethod("foo");
assertNotNull(classObjFoo);
}
private Runnable newRunnable() {
return new Runnable() {
@Override
public void run() {
}
};
}
public void testKt259() throws Exception {
blackBoxFile("regressions/kt259.jet");
System.out.println(generateToText());
}
public void testInner() throws Exception {
blackBoxFile("typeInfo/inner.jet");
System.out.println(generateToText());
}
}