From 2a5657e0e60580d837b86af26b86ebef9d97e3ea Mon Sep 17 00:00:00 2001 From: "Pavel V. Talanov" Date: Tue, 29 Oct 2013 16:14:15 +0400 Subject: [PATCH] Convert JavaToKotlinTranslator, StandaloneJavaToKotlinConverterTest, TestCaseBuilder to Kotlin --- .../tests/org/jetbrains/jet/JetTestUtils.java | 1 + .../jet/j2k/JavaToKotlinTranslator.java | 163 ---------------- .../jet/j2k/JavaToKotlinTranslator.kt | 141 ++++++++++++++ .../StandaloneJavaToKotlinConverterTest.java | 178 ----------------- .../jetbrains/jet/j2k/TestCaseBuilder.java | 97 ---------- .../jet/j2k/test/ConverterTestSuite.java | 40 ++++ .../StandaloneJavaToKotlinConverterTest.kt | 183 ++++++++++++++++++ 7 files changed, 365 insertions(+), 438 deletions(-) delete mode 100644 j2k/src/org/jetbrains/jet/j2k/JavaToKotlinTranslator.java create mode 100644 j2k/src/org/jetbrains/jet/j2k/JavaToKotlinTranslator.kt delete mode 100644 j2k/tests/test/org/jetbrains/jet/j2k/StandaloneJavaToKotlinConverterTest.java delete mode 100644 j2k/tests/test/org/jetbrains/jet/j2k/TestCaseBuilder.java create mode 100644 j2k/tests/test/org/jetbrains/jet/j2k/test/ConverterTestSuite.java create mode 100644 j2k/tests/test/org/jetbrains/jet/j2k/test/StandaloneJavaToKotlinConverterTest.kt diff --git a/compiler/tests/org/jetbrains/jet/JetTestUtils.java b/compiler/tests/org/jetbrains/jet/JetTestUtils.java index 9b0892a1b3f..be0f22513b2 100644 --- a/compiler/tests/org/jetbrains/jet/JetTestUtils.java +++ b/compiler/tests/org/jetbrains/jet/JetTestUtils.java @@ -231,6 +231,7 @@ public class JetTestUtils { return createEnvironmentWithMockJdkAndIdeaAnnotations(disposable, ConfigurationKind.ALL); } + @NotNull public static JetCoreEnvironment createEnvironmentWithMockJdkAndIdeaAnnotations(Disposable disposable, @NotNull ConfigurationKind configurationKind) { return createEnvironmentWithJdkAndNullabilityAnnotationsFromIdea(disposable, configurationKind, TestJdkKind.MOCK_JDK); } diff --git a/j2k/src/org/jetbrains/jet/j2k/JavaToKotlinTranslator.java b/j2k/src/org/jetbrains/jet/j2k/JavaToKotlinTranslator.java deleted file mode 100644 index 66b83b68eb5..00000000000 --- a/j2k/src/org/jetbrains/jet/j2k/JavaToKotlinTranslator.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright 2010-2013 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.jet.j2k; - -import com.intellij.core.JavaCoreApplicationEnvironment; -import com.intellij.core.JavaCoreProjectEnvironment; -import com.intellij.lang.java.JavaLanguage; -import com.intellij.openapi.Disposable; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.Disposer; -import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiFile; -import com.intellij.psi.PsiFileFactory; -import com.intellij.psi.PsiJavaFile; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.jetbrains.jet.j2k.visitors.ClassVisitor; -import org.jetbrains.jet.utils.PathUtil; - -import java.io.File; -import java.io.IOException; -import java.io.PrintStream; -import java.net.URL; -import java.net.URLClassLoader; - -public class JavaToKotlinTranslator { - - private static final Disposable DISPOSABLE = Disposer.newDisposable(); - - private JavaToKotlinTranslator() { - } - - @Nullable - private static PsiFile createFile(@NotNull String text) { - JavaCoreProjectEnvironment javaCoreEnvironment = setUpJavaCoreEnvironment(); - return PsiFileFactory.getInstance(javaCoreEnvironment.getProject()).createFileFromText( - "test.java", JavaLanguage.INSTANCE, text - ); - } - - @Nullable - static PsiFile createFile(@NotNull Project project, @NotNull String text) { - return PsiFileFactory.getInstance(project).createFileFromText( - "test.java", JavaLanguage.INSTANCE, text - ); - } - - @NotNull - static JavaCoreProjectEnvironment setUpJavaCoreEnvironment() { - JavaCoreApplicationEnvironment applicationEnvironment = new JavaCoreApplicationEnvironment(DISPOSABLE); - JavaCoreProjectEnvironment javaCoreEnvironment = new JavaCoreProjectEnvironment(DISPOSABLE, applicationEnvironment); - - javaCoreEnvironment.addJarToClassPath(PathUtil.findRtJar()); - File annotations = findAnnotations(); - if (annotations != null && annotations.exists()) { - javaCoreEnvironment.addJarToClassPath(annotations); - } - return javaCoreEnvironment; - } - - @NotNull - static String prettify(@Nullable String code) { - if (code == null) { - return ""; - } - return code - .trim() - .replaceAll("\r\n", "\n") - .replaceAll(" \n", "\n") - .replaceAll("\n ", "\n") - .replaceAll("\n+", "\n") - .replaceAll(" +", " ") - .trim() - ; - } - - @Nullable - public static File findAnnotations() { - ClassLoader classLoader = JavaToKotlinTranslator.class.getClassLoader(); - while (classLoader != null) { - if (classLoader instanceof URLClassLoader) { - URLClassLoader loader = (URLClassLoader) classLoader; - for (URL url : loader.getURLs()) - if ("file".equals(url.getProtocol()) && url.getFile().endsWith("/annotations.jar")) { - return new File(url.getFile()); - } - } - classLoader = classLoader.getParent(); - } - return null; - } - - static void setClassIdentifiers(@NotNull Converter converter, @NotNull PsiElement psiFile) { - ClassVisitor c = new ClassVisitor(); - psiFile.accept(c); - converter.clearClassIdentifiers(); - converter.setClassIdentifiers(c.getClassIdentifiers()); - } - - @NotNull - static String generateKotlinCode(@NotNull String javaCode) { - PsiFile file = createFile(javaCode); - if (file != null && file instanceof PsiJavaFile) { - Converter converter = new Converter(file.getProject()); - setClassIdentifiers(converter, file); - return prettify(converter.fileToFile((PsiJavaFile) file).toKotlin()); - } - return ""; - } - - @NotNull - static String generateKotlinCodeWithCompatibilityImport(@NotNull String javaCode) { - PsiFile file = createFile(javaCode); - if (file != null && file instanceof PsiJavaFile) { - Converter converter = new Converter(file.getProject()); - setClassIdentifiers(converter, file); - return prettify(converter.fileToFileWithCompatibilityImport((PsiJavaFile) file).toKotlin()); - } - return ""; - } - - public static void main(@NotNull String[] args) throws IOException { - //noinspection UseOfSystemOutOrSystemErr - PrintStream out = System.out; - if (args.length == 1) { - String kotlinCode = ""; - try { - kotlinCode = generateKotlinCode(args[0]); - } catch (Exception e) { - out.println("EXCEPTION: " + e.getMessage()); - } - if (kotlinCode.isEmpty()) { - out.println("EXCEPTION: generated code is empty."); - } - else { - out.println(kotlinCode); - } - } - else { - out.println("EXCEPTION: wrong number of arguments (should be 1)."); - } - } - - // Used in the Kotlin Web Demo. - @SuppressWarnings("UnusedDeclaration") - public static String translateToKotlin(String code) { - return generateKotlinCode(code); - } -} diff --git a/j2k/src/org/jetbrains/jet/j2k/JavaToKotlinTranslator.kt b/j2k/src/org/jetbrains/jet/j2k/JavaToKotlinTranslator.kt new file mode 100644 index 00000000000..fd968763746 --- /dev/null +++ b/j2k/src/org/jetbrains/jet/j2k/JavaToKotlinTranslator.kt @@ -0,0 +1,141 @@ +/* + * Copyright 2010-2013 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.j2k + +import com.intellij.core.JavaCoreApplicationEnvironment +import com.intellij.core.JavaCoreProjectEnvironment +import com.intellij.lang.java.JavaLanguage +import com.intellij.openapi.Disposable +import com.intellij.openapi.project.Project +import com.intellij.openapi.util.Disposer +import com.intellij.psi.PsiElement +import com.intellij.psi.PsiFile +import com.intellij.psi.PsiFileFactory +import com.intellij.psi.PsiJavaFile +import org.jetbrains.jet.j2k.visitors.ClassVisitor +import org.jetbrains.jet.utils.PathUtil +import java.io.File +import java.net.URLClassLoader +import java.util.HashSet + +object JavaToKotlinTranslator { + private val DISPOSABLE: Disposable? = Disposer.newDisposable() + + private fun createFile(text: String): PsiFile? { + val javaCoreEnvironment: JavaCoreProjectEnvironment? = setUpJavaCoreEnvironment() + return PsiFileFactory.getInstance(javaCoreEnvironment?.getProject())?.createFileFromText("test.java", JavaLanguage.INSTANCE, text) + } + + public fun createFile(project: Project, text: String): PsiFile? { + return PsiFileFactory.getInstance(project)?.createFileFromText("test.java", JavaLanguage.INSTANCE, text) + } + + fun setUpJavaCoreEnvironment(): JavaCoreProjectEnvironment { + val applicationEnvironment = JavaCoreApplicationEnvironment(DISPOSABLE) + val javaCoreEnvironment = JavaCoreProjectEnvironment(DISPOSABLE, applicationEnvironment) + javaCoreEnvironment.addJarToClassPath(PathUtil.findRtJar()) + val annotations: File? = findAnnotations() + if (annotations != null && annotations.exists()) { + javaCoreEnvironment.addJarToClassPath(annotations) + } + return javaCoreEnvironment + } + + fun prettify(code: String?): String { + if (code == null) { + return "" + } + + return code + .trim() + .replaceAll("\r\n", "\n") + .replaceAll(" \n", "\n") + .replaceAll("\n ", "\n") + .replaceAll("\n+", "\n") + .replaceAll(" +", " ") + .trim() + } + + public fun findAnnotations(): File? { + var classLoader = javaClass().getClassLoader() + while (classLoader != null) { + val loader = classLoader + if (loader is URLClassLoader) { + for (url in loader.getURLs()!!) { + if ("file" == url.getProtocol() && url.getFile()!!.endsWith("/annotations.jar")) { + return File(url.getFile()!!) + } + } + } + classLoader = classLoader?.getParent() + } + return null + } + + fun setClassIdentifiers(converter: Converter, psiFile: PsiElement): Unit { + val c = ClassVisitor() + psiFile.accept(c) + converter.clearClassIdentifiers() + converter.setClassIdentifiers(HashSet(c.getClassIdentifiers())) + } + + fun generateKotlinCode(javaCode: String): String { + val file = createFile(javaCode) + if (file is PsiJavaFile) { + val converter = Converter(file.getProject()) + setClassIdentifiers(converter, file) + return prettify(converter.fileToFile(file).toKotlin()) + } + return "" + } + + fun generateKotlinCodeWithCompatibilityImport(javaCode: String): String { + val file = createFile(javaCode) + if (file is PsiJavaFile) { + val converter = Converter(file.getProject()) + setClassIdentifiers(converter, file) + return prettify(converter.fileToFileWithCompatibilityImport(file).toKotlin()) + } + + return "" + } +} + +public fun main(args: Array) { + if (args.size == 1) { + try { + val kotlinCode = JavaToKotlinTranslator.generateKotlinCode(args[0]) + if (kotlinCode.isEmpty()) { + println("EXCEPTION: generated code is empty.") + } + else { + println(kotlinCode) + } + } + catch (e: Exception) { + println("EXCEPTION: " + e.getMessage()) + } + } + else { + println("EXCEPTION: wrong number of arguments (should be 1).") + } +} + +//used in Kotlin Web Demo +public fun translateToKotlin(code: String): String { + return JavaToKotlinTranslator.generateKotlinCode(code) +} \ No newline at end of file diff --git a/j2k/tests/test/org/jetbrains/jet/j2k/StandaloneJavaToKotlinConverterTest.java b/j2k/tests/test/org/jetbrains/jet/j2k/StandaloneJavaToKotlinConverterTest.java deleted file mode 100644 index 3ac81cb88b8..00000000000 --- a/j2k/tests/test/org/jetbrains/jet/j2k/StandaloneJavaToKotlinConverterTest.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Copyright 2010-2013 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.jet.j2k; - -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.psi.PsiFile; -import com.intellij.psi.PsiJavaFile; -import com.intellij.testFramework.UsefulTestCase; -import junit.framework.Assert; -import junit.framework.Test; -import junit.framework.TestSuite; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.jetbrains.jet.ConfigurationKind; -import org.jetbrains.jet.cli.jvm.compiler.JetCoreEnvironment; - -import java.io.File; -import java.io.IOException; - -import static org.jetbrains.jet.JetTestUtils.createEnvironmentWithMockJdkAndIdeaAnnotations; - -@SuppressWarnings("JUnitTestCaseWithNoTests") -public class StandaloneJavaToKotlinConverterTest extends UsefulTestCase { - private final String myDataPath; - private final String myName; - - @SuppressWarnings("JUnitTestCaseWithNonTrivialConstructors") - public StandaloneJavaToKotlinConverterTest(String dataPath, String name) { - myDataPath = dataPath; - myName = name; - } - - @Override - protected void runTest() throws Throwable { - JetCoreEnvironment jetCoreEnvironment = createEnvironmentWithMockJdkAndIdeaAnnotations(getTestRootDisposable(), ConfigurationKind.JDK_ONLY); - - Converter converter = new Converter(jetCoreEnvironment.getProject()); - - String javaPath = "j2k/tests/testData/" + getTestFilePath(); - String kotlinPath = javaPath.replace(".jav", ".kt"); - - File kotlinFile = new File(kotlinPath); - if (!kotlinFile.exists()) { - FileUtil.writeToFile(kotlinFile, ""); - } - String expected = FileUtil.loadFile(kotlinFile, true); - File javaFile = new File(javaPath); - String javaCode = FileUtil.loadFile(javaFile, true); - - String actual = ""; - String parentFileName = javaFile.getParentFile().getName(); - if (parentFileName.equals("expression")) { - actual = expressionToKotlin(converter, javaCode); - } - else if (parentFileName.equals("statement")) { - actual = statementToKotlin(converter, javaCode); - } - else if (parentFileName.equals("method")) { - actual = methodToKotlin(converter, javaCode); - } - else if (parentFileName.equals("class")) { - actual = fileToKotlin(converter, javaCode); - } - else if (parentFileName.equals("file")) { - actual = fileToKotlin(converter, javaCode); - } - else if (parentFileName.equals("comp")) actual = fileToFileWithCompatibilityImport(javaCode); - - assert !actual.isEmpty() : "Specify what is it: file, class, method, statement or expression: " + javaPath + " parent: " + parentFileName; - - File tmp = new File(kotlinPath + ".tmp"); - if (!expected.equals(actual)) FileUtil.writeToFile(tmp, actual); - if (expected.equals(actual) && tmp.exists()) { - //noinspection ResultOfMethodCallIgnored - tmp.delete(); - } - - Assert.assertEquals(expected, actual); - } - - @NotNull - String getTestFilePath() { - return myDataPath + "/" + myName + ".jav"; - } - - - @NotNull - @Override - public String getName() { - return "test_" + myName; - } - - @NotNull - public static Test suite() { - TestSuite suite = new TestSuite(); -// suite.addTest(new StandaloneJavaToKotlinConverterTest("ast/class/file", "kt-639")); - suite.addTest(TestCaseBuilder.suiteForDirectory("j2k/tests/testData", "/ast", new TestCaseBuilder.NamedTestFactory() { - @NotNull - @Override - public Test createTest(@NotNull String dataPath, @NotNull String name) { - return new StandaloneJavaToKotlinConverterTest(dataPath, name); - } - })); - return suite; - } - - @NotNull - private static String fileToFileWithCompatibilityImport(@NotNull String text) { - return JavaToKotlinTranslator.generateKotlinCodeWithCompatibilityImport(text); - } - - @NotNull - private static String fileToKotlin(Converter converter, @NotNull String text) { - return generateKotlinCode(converter, JavaToKotlinTranslator.createFile(converter.getProject(), text)); - } - - @NotNull - private static String generateKotlinCode(@NotNull Converter converter, @Nullable PsiFile file) { - if (file != null && file instanceof PsiJavaFile) { - JavaToKotlinTranslator.setClassIdentifiers(converter, file); - return prettify(converter.elementToKotlin(file)); - } - return ""; - } - - @NotNull - private static String methodToKotlin(Converter converter, String text) throws IOException { - String result = fileToKotlin(converter, "final class C {" + text + "}") - .replaceAll("class C\\(\\) \\{", ""); - result = result.substring(0, result.lastIndexOf("}")); - return prettify(result); - } - - @NotNull - private static String statementToKotlin(Converter converter, String text) throws Exception { - String result = methodToKotlin(converter, "void main() {" + text + "}"); - int pos = result.lastIndexOf("}"); - result = result.substring(0, pos).replaceFirst("fun main\\(\\) : Unit \\{", ""); - return prettify(result); - } - - @NotNull - private static String expressionToKotlin(Converter converter, String code) throws Exception { - String result = statementToKotlin(converter, "Object o =" + code + "}"); - result = result.replaceFirst("var o : Any\\? =", ""); - return prettify(result); - } - - @NotNull - private static String prettify(@Nullable String code) { - if (code == null) { - return ""; - } - return code - .trim() - .replaceAll("\r\n", "\n") - .replaceAll(" \n", "\n") - .replaceAll("\n ", "\n") - .replaceAll("\n+", "\n") - .replaceAll(" +", " ") - .trim() - ; - } -} diff --git a/j2k/tests/test/org/jetbrains/jet/j2k/TestCaseBuilder.java b/j2k/tests/test/org/jetbrains/jet/j2k/TestCaseBuilder.java deleted file mode 100644 index 44659027caa..00000000000 --- a/j2k/tests/test/org/jetbrains/jet/j2k/TestCaseBuilder.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright 2010-2013 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.jet.j2k; - -import junit.framework.Test; -import junit.framework.TestSuite; -import org.jetbrains.annotations.NotNull; - -import java.io.File; -import java.io.FileFilter; -import java.io.FilenameFilter; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -abstract class TestCaseBuilder { - @NotNull - private static final FilenameFilter emptyFilter = new FilenameFilter() { - @Override - public boolean accept(File file, String name) { - return true; - } - }; - - public interface NamedTestFactory { - @NotNull - Test createTest(@NotNull String dataPath, @NotNull String name); - } - - @NotNull - public static TestSuite suiteForDirectory(String baseDataDir, @NotNull String dataPath, @NotNull NamedTestFactory factory) { - return suiteForDirectory(baseDataDir, dataPath, true, emptyFilter, factory); - } - - @NotNull - private static TestSuite suiteForDirectory(String baseDataDir, @NotNull String dataPath, boolean recursive, @NotNull final FilenameFilter filter, @NotNull NamedTestFactory factory) { - TestSuite suite = new TestSuite(dataPath); - final String extensionJava = ".jav"; - - final FilenameFilter extensionFilter = new FilenameFilter() { - @Override - public boolean accept(File dir, @NotNull String name) { - return name.endsWith(extensionJava); - } - }; - FilenameFilter resultFilter; - if (filter != emptyFilter) { - resultFilter = new FilenameFilter() { - @Override - public boolean accept(File file, String s) { - return extensionFilter.accept(file, s) && filter.accept(file, s); - } - }; - } - else { - resultFilter = extensionFilter; - } - File dir = new File(baseDataDir + dataPath); - FileFilter dirFilter = new FileFilter() { - @Override - public boolean accept(@NotNull File pathname) { - return pathname.isDirectory(); - } - }; - if (recursive) { - File[] files = dir.listFiles(dirFilter); - assert files != null : dir; - List subdirs = Arrays.asList(files); - Collections.sort(subdirs); - for (File subdir : subdirs) { - suite.addTest(suiteForDirectory(baseDataDir, dataPath + "/" + subdir.getName(), recursive, filter, factory)); - } - } - List files = Arrays.asList(dir.listFiles(resultFilter)); - Collections.sort(files); - for (File file : files) { - String fileName = file.getName(); - assert fileName != null; - suite.addTest(factory.createTest(dataPath, fileName.substring(0, fileName.length() - extensionJava.length()))); - } - return suite; - } -} diff --git a/j2k/tests/test/org/jetbrains/jet/j2k/test/ConverterTestSuite.java b/j2k/tests/test/org/jetbrains/jet/j2k/test/ConverterTestSuite.java new file mode 100644 index 00000000000..e228d24ccbb --- /dev/null +++ b/j2k/tests/test/org/jetbrains/jet/j2k/test/ConverterTestSuite.java @@ -0,0 +1,40 @@ +/* + * Copyright 2010-2013 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.j2k.test; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import static org.jetbrains.jet.j2k.test.TestPackage.suiteForDirectory; + +public class ConverterTestSuite { + + private ConverterTestSuite() { + } + + public static Test suite() { + TestSuite suite = new TestSuite(); + suite.addTest(suiteForDirectory("j2k/tests/testData", "/ast", new NamedTestFactory() { + public Test createTest(String dataPath, String name) { + //noinspection JUnitTestCaseWithNoTests + return new StandaloneJavaToKotlinConverterTest(dataPath, name) { + }; + } + })); + return suite; + } +} diff --git a/j2k/tests/test/org/jetbrains/jet/j2k/test/StandaloneJavaToKotlinConverterTest.kt b/j2k/tests/test/org/jetbrains/jet/j2k/test/StandaloneJavaToKotlinConverterTest.kt new file mode 100644 index 00000000000..242b4a932d8 --- /dev/null +++ b/j2k/tests/test/org/jetbrains/jet/j2k/test/StandaloneJavaToKotlinConverterTest.kt @@ -0,0 +1,183 @@ +/* + * Copyright 2010-2013 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.j2k.test + +import java.io.File +import com.intellij.openapi.util.io.FileUtil +import junit.framework.Assert +import com.intellij.psi.PsiJavaFile +import com.intellij.psi.PsiFile +import junit.framework.Test +import junit.framework.TestSuite +import java.io.FilenameFilter +import java.io.FileFilter +import java.util.Collections +import org.jetbrains.jet.j2k.Converter +import org.jetbrains.jet.j2k.JavaToKotlinTranslator +import org.jetbrains.jet.ConfigurationKind +import org.jetbrains.jet.JetTestUtils.createEnvironmentWithMockJdkAndIdeaAnnotations +import com.intellij.testFramework.UsefulTestCase + +public abstract class StandaloneJavaToKotlinConverterTest(val dataPath: String, val name: String) : UsefulTestCase() { + + protected override fun runTest(): Unit { + val jetCoreEnvironment = createEnvironmentWithMockJdkAndIdeaAnnotations(getTestRootDisposable(), ConfigurationKind.JDK_ONLY) + val converter = Converter(jetCoreEnvironment.getProject()) + val javaPath = "j2k/tests/testData/" + getTestFilePath() + val kotlinPath = javaPath.replace(".jav", ".kt") + val kotlinFile = File(kotlinPath) + if (!kotlinFile.exists()) { + FileUtil.writeToFile(kotlinFile, "") + } + + val expected = FileUtil.loadFile(kotlinFile, true) + val javaFile = File(javaPath) + val javaCode = FileUtil.loadFile(javaFile, true) + val parentFileName = javaFile.getParentFile()?.getName() + + val actual = when (parentFileName) { + "expression" -> expressionToKotlin(converter, javaCode) + "statement" -> statementToKotlin(converter, javaCode) + "method" -> methodToKotlin(converter, javaCode) + "class" -> fileToKotlin(converter, javaCode) + "file" -> fileToKotlin(converter, javaCode) + "comp" -> fileToFileWithCompatibilityImport(javaCode) + else -> throw IllegalStateException("Specify what is it: file, class, method, statement or expression:" + + "$javaPath parent: $parentFileName") + } + + val tmp = File(kotlinPath + ".tmp") + if (expected != actual) { + FileUtil.writeToFile(tmp, actual) + } + + if (expected == actual && tmp.exists()) { + tmp.delete() + } + + Assert.assertEquals(expected, actual) + } + + fun getTestFilePath(): String { + return "$dataPath/$name.jav" + } + + private fun fileToKotlin(converter: Converter, text: String): String { + return generateKotlinCode(converter, JavaToKotlinTranslator.createFile(converter.project, text)) + } + + private fun methodToKotlin(converter: Converter, text: String?): String { + var result = fileToKotlin(converter, "final class C {" + text + "}").replaceAll("class C\\(\\) \\{", "") + result = result.substring(0, (result.lastIndexOf("}"))) + return prettify(result) + } + + private fun statementToKotlin(converter: Converter, text: String?): String { + var result = methodToKotlin(converter, "void main() {" + text + "}") + val pos = result.lastIndexOf("}") + result = result.substring(0, pos).replaceFirst("fun main\\(\\) : Unit \\{", "") + return prettify(result) + } + + private fun expressionToKotlin(converter: Converter, code: String?): String { + var result = statementToKotlin(converter, "Object o =" + code + "}") + result = result.replaceFirst("var o : Any\\? =", "") + return prettify(result) + } + + private fun fileToFileWithCompatibilityImport(text: String): String { + return JavaToKotlinTranslator.generateKotlinCodeWithCompatibilityImport(text) + } + + private fun generateKotlinCode(converter: Converter, file: PsiFile?): String { + if (file is PsiJavaFile) { + JavaToKotlinTranslator.setClassIdentifiers(converter, file) + return prettify(converter.elementToKotlin(file)) + } + + return "" + } + + private fun prettify(code: String?): String { + if (code == null) { + return "" + } + + return code.trim().replaceAll("\r\n", "\n").replaceAll(" \n", "\n").replaceAll("\n ", "\n").replaceAll("\n+", "\n").replaceAll(" +", " ").trim() + } + +} +private val emptyFilter = object : FilenameFilter { + public override fun accept(dir: File, name: String): Boolean { + return true + } +} + +public trait NamedTestFactory { + fun createTest(dataPath: String, name: String): Test +} + +public fun suiteForDirectory(baseDataDir: String?, dataPath: String, factory: NamedTestFactory): TestSuite { + return suiteForDirectory(baseDataDir, dataPath, true, emptyFilter, factory) +} + +public fun suiteForDirectory(baseDataDir: String?, dataPath: String, recursive: Boolean, filter: FilenameFilter, factory: NamedTestFactory): TestSuite { + val suite = TestSuite(dataPath) + val extensionJava = ".jav" + val extensionFilter = object : FilenameFilter { + public override fun accept(dir: File, name: String): Boolean { + return name.endsWith(extensionJava) + } + } + + val resultFilter = + if (filter != emptyFilter) { + object : FilenameFilter { + public override fun accept(dir: File, name: String): Boolean { + return (extensionFilter.accept(dir, name)) && filter.accept(dir, name) + } + } + } + else { + extensionFilter + } + + val dir = File(baseDataDir + dataPath) + val dirFilter = object : FileFilter { + public override fun accept(pathname: File): Boolean { + return pathname.isDirectory() + } + } + + if (recursive) { + val files = dir.listFiles(dirFilter) + val subdirs = files!!.toLinkedList() + Collections.sort(subdirs) + for (subdir in subdirs) { + suite.addTest(suiteForDirectory(baseDataDir, dataPath + "/" + subdir.getName(), recursive, filter, factory)) + } + } + + val files = (dir.listFiles(resultFilter))!!.toLinkedList() + Collections.sort(files) + for (file in files) { + val testName = file.getName().substring(0, (file.getName().length()) - (extensionJava.length())) + suite.addTest(factory.createTest(dataPath, testName)) + } + return suite +} +