Changed CRLF line-endings to LF

This commit is contained in:
Santeri Hiltunen
2013-01-29 16:00:01 +02:00
committed by Pavel V. Talanov
parent 3abeffb8b8
commit 453bb8b4f2
289 changed files with 5588 additions and 5588 deletions
+3 -3
View File
@@ -1,3 +1,3 @@
Manifest-Version: 1.0 Manifest-Version: 1.0
Main-Class: org.jetbrains.jet.j2k.JavaToKotlinCli Main-Class: org.jetbrains.jet.j2k.JavaToKotlinCli
File diff suppressed because it is too large Load Diff
@@ -1,8 +1,8 @@
package org.jetbrains.jet.j2k package org.jetbrains.jet.j2k
public enum class J2KConverterFlags { public enum class J2KConverterFlags {
FULLY_QUALIFIED_TYPE_NAMES FULLY_QUALIFIED_TYPE_NAMES
SKIP_BODIES SKIP_BODIES
SKIP_NON_PUBLIC_MEMBERS SKIP_NON_PUBLIC_MEMBERS
} }
+146 -146
View File
@@ -1,147 +1,147 @@
//package org.jetbrains.jet.j2k; //package org.jetbrains.jet.j2k;
// //
//import com.intellij.psi.PsiFile; //import com.intellij.psi.PsiFile;
//import com.intellij.psi.PsiJavaFile; //import com.intellij.psi.PsiJavaFile;
//import org.apache.commons.cli.*; //import org.apache.commons.cli.*;
//import org.jetbrains.annotations.NotNull; //import org.jetbrains.annotations.NotNull;
//import org.jetbrains.annotations.Nullable; //import org.jetbrains.annotations.Nullable;
// //
//import java.io.File; //import java.io.File;
//import java.io.FileNotFoundException; //import java.io.FileNotFoundException;
//import java.io.IOException; //import java.io.IOException;
//import java.util.ArrayList; //import java.util.ArrayList;
//import java.util.Arrays; //import java.util.Arrays;
//import java.util.List; //import java.util.List;
//import java.util.logging.Logger; //import java.util.logging.Logger;
//import java.util.regex.Pattern; //import java.util.regex.Pattern;
// //
//import static org.apache.commons.io.FileUtils.readFileToString; //import static org.apache.commons.io.FileUtils.readFileToString;
//import static org.apache.commons.io.FileUtils.writeStringToFile; //import static org.apache.commons.io.FileUtils.writeStringToFile;
// //
///** ///**
// * @author ignatov // * @author ignatov
// */ // */
//@SuppressWarnings({"CallToPrintStackTrace", "UseOfSystemOutOrSystemErr"}) //@SuppressWarnings({"CallToPrintStackTrace", "UseOfSystemOutOrSystemErr"})
//public class JavaToKotlinCli { //public class JavaToKotlinCli {
// private static final Logger myLogger = Logger.getAnonymousLogger(); // private static final Logger myLogger = Logger.getAnonymousLogger();
// //
// private JavaToKotlinCli() { // private JavaToKotlinCli() {
// } // }
// //
// public static void main(String[] args) { // public static void main(String[] args) {
// CommandLineParser parser = new BasicParser(); // CommandLineParser parser = new BasicParser();
// Options options = new Options() // Options options = new Options()
// .addOption("h", "help", false, "Print usage information") // .addOption("h", "help", false, "Print usage information")
// .addOption("f", "from", true, "Directory with Java sources") // .addOption("f", "from", true, "Directory with Java sources")
// .addOption("t", "to", true, "Directory with Kotlin sources") // .addOption("t", "to", true, "Directory with Kotlin sources")
// .addOption("p", "public-only", false, "Only public and protected members") // .addOption("p", "public-only", false, "Only public and protected members")
// .addOption("fqn", "fqn", false, "Full qualified names") // .addOption("fqn", "fqn", false, "Full qualified names")
// .addOption("d", "declarations-only", false, "Declarations only") // .addOption("d", "declarations-only", false, "Declarations only")
// ; // ;
// //
// try { // try {
// CommandLine commandLine = parser.parse(options, args); // CommandLine commandLine = parser.parse(options, args);
// //
// if (commandLine.hasOption("help")) // if (commandLine.hasOption("help"))
// showHelpAndExit(); // showHelpAndExit();
// //
// if (commandLine.hasOption("from") && commandLine.hasOption("to")) { // if (commandLine.hasOption("from") && commandLine.hasOption("to")) {
// String from = commandLine.getOptionValue("from"); // String from = commandLine.getOptionValue("from");
// String to = commandLine.getOptionValue("to"); // String to = commandLine.getOptionValue("to");
// //
// for (Option o : commandLine.getOptions()) { // for (Option o : commandLine.getOptions()) {
// Converter.addFlag(o.getLongOpt()); // Converter.addFlag(o.getLongOpt());
// } // }
// //
// if (!from.isEmpty() && !to.isEmpty()) // if (!from.isEmpty() && !to.isEmpty())
// convertSourceTree(from, to); // convertSourceTree(from, to);
// else // else
// showHelpAndExit(); // showHelpAndExit();
// } else // } else
// showHelpAndExit(); // showHelpAndExit();
// } catch (ParseException e) { // } catch (ParseException e) {
// e.printStackTrace(); // e.printStackTrace();
// } // }
// } // }
// //
// @SuppressWarnings("ResultOfMethodCallIgnored") // @SuppressWarnings("ResultOfMethodCallIgnored")
// private static void convertSourceTree(String javaPath, String kotlinPath) { // private static void convertSourceTree(String javaPath, String kotlinPath) {
// try { // try {
// File javaDir = new File(javaPath); // File javaDir = new File(javaPath);
// File kotlinDir = new File(kotlinPath); // File kotlinDir = new File(kotlinPath);
// //
// if (kotlinDir.exists()) // if (kotlinDir.exists())
// kotlinDir.delete(); // kotlinDir.delete();
// //
// if (!kotlinDir.exists() && !kotlinDir.mkdir()) // if (!kotlinDir.exists() && !kotlinDir.mkdir())
// myLogger.warning("Creation failed: " + kotlinDir.getAbsolutePath()); // myLogger.warning("Creation failed: " + kotlinDir.getAbsolutePath());
// //
// for (File f : getJavaFiles(javaDir.getAbsolutePath())) { // for (File f : getJavaFiles(javaDir.getAbsolutePath())) {
// String relative = javaDir.toURI().relativize(f.toURI()).getPath().replace(".java", ".kt"); // String relative = javaDir.toURI().relativize(f.toURI()).getPath().replace(".java", ".kt");
// File file = new File(kotlinPath, relative); // File file = new File(kotlinPath, relative);
// //
// if (file.exists()) // if (file.exists())
// file.delete(); // file.delete();
// //
// if (f.isDirectory()) // if (f.isDirectory())
// if (!file.exists() && !file.mkdir()) // if (!file.exists() && !file.mkdir())
// myLogger.warning("Creation failed: " + file.getAbsolutePath()); // myLogger.warning("Creation failed: " + file.getAbsolutePath());
// //
// if (f.isFile()) { // if (f.isFile()) {
// writeStringToFile(file, fileToKotlin(f)); // writeStringToFile(file, fileToKotlin(f));
// } // }
// } // }
// } catch (FileNotFoundException e) { // } catch (FileNotFoundException e) {
// e.printStackTrace(); // e.printStackTrace();
// } catch (IOException e) { // } catch (IOException e) {
// e.printStackTrace(); // e.printStackTrace();
// } // }
// } // }
// //
// @NotNull // @NotNull
// private static String fileToKotlin(File f) throws IOException { // private static String fileToKotlin(File f) throws IOException {
// final String javaCode = readJavaFileToString(f); // final String javaCode = readJavaFileToString(f);
// return generateKotlinCode(JavaToKotlinTranslator.createFile(JavaToKotlinTranslator.setUpJavaCoreEnvironment(), javaCode)); // return generateKotlinCode(JavaToKotlinTranslator.createFile(JavaToKotlinTranslator.setUpJavaCoreEnvironment(), javaCode));
// } // }
// //
// @NotNull // @NotNull
// private static String generateKotlinCode(@Nullable PsiFile file) { // private static String generateKotlinCode(@Nullable PsiFile file) {
// if (file != null && file instanceof PsiJavaFile) { // if (file != null && file instanceof PsiJavaFile) {
// JavaToKotlinTranslator.setClassIdentifiers(file); // JavaToKotlinTranslator.setClassIdentifiers(file);
// return JavaToKotlinTranslator.prettify(Converter.fileToFile((PsiJavaFile) file).toKotlin()); // return JavaToKotlinTranslator.prettify(Converter.fileToFile((PsiJavaFile) file).toKotlin());
// } // }
// return ""; // return "";
// } // }
// //
// @NotNull // @NotNull
// private static String readJavaFileToString(@NotNull File javaFile) throws IOException { // private static String readJavaFileToString(@NotNull File javaFile) throws IOException {
// return Pattern.compile("\\s*/\\*.*\\*/", Pattern.DOTALL).matcher(readFileToString(javaFile)).replaceAll(""); // return Pattern.compile("\\s*/\\*.*\\*/", Pattern.DOTALL).matcher(readFileToString(javaFile)).replaceAll("");
// } // }
// //
// private static void showHelpAndExit() { // private static void showHelpAndExit() {
// System.err.println("Usage: java -jar java2kotlin.jar -f <from> -t <to>"); // System.err.println("Usage: java -jar java2kotlin.jar -f <from> -t <to>");
// System.exit(1); // System.exit(1);
// } // }
// //
// static public List<File> getJavaFiles(String startDirName) throws FileNotFoundException { // static public List<File> getJavaFiles(String startDirName) throws FileNotFoundException {
// return getJavaFiles(new File(startDirName)); // return getJavaFiles(new File(startDirName));
// } // }
// //
// private static List<File> getJavaFiles(File start) throws FileNotFoundException { // private static List<File> getJavaFiles(File start) throws FileNotFoundException {
// List<File> result = new ArrayList<File>(); // List<File> result = new ArrayList<File>();
// //
// if (start.isFile()) // if (start.isFile())
// return Arrays.asList(start); // return Arrays.asList(start);
// //
// for (File file : Arrays.asList(start.listFiles())) { // for (File file : Arrays.asList(start.listFiles())) {
// if ((file.isFile() && file.getName().endsWith(".java")) || file.isDirectory()) // if ((file.isFile() && file.getName().endsWith(".java")) || file.isDirectory())
// result.add(file); // result.add(file);
// //
// if (file.isDirectory()) { // if (file.isDirectory()) {
// List<File> deeperList = getJavaFiles(file); // List<File> deeperList = getJavaFiles(file);
// result.addAll(deeperList); // result.addAll(deeperList);
// } // }
// } // }
// return result; // return result;
// } // }
//} //}
@@ -1,234 +1,234 @@
/* /*
* Copyright 2010-2012 JetBrains s.r.o. * Copyright 2010-2012 JetBrains s.r.o.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.jetbrains.jet.j2k; package org.jetbrains.jet.j2k;
import com.intellij.core.JavaCoreApplicationEnvironment; import com.intellij.core.JavaCoreApplicationEnvironment;
import com.intellij.core.JavaCoreProjectEnvironment; import com.intellij.core.JavaCoreProjectEnvironment;
import com.intellij.lang.java.JavaLanguage; import com.intellij.lang.java.JavaLanguage;
import com.intellij.openapi.Disposable; import com.intellij.openapi.Disposable;
import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileFactory; import com.intellij.psi.PsiFileFactory;
import com.intellij.psi.PsiJavaFile; import com.intellij.psi.PsiJavaFile;
import com.intellij.util.Function; import com.intellij.util.Function;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.jet.j2k.visitors.ClassVisitor; import org.jetbrains.jet.j2k.visitors.ClassVisitor;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.PrintStream; import java.io.PrintStream;
import java.net.URL; import java.net.URL;
import java.net.URLClassLoader; import java.net.URLClassLoader;
/** /**
* @author ignatov * @author ignatov
*/ */
public class JavaToKotlinTranslator { public class JavaToKotlinTranslator {
private JavaToKotlinTranslator() { private JavaToKotlinTranslator() {
} }
private static final Converter CONVERTER = new Converter(); private static final Converter CONVERTER = new Converter();
@Nullable @Nullable
private static PsiFile createFile(@NotNull String text) { private static PsiFile createFile(@NotNull String text) {
JavaCoreProjectEnvironment javaCoreEnvironment = setUpJavaCoreEnvironment(); JavaCoreProjectEnvironment javaCoreEnvironment = setUpJavaCoreEnvironment();
return PsiFileFactory.getInstance(javaCoreEnvironment.getProject()).createFileFromText( return PsiFileFactory.getInstance(javaCoreEnvironment.getProject()).createFileFromText(
"test.java", JavaLanguage.INSTANCE, text "test.java", JavaLanguage.INSTANCE, text
); );
} }
@Nullable @Nullable
static PsiFile createFile(@NotNull JavaCoreProjectEnvironment javaCoreEnvironment, @NotNull String text) { static PsiFile createFile(@NotNull JavaCoreProjectEnvironment javaCoreEnvironment, @NotNull String text) {
return PsiFileFactory.getInstance(javaCoreEnvironment.getProject()).createFileFromText( return PsiFileFactory.getInstance(javaCoreEnvironment.getProject()).createFileFromText(
"test.java", JavaLanguage.INSTANCE, text "test.java", JavaLanguage.INSTANCE, text
); );
} }
@NotNull @NotNull
static JavaCoreProjectEnvironment setUpJavaCoreEnvironment() { static JavaCoreProjectEnvironment setUpJavaCoreEnvironment() {
Disposable parentDisposable = new Disposable() { Disposable parentDisposable = new Disposable() {
@Override @Override
public void dispose() { public void dispose() {
} }
}; };
JavaCoreApplicationEnvironment applicationEnvironment = new JavaCoreApplicationEnvironment(parentDisposable); JavaCoreApplicationEnvironment applicationEnvironment = new JavaCoreApplicationEnvironment(parentDisposable);
JavaCoreProjectEnvironment javaCoreEnvironment = new JavaCoreProjectEnvironment(parentDisposable, applicationEnvironment); JavaCoreProjectEnvironment javaCoreEnvironment = new JavaCoreProjectEnvironment(parentDisposable, applicationEnvironment);
javaCoreEnvironment.addJarToClassPath(findRtJar()); javaCoreEnvironment.addJarToClassPath(findRtJar());
File annotations = findAnnotations(); File annotations = findAnnotations();
if (annotations != null && annotations.exists()) { if (annotations != null && annotations.exists()) {
javaCoreEnvironment.addJarToClassPath(annotations); javaCoreEnvironment.addJarToClassPath(annotations);
} }
return javaCoreEnvironment; return javaCoreEnvironment;
} }
@NotNull @NotNull
static String prettify(@Nullable String code) { static String prettify(@Nullable String code) {
if (code == null) { if (code == null) {
return ""; return "";
} }
return code return code
.trim() .trim()
.replaceAll("\r\n", "\n") .replaceAll("\r\n", "\n")
.replaceAll(" \n", "\n") .replaceAll(" \n", "\n")
.replaceAll("\n ", "\n") .replaceAll("\n ", "\n")
.replaceAll("\n+", "\n") .replaceAll("\n+", "\n")
.replaceAll(" +", " ") .replaceAll(" +", " ")
.trim() .trim()
; ;
} }
@Nullable @Nullable
private static File findRtJar() { private static File findRtJar() {
String javaHome = System.getenv("JAVA_HOME"); String javaHome = System.getenv("JAVA_HOME");
File rtJar; File rtJar;
if (javaHome == null) { if (javaHome == null) {
rtJar = findActiveRtJar(true); rtJar = findActiveRtJar(true);
if (rtJar == null) { if (rtJar == null) {
throw new SetupJavaCoreEnvironmentException("JAVA_HOME environment variable needs to be defined"); throw new SetupJavaCoreEnvironmentException("JAVA_HOME environment variable needs to be defined");
} }
} }
else { else {
rtJar = findRtJar(javaHome); rtJar = findRtJar(javaHome);
} }
if (rtJar == null || !rtJar.exists()) { if (rtJar == null || !rtJar.exists()) {
rtJar = findActiveRtJar(true); rtJar = findActiveRtJar(true);
if ((rtJar == null || !rtJar.exists())) { if ((rtJar == null || !rtJar.exists())) {
throw new SetupJavaCoreEnvironmentException("No rt.jar found under JAVA_HOME=" + javaHome); throw new SetupJavaCoreEnvironmentException("No rt.jar found under JAVA_HOME=" + javaHome);
} }
} }
return rtJar; return rtJar;
} }
@Nullable @Nullable
private static File findRtJar(String javaHome) { private static File findRtJar(String javaHome) {
File rtJar = new File(javaHome, "jre/lib/rt.jar"); File rtJar = new File(javaHome, "jre/lib/rt.jar");
if (rtJar.exists()) { if (rtJar.exists()) {
return rtJar; return rtJar;
} }
File classesJar = new File(new File(javaHome).getParentFile().getAbsolutePath(), "Classes/classes.jar"); File classesJar = new File(new File(javaHome).getParentFile().getAbsolutePath(), "Classes/classes.jar");
if (classesJar.exists()) { if (classesJar.exists()) {
return classesJar; return classesJar;
} }
return null; return null;
} }
@Nullable @Nullable
private static File findAnnotations() { private static File findAnnotations() {
ClassLoader classLoader = JavaToKotlinTranslator.class.getClassLoader(); ClassLoader classLoader = JavaToKotlinTranslator.class.getClassLoader();
while (classLoader != null) { while (classLoader != null) {
if (classLoader instanceof URLClassLoader) { if (classLoader instanceof URLClassLoader) {
URLClassLoader loader = (URLClassLoader) classLoader; URLClassLoader loader = (URLClassLoader) classLoader;
for (URL url : loader.getURLs()) for (URL url : loader.getURLs())
if ("file".equals(url.getProtocol()) && url.getFile().endsWith("/annotations.jar")) { if ("file".equals(url.getProtocol()) && url.getFile().endsWith("/annotations.jar")) {
return new File(url.getFile()); return new File(url.getFile());
} }
} }
classLoader = classLoader.getParent(); classLoader = classLoader.getParent();
} }
return null; return null;
} }
@Nullable @Nullable
private static File findActiveRtJar(boolean failOnError) { private static File findActiveRtJar(boolean failOnError) {
ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader(); ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
if (systemClassLoader instanceof URLClassLoader) { if (systemClassLoader instanceof URLClassLoader) {
URLClassLoader loader = (URLClassLoader) systemClassLoader; URLClassLoader loader = (URLClassLoader) systemClassLoader;
for (URL url : loader.getURLs()) { for (URL url : loader.getURLs()) {
if ("file".equals(url.getProtocol())) { if ("file".equals(url.getProtocol())) {
if (url.getFile().endsWith("/lib/rt.jar")) { if (url.getFile().endsWith("/lib/rt.jar")) {
return new File(url.getFile()); return new File(url.getFile());
} }
if (url.getFile().endsWith("/Classes/classes.jar")) { if (url.getFile().endsWith("/Classes/classes.jar")) {
return new File(url.getFile()).getAbsoluteFile(); return new File(url.getFile()).getAbsoluteFile();
} }
} }
} }
if (failOnError) { if (failOnError) {
throw new SetupJavaCoreEnvironmentException("Could not find rt.jar in system class loader: " + StringUtil.join(loader.getURLs(), new Function<URL, String>() { throw new SetupJavaCoreEnvironmentException("Could not find rt.jar in system class loader: " + StringUtil.join(loader.getURLs(), new Function<URL, String>() {
@NotNull @NotNull
@Override @Override
public String fun(@NotNull URL url) { public String fun(@NotNull URL url) {
return url.toString() + "\n"; return url.toString() + "\n";
} }
}, ", ")); }, ", "));
} }
} }
else if (failOnError) { else if (failOnError) {
throw new SetupJavaCoreEnvironmentException("System class loader is not an URLClassLoader: " + systemClassLoader); throw new SetupJavaCoreEnvironmentException("System class loader is not an URLClassLoader: " + systemClassLoader);
} }
return null; return null;
} }
static void setClassIdentifiers(@NotNull Converter converter, @NotNull PsiElement psiFile) { static void setClassIdentifiers(@NotNull Converter converter, @NotNull PsiElement psiFile) {
ClassVisitor c = new ClassVisitor(); ClassVisitor c = new ClassVisitor();
psiFile.accept(c); psiFile.accept(c);
converter.clearClassIdentifiers(); converter.clearClassIdentifiers();
converter.setClassIdentifiers(c.getClassIdentifiers()); converter.setClassIdentifiers(c.getClassIdentifiers());
} }
@NotNull @NotNull
static String generateKotlinCode(@NotNull String javaCode) { static String generateKotlinCode(@NotNull String javaCode) {
PsiFile file = createFile(javaCode); PsiFile file = createFile(javaCode);
if (file != null && file instanceof PsiJavaFile) { if (file != null && file instanceof PsiJavaFile) {
setClassIdentifiers(CONVERTER, file); setClassIdentifiers(CONVERTER, file);
return prettify(CONVERTER.fileToFile((PsiJavaFile) file).toKotlin()); return prettify(CONVERTER.fileToFile((PsiJavaFile) file).toKotlin());
} }
return ""; return "";
} }
@NotNull @NotNull
static String generateKotlinCodeWithCompatibilityImport(@NotNull String javaCode) { static String generateKotlinCodeWithCompatibilityImport(@NotNull String javaCode) {
PsiFile file = createFile(javaCode); PsiFile file = createFile(javaCode);
if (file != null && file instanceof PsiJavaFile) { if (file != null && file instanceof PsiJavaFile) {
setClassIdentifiers(CONVERTER, file); setClassIdentifiers(CONVERTER, file);
return prettify(CONVERTER.fileToFileWithCompatibilityImport((PsiJavaFile) file).toKotlin()); return prettify(CONVERTER.fileToFileWithCompatibilityImport((PsiJavaFile) file).toKotlin());
} }
return ""; return "";
} }
public static void main(@NotNull String[] args) throws IOException { public static void main(@NotNull String[] args) throws IOException {
//noinspection UseOfSystemOutOrSystemErr //noinspection UseOfSystemOutOrSystemErr
final PrintStream out = System.out; final PrintStream out = System.out;
if (args.length == 1) { if (args.length == 1) {
String kotlinCode = ""; String kotlinCode = "";
try { try {
kotlinCode = generateKotlinCode(args[0]); kotlinCode = generateKotlinCode(args[0]);
} catch (Exception e) { } catch (Exception e) {
out.println("EXCEPTION: " + e.getMessage()); out.println("EXCEPTION: " + e.getMessage());
} }
if (kotlinCode.isEmpty()) { if (kotlinCode.isEmpty()) {
out.println("EXCEPTION: generated code is empty."); out.println("EXCEPTION: generated code is empty.");
} }
else { else {
out.println(kotlinCode); out.println(kotlinCode);
} }
} }
else { else {
out.println("EXCEPTION: wrong number of arguments (should be 1)."); out.println("EXCEPTION: wrong number of arguments (should be 1).");
} }
} }
public static String translateToKotlin(String code) { public static String translateToKotlin(String code) {
return generateKotlinCode(code); return generateKotlinCode(code);
} }
} }
@@ -1,23 +1,23 @@
package org.jetbrains.jet.j2k package org.jetbrains.jet.j2k
/* /*
* Copyright 2010-2012 JetBrains s.r.o. * Copyright 2010-2012 JetBrains s.r.o.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
/** /**
* @author ignatov * @author ignatov
*/ */
public open class SetupJavaCoreEnvironmentException(s: String?): RuntimeException() { public open class SetupJavaCoreEnvironmentException(s: String?): RuntimeException() {
} }
@@ -1,43 +1,43 @@
//package org.jetbrains.jet.j2k.actions //package org.jetbrains.jet.j2k.actions
// //
//import com.intellij.openapi.actionSystem.AnAction //import com.intellij.openapi.actionSystem.AnAction
//import com.intellij.openapi.actionSystem.AnActionEvent //import com.intellij.openapi.actionSystem.AnActionEvent
//import org.jetbrains.jet.j2k.Converter //import org.jetbrains.jet.j2k.Converter
//import com.intellij.openapi.actionSystem.PlatformDataKeys //import com.intellij.openapi.actionSystem.PlatformDataKeys
//import com.intellij.openapi.actionSystem.LangDataKeys //import com.intellij.openapi.actionSystem.LangDataKeys
//import com.intellij.psi.PsiJavaFile //import com.intellij.psi.PsiJavaFile
//import com.intellij.openapi.util.io.FileUtil //import com.intellij.openapi.util.io.FileUtil
//import com.intellij.openapi.fileEditor.FileDocumentManager //import com.intellij.openapi.fileEditor.FileDocumentManager
//import com.intellij.psi.PsiDocumentManager //import com.intellij.psi.PsiDocumentManager
//import com.intellij.openapi.command.WriteCommandAction //import com.intellij.openapi.command.WriteCommandAction
//import com.intellij.openapi.application.ApplicationManager //import com.intellij.openapi.application.ApplicationManager
//import com.intellij.psi.codeStyle.CodeStyleManager //import com.intellij.psi.codeStyle.CodeStyleManager
// //
//class JavaToKotlinAction(): AnAction() { //class JavaToKotlinAction(): AnAction() {
// public override fun actionPerformed(event : AnActionEvent?) { // public override fun actionPerformed(event : AnActionEvent?) {
// val converter = Converter() // val converter = Converter()
// val psiFile = event!!.getData(LangDataKeys.PSI_FILE)!! // val psiFile = event!!.getData(LangDataKeys.PSI_FILE)!!
// ApplicationManager.getApplication()?.runWriteAction(object : Runnable { // ApplicationManager.getApplication()?.runWriteAction(object : Runnable {
// public override fun run() { // public override fun run() {
// val result = converter.fileToFile(psiFile as PsiJavaFile).toKotlin() // val result = converter.fileToFile(psiFile as PsiJavaFile).toKotlin()
// val newName = FileUtil.getNameWithoutExtension(psiFile.getName()) + ".kt" // val newName = FileUtil.getNameWithoutExtension(psiFile.getName()) + ".kt"
// val newFile = psiFile.getContainingDirectory()?.createFile(newName)!! // val newFile = psiFile.getContainingDirectory()?.createFile(newName)!!
// val project = psiFile.getProject() // val project = psiFile.getProject()
// val psiDocumentManager = PsiDocumentManager.getInstance(project)!! // val psiDocumentManager = PsiDocumentManager.getInstance(project)!!
// val document = psiDocumentManager.getDocument(newFile)!! // val document = psiDocumentManager.getDocument(newFile)!!
// document.setText(result) // document.setText(result)
// psiDocumentManager.doPostponedOperationsAndUnblockDocument(document) // psiDocumentManager.doPostponedOperationsAndUnblockDocument(document)
// psiDocumentManager.commitDocument(document) // psiDocumentManager.commitDocument(document)
// CodeStyleManager.getInstance(project)!!.reformat(newFile) // CodeStyleManager.getInstance(project)!!.reformat(newFile)
// psiFile.setName(psiFile.getName() + ".old") // psiFile.setName(psiFile.getName() + ".old")
// newFile.navigate(true) // newFile.navigate(true)
// } // }
// }) // })
// } // }
// //
// //
// public override fun update(e : AnActionEvent?) { // public override fun update(e : AnActionEvent?) {
// val psiFile = e!!.getData(LangDataKeys.PSI_FILE) // val psiFile = e!!.getData(LangDataKeys.PSI_FILE)
// e.getPresentation().setEnabled(psiFile is PsiJavaFile) // e.getPresentation().setEnabled(psiFile is PsiJavaFile)
// } // }
//} //}
+17 -17
View File
@@ -1,17 +1,17 @@
package org.jetbrains.jet.j2k.ast package org.jetbrains.jet.j2k.ast
import org.jetbrains.jet.j2k.Converter import org.jetbrains.jet.j2k.Converter
import org.jetbrains.jet.j2k.ast.types.Type import org.jetbrains.jet.j2k.ast.types.Type
import java.util.Collections import java.util.Collections
public open class AnonymousClass(converter : Converter, members : List<Node>) public open class AnonymousClass(converter : Converter, members : List<Node>)
: Class(converter, : Class(converter,
Identifier("anonClass"), Identifier("anonClass"),
arrayList(), arrayList(),
Collections.emptySet<Modifier>()!!, Collections.emptySet<Modifier>()!!,
Collections.emptyList<Element>()!!, Collections.emptyList<Element>()!!,
Collections.emptyList<Type>()!!, Collections.emptyList<Type>()!!,
Collections.emptyList<Expression>()!!, Collections.emptyList<Expression>()!!,
Collections.emptyList<Type>()!!, members) { Collections.emptyList<Type>()!!, members) {
public override fun toKotlin() = bodyToKotlin() public override fun toKotlin() = bodyToKotlin()
} }
@@ -1,60 +1,60 @@
package org.jetbrains.jet.j2k.ast package org.jetbrains.jet.j2k.ast
import org.jetbrains.jet.j2k.ast.types.Type import org.jetbrains.jet.j2k.ast.types.Type
import org.jetbrains.jet.lang.types.expressions.OperatorConventions import org.jetbrains.jet.lang.types.expressions.OperatorConventions
import java.util.* import java.util.*
import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.util.text.StringUtil
public open class ArrayInitializerExpression(val `type` : Type, val initializers : List<Expression>) : Expression() { public open class ArrayInitializerExpression(val `type` : Type, val initializers : List<Expression>) : Expression() {
public override fun toKotlin() : String { public override fun toKotlin() : String {
return createArrayFunction() + "(" + createInitializers() + ")" return createArrayFunction() + "(" + createInitializers() + ")"
} }
private fun createInitializers(): String { private fun createInitializers(): String {
return initializers.map { explicitConvertIfNeeded(it) }.makeString(", ") return initializers.map { explicitConvertIfNeeded(it) }.makeString(", ")
} }
private fun createArrayFunction() : String { private fun createArrayFunction() : String {
var sType : String? = innerTypeStr() var sType : String? = innerTypeStr()
if (Node.PRIMITIVE_TYPES.contains(sType)) { if (Node.PRIMITIVE_TYPES.contains(sType)) {
return sType + "Array" return sType + "Array"
} }
return StringUtil.decapitalize(`type`.convertedToNotNull().toKotlin())!! return StringUtil.decapitalize(`type`.convertedToNotNull().toKotlin())!!
} }
private fun innerTypeStr() : String { private fun innerTypeStr() : String {
return `type`.convertedToNotNull().toKotlin().replace("Array", "").toLowerCase() return `type`.convertedToNotNull().toKotlin().replace("Array", "").toLowerCase()
} }
private fun explicitConvertIfNeeded(i : Expression) : String { private fun explicitConvertIfNeeded(i : Expression) : String {
val doubleOrFloatTypes = hashSet("double", "float", "java.lang.double", "java.lang.float") val doubleOrFloatTypes = hashSet("double", "float", "java.lang.double", "java.lang.float")
val afterReplace : String = innerTypeStr().replace(">", "").replace("<", "").replace("?", "") val afterReplace : String = innerTypeStr().replace(">", "").replace("<", "").replace("?", "")
if (doubleOrFloatTypes.contains(afterReplace)) if (doubleOrFloatTypes.contains(afterReplace))
{ {
if (i is LiteralExpression) { if (i is LiteralExpression) {
if (i.toKotlin().contains(".")) { if (i.toKotlin().contains(".")) {
return i.toKotlin() return i.toKotlin()
} }
return i.toKotlin() + ".0" return i.toKotlin() + ".0"
} }
return "(" + i.toKotlin() + ")" + getConversion(afterReplace) return "(" + i.toKotlin() + ")" + getConversion(afterReplace)
} }
return i.toKotlin() return i.toKotlin()
} }
class object { class object {
private open fun getConversion(afterReplace : String) : String { private open fun getConversion(afterReplace : String) : String {
if (afterReplace.contains("double")!!) if (afterReplace.contains("double")!!)
return "." + OperatorConventions.DOUBLE + "()" return "." + OperatorConventions.DOUBLE + "()"
if (afterReplace.contains("float")!!) if (afterReplace.contains("float")!!)
return "." + OperatorConventions.FLOAT + "()" return "." + OperatorConventions.FLOAT + "()"
return "" return ""
} }
} }
} }
@@ -1,39 +1,39 @@
package org.jetbrains.jet.j2k.ast package org.jetbrains.jet.j2k.ast
import org.jetbrains.jet.j2k.ast.types.ArrayType import org.jetbrains.jet.j2k.ast.types.ArrayType
import org.jetbrains.jet.j2k.ast.types.Type import org.jetbrains.jet.j2k.ast.types.Type
public open class ArrayWithoutInitializationExpression(val `type` : Type, val expressions : List<Expression>) : Expression() { public open class ArrayWithoutInitializationExpression(val `type` : Type, val expressions : List<Expression>) : Expression() {
public override fun toKotlin() : String { public override fun toKotlin() : String {
if (`type` is ArrayType) { if (`type` is ArrayType) {
return constructInnerType(`type`, expressions) return constructInnerType(`type`, expressions)
} }
return getConstructorName(`type`) return getConstructorName(`type`)
} }
private fun constructInnerType(hostType : ArrayType, expressions: List<Expression>) : String { private fun constructInnerType(hostType : ArrayType, expressions: List<Expression>) : String {
if (expressions.size() == 1) { if (expressions.size() == 1) {
return oneDim(hostType, expressions[0]) return oneDim(hostType, expressions[0])
} }
val innerType = hostType.elementType val innerType = hostType.elementType
if (expressions.size() > 1 && innerType is ArrayType) { if (expressions.size() > 1 && innerType is ArrayType) {
return oneDim(hostType, expressions[0], "{" + constructInnerType(innerType, expressions.subList(1, expressions.size())) + "}") return oneDim(hostType, expressions[0], "{" + constructInnerType(innerType, expressions.subList(1, expressions.size())) + "}")
} }
return getConstructorName(hostType) return getConstructorName(hostType)
} }
class object { class object {
private open fun oneDim(`type` : Type, size : Expression) : String { private open fun oneDim(`type` : Type, size : Expression) : String {
return oneDim(`type`, size, "") return oneDim(`type`, size, "")
} }
private open fun oneDim(`type` : Type, size : Expression, init : String) : String { private open fun oneDim(`type` : Type, size : Expression, init : String) : String {
return getConstructorName(`type`) + "(" + size.toKotlin() + init.withPrefix(", ") + ")" return getConstructorName(`type`) + "(" + size.toKotlin() + init.withPrefix(", ") + ")"
} }
private open fun getConstructorName(`type` : Type) : String = `type`.convertedToNotNull().toKotlin() private open fun getConstructorName(`type` : Type) : String = `type`.convertedToNotNull().toKotlin()
} }
} }
@@ -1,12 +1,12 @@
package org.jetbrains.jet.j2k.ast package org.jetbrains.jet.j2k.ast
public open class AssertStatement(val condition : Expression, val detail : Expression) : Statement() { public open class AssertStatement(val condition : Expression, val detail : Expression) : Statement() {
public override fun toKotlin() : String { public override fun toKotlin() : String {
var detail : String? = (if (detail != Expression.EMPTY_EXPRESSION) var detail : String? = (if (detail != Expression.EMPTY_EXPRESSION)
"(" + detail.toKotlin() + ")" "(" + detail.toKotlin() + ")"
else else
"") "")
return "assert" + detail + " {" + condition.toKotlin() + "}" return "assert" + detail + " {" + condition.toKotlin() + "}"
} }
} }
+21 -21
View File
@@ -1,21 +1,21 @@
package org.jetbrains.jet.j2k.ast package org.jetbrains.jet.j2k.ast
import java.util.LinkedList import java.util.LinkedList
public open class Block(val statements: List<Element>, val notEmpty: Boolean = false): Statement() { public open class Block(val statements: List<Element>, val notEmpty: Boolean = false): Statement() {
public override fun isEmpty(): Boolean { public override fun isEmpty(): Boolean {
return !notEmpty && statements.size() == 0 return !notEmpty && statements.size() == 0
} }
public override fun toKotlin(): String { public override fun toKotlin(): String {
if (!isEmpty()) { if (!isEmpty()) {
return "{\n" + statements.toKotlin("\n") + "\n}" return "{\n" + statements.toKotlin("\n") + "\n}"
} }
return "" return ""
} }
class object { class object {
public val EMPTY_BLOCK: Block = Block(arrayList()) public val EMPTY_BLOCK: Block = Block(arrayList())
} }
} }
@@ -1,16 +1,16 @@
package org.jetbrains.jet.j2k.ast package org.jetbrains.jet.j2k.ast
public open class CallChainExpression(val expression : Expression, val identifier : Expression) : Expression() { public open class CallChainExpression(val expression : Expression, val identifier : Expression) : Expression() {
public override fun isNullable() : Boolean { public override fun isNullable() : Boolean {
if (!expression.isEmpty() && expression.isNullable()) return true if (!expression.isEmpty() && expression.isNullable()) return true
return identifier.isNullable() return identifier.isNullable()
} }
public override fun toKotlin() : String { public override fun toKotlin() : String {
if (!expression.isEmpty()) { if (!expression.isEmpty()) {
return expression.toKotlin() + (if (expression.isNullable()) "?." else ".") + identifier.toKotlin() return expression.toKotlin() + (if (expression.isNullable()) "?." else ".") + identifier.toKotlin()
} }
return identifier.toKotlin() return identifier.toKotlin()
} }
} }
+152 -152
View File
@@ -1,152 +1,152 @@
package org.jetbrains.jet.j2k.ast package org.jetbrains.jet.j2k.ast
import org.jetbrains.annotations.Nullable import org.jetbrains.annotations.Nullable
import org.jetbrains.jet.j2k.Converter import org.jetbrains.jet.j2k.Converter
import org.jetbrains.jet.j2k.J2KConverterFlags import org.jetbrains.jet.j2k.J2KConverterFlags
import org.jetbrains.jet.j2k.ast.types.ClassType import org.jetbrains.jet.j2k.ast.types.ClassType
import org.jetbrains.jet.j2k.ast.types.Type import org.jetbrains.jet.j2k.ast.types.Type
import java.util.HashSet import java.util.HashSet
import java.util.LinkedList import java.util.LinkedList
import java.util.ArrayList import java.util.ArrayList
public open class Class(converter : Converter, public open class Class(converter : Converter,
val name : Identifier, val name : Identifier,
val docComments: List<Node>, val docComments: List<Node>,
modifiers : Set<Modifier>, modifiers : Set<Modifier>,
val typeParameters : List<Element>, val typeParameters : List<Element>,
val extendsTypes : List<Type>, val extendsTypes : List<Type>,
val baseClassParams : List<Expression>, val baseClassParams : List<Expression>,
val implementsTypes : List<Type>, val implementsTypes : List<Type>,
members : List<Node>) : Member(modifiers) { members : List<Node>) : Member(modifiers) {
val members = getMembers(members, converter) val members = getMembers(members, converter)
open val TYPE: String open val TYPE: String
get() = "class" get() = "class"
private fun getPrimaryConstructor() : Constructor? { private fun getPrimaryConstructor() : Constructor? {
return members.find { it is Constructor && it.isPrimary } as Constructor? return members.find { it is Constructor && it.isPrimary } as Constructor?
} }
open fun primaryConstructorSignatureToKotlin() : String { open fun primaryConstructorSignatureToKotlin() : String {
val maybeConstructor : Constructor? = getPrimaryConstructor() val maybeConstructor : Constructor? = getPrimaryConstructor()
return if (maybeConstructor != null) maybeConstructor.primarySignatureToKotlin() else "()" return if (maybeConstructor != null) maybeConstructor.primarySignatureToKotlin() else "()"
} }
open fun primaryConstructorBodyToKotlin() : String? { open fun primaryConstructorBodyToKotlin() : String? {
val maybeConstructor : Constructor? = getPrimaryConstructor() val maybeConstructor : Constructor? = getPrimaryConstructor()
if (maybeConstructor != null && !(maybeConstructor.block?.isEmpty() ?: true)) { if (maybeConstructor != null && !(maybeConstructor.block?.isEmpty() ?: true)) {
return maybeConstructor.primaryBodyToKotlin() return maybeConstructor.primaryBodyToKotlin()
} }
return "" return ""
} }
private fun hasWhere() : Boolean = typeParameters.any { it is TypeParameter && it.hasWhere() } private fun hasWhere() : Boolean = typeParameters.any { it is TypeParameter && it.hasWhere() }
open fun typeParameterWhereToKotlin() : String { open fun typeParameterWhereToKotlin() : String {
if (hasWhere()) { if (hasWhere()) {
val wheres = typeParameters.filter { it is TypeParameter }.map { (it as TypeParameter).getWhereToKotlin() } val wheres = typeParameters.filter { it is TypeParameter }.map { (it as TypeParameter).getWhereToKotlin() }
return " where " + wheres.makeString(", ") + " " return " where " + wheres.makeString(", ") + " "
} }
return "" return ""
} }
open fun membersExceptConstructors() : List<Node> = members.filterNot { it is Constructor } open fun membersExceptConstructors() : List<Node> = members.filterNot { it is Constructor }
open fun secondaryConstructorsAsStaticInitFunction() : List<Function> { open fun secondaryConstructorsAsStaticInitFunction() : List<Function> {
return members.filter { it is Constructor && !it.isPrimary }.map { constructorToInit(it as Function) } return members.filter { it is Constructor && !it.isPrimary }.map { constructorToInit(it as Function) }
} }
private fun constructorToInit(f: Function): Function { private fun constructorToInit(f: Function): Function {
val modifiers = HashSet<Modifier>(f.modifiers) val modifiers = HashSet<Modifier>(f.modifiers)
modifiers.add(Modifier.STATIC) modifiers.add(Modifier.STATIC)
val statements = ArrayList<Element>(f.block?.statements ?: listOf()) val statements = ArrayList<Element>(f.block?.statements ?: listOf())
statements.add(ReturnStatement(Identifier("__"))) statements.add(ReturnStatement(Identifier("__")))
val block = Block(statements) val block = Block(statements)
val constructorTypeParameters = ArrayList<Element>() val constructorTypeParameters = ArrayList<Element>()
constructorTypeParameters.addAll(typeParameters) constructorTypeParameters.addAll(typeParameters)
constructorTypeParameters.addAll(f.typeParameters) constructorTypeParameters.addAll(f.typeParameters)
return Function(Identifier("init"), arrayList(), modifiers, ClassType(name, constructorTypeParameters, false), return Function(Identifier("init"), arrayList(), modifiers, ClassType(name, constructorTypeParameters, false),
constructorTypeParameters, f.params, block) constructorTypeParameters, f.params, block)
} }
open fun typeParametersToKotlin() : String = typeParameters.toKotlin(", ", "<", ">") open fun typeParametersToKotlin() : String = typeParameters.toKotlin(", ", "<", ">")
open fun baseClassSignatureWithParams() : List<String> { open fun baseClassSignatureWithParams() : List<String> {
if (TYPE.equals("class") && extendsTypes.size() == 1) { if (TYPE.equals("class") && extendsTypes.size() == 1) {
val baseParams = baseClassParams.toKotlin(", ") val baseParams = baseClassParams.toKotlin(", ")
return arrayList(extendsTypes[0].toKotlin() + "(" + baseParams + ")") return arrayList(extendsTypes[0].toKotlin() + "(" + baseParams + ")")
} }
return extendsTypes.map { it.toKotlin() } return extendsTypes.map { it.toKotlin() }
} }
open fun implementTypesToKotlin() : String { open fun implementTypesToKotlin() : String {
val allTypes = ArrayList<String>() val allTypes = ArrayList<String>()
allTypes.addAll(baseClassSignatureWithParams()) allTypes.addAll(baseClassSignatureWithParams())
allTypes.addAll(implementsTypes.map { it.toKotlin() }) allTypes.addAll(implementsTypes.map { it.toKotlin() })
return if (allTypes.size() == 0) return if (allTypes.size() == 0)
"" ""
else else
" : " + allTypes.makeString(", ") " : " + allTypes.makeString(", ")
} }
open fun modifiersToKotlin() : String { open fun modifiersToKotlin() : String {
val modifierList = ArrayList<Modifier>() val modifierList = ArrayList<Modifier>()
val modifier = accessModifier() val modifier = accessModifier()
if (modifier != null) { if (modifier != null) {
modifierList.add(modifier) modifierList.add(modifier)
} }
if (needAbstractModifier()) { if (needAbstractModifier()) {
modifierList.add(Modifier.ABSTRACT) modifierList.add(Modifier.ABSTRACT)
} }
if (needOpenModifier()) { if (needOpenModifier()) {
modifierList.add(Modifier.OPEN) modifierList.add(Modifier.OPEN)
} }
return modifierList.toKotlin() return modifierList.toKotlin()
} }
open fun needOpenModifier() = !modifiers.contains(Modifier.FINAL) && !modifiers.contains(Modifier.ABSTRACT) open fun needOpenModifier() = !modifiers.contains(Modifier.FINAL) && !modifiers.contains(Modifier.ABSTRACT)
open fun needAbstractModifier() = isAbstract() open fun needAbstractModifier() = isAbstract()
open fun bodyToKotlin() : String { open fun bodyToKotlin() : String {
return " {\n" + getNonStatic(membersExceptConstructors()).toKotlin("\n") + "\n" + primaryConstructorBodyToKotlin() + "\n" + classObjectToKotlin() + "\n}" return " {\n" + getNonStatic(membersExceptConstructors()).toKotlin("\n") + "\n" + primaryConstructorBodyToKotlin() + "\n" + classObjectToKotlin() + "\n}"
} }
private fun classObjectToKotlin() : String { private fun classObjectToKotlin() : String {
val staticMembers = ArrayList<Node>() val staticMembers = ArrayList<Node>()
staticMembers.addAll(secondaryConstructorsAsStaticInitFunction()) staticMembers.addAll(secondaryConstructorsAsStaticInitFunction())
staticMembers.addAll(getStatic(membersExceptConstructors())) staticMembers.addAll(getStatic(membersExceptConstructors()))
return staticMembers.toKotlin("\n", "class object {\n", "\n}") return staticMembers.toKotlin("\n", "class object {\n", "\n}")
} }
public override fun toKotlin() : String = public override fun toKotlin() : String =
docComments.toKotlin("\n", "", "\n") + docComments.toKotlin("\n", "", "\n") +
modifiersToKotlin() + modifiersToKotlin() +
TYPE + " " + name.toKotlin() + TYPE + " " + name.toKotlin() +
typeParametersToKotlin() + typeParametersToKotlin() +
primaryConstructorSignatureToKotlin() + primaryConstructorSignatureToKotlin() +
implementTypesToKotlin() + implementTypesToKotlin() +
typeParameterWhereToKotlin() + typeParameterWhereToKotlin() +
bodyToKotlin() bodyToKotlin()
class object { class object {
open fun getMembers(members : List<Node>, converter : Converter) : List<Node> { open fun getMembers(members : List<Node>, converter : Converter) : List<Node> {
if (converter.hasFlag(J2KConverterFlags.SKIP_NON_PUBLIC_MEMBERS)) { if (converter.hasFlag(J2KConverterFlags.SKIP_NON_PUBLIC_MEMBERS)) {
return members.filter { it is Comment || return members.filter { it is Comment ||
(it as Member).accessModifier() == Modifier.PUBLIC || (it as Member).accessModifier() == Modifier.PUBLIC ||
(it as Member).accessModifier() == Modifier.PROTECTED } (it as Member).accessModifier() == Modifier.PROTECTED }
} }
return members return members
} }
private fun getStatic(members : List<Node>) : List<Node> { private fun getStatic(members : List<Node>) : List<Node> {
return members.filter { it is Member && it.isStatic() } return members.filter { it is Member && it.isStatic() }
} }
private fun getNonStatic(members : List<Node>) : List<Node> { private fun getNonStatic(members : List<Node>) : List<Node> {
return members.filterNot { it is Member && it.isStatic() } return members.filterNot { it is Member && it.isStatic() }
} }
} }
} }
+21 -21
View File
@@ -1,21 +1,21 @@
package org.jetbrains.jet.j2k.ast package org.jetbrains.jet.j2k.ast
import org.jetbrains.jet.j2k.ast.types.Type import org.jetbrains.jet.j2k.ast.types.Type
public open class Constructor(identifier : Identifier, public open class Constructor(identifier : Identifier,
docComments: List<Node>, docComments: List<Node>,
modifiers : Set<Modifier>, modifiers : Set<Modifier>,
`type` : Type, `type` : Type,
typeParameters : List<Element>, typeParameters : List<Element>,
params : Element, params : Element,
block : Block, block : Block,
val isPrimary : Boolean) : Function(identifier, docComments, modifiers, `type`, typeParameters, params, block) { val isPrimary : Boolean) : Function(identifier, docComments, modifiers, `type`, typeParameters, params, block) {
public open fun primarySignatureToKotlin() : String { public open fun primarySignatureToKotlin() : String {
return "(" + params.toKotlin() + ")" return "(" + params.toKotlin() + ")"
} }
public open fun primaryBodyToKotlin() : String { public open fun primaryBodyToKotlin() : String {
return block!!.toKotlin() return block!!.toKotlin()
} }
} }
@@ -1,6 +1,6 @@
package org.jetbrains.jet.j2k.ast package org.jetbrains.jet.j2k.ast
public open class DummyStringExpression(val string: String): Expression() { public open class DummyStringExpression(val string: String): Expression() {
public override fun toKotlin(): String = string public override fun toKotlin(): String = string
} }
+17 -17
View File
@@ -1,17 +1,17 @@
package org.jetbrains.jet.j2k.ast package org.jetbrains.jet.j2k.ast
public abstract class Element(): Node() { public abstract class Element(): Node() {
public open fun isEmpty(): Boolean = false public open fun isEmpty(): Boolean = false
class object { class object {
public val EMPTY_ELEMENT: Element = object : Element() { public val EMPTY_ELEMENT: Element = object : Element() {
override fun toKotlin() = "" override fun toKotlin() = ""
override fun isEmpty() = true override fun isEmpty() = true
} }
} }
} }
public class Comment(val text: String): Element() { public class Comment(val text: String): Element() {
override fun toKotlin() = text override fun toKotlin() = text
} }
+34 -34
View File
@@ -1,34 +1,34 @@
package org.jetbrains.jet.j2k.ast package org.jetbrains.jet.j2k.ast
import org.jetbrains.jet.j2k.Converter import org.jetbrains.jet.j2k.Converter
import org.jetbrains.jet.j2k.ast.types.Type import org.jetbrains.jet.j2k.ast.types.Type
public open class Enum(converter : Converter, public open class Enum(converter : Converter,
name : Identifier, name : Identifier,
docComments: List<Node>, docComments: List<Node>,
modifiers : Set<Modifier>, modifiers : Set<Modifier>,
typeParameters : List<Element>, typeParameters : List<Element>,
extendsTypes : List<Type>, extendsTypes : List<Type>,
baseClassParams : List<Expression>, baseClassParams : List<Expression>,
implementsTypes : List<Type>, implementsTypes : List<Type>,
members : List<Node>) : Class(converter, name, docComments, modifiers, typeParameters, members : List<Node>) : Class(converter, name, docComments, modifiers, typeParameters,
extendsTypes, baseClassParams, implementsTypes, members) { extendsTypes, baseClassParams, implementsTypes, members) {
override fun primaryConstructorSignatureToKotlin() : String { override fun primaryConstructorSignatureToKotlin() : String {
val s : String = super.primaryConstructorSignatureToKotlin() val s : String = super.primaryConstructorSignatureToKotlin()
return if (s.equals("()")) "" else s return if (s.equals("()")) "" else s
} }
override fun needOpenModifier() = false override fun needOpenModifier() = false
public override fun toKotlin() : String { public override fun toKotlin() : String {
return modifiersToKotlin() + return modifiersToKotlin() +
"enum class " + name.toKotlin() + "enum class " + name.toKotlin() +
primaryConstructorSignatureToKotlin() + primaryConstructorSignatureToKotlin() +
typeParametersToKotlin() + typeParametersToKotlin() +
implementTypesToKotlin() + implementTypesToKotlin() +
" {\n" + membersExceptConstructors().toKotlin("\n") + "\n" + " {\n" + membersExceptConstructors().toKotlin("\n") + "\n" +
primaryConstructorBodyToKotlin() + primaryConstructorBodyToKotlin() +
"\npublic fun name() : String { return \"\" }\npublic fun order() : Int { return 0 }\n}" "\npublic fun name() : String { return \"\" }\npublic fun order() : Int { return 0 }\n}"
} }
} }
+20 -20
View File
@@ -1,20 +1,20 @@
package org.jetbrains.jet.j2k.ast package org.jetbrains.jet.j2k.ast
import org.jetbrains.jet.j2k.ast.types.Type import org.jetbrains.jet.j2k.ast.types.Type
public open class EnumConstant(identifier : Identifier, public open class EnumConstant(identifier : Identifier,
docComments: List<Node>, docComments: List<Node>,
modifiers : Set<Modifier>, modifiers : Set<Modifier>,
`type` : Type, `type` : Type,
params : Element) : Field(identifier, docComments, modifiers, `type`.convertedToNotNull(), params, 0) { params : Element) : Field(identifier, docComments, modifiers, `type`.convertedToNotNull(), params, 0) {
public override fun toKotlin() : String { public override fun toKotlin() : String {
if (initializer.toKotlin().isEmpty()) { if (initializer.toKotlin().isEmpty()) {
return identifier.toKotlin() return identifier.toKotlin()
} }
return identifier.toKotlin() + " : " + `type`.toKotlin() + "(" + initializer.toKotlin() + ")" return identifier.toKotlin() + " : " + `type`.toKotlin() + "(" + initializer.toKotlin() + ")"
} }
} }
+15 -15
View File
@@ -1,15 +1,15 @@
package org.jetbrains.jet.j2k.ast package org.jetbrains.jet.j2k.ast
public abstract class Expression(): Statement() { public abstract class Expression(): Statement() {
public open fun isNullable(): Boolean { public open fun isNullable(): Boolean {
return false return false
} }
class object { class object {
public val EMPTY_EXPRESSION: Expression = object: Expression() { public val EMPTY_EXPRESSION: Expression = object: Expression() {
public override fun toKotlin()= "" public override fun toKotlin()= ""
public override fun isEmpty() = true public override fun isEmpty() = true
} }
} }
} }
@@ -1,7 +1,7 @@
package org.jetbrains.jet.j2k.ast package org.jetbrains.jet.j2k.ast
import org.jetbrains.jet.j2k.ast.types.Type import org.jetbrains.jet.j2k.ast.types.Type
public open class ExpressionList(val expressions: List<Expression>): Expression() { public open class ExpressionList(val expressions: List<Expression>): Expression() {
public override fun toKotlin(): String = expressions.map { it.toKotlin() }.makeString(", ") public override fun toKotlin(): String = expressions.map { it.toKotlin() }.makeString(", ")
} }
+58 -58
View File
@@ -1,58 +1,58 @@
package org.jetbrains.jet.j2k.ast package org.jetbrains.jet.j2k.ast
import org.jetbrains.jet.j2k.ast.types.Type import org.jetbrains.jet.j2k.ast.types.Type
public open class ArrayAccessExpression(val expression: Expression, val index: Expression, val lvalue: Boolean) : Expression() { public open class ArrayAccessExpression(val expression: Expression, val index: Expression, val lvalue: Boolean) : Expression() {
override fun toKotlin() = expression.toKotlin() + override fun toKotlin() = expression.toKotlin() +
(if (!lvalue && expression.isNullable()) "!!" else "") + (if (!lvalue && expression.isNullable()) "!!" else "") +
"[" + index.toKotlin() + "]" "[" + index.toKotlin() + "]"
} }
public open class AssignmentExpression(val left : Expression, val right : Expression, val op : String) : Expression() { public open class AssignmentExpression(val left : Expression, val right : Expression, val op : String) : Expression() {
override fun toKotlin() = left.toKotlin() + " "+ op + " "+ right.toKotlin() override fun toKotlin() = left.toKotlin() + " "+ op + " "+ right.toKotlin()
} }
public class BangBangExpression(val expr: Expression): Expression() { public class BangBangExpression(val expr: Expression): Expression() {
override fun toKotlin() = expr.toKotlin() + "!!" override fun toKotlin() = expr.toKotlin() + "!!"
} }
public open class BinaryExpression(val left: Expression, val right: Expression, val op: String): Expression() { public open class BinaryExpression(val left: Expression, val right: Expression, val op: String): Expression() {
override fun toKotlin() = left.toKotlin() + " " + op + " " + right.toKotlin() override fun toKotlin() = left.toKotlin() + " " + op + " " + right.toKotlin()
} }
public open class ClassObjectAccessExpression(val typeElement: TypeElement): Expression() { public open class ClassObjectAccessExpression(val typeElement: TypeElement): Expression() {
override fun toKotlin() = "javaClass<" + typeElement.toKotlinNotNull() + ">()" override fun toKotlin() = "javaClass<" + typeElement.toKotlinNotNull() + ">()"
} }
public open class IsOperator(val expression: Expression, val typeElement: TypeElement): Expression() { public open class IsOperator(val expression: Expression, val typeElement: TypeElement): Expression() {
override fun toKotlin() = expression.toKotlin() + " is " + typeElement.toKotlinNotNull() override fun toKotlin() = expression.toKotlin() + " is " + typeElement.toKotlinNotNull()
} }
public open class TypeCastExpression(val `type` : Type, val expression : Expression) : Expression() { public open class TypeCastExpression(val `type` : Type, val expression : Expression) : Expression() {
override fun toKotlin() = "(" + expression.toKotlin() + " as " + `type`.toKotlin() + ")" override fun toKotlin() = "(" + expression.toKotlin() + " as " + `type`.toKotlin() + ")"
} }
public open class LiteralExpression(val literalText: String): Expression() { public open class LiteralExpression(val literalText: String): Expression() {
override fun toKotlin() = literalText override fun toKotlin() = literalText
} }
public open class ParenthesizedExpression(val expression : Expression) : Expression() { public open class ParenthesizedExpression(val expression : Expression) : Expression() {
override fun toKotlin() = "(" + expression.toKotlin() + ")" override fun toKotlin() = "(" + expression.toKotlin() + ")"
} }
public open class PrefixOperator(val op: String, val expression: Expression): Expression() { public open class PrefixOperator(val op: String, val expression: Expression): Expression() {
override fun toKotlin() = op + expression.toKotlin() override fun toKotlin() = op + expression.toKotlin()
override fun isNullable() = expression.isNullable() override fun isNullable() = expression.isNullable()
} }
public open class PostfixOperator(val op: String, val expression: Expression): Expression() { public open class PostfixOperator(val op: String, val expression: Expression): Expression() {
override fun toKotlin() = expression.toKotlin() + op override fun toKotlin() = expression.toKotlin() + op
} }
public open class ThisExpression(val identifier: Identifier) : Expression() { public open class ThisExpression(val identifier: Identifier) : Expression() {
override fun toKotlin() = "this" + identifier.withPrefix("@") override fun toKotlin() = "this" + identifier.withPrefix("@")
} }
public open class SuperExpression(val identifier : Identifier) : Expression() { public open class SuperExpression(val identifier : Identifier) : Expression() {
override fun toKotlin() = "super" + identifier.withPrefix("@") override fun toKotlin() = "super" + identifier.withPrefix("@")
} }
+44 -44
View File
@@ -1,44 +1,44 @@
package org.jetbrains.jet.j2k.ast package org.jetbrains.jet.j2k.ast
import org.jetbrains.jet.j2k.ast.types.Type import org.jetbrains.jet.j2k.ast.types.Type
import java.util.LinkedList import java.util.LinkedList
import org.jetbrains.jet.j2k.Converter import org.jetbrains.jet.j2k.Converter
import java.util.ArrayList import java.util.ArrayList
public open class Field(val identifier : Identifier, public open class Field(val identifier : Identifier,
val docComments: List<Node>, val docComments: List<Node>,
modifiers : Set<Modifier>, modifiers : Set<Modifier>,
val `type` : Type, val `type` : Type,
val initializer : Element, val initializer : Element,
val writingAccesses : Int) : Member(modifiers) { val writingAccesses : Int) : Member(modifiers) {
open fun modifiersToKotlin() : String { open fun modifiersToKotlin() : String {
val modifierList = ArrayList<Modifier>() val modifierList = ArrayList<Modifier>()
if (isAbstract()) { if (isAbstract()) {
modifierList.add(Modifier.ABSTRACT) modifierList.add(Modifier.ABSTRACT)
} }
val modifier = accessModifier() val modifier = accessModifier()
if (modifier != null) { if (modifier != null) {
modifierList.add(modifier) modifierList.add(modifier)
} }
return modifierList.toKotlin() + (if (isVal()) "val " else "var ") return modifierList.toKotlin() + (if (isVal()) "val " else "var ")
} }
public open fun isVal() : Boolean = modifiers.contains(Modifier.FINAL) public open fun isVal() : Boolean = modifiers.contains(Modifier.FINAL)
public override fun isStatic() : Boolean = modifiers.contains(Modifier.STATIC) public override fun isStatic() : Boolean = modifiers.contains(Modifier.STATIC)
public override fun toKotlin() : String { public override fun toKotlin() : String {
val declaration : String = docComments.toKotlin("\n", "", "\n") + val declaration : String = docComments.toKotlin("\n", "", "\n") +
modifiersToKotlin() + identifier.toKotlin() + " : " + `type`.toKotlin() modifiersToKotlin() + identifier.toKotlin() + " : " + `type`.toKotlin()
if (initializer.isEmpty()) { if (initializer.isEmpty()) {
return declaration + ((if (isVal() && !isStatic() && writingAccesses == 1) return declaration + ((if (isVal() && !isStatic() && writingAccesses == 1)
"" ""
else else
" = " + Converter.getDefaultInitializer(this))) " = " + Converter.getDefaultInitializer(this)))
} }
return declaration + " = " + initializer.toKotlin() return declaration + " = " + initializer.toKotlin()
} }
} }
+16 -16
View File
@@ -1,16 +1,16 @@
package org.jetbrains.jet.j2k.ast package org.jetbrains.jet.j2k.ast
public open class File(val packageName: String, public open class File(val packageName: String,
val imports: MutableList<Import>, val imports: MutableList<Import>,
val body: MutableList<Node>, val body: MutableList<Node>,
val mainFunction: String): Node() { val mainFunction: String): Node() {
public override fun toKotlin(): String { public override fun toKotlin(): String {
val common: String = imports.toKotlin("\n") + "\n\n" + body.toKotlin("\n") + "\n" + mainFunction val common: String = imports.toKotlin("\n") + "\n\n" + body.toKotlin("\n") + "\n" + mainFunction
if (packageName.isEmpty()) { if (packageName.isEmpty()) {
return common return common
} }
return "package " + packageName + "\n" + common return "package " + packageName + "\n" + common
} }
} }
+71 -71
View File
@@ -1,71 +1,71 @@
package org.jetbrains.jet.j2k.ast package org.jetbrains.jet.j2k.ast
import java.util.LinkedList import java.util.LinkedList
import org.jetbrains.jet.j2k.ast.types.Type import org.jetbrains.jet.j2k.ast.types.Type
import java.util.ArrayList import java.util.ArrayList
public open class Function(val name : Identifier, public open class Function(val name : Identifier,
val docComments: List<Node>, val docComments: List<Node>,
modifiers : Set<Modifier>, modifiers : Set<Modifier>,
val `type` : Type, val `type` : Type,
val typeParameters : List<Element>, val typeParameters : List<Element>,
val params : Element, val params : Element,
var block : Block?) : Member(modifiers) { var block : Block?) : Member(modifiers) {
private fun typeParametersToKotlin() : String { private fun typeParametersToKotlin() : String {
return (if (typeParameters.size() > 0) return (if (typeParameters.size() > 0)
"<" + typeParameters.map { it.toKotlin() }.makeString(", ") + ">" "<" + typeParameters.map { it.toKotlin() }.makeString(", ") + ">"
else else
"") "")
} }
private fun hasWhere() : Boolean = typeParameters.any { it is TypeParameter && it.hasWhere() } private fun hasWhere() : Boolean = typeParameters.any { it is TypeParameter && it.hasWhere() }
private fun typeParameterWhereToKotlin() : String { private fun typeParameterWhereToKotlin() : String {
if (hasWhere()) if (hasWhere())
{ {
val wheres = typeParameters.filter { it is TypeParameter }.map { ((it as TypeParameter).getWhereToKotlin() )} val wheres = typeParameters.filter { it is TypeParameter }.map { ((it as TypeParameter).getWhereToKotlin() )}
return " where " + wheres.makeString(", ") + " " return " where " + wheres.makeString(", ") + " "
} }
return "" return ""
} }
open fun modifiersToKotlin() : String { open fun modifiersToKotlin() : String {
val modifierList = ArrayList<Modifier>() val modifierList = ArrayList<Modifier>()
val accessModifier = accessModifier() val accessModifier = accessModifier()
if (accessModifier != null) { if (accessModifier != null) {
modifierList.add(accessModifier) modifierList.add(accessModifier)
} }
if (isAbstract()) { if (isAbstract()) {
modifierList.add(Modifier.ABSTRACT) modifierList.add(Modifier.ABSTRACT)
} }
if (modifiers.contains(Modifier.OVERRIDE)) { if (modifiers.contains(Modifier.OVERRIDE)) {
modifierList.add(Modifier.OVERRIDE) modifierList.add(Modifier.OVERRIDE)
} }
if (!modifiers.contains(Modifier.ABSTRACT) && if (!modifiers.contains(Modifier.ABSTRACT) &&
!modifiers.contains(Modifier.OVERRIDE) && !modifiers.contains(Modifier.OVERRIDE) &&
!modifiers.contains(Modifier.FINAL) && !modifiers.contains(Modifier.FINAL) &&
!modifiers.contains(Modifier.PRIVATE)) { !modifiers.contains(Modifier.PRIVATE)) {
modifierList.add(Modifier.OPEN) modifierList.add(Modifier.OPEN)
} }
if (modifiers.contains(Modifier.NOT_OPEN)) { if (modifiers.contains(Modifier.NOT_OPEN)) {
modifierList.remove(Modifier.OPEN) modifierList.remove(Modifier.OPEN)
} }
return modifierList.toKotlin() return modifierList.toKotlin()
} }
public override fun toKotlin() : String { public override fun toKotlin() : String {
return docComments.toKotlin("\n", "", "\n") + return docComments.toKotlin("\n", "", "\n") +
modifiersToKotlin() + modifiersToKotlin() +
"fun " + name.toKotlin() + "fun " + name.toKotlin() +
typeParametersToKotlin() + typeParametersToKotlin() +
"(" + params.toKotlin() + ") : " + "(" + params.toKotlin() + ") : " +
`type`.toKotlin() + " "+ typeParameterWhereToKotlin() + `type`.toKotlin() + " "+ typeParameterWhereToKotlin() +
block?.toKotlin() block?.toKotlin()
} }
} }
+31 -31
View File
@@ -1,31 +1,31 @@
package org.jetbrains.jet.j2k.ast package org.jetbrains.jet.j2k.ast
public open class Identifier(val name: String, public open class Identifier(val name: String,
val myNullable: Boolean = true, val myNullable: Boolean = true,
val quotingNeeded: Boolean = true): Expression() { val quotingNeeded: Boolean = true): Expression() {
public override fun isEmpty() = name.length() == 0 public override fun isEmpty() = name.length() == 0
private open fun ifNeedQuote(): String { private open fun ifNeedQuote(): String {
if (quotingNeeded && (ONLY_KOTLIN_KEYWORDS.contains(name)) || name.contains("$")) { if (quotingNeeded && (ONLY_KOTLIN_KEYWORDS.contains(name)) || name.contains("$")) {
return quote(name) return quote(name)
} }
return name return name
} }
public override fun toKotlin(): String = ifNeedQuote() public override fun toKotlin(): String = ifNeedQuote()
public override fun isNullable(): Boolean = myNullable public override fun isNullable(): Boolean = myNullable
class object { class object {
public val EMPTY_IDENTIFIER: Identifier = Identifier("") public val EMPTY_IDENTIFIER: Identifier = Identifier("")
private open fun quote(str: String): String { private open fun quote(str: String): String {
return "`" + str + "`" return "`" + str + "`"
} }
public val ONLY_KOTLIN_KEYWORDS: Set<String> = hashSet( public val ONLY_KOTLIN_KEYWORDS: Set<String> = hashSet(
"package", "as", "type", "val", "var", "fun", "is", "in", "object", "when", "trait", "This" "package", "as", "type", "val", "var", "fun", "is", "in", "object", "when", "trait", "This"
); );
} }
} }
+6 -6
View File
@@ -1,6 +1,6 @@
package org.jetbrains.jet.j2k.ast package org.jetbrains.jet.j2k.ast
public open class Import(val name: String): Node() { public open class Import(val name: String): Node() {
public override fun toKotlin() = "import " + name public override fun toKotlin() = "import " + name
} }
+8 -8
View File
@@ -1,8 +1,8 @@
package org.jetbrains.jet.j2k.ast package org.jetbrains.jet.j2k.ast
public open class Initializer(val block : Block, modifiers : Set<Modifier>) : Member(modifiers) { public open class Initializer(val block : Block, modifiers : Set<Modifier>) : Member(modifiers) {
public override fun toKotlin() : String { public override fun toKotlin() : String {
return block.toKotlin() return block.toKotlin()
} }
} }
+19 -19
View File
@@ -1,19 +1,19 @@
package org.jetbrains.jet.j2k.ast package org.jetbrains.jet.j2k.ast
import org.jetbrains.jet.j2k.ast.types.Type import org.jetbrains.jet.j2k.ast.types.Type
public open class LocalVariable(val identifier: Identifier, public open class LocalVariable(val identifier: Identifier,
val modifiersSet: Set<Modifier>, val modifiersSet: Set<Modifier>,
val `type`: Type, val `type`: Type,
val initializer: Expression): Expression() { val initializer: Expression): Expression() {
public open fun hasModifier(modifier: Modifier): Boolean = modifiersSet.contains(modifier) public open fun hasModifier(modifier: Modifier): Boolean = modifiersSet.contains(modifier)
public override fun toKotlin(): String { public override fun toKotlin(): String {
if (initializer.isEmpty()) { if (initializer.isEmpty()) {
return identifier.toKotlin() + " : " + `type`.toKotlin() return identifier.toKotlin() + " : " + `type`.toKotlin()
} }
return identifier.toKotlin() + " : " + `type`.toKotlin() + " = " + initializer.toKotlin() return identifier.toKotlin() + " : " + `type`.toKotlin() + " = " + initializer.toKotlin()
} }
} }
+10 -10
View File
@@ -1,10 +1,10 @@
package org.jetbrains.jet.j2k.ast package org.jetbrains.jet.j2k.ast
public abstract class Member(val modifiers : Set<Modifier>) : Node() { public abstract class Member(val modifiers : Set<Modifier>) : Node() {
open fun accessModifier() : Modifier? { open fun accessModifier() : Modifier? {
return modifiers.find { m -> m == Modifier.PUBLIC || m == Modifier.PROTECTED || m == Modifier.PRIVATE } return modifiers.find { m -> m == Modifier.PUBLIC || m == Modifier.PROTECTED || m == Modifier.PRIVATE }
} }
public open fun isAbstract() : Boolean = modifiers.contains(Modifier.ABSTRACT) public open fun isAbstract() : Boolean = modifiers.contains(Modifier.ABSTRACT)
public open fun isStatic() : Boolean = modifiers.contains(Modifier.STATIC) public open fun isStatic() : Boolean = modifiers.contains(Modifier.STATIC)
} }
@@ -1,24 +1,24 @@
package org.jetbrains.jet.j2k.ast package org.jetbrains.jet.j2k.ast
import org.jetbrains.jet.j2k.ast.types.Type import org.jetbrains.jet.j2k.ast.types.Type
public open class MethodCallExpression(val methodCall: Expression, public open class MethodCallExpression(val methodCall: Expression,
val arguments: List<Expression>, val arguments: List<Expression>,
val typeParameters: List<Type>, val typeParameters: List<Type>,
val resultIsNullable: Boolean = false): Expression() { val resultIsNullable: Boolean = false): Expression() {
public override fun isNullable(): Boolean = methodCall.isNullable() || resultIsNullable public override fun isNullable(): Boolean = methodCall.isNullable() || resultIsNullable
public override fun toKotlin(): String { public override fun toKotlin(): String {
val typeParamsToKotlin: String = typeParameters.toKotlin(", ", "<", ">") val typeParamsToKotlin: String = typeParameters.toKotlin(", ", "<", ">")
val argumentsMapped = arguments.map { it.toKotlin() } val argumentsMapped = arguments.map { it.toKotlin() }
return methodCall.toKotlin() + typeParamsToKotlin + "(" + argumentsMapped.makeString(", ") + ")" return methodCall.toKotlin() + typeParamsToKotlin + "(" + argumentsMapped.makeString(", ") + ")"
} }
class object { class object {
fun build(receiver: Expression, methodName: String, arguments: List<Expression> = arrayList()): MethodCallExpression { fun build(receiver: Expression, methodName: String, arguments: List<Expression> = arrayList()): MethodCallExpression {
return MethodCallExpression(CallChainExpression(receiver, Identifier(methodName, false)), return MethodCallExpression(CallChainExpression(receiver, Identifier(methodName, false)),
arguments, arguments,
arrayList(), false) arrayList(), false)
} }
} }
} }
+33 -33
View File
@@ -1,33 +1,33 @@
package org.jetbrains.jet.j2k.ast package org.jetbrains.jet.j2k.ast
/* /*
* Copyright 2010-2012 JetBrains s.r.o. * Copyright 2010-2012 JetBrains s.r.o.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
/** /**
* @author ignatov * @author ignatov
*/ */
public enum class Modifier(val name: String) { public enum class Modifier(val name: String) {
PUBLIC: Modifier("public") PUBLIC: Modifier("public")
PROTECTED: Modifier("protected") PROTECTED: Modifier("protected")
PRIVATE: Modifier("private") PRIVATE: Modifier("private")
INTERNAL: Modifier("internal") INTERNAL: Modifier("internal")
STATIC: Modifier("static") STATIC: Modifier("static")
ABSTRACT: Modifier("abstract") ABSTRACT: Modifier("abstract")
FINAL: Modifier("final") FINAL: Modifier("final")
OPEN: Modifier("open") OPEN: Modifier("open")
NOT_OPEN: Modifier("not open") NOT_OPEN: Modifier("not open")
OVERRIDE: Modifier("override") OVERRIDE: Modifier("override")
} }
@@ -1,24 +1,24 @@
package org.jetbrains.jet.j2k.ast package org.jetbrains.jet.j2k.ast
import org.jetbrains.annotations.Nullable import org.jetbrains.annotations.Nullable
public open class NewClassExpression(val name: Element, public open class NewClassExpression(val name: Element,
val arguments: List<Expression>, val arguments: List<Expression>,
val qualifier: Expression = Expression.EMPTY_EXPRESSION, val qualifier: Expression = Expression.EMPTY_EXPRESSION,
val anonymousClass: AnonymousClass? = null): Expression() { val anonymousClass: AnonymousClass? = null): Expression() {
public override fun toKotlin(): String { public override fun toKotlin(): String {
val callOperator: String? = (if (qualifier.isNullable()!!) val callOperator: String? = (if (qualifier.isNullable()!!)
"?." "?."
else else
".") ".")
val qualifier: String? = (if (qualifier.isEmpty()!!) val qualifier: String? = (if (qualifier.isEmpty()!!)
"" ""
else else
qualifier.toKotlin() + callOperator) qualifier.toKotlin() + callOperator)
val appliedArguments: String = arguments.toKotlin(", ") val appliedArguments: String = arguments.toKotlin(", ")
return (if (anonymousClass != null) return (if (anonymousClass != null)
"object : " + qualifier + name.toKotlin() + "(" + appliedArguments + ")" + anonymousClass.toKotlin() "object : " + qualifier + name.toKotlin() + "(" + appliedArguments + ")" + anonymousClass.toKotlin()
else else
qualifier + name.toKotlin() + "(" + appliedArguments + ")") qualifier + name.toKotlin() + "(" + appliedArguments + ")")
} }
} }
+11 -11
View File
@@ -1,11 +1,11 @@
package org.jetbrains.jet.j2k.ast package org.jetbrains.jet.j2k.ast
public abstract class Node() { public abstract class Node() {
public abstract fun toKotlin(): String public abstract fun toKotlin(): String
class object { class object {
public val PRIMITIVE_TYPES: Set<String> = hashSet( public val PRIMITIVE_TYPES: Set<String> = hashSet(
"double", "float", "long", "int", "short", "byte", "boolean", "char") "double", "float", "long", "int", "short", "byte", "boolean", "char")
} }
} }
+18 -18
View File
@@ -1,18 +1,18 @@
package org.jetbrains.jet.j2k.ast package org.jetbrains.jet.j2k.ast
import org.jetbrains.jet.j2k.ast.types.Type import org.jetbrains.jet.j2k.ast.types.Type
import org.jetbrains.jet.j2k.ast.types.VarArg import org.jetbrains.jet.j2k.ast.types.VarArg
public open class Parameter(val identifier : Identifier, val `type` : Type, val readOnly: Boolean = true) : Expression() { public open class Parameter(val identifier : Identifier, val `type` : Type, val readOnly: Boolean = true) : Expression() {
public override fun toKotlin() : String { public override fun toKotlin() : String {
val vararg : String = (if (`type` is VarArg) val vararg : String = (if (`type` is VarArg)
"vararg " "vararg "
else else
"") "")
val `var` : String? = (if (readOnly) val `var` : String? = (if (readOnly)
"" ""
else else
"var ") "var ")
return vararg + `var` + identifier.toKotlin() + " : " + `type`.toKotlin() return vararg + `var` + identifier.toKotlin() + " : " + `type`.toKotlin()
} }
} }
@@ -1,7 +1,7 @@
package org.jetbrains.jet.j2k.ast package org.jetbrains.jet.j2k.ast
public open class ParameterList(val parameters : List<Parameter>) : Expression() { public open class ParameterList(val parameters : List<Parameter>) : Expression() {
public override fun toKotlin() = parameters.map { it.toKotlin() }.makeString(", ") public override fun toKotlin() = parameters.map { it.toKotlin() }.makeString(", ")
} }
@@ -1,9 +1,9 @@
package org.jetbrains.jet.j2k.ast package org.jetbrains.jet.j2k.ast
public open class PolyadicExpression(val expressions: List<Expression>, val token: String): Expression() { public open class PolyadicExpression(val expressions: List<Expression>, val token: String): Expression() {
public override fun toKotlin(): String { public override fun toKotlin(): String {
val expressionsWithConversions = expressions.map { it.toKotlin() } val expressionsWithConversions = expressions.map { it.toKotlin() }
return expressionsWithConversions.makeString(" " + token + " ") return expressionsWithConversions.makeString(" " + token + " ")
} }
} }
@@ -1,7 +1,7 @@
package org.jetbrains.jet.j2k.ast package org.jetbrains.jet.j2k.ast
import org.jetbrains.jet.j2k.ast.types.Type import org.jetbrains.jet.j2k.ast.types.Type
public open class ReferenceElement(val reference : Identifier, val types : List<Type>) : Element() { public open class ReferenceElement(val reference : Identifier, val types : List<Type>) : Element() {
public override fun toKotlin() = reference.toKotlin() + types.toKotlin(", ", "<", ">") public override fun toKotlin() = reference.toKotlin() + types.toKotlin(", ", "<", ">")
} }
+132 -132
View File
@@ -1,132 +1,132 @@
package org.jetbrains.jet.j2k.ast package org.jetbrains.jet.j2k.ast
public abstract class Statement(): Element() { public abstract class Statement(): Element() {
class object { class object {
public val EMPTY_STATEMENT: Statement = object : Statement() { public val EMPTY_STATEMENT: Statement = object : Statement() {
public override fun toKotlin() = "" public override fun toKotlin() = ""
} }
} }
} }
public open class DeclarationStatement(val elements: List<Element>): Statement() { public open class DeclarationStatement(val elements: List<Element>): Statement() {
public override fun toKotlin(): String { public override fun toKotlin(): String {
return elements.filter { it is LocalVariable }.map { convertDeclaration(it as LocalVariable) }.makeString("\n") return elements.filter { it is LocalVariable }.map { convertDeclaration(it as LocalVariable) }.makeString("\n")
} }
private fun convertDeclaration(v: LocalVariable): String { private fun convertDeclaration(v: LocalVariable): String {
val varKeyword: String? = (if (v.hasModifier(Modifier.FINAL)) val varKeyword: String? = (if (v.hasModifier(Modifier.FINAL))
"val" "val"
else else
"var") "var")
return varKeyword + " " + v.toKotlin() return varKeyword + " " + v.toKotlin()
} }
} }
public open class ExpressionListStatement(val expressions: List<Expression>): Expression() { public open class ExpressionListStatement(val expressions: List<Expression>): Expression() {
public override fun toKotlin() = expressions.toKotlin("\n") public override fun toKotlin() = expressions.toKotlin("\n")
} }
public open class LabelStatement(val name: Identifier, val statement: Element): Statement() { public open class LabelStatement(val name: Identifier, val statement: Element): Statement() {
public override fun toKotlin(): String = "@" + name.toKotlin() + " " + statement.toKotlin() public override fun toKotlin(): String = "@" + name.toKotlin() + " " + statement.toKotlin()
} }
public open class ReturnStatement(val expression: Expression): Statement() { public open class ReturnStatement(val expression: Expression): Statement() {
public override fun toKotlin() = "return " + expression.toKotlin() public override fun toKotlin() = "return " + expression.toKotlin()
} }
public open class IfStatement(val condition: Expression, public open class IfStatement(val condition: Expression,
val thenStatement: Element, val thenStatement: Element,
val elseStatement: Element): Expression() { val elseStatement: Element): Expression() {
public override fun toKotlin(): String { public override fun toKotlin(): String {
val result: String = "if (" + condition.toKotlin() + ")\n" + thenStatement.toKotlin() + "\n" val result: String = "if (" + condition.toKotlin() + ")\n" + thenStatement.toKotlin() + "\n"
if (elseStatement != Statement.EMPTY_STATEMENT) { if (elseStatement != Statement.EMPTY_STATEMENT) {
return result + "else\n" + elseStatement.toKotlin() return result + "else\n" + elseStatement.toKotlin()
} }
return result return result
} }
} }
// Loops -------------------------------------------------------------------------------------------------- // Loops --------------------------------------------------------------------------------------------------
public open class WhileStatement(val condition: Expression, val body: Element): Statement() { public open class WhileStatement(val condition: Expression, val body: Element): Statement() {
public override fun toKotlin() = "while (" + condition.toKotlin() + ")\n" + body.toKotlin() public override fun toKotlin() = "while (" + condition.toKotlin() + ")\n" + body.toKotlin()
} }
public open class DoWhileStatement(condition: Expression, body: Element): WhileStatement(condition, body) { public open class DoWhileStatement(condition: Expression, body: Element): WhileStatement(condition, body) {
public override fun toKotlin() = "do\n" + body.toKotlin() + "\nwhile (" + condition.toKotlin() + ")" public override fun toKotlin() = "do\n" + body.toKotlin() + "\nwhile (" + condition.toKotlin() + ")"
} }
public open class ForeachStatement(val variable: Parameter, public open class ForeachStatement(val variable: Parameter,
val expression: Expression, val expression: Expression,
val body: Element): Statement() { val body: Element): Statement() {
public override fun toKotlin() = "for (" + variable.toKotlin() + " in " + public override fun toKotlin() = "for (" + variable.toKotlin() + " in " +
expression.toKotlin() + ")\n" + body.toKotlin() expression.toKotlin() + ")\n" + body.toKotlin()
} }
public open class ForeachWithRangeStatement(val identifier: Identifier, public open class ForeachWithRangeStatement(val identifier: Identifier,
val start: Expression, val start: Expression,
val end: Expression, val end: Expression,
val body: Element): Statement() { val body: Element): Statement() {
public override fun toKotlin() = "for (" + identifier.toKotlin() + " in " + public override fun toKotlin() = "for (" + identifier.toKotlin() + " in " +
start.toKotlin() + ".." + end.toKotlin() + ") " + body.toKotlin() start.toKotlin() + ".." + end.toKotlin() + ") " + body.toKotlin()
} }
public open class BreakStatement(val label: Identifier = Identifier.EMPTY_IDENTIFIER) : Statement() { public open class BreakStatement(val label: Identifier = Identifier.EMPTY_IDENTIFIER) : Statement() {
public override fun toKotlin() = "break" + label.withPrefix("@") public override fun toKotlin() = "break" + label.withPrefix("@")
} }
public open class ContinueStatement(val label: Identifier = Identifier.EMPTY_IDENTIFIER): Statement() { public open class ContinueStatement(val label: Identifier = Identifier.EMPTY_IDENTIFIER): Statement() {
public override fun toKotlin() = "continue" + label.withPrefix("@") public override fun toKotlin() = "continue" + label.withPrefix("@")
} }
// Exceptions ---------------------------------------------------------------------------------------------- // Exceptions ----------------------------------------------------------------------------------------------
public open class TryStatement(val block: Block, val catches: List<CatchStatement>, val finallyBlock: Block): Statement() { public open class TryStatement(val block: Block, val catches: List<CatchStatement>, val finallyBlock: Block): Statement() {
public override fun toKotlin(): String { public override fun toKotlin(): String {
return "try\n" + block.toKotlin() + "\n" + catches.toKotlin("\n") + "\n" + (if (finallyBlock.isEmpty()) return "try\n" + block.toKotlin() + "\n" + catches.toKotlin("\n") + "\n" + (if (finallyBlock.isEmpty())
"" ""
else else
"finally\n" + finallyBlock.toKotlin()) "finally\n" + finallyBlock.toKotlin())
} }
} }
public open class ThrowStatement(val expression: Expression): Expression() { public open class ThrowStatement(val expression: Expression): Expression() {
public override fun toKotlin() = "throw " + expression.toKotlin() public override fun toKotlin() = "throw " + expression.toKotlin()
} }
public open class CatchStatement(val variable: Parameter, val block: Block): Statement() { public open class CatchStatement(val variable: Parameter, val block: Block): Statement() {
public override fun toKotlin(): String = "catch (" + variable.toKotlin() + ") " + block.toKotlin() public override fun toKotlin(): String = "catch (" + variable.toKotlin() + ") " + block.toKotlin()
} }
// Switch -------------------------------------------------------------------------------------------------- // Switch --------------------------------------------------------------------------------------------------
public open class SwitchContainer(val expression: Expression, val caseContainers: List<CaseContainer>): Statement() { public open class SwitchContainer(val expression: Expression, val caseContainers: List<CaseContainer>): Statement() {
public override fun toKotlin() = "when (" + expression.toKotlin() + ") {\n" + caseContainers.toKotlin("\n") + "\n}" public override fun toKotlin() = "when (" + expression.toKotlin() + ") {\n" + caseContainers.toKotlin("\n") + "\n}"
} }
public open class CaseContainer(val caseStatement: List<Element>, statements: List<Element>): Statement() { public open class CaseContainer(val caseStatement: List<Element>, statements: List<Element>): Statement() {
private val myBlock: Block private val myBlock: Block
{ {
val newStatements = statements.filterNot { it is BreakStatement || it is ContinueStatement } val newStatements = statements.filterNot { it is BreakStatement || it is ContinueStatement }
myBlock = Block(newStatements, false) myBlock = Block(newStatements, false)
} }
public override fun toKotlin() = caseStatement.toKotlin(", ") + " -> " + myBlock.toKotlin() public override fun toKotlin() = caseStatement.toKotlin(", ") + " -> " + myBlock.toKotlin()
} }
public open class SwitchLabelStatement(val expression: Expression): Statement() { public open class SwitchLabelStatement(val expression: Expression): Statement() {
public override fun toKotlin() = expression.toKotlin() public override fun toKotlin() = expression.toKotlin()
} }
public open class DefaultSwitchLabelStatement(): Statement() { public open class DefaultSwitchLabelStatement(): Statement() {
public override fun toKotlin() = "else" public override fun toKotlin() = "else"
} }
// Other ------------------------------------------------------------------------------------------------------ // Other ------------------------------------------------------------------------------------------------------
public open class SynchronizedStatement(val expression: Expression, val block: Block): Statement() { public open class SynchronizedStatement(val expression: Expression, val block: Block): Statement() {
public override fun toKotlin() = "synchronized (" + expression.toKotlin() + ") "+ block.toKotlin() public override fun toKotlin() = "synchronized (" + expression.toKotlin() + ") "+ block.toKotlin()
} }
+22 -22
View File
@@ -1,22 +1,22 @@
package org.jetbrains.jet.j2k.ast package org.jetbrains.jet.j2k.ast
import org.jetbrains.jet.j2k.Converter import org.jetbrains.jet.j2k.Converter
import org.jetbrains.jet.j2k.ast.types.Type import org.jetbrains.jet.j2k.ast.types.Type
public open class Trait(converter : Converter, public open class Trait(converter : Converter,
name : Identifier, name : Identifier,
docComments: List<Node>, docComments: List<Node>,
modifiers : Set<Modifier>, modifiers : Set<Modifier>,
typeParameters : List<Element>, typeParameters : List<Element>,
extendsTypes : List<Type>, extendsTypes : List<Type>,
baseClassParams : List<Expression>, baseClassParams : List<Expression>,
implementsTypes : List<Type>, implementsTypes : List<Type>,
members : List<Node>) : Class(converter, name, docComments, modifiers, typeParameters, members : List<Node>) : Class(converter, name, docComments, modifiers, typeParameters,
extendsTypes, baseClassParams, implementsTypes, members) { extendsTypes, baseClassParams, implementsTypes, members) {
override val TYPE: String override val TYPE: String
get() = "trait" get() = "trait"
override fun primaryConstructorSignatureToKotlin() = "" override fun primaryConstructorSignatureToKotlin() = ""
override fun needOpenModifier() = false override fun needOpenModifier() = false
} }
+9 -9
View File
@@ -1,9 +1,9 @@
package org.jetbrains.jet.j2k.ast package org.jetbrains.jet.j2k.ast
import org.jetbrains.jet.j2k.ast.types.Type import org.jetbrains.jet.j2k.ast.types.Type
public open class TypeElement(val `type` : Type) : Element() { public open class TypeElement(val `type` : Type) : Element() {
override fun toKotlin() = `type`.toKotlin() override fun toKotlin() = `type`.toKotlin()
public fun toKotlinNotNull(): String = `type`.convertedToNotNull().toKotlin() public fun toKotlinNotNull(): String = `type`.convertedToNotNull().toKotlin()
} }
+22 -22
View File
@@ -1,22 +1,22 @@
package org.jetbrains.jet.j2k.ast package org.jetbrains.jet.j2k.ast
import org.jetbrains.jet.j2k.ast.types.Type import org.jetbrains.jet.j2k.ast.types.Type
public open class TypeParameter(val name : Identifier, val extendsTypes : List<Type>) : Element() { public open class TypeParameter(val name : Identifier, val extendsTypes : List<Type>) : Element() {
public open fun hasWhere() : Boolean = extendsTypes.size() > 1 public open fun hasWhere() : Boolean = extendsTypes.size() > 1
public open fun getWhereToKotlin() : String { public open fun getWhereToKotlin() : String {
if (hasWhere()) { if (hasWhere()) {
return name.toKotlin() + " : " + extendsTypes.get(1).toKotlin() return name.toKotlin() + " : " + extendsTypes.get(1).toKotlin()
} }
return "" return ""
} }
public override fun toKotlin() : String { public override fun toKotlin() : String {
if (extendsTypes.size() > 0) { if (extendsTypes.size() > 0) {
return name.toKotlin() + " : " + extendsTypes [0].toKotlin() return name.toKotlin() + " : " + extendsTypes [0].toKotlin()
} }
return name.toKotlin() return name.toKotlin()
} }
} }
+28 -28
View File
@@ -1,28 +1,28 @@
package org.jetbrains.jet.j2k.ast package org.jetbrains.jet.j2k.ast
fun List<Node>.toKotlin(separator: String, prefix: String = "", suffix: String = ""): String { fun List<Node>.toKotlin(separator: String, prefix: String = "", suffix: String = ""): String {
val result = StringBuilder() val result = StringBuilder()
if (size() > 0) { if (size() > 0) {
result.append(prefix) result.append(prefix)
var first = true var first = true
for(x in this) { for(x in this) {
if (!first) result.append(separator) if (!first) result.append(separator)
first = false first = false
result.append(x.toKotlin()) result.append(x.toKotlin())
} }
result.append(suffix) result.append(suffix)
} }
return result.toString() return result.toString()
} }
fun Collection<Modifier>.toKotlin(separator: String = " "): String { fun Collection<Modifier>.toKotlin(separator: String = " "): String {
val result = StringBuilder() val result = StringBuilder()
for(x in this) { for(x in this) {
result.append(x.name) result.append(x.name)
result.append(separator) result.append(separator)
} }
return result.toString() return result.toString()
} }
fun String.withPrefix(prefix: String) = if (isEmpty()) "" else prefix + this fun String.withPrefix(prefix: String) = if (isEmpty()) "" else prefix + this
fun Expression.withPrefix(prefix: String) = if (isEmpty()) "" else prefix + toKotlin() fun Expression.withPrefix(prefix: String) = if (isEmpty()) "" else prefix + toKotlin()
@@ -1,13 +1,13 @@
package org.jetbrains.jet.j2k.ast.types package org.jetbrains.jet.j2k.ast.types
public open class ArrayType(val elementType : Type, nullable: Boolean) : Type(nullable) { public open class ArrayType(val elementType : Type, nullable: Boolean) : Type(nullable) {
public override fun toKotlin() : String { public override fun toKotlin() : String {
if (elementType is PrimitiveType) { if (elementType is PrimitiveType) {
return elementType.toKotlin() + "Array" + isNullableStr() return elementType.toKotlin() + "Array" + isNullableStr()
} }
return "Array<" + elementType.toKotlin() + ">" + isNullableStr() return "Array<" + elementType.toKotlin() + ">" + isNullableStr()
} }
public override fun convertedToNotNull() : Type = ArrayType(elementType, false) public override fun convertedToNotNull() : Type = ArrayType(elementType, false)
} }
@@ -1,24 +1,24 @@
package org.jetbrains.jet.j2k.ast.types package org.jetbrains.jet.j2k.ast.types
import org.jetbrains.jet.j2k.ast.Element import org.jetbrains.jet.j2k.ast.Element
import org.jetbrains.jet.j2k.ast.Identifier import org.jetbrains.jet.j2k.ast.Identifier
import java.util.Collections import java.util.Collections
import java.util.ArrayList import java.util.ArrayList
public open class ClassType(val `type` : Identifier, val parameters : List<out Element>, nullable : Boolean) : Type(nullable) { public open class ClassType(val `type` : Identifier, val parameters : List<out Element>, nullable : Boolean) : Type(nullable) {
public override fun toKotlin() : String { public override fun toKotlin() : String {
// TODO change to map() when KT-2051 is fixed // TODO change to map() when KT-2051 is fixed
val parametersToKotlin = ArrayList<String>() val parametersToKotlin = ArrayList<String>()
for(val param in parameters) { for(val param in parameters) {
parametersToKotlin.add(param.toKotlin()) parametersToKotlin.add(param.toKotlin())
} }
var params : String = if (parametersToKotlin.size() == 0) var params : String = if (parametersToKotlin.size() == 0)
"" ""
else else
"<" + parametersToKotlin.makeString(", ") + ">" "<" + parametersToKotlin.makeString(", ") + ">"
return `type`.toKotlin() + params + isNullableStr() return `type`.toKotlin() + params + isNullableStr()
} }
public override fun convertedToNotNull() : Type = ClassType(`type`, parameters, false) public override fun convertedToNotNull() : Type = ClassType(`type`, parameters, false)
} }
@@ -1,5 +1,5 @@
package org.jetbrains.jet.j2k.ast.types package org.jetbrains.jet.j2k.ast.types
public open class EmptyType() : Type(false) { public open class EmptyType() : Type(false) {
public override fun toKotlin() : String = "UNRESOLVED_TYPE" public override fun toKotlin() : String = "UNRESOLVED_TYPE"
} }
@@ -1,5 +1,5 @@
package org.jetbrains.jet.j2k.ast.types package org.jetbrains.jet.j2k.ast.types
public open class InProjectionType(val bound : Type) : Type(false) { public open class InProjectionType(val bound : Type) : Type(false) {
public override fun toKotlin() : String = "in " + bound.toKotlin() public override fun toKotlin() : String = "in " + bound.toKotlin()
} }
@@ -1,5 +1,5 @@
package org.jetbrains.jet.j2k.ast.types package org.jetbrains.jet.j2k.ast.types
public open class OutProjectionType(val bound : Type) : Type(false) { public open class OutProjectionType(val bound : Type) : Type(false) {
public override fun toKotlin() : String = "out " + bound.toKotlin() public override fun toKotlin() : String = "out " + bound.toKotlin()
} }
@@ -1,7 +1,7 @@
package org.jetbrains.jet.j2k.ast.types package org.jetbrains.jet.j2k.ast.types
import org.jetbrains.jet.j2k.ast.Identifier import org.jetbrains.jet.j2k.ast.Identifier
public open class PrimitiveType(val `type` : Identifier) : Type(false) { public open class PrimitiveType(val `type` : Identifier) : Type(false) {
public override fun toKotlin() : String = `type`.toKotlin() public override fun toKotlin() : String = `type`.toKotlin()
} }
@@ -1,5 +1,5 @@
package org.jetbrains.jet.j2k.ast.types package org.jetbrains.jet.j2k.ast.types
public open class StarProjectionType() : Type(false) { public open class StarProjectionType() : Type(false) {
public override fun toKotlin() : String = "*" public override fun toKotlin() : String = "*"
} }
+17 -17
View File
@@ -1,17 +1,17 @@
package org.jetbrains.jet.j2k.ast.types package org.jetbrains.jet.j2k.ast.types
import org.jetbrains.jet.j2k.ast.Element import org.jetbrains.jet.j2k.ast.Element
public abstract class Type(val nullable: Boolean) : Element() { public abstract class Type(val nullable: Boolean) : Element() {
public open fun convertedToNotNull() : Type { public open fun convertedToNotNull() : Type {
if (nullable) throw UnsupportedOperationException("convertedToNotNull must be defined") if (nullable) throw UnsupportedOperationException("convertedToNotNull must be defined")
return this return this
} }
public open fun isNullableStr() : String? { public open fun isNullableStr() : String? {
return (if (nullable) return (if (nullable)
"?" "?"
else else
"") "")
} }
} }
@@ -1,7 +1,7 @@
package org.jetbrains.jet.j2k.ast.types package org.jetbrains.jet.j2k.ast.types
import org.jetbrains.jet.j2k.ast.types.Type import org.jetbrains.jet.j2k.ast.types.Type
public open class VarArg(val `type` : Type) : Type(false) { public open class VarArg(val `type` : Type) : Type(false) {
public override fun toKotlin() : String = `type`.toKotlin() public override fun toKotlin() : String = `type`.toKotlin()
} }
@@ -1,21 +1,21 @@
package org.jetbrains.jet.j2k.visitors package org.jetbrains.jet.j2k.visitors
import com.intellij.psi.JavaRecursiveElementVisitor import com.intellij.psi.JavaRecursiveElementVisitor
import com.intellij.psi.PsiClass import com.intellij.psi.PsiClass
import java.util.HashSet import java.util.HashSet
public open class ClassVisitor(): JavaRecursiveElementVisitor() { public open class ClassVisitor(): JavaRecursiveElementVisitor() {
private val myClassIdentifiers = HashSet<String>() private val myClassIdentifiers = HashSet<String>()
public open fun getClassIdentifiers(): Set<String> { public open fun getClassIdentifiers(): Set<String> {
return HashSet<String>(myClassIdentifiers) return HashSet<String>(myClassIdentifiers)
} }
public override fun visitClass(aClass: PsiClass?): Unit { public override fun visitClass(aClass: PsiClass?): Unit {
val qName = aClass?.getQualifiedName() val qName = aClass?.getQualifiedName()
if (qName != null) { if (qName != null) {
myClassIdentifiers.add(qName) myClassIdentifiers.add(qName)
} }
super.visitClass(aClass) super.visitClass(aClass)
} }
} }
@@ -1,7 +1,7 @@
package org.jetbrains.jet.j2k.visitors package org.jetbrains.jet.j2k.visitors
import org.jetbrains.jet.j2k.Converter import org.jetbrains.jet.j2k.Converter
public open class Dispatcher(converter: Converter) { public open class Dispatcher(converter: Converter) {
public var expressionVisitor: ExpressionVisitor = ExpressionVisitor(converter) public var expressionVisitor: ExpressionVisitor = ExpressionVisitor(converter)
} }
@@ -1,72 +1,72 @@
package org.jetbrains.jet.j2k.visitors package org.jetbrains.jet.j2k.visitors
import com.intellij.psi.* import com.intellij.psi.*
import org.jetbrains.jet.j2k.Converter import org.jetbrains.jet.j2k.Converter
import org.jetbrains.jet.j2k.ast.* import org.jetbrains.jet.j2k.ast.*
import org.jetbrains.jet.j2k.ast.types.Type import org.jetbrains.jet.j2k.ast.types.Type
import org.jetbrains.jet.j2k.isAnnotatedAsNotNull import org.jetbrains.jet.j2k.isAnnotatedAsNotNull
import org.jetbrains.jet.j2k.isDefinitelyNotNull import org.jetbrains.jet.j2k.isDefinitelyNotNull
public open class ElementVisitor(val myConverter : Converter) : JavaElementVisitor() { public open class ElementVisitor(val myConverter : Converter) : JavaElementVisitor() {
protected var myResult : Element = Element.EMPTY_ELEMENT protected var myResult : Element = Element.EMPTY_ELEMENT
public fun getConverter() : Converter { public fun getConverter() : Converter {
return myConverter return myConverter
} }
public open fun getResult() : Element { public open fun getResult() : Element {
return myResult return myResult
} }
public override fun visitLocalVariable(variable : PsiLocalVariable?) : Unit { public override fun visitLocalVariable(variable : PsiLocalVariable?) : Unit {
val theVariable = variable!! val theVariable = variable!!
var kType = myConverter.typeToType(theVariable.getType(), isAnnotatedAsNotNull(theVariable.getModifierList())) var kType = myConverter.typeToType(theVariable.getType(), isAnnotatedAsNotNull(theVariable.getModifierList()))
if (theVariable.hasModifierProperty(PsiModifier.FINAL) && isDefinitelyNotNull(theVariable.getInitializer())) { if (theVariable.hasModifierProperty(PsiModifier.FINAL) && isDefinitelyNotNull(theVariable.getInitializer())) {
kType = kType.convertedToNotNull(); kType = kType.convertedToNotNull();
} }
myResult = LocalVariable(Identifier(theVariable.getName()!!), myResult = LocalVariable(Identifier(theVariable.getName()!!),
Converter.modifiersListToModifiersSet(theVariable.getModifierList()), Converter.modifiersListToModifiersSet(theVariable.getModifierList()),
kType, kType,
myConverter.expressionToExpression(theVariable.getInitializer(), theVariable.getType())) myConverter.expressionToExpression(theVariable.getInitializer(), theVariable.getType()))
} }
public override fun visitExpressionList(list : PsiExpressionList?) : Unit { public override fun visitExpressionList(list : PsiExpressionList?) : Unit {
myResult = ExpressionList(myConverter.expressionsToExpressionList(list!!.getExpressions())) myResult = ExpressionList(myConverter.expressionsToExpressionList(list!!.getExpressions()))
} }
public override fun visitReferenceElement(reference : PsiJavaCodeReferenceElement?) : Unit { public override fun visitReferenceElement(reference : PsiJavaCodeReferenceElement?) : Unit {
val theReference = reference!! val theReference = reference!!
val types : List<Type> = myConverter.typesToTypeList(theReference.getTypeParameters()) val types : List<Type> = myConverter.typesToTypeList(theReference.getTypeParameters())
if (!theReference.isQualified()) { if (!theReference.isQualified()) {
myResult = ReferenceElement(Identifier(theReference.getReferenceName()!!), types) myResult = ReferenceElement(Identifier(theReference.getReferenceName()!!), types)
} }
else { else {
var result : String = Identifier(reference?.getReferenceName()!!).toKotlin() var result : String = Identifier(reference?.getReferenceName()!!).toKotlin()
var qualifier : PsiElement? = theReference.getQualifier() var qualifier : PsiElement? = theReference.getQualifier()
while (qualifier != null) while (qualifier != null)
{ {
val p : PsiJavaCodeReferenceElement = (qualifier as PsiJavaCodeReferenceElement) val p : PsiJavaCodeReferenceElement = (qualifier as PsiJavaCodeReferenceElement)
result = Identifier(p.getReferenceName()!!).toKotlin() + "." + result result = Identifier(p.getReferenceName()!!).toKotlin() + "." + result
qualifier = p.getQualifier() qualifier = p.getQualifier()
} }
myResult = ReferenceElement(Identifier(result), types) myResult = ReferenceElement(Identifier(result), types)
} }
} }
public override fun visitTypeElement(`type` : PsiTypeElement?) : Unit { public override fun visitTypeElement(`type` : PsiTypeElement?) : Unit {
myResult = TypeElement(myConverter.typeToType(`type`!!.getType())) myResult = TypeElement(myConverter.typeToType(`type`!!.getType()))
} }
public override fun visitTypeParameter(classParameter : PsiTypeParameter?) : Unit { public override fun visitTypeParameter(classParameter : PsiTypeParameter?) : Unit {
myResult = TypeParameter(Identifier(classParameter!!.getName()!!), myResult = TypeParameter(Identifier(classParameter!!.getName()!!),
classParameter!!.getExtendsListTypes().map { myConverter.typeToType(it) } ) classParameter!!.getExtendsListTypes().map { myConverter.typeToType(it) } )
} }
public override fun visitParameterList(list : PsiParameterList?) : Unit { public override fun visitParameterList(list : PsiParameterList?) : Unit {
myResult = ParameterList(myConverter.parametersToParameterList(list!!.getParameters()).requireNoNulls()) myResult = ParameterList(myConverter.parametersToParameterList(list!!.getParameters()).requireNoNulls())
} }
public override fun visitComment(comment: PsiComment?) { public override fun visitComment(comment: PsiComment?) {
myResult = Comment(comment?.getText()!!) myResult = Comment(comment?.getText()!!)
} }
} }
@@ -1,490 +1,490 @@
package org.jetbrains.jet.j2k.visitors package org.jetbrains.jet.j2k.visitors
import com.intellij.psi.* import com.intellij.psi.*
import com.intellij.psi.tree.IElementType import com.intellij.psi.tree.IElementType
import org.jetbrains.annotations.Nullable import org.jetbrains.annotations.Nullable
import org.jetbrains.jet.j2k.Converter import org.jetbrains.jet.j2k.Converter
import org.jetbrains.jet.j2k.ast.* import org.jetbrains.jet.j2k.ast.*
import org.jetbrains.jet.j2k.ast.types.EmptyType import org.jetbrains.jet.j2k.ast.types.EmptyType
import org.jetbrains.jet.j2k.ast.types.Type import org.jetbrains.jet.j2k.ast.types.Type
import org.jetbrains.jet.lang.types.expressions.OperatorConventions import org.jetbrains.jet.lang.types.expressions.OperatorConventions
import java.util.ArrayList import java.util.ArrayList
import java.util.Collections import java.util.Collections
import com.intellij.psi.CommonClassNames.* import com.intellij.psi.CommonClassNames.*
import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.PsiTreeUtil
public open class ExpressionVisitor(converter: Converter): StatementVisitor(converter) { public open class ExpressionVisitor(converter: Converter): StatementVisitor(converter) {
{ {
myResult = Expression.EMPTY_EXPRESSION myResult = Expression.EMPTY_EXPRESSION
} }
public override fun getResult(): Expression { public override fun getResult(): Expression {
return myResult as Expression return myResult as Expression
} }
public override fun visitArrayAccessExpression(expression: PsiArrayAccessExpression?): Unit { public override fun visitArrayAccessExpression(expression: PsiArrayAccessExpression?): Unit {
val assignment = PsiTreeUtil.getParentOfType(expression, javaClass<PsiAssignmentExpression>()) val assignment = PsiTreeUtil.getParentOfType(expression, javaClass<PsiAssignmentExpression>())
val lvalue = assignment != null && expression == assignment.getLExpression(); val lvalue = assignment != null && expression == assignment.getLExpression();
myResult = ArrayAccessExpression(getConverter().expressionToExpression(expression?.getArrayExpression()), myResult = ArrayAccessExpression(getConverter().expressionToExpression(expression?.getArrayExpression()),
getConverter().expressionToExpression(expression?.getIndexExpression()), getConverter().expressionToExpression(expression?.getIndexExpression()),
lvalue) lvalue)
} }
public override fun visitArrayInitializerExpression(expression: PsiArrayInitializerExpression?): Unit { public override fun visitArrayInitializerExpression(expression: PsiArrayInitializerExpression?): Unit {
myResult = ArrayInitializerExpression(getConverter().typeToType(expression?.getType()), myResult = ArrayInitializerExpression(getConverter().typeToType(expression?.getType()),
getConverter().expressionsToExpressionList(expression?.getInitializers()!!)) getConverter().expressionsToExpressionList(expression?.getInitializers()!!))
} }
public override fun visitAssignmentExpression(expression: PsiAssignmentExpression?): Unit { public override fun visitAssignmentExpression(expression: PsiAssignmentExpression?): Unit {
val tokenType: IElementType = expression?.getOperationSign()?.getTokenType()!! val tokenType: IElementType = expression?.getOperationSign()?.getTokenType()!!
val secondOp: String = when(tokenType) { val secondOp: String = when(tokenType) {
JavaTokenType.GTGTEQ -> "shr" JavaTokenType.GTGTEQ -> "shr"
JavaTokenType.LTLTEQ -> "shl" JavaTokenType.LTLTEQ -> "shl"
JavaTokenType.XOREQ -> "xor" JavaTokenType.XOREQ -> "xor"
JavaTokenType.ANDEQ -> "and" JavaTokenType.ANDEQ -> "and"
JavaTokenType.OREQ -> "or" JavaTokenType.OREQ -> "or"
JavaTokenType.GTGTGTEQ -> "ushr" JavaTokenType.GTGTGTEQ -> "ushr"
else -> "" else -> ""
} }
val lhs = getConverter().expressionToExpression(expression?.getLExpression()!!) val lhs = getConverter().expressionToExpression(expression?.getLExpression()!!)
val rhs = getConverter().expressionToExpression(expression?.getRExpression()!!, expression?.getRExpression()?.getType()) val rhs = getConverter().expressionToExpression(expression?.getRExpression()!!, expression?.getRExpression()?.getType())
if (!secondOp.isEmpty()) { if (!secondOp.isEmpty()) {
myResult = AssignmentExpression(lhs, BinaryExpression(lhs, rhs, secondOp), "=") myResult = AssignmentExpression(lhs, BinaryExpression(lhs, rhs, secondOp), "=")
} }
else { else {
myResult = AssignmentExpression(lhs, rhs, expression?.getOperationSign()?.getText()!!) myResult = AssignmentExpression(lhs, rhs, expression?.getOperationSign()?.getText()!!)
} }
} }
public override fun visitBinaryExpression(expression: PsiBinaryExpression?): Unit { public override fun visitBinaryExpression(expression: PsiBinaryExpression?): Unit {
val lhs = getConverter().expressionToExpression(expression?.getLOperand()!!, expression?.getType()) val lhs = getConverter().expressionToExpression(expression?.getLOperand()!!, expression?.getType())
val rhs = getConverter().expressionToExpression(expression?.getROperand(), expression?.getType()) val rhs = getConverter().expressionToExpression(expression?.getROperand(), expression?.getType())
if (expression?.getOperationSign()?.getTokenType() == JavaTokenType.GTGTGT) { if (expression?.getOperationSign()?.getTokenType() == JavaTokenType.GTGTGT) {
myResult = MethodCallExpression.build(lhs, "ushr", arrayList(rhs)) myResult = MethodCallExpression.build(lhs, "ushr", arrayList(rhs))
} }
else { else {
myResult = BinaryExpression(lhs, rhs, myResult = BinaryExpression(lhs, rhs,
getOperatorString(expression?.getOperationSign()?.getTokenType()!!)) getOperatorString(expression?.getOperationSign()?.getTokenType()!!))
} }
} }
public override fun visitClassObjectAccessExpression(expression: PsiClassObjectAccessExpression?): Unit { public override fun visitClassObjectAccessExpression(expression: PsiClassObjectAccessExpression?): Unit {
myResult = ClassObjectAccessExpression(getConverter().typeElementToTypeElement(expression?.getOperand())) myResult = ClassObjectAccessExpression(getConverter().typeElementToTypeElement(expression?.getOperand()))
} }
public override fun visitConditionalExpression(expression: PsiConditionalExpression?): Unit { public override fun visitConditionalExpression(expression: PsiConditionalExpression?): Unit {
val condition: PsiExpression? = expression?.getCondition() val condition: PsiExpression? = expression?.getCondition()
val `type`: PsiType? = condition?.getType() val `type`: PsiType? = condition?.getType()
val e: Expression = (if (`type` != null) val e: Expression = (if (`type` != null)
getConverter().expressionToExpression(condition, `type`) getConverter().expressionToExpression(condition, `type`)
else else
getConverter().expressionToExpression(condition)) getConverter().expressionToExpression(condition))
myResult = ParenthesizedExpression(IfStatement(e, myResult = ParenthesizedExpression(IfStatement(e,
getConverter().expressionToExpression(expression?.getThenExpression()), getConverter().expressionToExpression(expression?.getThenExpression()),
getConverter().expressionToExpression(expression?.getElseExpression()))) getConverter().expressionToExpression(expression?.getElseExpression())))
} }
public override fun visitExpressionList(list: PsiExpressionList?): Unit { public override fun visitExpressionList(list: PsiExpressionList?): Unit {
myResult = ExpressionList(getConverter().expressionsToExpressionList(list!!.getExpressions())) myResult = ExpressionList(getConverter().expressionsToExpressionList(list!!.getExpressions()))
} }
public override fun visitInstanceOfExpression(expression: PsiInstanceOfExpression?): Unit { public override fun visitInstanceOfExpression(expression: PsiInstanceOfExpression?): Unit {
val checkType: PsiTypeElement? = expression?.getCheckType() val checkType: PsiTypeElement? = expression?.getCheckType()
myResult = IsOperator(getConverter().expressionToExpression(expression?.getOperand()), myResult = IsOperator(getConverter().expressionToExpression(expression?.getOperand()),
myConverter.typeElementToTypeElement(checkType)) myConverter.typeElementToTypeElement(checkType))
} }
public override fun visitLiteralExpression(expression: PsiLiteralExpression?): Unit { public override fun visitLiteralExpression(expression: PsiLiteralExpression?): Unit {
val value: Any? = expression?.getValue() val value: Any? = expression?.getValue()
var text: String = expression?.getText()!! var text: String = expression?.getText()!!
val `type`: PsiType? = expression?.getType() val `type`: PsiType? = expression?.getType()
if (`type` != null) { if (`type` != null) {
val canonicalTypeStr: String? = `type`.getCanonicalText() val canonicalTypeStr: String? = `type`.getCanonicalText()
if (canonicalTypeStr?.equals("double")!! || canonicalTypeStr?.equals(JAVA_LANG_DOUBLE)!!) { if (canonicalTypeStr?.equals("double")!! || canonicalTypeStr?.equals(JAVA_LANG_DOUBLE)!!) {
text = text.replace("D", "").replace("d", "") text = text.replace("D", "").replace("d", "")
if (!text.contains(".")) { if (!text.contains(".")) {
text += ".0" text += ".0"
} }
} }
if (canonicalTypeStr?.equals("float")!! || canonicalTypeStr?.equals(JAVA_LANG_FLOAT)!!) { if (canonicalTypeStr?.equals("float")!! || canonicalTypeStr?.equals(JAVA_LANG_FLOAT)!!) {
text = text.replace("F", "").replace("f", "") + "." + OperatorConventions.FLOAT + "()" text = text.replace("F", "").replace("f", "") + "." + OperatorConventions.FLOAT + "()"
} }
if (canonicalTypeStr?.equals("long")!! || canonicalTypeStr?.equals(JAVA_LANG_LONG)!!) { if (canonicalTypeStr?.equals("long")!! || canonicalTypeStr?.equals(JAVA_LANG_LONG)!!) {
text = text.replace("L", "").replace("l", "") text = text.replace("L", "").replace("l", "")
} }
if (canonicalTypeStr?.equals("int")!! || canonicalTypeStr?.equals(JAVA_LANG_INTEGER)!!) { if (canonicalTypeStr?.equals("int")!! || canonicalTypeStr?.equals(JAVA_LANG_INTEGER)!!) {
text = (if (value != null) value.toString() else text) text = (if (value != null) value.toString() else text)
} }
} }
myResult = LiteralExpression(text) myResult = LiteralExpression(text)
} }
public override fun visitMethodCallExpression(expression: PsiMethodCallExpression?): Unit { public override fun visitMethodCallExpression(expression: PsiMethodCallExpression?): Unit {
convertMethodCallExpression(expression!!) convertMethodCallExpression(expression!!)
} }
protected fun convertMethodCallExpression(expression: PsiMethodCallExpression) { protected fun convertMethodCallExpression(expression: PsiMethodCallExpression) {
if (!SuperVisitor.isSuper(expression.getMethodExpression()) || !isInsidePrimaryConstructor(expression)) { if (!SuperVisitor.isSuper(expression.getMethodExpression()) || !isInsidePrimaryConstructor(expression)) {
myResult = MethodCallExpression(getConverter().expressionToExpression(expression.getMethodExpression()), myResult = MethodCallExpression(getConverter().expressionToExpression(expression.getMethodExpression()),
getConverter().argumentsToExpressionList(expression), getConverter().argumentsToExpressionList(expression),
getConverter().typesToTypeList(expression.getTypeArguments()), getConverter().typesToTypeList(expression.getTypeArguments()),
getConverter().typeToType(expression.getType()).nullable) getConverter().typeToType(expression.getType()).nullable)
} }
} }
public override fun visitNewExpression(expression: PsiNewExpression?): Unit { public override fun visitNewExpression(expression: PsiNewExpression?): Unit {
if (expression?.getArrayInitializer() != null) if (expression?.getArrayInitializer() != null)
{ {
myResult = createNewEmptyArray(expression) myResult = createNewEmptyArray(expression)
} }
else else
if (expression?.getArrayDimensions()?.size!! > 0) { if (expression?.getArrayDimensions()?.size!! > 0) {
myResult = createNewEmptyArrayWithoutInitialization(expression!!) myResult = createNewEmptyArrayWithoutInitialization(expression!!)
} }
else else
{ {
myResult = createNewClassExpression(expression) myResult = createNewClassExpression(expression)
} }
} }
private fun createNewClassExpression(expression: PsiNewExpression?): Expression { private fun createNewClassExpression(expression: PsiNewExpression?): Expression {
val anonymousClass: PsiAnonymousClass? = expression?.getAnonymousClass() val anonymousClass: PsiAnonymousClass? = expression?.getAnonymousClass()
val constructor: PsiMethod? = expression?.resolveMethod() val constructor: PsiMethod? = expression?.resolveMethod()
var classReference: PsiJavaCodeReferenceElement? = expression?.getClassOrAnonymousClassReference() var classReference: PsiJavaCodeReferenceElement? = expression?.getClassOrAnonymousClassReference()
val isNotConvertedClass: Boolean = classReference != null && !getConverter().getClassIdentifiers().contains(classReference?.getQualifiedName()) val isNotConvertedClass: Boolean = classReference != null && !getConverter().getClassIdentifiers().contains(classReference?.getQualifiedName())
var argumentList: PsiExpressionList? = expression?.getArgumentList() var argumentList: PsiExpressionList? = expression?.getArgumentList()
var arguments: Array<PsiExpression> = (if (argumentList != null) var arguments: Array<PsiExpression> = (if (argumentList != null)
argumentList?.getExpressions()!! argumentList?.getExpressions()!!
else else
array<PsiExpression>()) array<PsiExpression>())
if (constructor == null || Converter.isConstructorPrimary(constructor) || isNotConvertedClass) if (constructor == null || Converter.isConstructorPrimary(constructor) || isNotConvertedClass)
{ {
return NewClassExpression(getConverter().elementToElement(classReference), return NewClassExpression(getConverter().elementToElement(classReference),
getConverter().argumentsToExpressionList(expression!!), getConverter().argumentsToExpressionList(expression!!),
getConverter().expressionToExpression(expression?.getQualifier()), getConverter().expressionToExpression(expression?.getQualifier()),
(if (anonymousClass != null) (if (anonymousClass != null)
getConverter().anonymousClassToAnonymousClass(anonymousClass) getConverter().anonymousClassToAnonymousClass(anonymousClass)
else else
null)) null))
} }
val reference: PsiJavaCodeReferenceElement? = expression?.getClassReference() val reference: PsiJavaCodeReferenceElement? = expression?.getClassReference()
val typeParameters: List<Type> = (if (reference != null) val typeParameters: List<Type> = (if (reference != null)
getConverter().typesToTypeList(reference.getTypeParameters()) getConverter().typesToTypeList(reference.getTypeParameters())
else else
Collections.emptyList<Type>()!!) Collections.emptyList<Type>()!!)
return CallChainExpression(Identifier(constructor.getName(), false), return CallChainExpression(Identifier(constructor.getName(), false),
MethodCallExpression(Identifier("init"), getConverter().expressionsToExpressionList(arguments), typeParameters, false)) MethodCallExpression(Identifier("init"), getConverter().expressionsToExpressionList(arguments), typeParameters, false))
} }
private fun createNewEmptyArrayWithoutInitialization(expression: PsiNewExpression): Expression { private fun createNewEmptyArrayWithoutInitialization(expression: PsiNewExpression): Expression {
return ArrayWithoutInitializationExpression( return ArrayWithoutInitializationExpression(
getConverter().typeToType(expression.getType(), true), getConverter().typeToType(expression.getType(), true),
getConverter().expressionsToExpressionList(expression.getArrayDimensions())) getConverter().expressionsToExpressionList(expression.getArrayDimensions()))
} }
private fun createNewEmptyArray(expression: PsiNewExpression?): Expression { private fun createNewEmptyArray(expression: PsiNewExpression?): Expression {
return getConverter().expressionToExpression(expression?.getArrayInitializer()) return getConverter().expressionToExpression(expression?.getArrayInitializer())
} }
public override fun visitParenthesizedExpression(expression: PsiParenthesizedExpression?): Unit { public override fun visitParenthesizedExpression(expression: PsiParenthesizedExpression?): Unit {
myResult = ParenthesizedExpression(getConverter().expressionToExpression(expression?.getExpression())) myResult = ParenthesizedExpression(getConverter().expressionToExpression(expression?.getExpression()))
} }
public override fun visitPostfixExpression(expression: PsiPostfixExpression?): Unit { public override fun visitPostfixExpression(expression: PsiPostfixExpression?): Unit {
myResult = PostfixOperator(getOperatorString(expression!!.getOperationSign().getTokenType()!!), myResult = PostfixOperator(getOperatorString(expression!!.getOperationSign().getTokenType()!!),
getConverter().expressionToExpression(expression?.getOperand())) getConverter().expressionToExpression(expression?.getOperand()))
} }
public override fun visitPrefixExpression(expression: PsiPrefixExpression?): Unit { public override fun visitPrefixExpression(expression: PsiPrefixExpression?): Unit {
val operand = getConverter().expressionToExpression(expression?.getOperand(), expression?.getOperand()!!.getType()) val operand = getConverter().expressionToExpression(expression?.getOperand(), expression?.getOperand()!!.getType())
val token = expression?.getOperationTokenType()!! val token = expression?.getOperationTokenType()!!
if (token == JavaTokenType.TILDE) { if (token == JavaTokenType.TILDE) {
myResult = MethodCallExpression.build(ParenthesizedExpression(operand), "inv", arrayList()) myResult = MethodCallExpression.build(ParenthesizedExpression(operand), "inv", arrayList())
} }
else { else {
myResult = PrefixOperator(getOperatorString(token), operand) myResult = PrefixOperator(getOperatorString(token), operand)
} }
} }
public override fun visitReferenceExpression(expression: PsiReferenceExpression?): Unit { public override fun visitReferenceExpression(expression: PsiReferenceExpression?): Unit {
val isFieldReference: Boolean = isFieldReference(expression!!, getContainingClass(expression!!)) val isFieldReference: Boolean = isFieldReference(expression!!, getContainingClass(expression!!))
val insideSecondaryConstructor: Boolean = isInsideSecondaryConstructor(expression!!) val insideSecondaryConstructor: Boolean = isInsideSecondaryConstructor(expression!!)
val hasReceiver: Boolean = isFieldReference && insideSecondaryConstructor val hasReceiver: Boolean = isFieldReference && insideSecondaryConstructor
val isThis: Boolean = isThisExpression(expression!!) val isThis: Boolean = isThisExpression(expression!!)
val isNullable: Boolean = getConverter().typeToType(expression?.getType()).nullable val isNullable: Boolean = getConverter().typeToType(expression?.getType()).nullable
val className: String = getClassNameWithConstructor(expression!!) val className: String = getClassNameWithConstructor(expression!!)
val referencedName = expression?.getReferenceName()!! val referencedName = expression?.getReferenceName()!!
var identifier: Expression = Identifier(referencedName, isNullable) var identifier: Expression = Identifier(referencedName, isNullable)
val __: String = "__" val __: String = "__"
val qualifier = expression?.getQualifierExpression() val qualifier = expression?.getQualifierExpression()
if (hasReceiver){ if (hasReceiver){
identifier = CallChainExpression(Identifier(__, false), Identifier(referencedName, isNullable)) identifier = CallChainExpression(Identifier(__, false), Identifier(referencedName, isNullable))
} }
else if (insideSecondaryConstructor && isThis) { else if (insideSecondaryConstructor && isThis) {
identifier = Identifier("val __ = " + className) identifier = Identifier("val __ = " + className)
} }
else if (qualifier != null && qualifier.getType() is PsiArrayType && referencedName == "length") { else if (qualifier != null && qualifier.getType() is PsiArrayType && referencedName == "length") {
identifier = Identifier("size", isNullable) identifier = Identifier("size", isNullable)
} }
else if (qualifier == null) { else if (qualifier == null) {
val resolved = expression?.getReference()?.resolve() val resolved = expression?.getReference()?.resolve()
if (resolved is PsiMember && resolved.hasModifierProperty(PsiModifier.STATIC) && if (resolved is PsiMember && resolved.hasModifierProperty(PsiModifier.STATIC) &&
resolved.getContainingClass() != null && resolved.getContainingClass() != null &&
PsiTreeUtil.getParentOfType(expression, javaClass<PsiClass>()) != resolved.getContainingClass() && PsiTreeUtil.getParentOfType(expression, javaClass<PsiClass>()) != resolved.getContainingClass() &&
!isStaticallyImported(resolved, expression!!)) { !isStaticallyImported(resolved, expression!!)) {
var member = resolved as PsiMember var member = resolved as PsiMember
var result = Identifier(referencedName).toKotlin() var result = Identifier(referencedName).toKotlin()
while(member.getContainingClass() != null) { while(member.getContainingClass() != null) {
result = Identifier(member.getContainingClass()!!.getName()!!).toKotlin() + "." + result result = Identifier(member.getContainingClass()!!.getName()!!).toKotlin() + "." + result
member = member.getContainingClass()!! member = member.getContainingClass()!!
} }
myResult = Identifier(result, false, false) myResult = Identifier(result, false, false)
return return
} }
} }
myResult = CallChainExpression(getConverter().expressionToExpression(qualifier), identifier) myResult = CallChainExpression(getConverter().expressionToExpression(qualifier), identifier)
} }
public override fun visitSuperExpression(expression: PsiSuperExpression?): Unit { public override fun visitSuperExpression(expression: PsiSuperExpression?): Unit {
val qualifier: PsiJavaCodeReferenceElement? = expression?.getQualifier() val qualifier: PsiJavaCodeReferenceElement? = expression?.getQualifier()
myResult = SuperExpression((if (qualifier != null) myResult = SuperExpression((if (qualifier != null)
Identifier(qualifier.getQualifiedName()!!) Identifier(qualifier.getQualifiedName()!!)
else else
Identifier.EMPTY_IDENTIFIER)) Identifier.EMPTY_IDENTIFIER))
} }
public override fun visitThisExpression(expression: PsiThisExpression?): Unit { public override fun visitThisExpression(expression: PsiThisExpression?): Unit {
val qualifier: PsiJavaCodeReferenceElement? = expression?.getQualifier() val qualifier: PsiJavaCodeReferenceElement? = expression?.getQualifier()
myResult = ThisExpression((if (qualifier != null) myResult = ThisExpression((if (qualifier != null)
Identifier(qualifier.getQualifiedName()!!) Identifier(qualifier.getQualifiedName()!!)
else else
Identifier.EMPTY_IDENTIFIER)) Identifier.EMPTY_IDENTIFIER))
} }
public override fun visitTypeCastExpression(expression: PsiTypeCastExpression?): Unit { public override fun visitTypeCastExpression(expression: PsiTypeCastExpression?): Unit {
val castType: PsiTypeElement? = expression?.getCastType() val castType: PsiTypeElement? = expression?.getCastType()
if (castType != null) { if (castType != null) {
val operand = expression?.getOperand() val operand = expression?.getOperand()
val operandType = operand?.getType() val operandType = operand?.getType()
val typeText = castType.getType().getCanonicalText() val typeText = castType.getType().getCanonicalText()
val typeConversion = Converter.PRIMITIVE_TYPE_CONVERSIONS[typeText] val typeConversion = Converter.PRIMITIVE_TYPE_CONVERSIONS[typeText]
if (operandType is PsiPrimitiveType && typeConversion != null) { if (operandType is PsiPrimitiveType && typeConversion != null) {
myResult = MethodCallExpression.build(getConverter().expressionToExpression(operand), typeConversion) myResult = MethodCallExpression.build(getConverter().expressionToExpression(operand), typeConversion)
} }
else { else {
myResult = TypeCastExpression(getConverter().typeToType(castType.getType()), myResult = TypeCastExpression(getConverter().typeToType(castType.getType()),
getConverter().expressionToExpression(operand)) getConverter().expressionToExpression(operand))
} }
} }
} }
public override fun visitPolyadicExpression(expression: PsiPolyadicExpression?): Unit { public override fun visitPolyadicExpression(expression: PsiPolyadicExpression?): Unit {
var parameters = ArrayList<Expression>() var parameters = ArrayList<Expression>()
for (operand : PsiExpression in expression?.getOperands()!!) { for (operand : PsiExpression in expression?.getOperands()!!) {
parameters.add(getConverter().expressionToExpression(operand, expression?.getType())) parameters.add(getConverter().expressionToExpression(operand, expression?.getType()))
} }
myResult = PolyadicExpression(parameters, getOperatorString(expression?.getOperationTokenType()!!)) myResult = PolyadicExpression(parameters, getOperatorString(expression?.getOperationTokenType()!!))
} }
class object { class object {
private fun getOperatorString(tokenType: IElementType): String { private fun getOperatorString(tokenType: IElementType): String {
if (tokenType == JavaTokenType.PLUS) if (tokenType == JavaTokenType.PLUS)
return "+" return "+"
if (tokenType == JavaTokenType.MINUS) if (tokenType == JavaTokenType.MINUS)
return "-" return "-"
if (tokenType == JavaTokenType.ASTERISK) if (tokenType == JavaTokenType.ASTERISK)
return "*" return "*"
if (tokenType == JavaTokenType.DIV) if (tokenType == JavaTokenType.DIV)
return "/" return "/"
if (tokenType == JavaTokenType.PERC) if (tokenType == JavaTokenType.PERC)
return "%" return "%"
if (tokenType == JavaTokenType.GTGT) if (tokenType == JavaTokenType.GTGT)
return "shr" return "shr"
if (tokenType == JavaTokenType.LTLT) if (tokenType == JavaTokenType.LTLT)
return "shl" return "shl"
if (tokenType == JavaTokenType.XOR) if (tokenType == JavaTokenType.XOR)
return "xor" return "xor"
if (tokenType == JavaTokenType.AND) if (tokenType == JavaTokenType.AND)
return "and" return "and"
if (tokenType == JavaTokenType.OR) if (tokenType == JavaTokenType.OR)
return "or" return "or"
if (tokenType == JavaTokenType.GTGTGT) if (tokenType == JavaTokenType.GTGTGT)
return "ushr" return "ushr"
if (tokenType == JavaTokenType.GT) if (tokenType == JavaTokenType.GT)
return ">" return ">"
if (tokenType == JavaTokenType.LT) if (tokenType == JavaTokenType.LT)
return "<" return "<"
if (tokenType == JavaTokenType.GE) if (tokenType == JavaTokenType.GE)
return ">=" return ">="
if (tokenType == JavaTokenType.LE) if (tokenType == JavaTokenType.LE)
return "<=" return "<="
if (tokenType == JavaTokenType.EQEQ) if (tokenType == JavaTokenType.EQEQ)
return "==" return "=="
if (tokenType == JavaTokenType.NE) if (tokenType == JavaTokenType.NE)
return "!=" return "!="
if (tokenType == JavaTokenType.ANDAND) if (tokenType == JavaTokenType.ANDAND)
return "&&" return "&&"
if (tokenType == JavaTokenType.OROR) if (tokenType == JavaTokenType.OROR)
return "||" return "||"
if (tokenType == JavaTokenType.PLUSPLUS) if (tokenType == JavaTokenType.PLUSPLUS)
return "++" return "++"
if (tokenType == JavaTokenType.MINUSMINUS) if (tokenType == JavaTokenType.MINUSMINUS)
return "--" return "--"
if (tokenType == JavaTokenType.EXCL) if (tokenType == JavaTokenType.EXCL)
return "!" return "!"
// System.out.println("UNSUPPORTED TOKEN TYPE: " + tokenType?.toString()) // System.out.println("UNSUPPORTED TOKEN TYPE: " + tokenType?.toString())
return "" return ""
} }
private fun getClassNameWithConstructor(expression: PsiReferenceExpression): String { private fun getClassNameWithConstructor(expression: PsiReferenceExpression): String {
var context: PsiElement? = expression.getContext() var context: PsiElement? = expression.getContext()
while (context != null) { while (context != null) {
if (context is PsiMethod && ((context as PsiMethod)).isConstructor()) { if (context is PsiMethod && ((context as PsiMethod)).isConstructor()) {
val containingClass: PsiClass? = ((context as PsiMethod)).getContainingClass() val containingClass: PsiClass? = ((context as PsiMethod)).getContainingClass()
if (containingClass != null) { if (containingClass != null) {
val identifier: PsiIdentifier? = containingClass.getNameIdentifier() val identifier: PsiIdentifier? = containingClass.getNameIdentifier()
if (identifier != null) { if (identifier != null) {
return identifier.getText()!! return identifier.getText()!!
} }
} }
} }
context = context?.getContext() context = context?.getContext()
} }
return "" return ""
} }
open fun getClassName(expression: PsiExpression): String { open fun getClassName(expression: PsiExpression): String {
var context: PsiElement? = expression.getContext() var context: PsiElement? = expression.getContext()
while (context != null) while (context != null)
{ {
if ((context is PsiClass?)) { if ((context is PsiClass?)) {
val containingClass: PsiClass? = (context as PsiClass?) val containingClass: PsiClass? = (context as PsiClass?)
val identifier: PsiIdentifier? = containingClass?.getNameIdentifier() val identifier: PsiIdentifier? = containingClass?.getNameIdentifier()
if (identifier != null) { if (identifier != null) {
return identifier.getText()!! return identifier.getText()!!
} }
} }
context = context?.getContext() context = context?.getContext()
} }
return "" return ""
} }
private fun isFieldReference(expression: PsiReferenceExpression, currentClass: PsiClass?): Boolean { private fun isFieldReference(expression: PsiReferenceExpression, currentClass: PsiClass?): Boolean {
val reference: PsiReference? = expression.getReference() val reference: PsiReference? = expression.getReference()
if (reference != null) { if (reference != null) {
val resolvedReference: PsiElement? = reference.resolve() val resolvedReference: PsiElement? = reference.resolve()
if (resolvedReference is PsiField) { if (resolvedReference is PsiField) {
return (resolvedReference as PsiField).getContainingClass() == currentClass return (resolvedReference as PsiField).getContainingClass() == currentClass
} }
} }
return false return false
} }
private fun isInsideSecondaryConstructor(expression: PsiReferenceExpression): Boolean { private fun isInsideSecondaryConstructor(expression: PsiReferenceExpression): Boolean {
var context: PsiElement? = expression.getContext() var context: PsiElement? = expression.getContext()
while (context != null) { while (context != null) {
if (context is PsiMethod && (context as PsiMethod).isConstructor()) { if (context is PsiMethod && (context as PsiMethod).isConstructor()) {
return !Converter.isConstructorPrimary((context as PsiMethod)) return !Converter.isConstructorPrimary((context as PsiMethod))
} }
context = context?.getContext() context = context?.getContext()
} }
return false return false
} }
private fun isInsidePrimaryConstructor(expression: PsiExpression): Boolean { private fun isInsidePrimaryConstructor(expression: PsiExpression): Boolean {
var context: PsiElement? = expression.getContext() var context: PsiElement? = expression.getContext()
while (context != null) { while (context != null) {
if (context is PsiMethod && (context as PsiMethod).isConstructor()) { if (context is PsiMethod && (context as PsiMethod).isConstructor()) {
return Converter.isConstructorPrimary(context as PsiMethod) return Converter.isConstructorPrimary(context as PsiMethod)
} }
context = context?.getContext() context = context?.getContext()
} }
return false return false
} }
private fun getContainingClass(expression: PsiExpression): PsiClass? { private fun getContainingClass(expression: PsiExpression): PsiClass? {
var context: PsiElement? = expression.getContext() var context: PsiElement? = expression.getContext()
while (context != null) while (context != null)
{ {
if (context is PsiMethod && (context as PsiMethod).isConstructor()) if (context is PsiMethod && (context as PsiMethod).isConstructor())
{ {
return (context as PsiMethod).getContainingClass() return (context as PsiMethod).getContainingClass()
} }
context = context?.getContext() context = context?.getContext()
} }
return null return null
} }
private fun isThisExpression(expression: PsiReferenceExpression): Boolean { private fun isThisExpression(expression: PsiReferenceExpression): Boolean {
for (r : PsiReference? in expression.getReferences()) for (r : PsiReference? in expression.getReferences())
if (r?.getCanonicalText()?.equals("this")!!) if (r?.getCanonicalText()?.equals("this")!!)
{ {
val res: PsiElement? = r?.resolve() val res: PsiElement? = r?.resolve()
if (res is PsiMethod && res.isConstructor()) { if (res is PsiMethod && res.isConstructor()) {
return true return true
} }
} }
return false return false
} }
} }
} }
private fun isStaticallyImported(member: PsiMember, context: PsiElement): Boolean { private fun isStaticallyImported(member: PsiMember, context: PsiElement): Boolean {
val containingFile = context.getContainingFile() val containingFile = context.getContainingFile()
val targetContainingClass = member.getContainingClass() val targetContainingClass = member.getContainingClass()
if (containingFile is PsiJavaFile && targetContainingClass != null) { if (containingFile is PsiJavaFile && targetContainingClass != null) {
val importList = containingFile.getImportList(); val importList = containingFile.getImportList();
if (importList != null) { if (importList != null) {
val importStatics = importList.getImportStaticStatements(); val importStatics = importList.getImportStaticStatements();
return importStatics.any { importResolvesTo(it, member) } return importStatics.any { importResolvesTo(it, member) }
} }
} }
return false return false
} }
private fun importResolvesTo(stmt: PsiImportStaticStatement?, member: PsiMember): Boolean { private fun importResolvesTo(stmt: PsiImportStaticStatement?, member: PsiMember): Boolean {
val targetContainingClass = member.getContainingClass() val targetContainingClass = member.getContainingClass()
var importedClass = stmt?.resolveTargetClass() var importedClass = stmt?.resolveTargetClass()
return importedClass == targetContainingClass && (stmt?.isOnDemand() ?: false || return importedClass == targetContainingClass && (stmt?.isOnDemand() ?: false ||
stmt?.getReferenceName() == member.getName()) stmt?.getReferenceName() == member.getName())
} }
@@ -1,41 +1,41 @@
package org.jetbrains.jet.j2k.visitors package org.jetbrains.jet.j2k.visitors
import com.intellij.psi.* import com.intellij.psi.*
import org.jetbrains.jet.j2k.Converter import org.jetbrains.jet.j2k.Converter
import org.jetbrains.jet.j2k.ast.DummyStringExpression import org.jetbrains.jet.j2k.ast.DummyStringExpression
import org.jetbrains.jet.j2k.ast.Identifier import org.jetbrains.jet.j2k.ast.Identifier
import com.intellij.psi.CommonClassNames.JAVA_LANG_OBJECT import com.intellij.psi.CommonClassNames.JAVA_LANG_OBJECT
import org.jetbrains.jet.j2k.ast.MethodCallExpression import org.jetbrains.jet.j2k.ast.MethodCallExpression
public open class ExpressionVisitorForDirectObjectInheritors(converter: Converter): ExpressionVisitor(converter) { public open class ExpressionVisitorForDirectObjectInheritors(converter: Converter): ExpressionVisitor(converter) {
public override fun visitMethodCallExpression(expression: PsiMethodCallExpression?): Unit { public override fun visitMethodCallExpression(expression: PsiMethodCallExpression?): Unit {
val methodExpression = expression?.getMethodExpression()!! val methodExpression = expression?.getMethodExpression()!!
if (superMethodInvocation(methodExpression, "hashCode")) { if (superMethodInvocation(methodExpression, "hashCode")) {
myResult = MethodCallExpression.build(Identifier("System", false), "identityHashCode", arrayList(Identifier("this"))) myResult = MethodCallExpression.build(Identifier("System", false), "identityHashCode", arrayList(Identifier("this")))
} }
else if (superMethodInvocation(methodExpression, "equals")) { else if (superMethodInvocation(methodExpression, "equals")) {
myResult = MethodCallExpression.build(Identifier("this", false), "identityEquals", getConverter().argumentsToExpressionList(expression!!)) myResult = MethodCallExpression.build(Identifier("this", false), "identityEquals", getConverter().argumentsToExpressionList(expression!!))
} }
else if (superMethodInvocation(methodExpression, "toString")) { else if (superMethodInvocation(methodExpression, "toString")) {
myResult = DummyStringExpression(java.lang.String.format("getJavaClass<%s>.getName() + '@' + Integer.toHexString(hashCode())", myResult = DummyStringExpression(java.lang.String.format("getJavaClass<%s>.getName() + '@' + Integer.toHexString(hashCode())",
ExpressionVisitor.getClassName(methodExpression))!!) ExpressionVisitor.getClassName(methodExpression))!!)
} }
else { else {
convertMethodCallExpression(expression!!) convertMethodCallExpression(expression!!)
} }
} }
class object { class object {
private fun superMethodInvocation(expression: PsiReferenceExpression, methodName: String?): Boolean { private fun superMethodInvocation(expression: PsiReferenceExpression, methodName: String?): Boolean {
val referenceName: String? = expression.getReferenceName() val referenceName: String? = expression.getReferenceName()
val qualifierExpression: PsiExpression? = expression.getQualifierExpression() val qualifierExpression: PsiExpression? = expression.getQualifierExpression()
if (referenceName == methodName && qualifierExpression is PsiSuperExpression) { if (referenceName == methodName && qualifierExpression is PsiSuperExpression) {
val `type`: PsiType? = qualifierExpression.getType() val `type`: PsiType? = qualifierExpression.getType()
if (`type` != null && `type`.getCanonicalText() == JAVA_LANG_OBJECT) { if (`type` != null && `type`.getCanonicalText() == JAVA_LANG_OBJECT) {
return true return true
} }
} }
return false return false
} }
} }
} }
@@ -1,266 +1,266 @@
package org.jetbrains.jet.j2k.visitors package org.jetbrains.jet.j2k.visitors
import com.intellij.psi.* import com.intellij.psi.*
import com.intellij.psi.tree.IElementType import com.intellij.psi.tree.IElementType
import org.jetbrains.annotations.Nullable import org.jetbrains.annotations.Nullable
import org.jetbrains.jet.j2k.Converter import org.jetbrains.jet.j2k.Converter
import org.jetbrains.jet.j2k.ast.* import org.jetbrains.jet.j2k.ast.*
import java.util.Arrays import java.util.Arrays
import java.util.Collections import java.util.Collections
import java.util.LinkedList import java.util.LinkedList
import org.jetbrains.jet.j2k.countWritingAccesses import org.jetbrains.jet.j2k.countWritingAccesses
import java.util.ArrayList import java.util.ArrayList
public open class StatementVisitor(converter: Converter): ElementVisitor(converter) { public open class StatementVisitor(converter: Converter): ElementVisitor(converter) {
public override fun visitAssertStatement(statement: PsiAssertStatement?): Unit { public override fun visitAssertStatement(statement: PsiAssertStatement?): Unit {
myResult = AssertStatement(getConverter().expressionToExpression(statement?.getAssertCondition()), myResult = AssertStatement(getConverter().expressionToExpression(statement?.getAssertCondition()),
getConverter().expressionToExpression(statement?.getAssertDescription())) getConverter().expressionToExpression(statement?.getAssertDescription()))
} }
public override fun visitBlockStatement(statement: PsiBlockStatement?): Unit { public override fun visitBlockStatement(statement: PsiBlockStatement?): Unit {
myResult = myConverter.blockToBlock(statement?.getCodeBlock(), true) myResult = myConverter.blockToBlock(statement?.getCodeBlock(), true)
} }
public override fun visitBreakStatement(statement: PsiBreakStatement?): Unit { public override fun visitBreakStatement(statement: PsiBreakStatement?): Unit {
if (statement?.getLabelIdentifier() == null) { if (statement?.getLabelIdentifier() == null) {
myResult = BreakStatement(Identifier.EMPTY_IDENTIFIER) myResult = BreakStatement(Identifier.EMPTY_IDENTIFIER)
} }
else else
{ {
myResult = BreakStatement(Converter.identifierToIdentifier(statement?.getLabelIdentifier())) myResult = BreakStatement(Converter.identifierToIdentifier(statement?.getLabelIdentifier()))
} }
} }
public override fun visitContinueStatement(statement: PsiContinueStatement?): Unit { public override fun visitContinueStatement(statement: PsiContinueStatement?): Unit {
if (statement?.getLabelIdentifier() == null) if (statement?.getLabelIdentifier() == null)
{ {
myResult = ContinueStatement(Identifier.EMPTY_IDENTIFIER) myResult = ContinueStatement(Identifier.EMPTY_IDENTIFIER)
} }
else else
{ {
myResult = ContinueStatement(Converter.identifierToIdentifier(statement?.getLabelIdentifier())) myResult = ContinueStatement(Converter.identifierToIdentifier(statement?.getLabelIdentifier()))
} }
} }
public override fun visitDeclarationStatement(statement: PsiDeclarationStatement?): Unit { public override fun visitDeclarationStatement(statement: PsiDeclarationStatement?): Unit {
myResult = DeclarationStatement(getConverter().elementsToElementList(statement?.getDeclaredElements()!!)) myResult = DeclarationStatement(getConverter().elementsToElementList(statement?.getDeclaredElements()!!))
} }
public override fun visitDoWhileStatement(statement: PsiDoWhileStatement?): Unit { public override fun visitDoWhileStatement(statement: PsiDoWhileStatement?): Unit {
val condition: PsiExpression? = statement?.getCondition() val condition: PsiExpression? = statement?.getCondition()
val expression: Expression = (if (condition != null && condition.getType() != null) val expression: Expression = (if (condition != null && condition.getType() != null)
getConverter().expressionToExpression(condition, condition.getType()) getConverter().expressionToExpression(condition, condition.getType())
else else
getConverter().expressionToExpression(condition)) getConverter().expressionToExpression(condition))
myResult = DoWhileStatement(expression, getConverter().statementToStatement(statement?.getBody())) myResult = DoWhileStatement(expression, getConverter().statementToStatement(statement?.getBody()))
} }
public override fun visitExpressionStatement(statement: PsiExpressionStatement?): Unit { public override fun visitExpressionStatement(statement: PsiExpressionStatement?): Unit {
myResult = getConverter().expressionToExpression(statement?.getExpression()) myResult = getConverter().expressionToExpression(statement?.getExpression())
} }
public override fun visitExpressionListStatement(statement: PsiExpressionListStatement?): Unit { public override fun visitExpressionListStatement(statement: PsiExpressionListStatement?): Unit {
myResult = ExpressionListStatement(getConverter().expressionsToExpressionList( myResult = ExpressionListStatement(getConverter().expressionsToExpressionList(
statement?.getExpressionList()?.getExpressions()!!)) statement?.getExpressionList()?.getExpressions()!!))
} }
public override fun visitForStatement(statement: PsiForStatement?): Unit { public override fun visitForStatement(statement: PsiForStatement?): Unit {
val initialization: PsiStatement? = statement?.getInitialization() val initialization: PsiStatement? = statement?.getInitialization()
val update: PsiStatement? = statement?.getUpdate() val update: PsiStatement? = statement?.getUpdate()
val condition: PsiExpression? = statement?.getCondition() val condition: PsiExpression? = statement?.getCondition()
val body: PsiStatement? = statement?.getBody() val body: PsiStatement? = statement?.getBody()
val firstChild: PsiLocalVariable? = (if (initialization != null && (initialization.getFirstChild() is PsiLocalVariable)) val firstChild: PsiLocalVariable? = (if (initialization != null && (initialization.getFirstChild() is PsiLocalVariable))
(initialization.getFirstChild() as PsiLocalVariable) (initialization.getFirstChild() as PsiLocalVariable)
else else
null) null)
var bodyWriteCount: Int = countWritingAccesses(firstChild, body) var bodyWriteCount: Int = countWritingAccesses(firstChild, body)
var conditionWriteCount: Int = countWritingAccesses(firstChild, condition) var conditionWriteCount: Int = countWritingAccesses(firstChild, condition)
var updateWriteCount: Int = countWritingAccesses(firstChild, update) var updateWriteCount: Int = countWritingAccesses(firstChild, update)
val onceWritableIterator: Boolean = updateWriteCount == 1 && bodyWriteCount + conditionWriteCount == 0 val onceWritableIterator: Boolean = updateWriteCount == 1 && bodyWriteCount + conditionWriteCount == 0
val operationTokenType: IElementType? = (if (condition is PsiBinaryExpression) val operationTokenType: IElementType? = (if (condition is PsiBinaryExpression)
condition.getOperationTokenType() condition.getOperationTokenType()
else else
null) null)
if (initialization is PsiDeclarationStatement && initialization.getFirstChild() == initialization.getLastChild() && if (initialization is PsiDeclarationStatement && initialization.getFirstChild() == initialization.getLastChild() &&
condition != null && update != null && update.getChildren().size == 1 && condition != null && update != null && update.getChildren().size == 1 &&
(isPlusPlusExpression(update.getChildren()[0]!!)) && (operationTokenType == JavaTokenType.LT || operationTokenType == JavaTokenType.LE) && (isPlusPlusExpression(update.getChildren()[0]!!)) && (operationTokenType == JavaTokenType.LT || operationTokenType == JavaTokenType.LE) &&
initialization.getFirstChild() != null && (initialization.getFirstChild() is PsiLocalVariable) && initialization.getFirstChild() != null && (initialization.getFirstChild() is PsiLocalVariable) &&
firstChild != null && firstChild.getNameIdentifier() != null && onceWritableIterator) { firstChild != null && firstChild.getNameIdentifier() != null && onceWritableIterator) {
val end: Expression = getConverter().expressionToExpression((condition as PsiBinaryExpression).getROperand()) val end: Expression = getConverter().expressionToExpression((condition as PsiBinaryExpression).getROperand())
val endExpression: Expression = (if (operationTokenType == JavaTokenType.LT) val endExpression: Expression = (if (operationTokenType == JavaTokenType.LT)
BinaryExpression(end, Identifier("1"), "-") BinaryExpression(end, Identifier("1"), "-")
else else
end) end)
myResult = ForeachWithRangeStatement(Identifier(firstChild.getName()!!), myResult = ForeachWithRangeStatement(Identifier(firstChild.getName()!!),
getConverter().expressionToExpression(firstChild.getInitializer()), getConverter().expressionToExpression(firstChild.getInitializer()),
endExpression, endExpression,
getConverter().statementToStatement(body)) getConverter().statementToStatement(body))
} }
else { else {
var forStatements = ArrayList<Element>() var forStatements = ArrayList<Element>()
forStatements.add(getConverter().statementToStatement(initialization)) forStatements.add(getConverter().statementToStatement(initialization))
forStatements.add(WhileStatement(getConverter().expressionToExpression(condition), forStatements.add(WhileStatement(getConverter().expressionToExpression(condition),
Block(arrayList(getConverter().statementToStatement(body), Block(arrayList(getConverter().statementToStatement(body),
Block(arrayList(getConverter().statementToStatement(update)), false)), false))) Block(arrayList(getConverter().statementToStatement(update)), false)), false)))
myResult = Block(forStatements, false) myResult = Block(forStatements, false)
} }
} }
public override fun visitForeachStatement(statement: PsiForeachStatement?): Unit { public override fun visitForeachStatement(statement: PsiForeachStatement?): Unit {
myResult = ForeachStatement(getConverter().parameterToParameter(statement?.getIterationParameter()!!), myResult = ForeachStatement(getConverter().parameterToParameter(statement?.getIterationParameter()!!),
getConverter().expressionToExpression(statement?.getIteratedValue()), getConverter().expressionToExpression(statement?.getIteratedValue()),
getConverter().statementToStatement(statement?.getBody())) getConverter().statementToStatement(statement?.getBody()))
} }
public override fun visitIfStatement(statement: PsiIfStatement?): Unit { public override fun visitIfStatement(statement: PsiIfStatement?): Unit {
val condition: PsiExpression? = statement?.getCondition() val condition: PsiExpression? = statement?.getCondition()
val expression: Expression = getConverter().expressionToExpression(condition, PsiType.BOOLEAN) val expression: Expression = getConverter().expressionToExpression(condition, PsiType.BOOLEAN)
myResult = IfStatement(expression, myResult = IfStatement(expression,
getConverter().statementToStatement(statement?.getThenBranch()), getConverter().statementToStatement(statement?.getThenBranch()),
getConverter().statementToStatement(statement?.getElseBranch())) getConverter().statementToStatement(statement?.getElseBranch()))
} }
public override fun visitLabeledStatement(statement: PsiLabeledStatement?): Unit { public override fun visitLabeledStatement(statement: PsiLabeledStatement?): Unit {
myResult = LabelStatement(Converter.identifierToIdentifier(statement?.getLabelIdentifier()), myResult = LabelStatement(Converter.identifierToIdentifier(statement?.getLabelIdentifier()),
getConverter().statementToStatement(statement?.getStatement())) getConverter().statementToStatement(statement?.getStatement()))
} }
public override fun visitSwitchLabelStatement(statement: PsiSwitchLabelStatement?): Unit { public override fun visitSwitchLabelStatement(statement: PsiSwitchLabelStatement?): Unit {
myResult = (if (statement?.isDefaultCase()!!) myResult = (if (statement?.isDefaultCase()!!)
DefaultSwitchLabelStatement() DefaultSwitchLabelStatement()
else else
SwitchLabelStatement(getConverter().expressionToExpression(statement?.getCaseValue()))) SwitchLabelStatement(getConverter().expressionToExpression(statement?.getCaseValue())))
} }
public override fun visitSwitchStatement(statement: PsiSwitchStatement?): Unit { public override fun visitSwitchStatement(statement: PsiSwitchStatement?): Unit {
myResult = SwitchContainer(getConverter().expressionToExpression(statement?.getExpression()), myResult = SwitchContainer(getConverter().expressionToExpression(statement?.getExpression()),
switchBodyToCases(statement?.getBody())) switchBodyToCases(statement?.getBody()))
} }
private open fun switchBodyToCases(body: PsiCodeBlock?): List<CaseContainer> { private open fun switchBodyToCases(body: PsiCodeBlock?): List<CaseContainer> {
val cases: List<List<PsiElement>> = splitToCases(body) val cases: List<List<PsiElement>> = splitToCases(body)
val allSwitchStatements = ArrayList<PsiElement>() val allSwitchStatements = ArrayList<PsiElement>()
if (body != null) { if (body != null) {
// TODO Arrays.asList() // TODO Arrays.asList()
for(s in body.getStatements()) allSwitchStatements.add(s) for(s in body.getStatements()) allSwitchStatements.add(s)
} }
val result = ArrayList<CaseContainer>() val result = ArrayList<CaseContainer>()
var pendingLabels = ArrayList<Element>() var pendingLabels = ArrayList<Element>()
var i: Int = 0 var i: Int = 0
for (ls in cases) { for (ls in cases) {
// TODO assert {(ls?.size()).sure() > 0} // TODO assert {(ls?.size()).sure() > 0}
var label = ls[0] var label = ls[0]
// TODO assert {(label is PsiSwitchLabelStatement?)} // TODO assert {(label is PsiSwitchLabelStatement?)}
// TODO assert("not a right index") {allSwitchStatements?.get(i) == label} // TODO assert("not a right index") {allSwitchStatements?.get(i) == label}
if (ls.size() > 1) { if (ls.size() > 1) {
pendingLabels.add(getConverter().statementToStatement(label)) pendingLabels.add(getConverter().statementToStatement(label))
val slice: List<PsiElement> = ls.subList(1, (ls.size())) val slice: List<PsiElement> = ls.subList(1, (ls.size()))
if (!containsBreak(slice)) { if (!containsBreak(slice)) {
val statements = ArrayList(getConverter().statementsToStatementList(slice)) val statements = ArrayList(getConverter().statementsToStatementList(slice))
statements.addAll(getConverter().statementsToStatementList(getAllToNextBreak(allSwitchStatements, i + ls.size()))) statements.addAll(getConverter().statementsToStatementList(getAllToNextBreak(allSwitchStatements, i + ls.size())))
result.add(CaseContainer(pendingLabels, statements)) result.add(CaseContainer(pendingLabels, statements))
pendingLabels = arrayList() pendingLabels = arrayList()
} }
else { else {
result.add(CaseContainer(pendingLabels, getConverter().statementsToStatementList(slice))) result.add(CaseContainer(pendingLabels, getConverter().statementsToStatementList(slice)))
pendingLabels = arrayList() pendingLabels = arrayList()
} }
} }
else { else {
pendingLabels.add(getConverter().statementToStatement(label)) pendingLabels.add(getConverter().statementToStatement(label))
} }
i += ls.size() i += ls.size()
} }
return result return result
} }
public override fun visitSynchronizedStatement(statement: PsiSynchronizedStatement?): Unit { public override fun visitSynchronizedStatement(statement: PsiSynchronizedStatement?): Unit {
myResult = SynchronizedStatement(getConverter().expressionToExpression(statement?.getLockExpression()), myResult = SynchronizedStatement(getConverter().expressionToExpression(statement?.getLockExpression()),
getConverter().blockToBlock(statement?.getBody())) getConverter().blockToBlock(statement?.getBody()))
} }
public override fun visitThrowStatement(statement: PsiThrowStatement?): Unit { public override fun visitThrowStatement(statement: PsiThrowStatement?): Unit {
myResult = ThrowStatement(getConverter().expressionToExpression(statement?.getException())) myResult = ThrowStatement(getConverter().expressionToExpression(statement?.getException()))
} }
public override fun visitTryStatement(statement: PsiTryStatement?): Unit { public override fun visitTryStatement(statement: PsiTryStatement?): Unit {
val catches = ArrayList<CatchStatement>() val catches = ArrayList<CatchStatement>()
val catchBlocks = statement?.getCatchBlocks()!! val catchBlocks = statement?.getCatchBlocks()!!
val catchBlockParameters = statement?.getCatchBlockParameters()!! val catchBlockParameters = statement?.getCatchBlockParameters()!!
for (i in 0..catchBlocks.size - 1) { for (i in 0..catchBlocks.size - 1) {
catches.add(CatchStatement(getConverter().parameterToParameter(catchBlockParameters[i]!!, true), catches.add(CatchStatement(getConverter().parameterToParameter(catchBlockParameters[i]!!, true),
getConverter().blockToBlock(catchBlocks[i], true))) getConverter().blockToBlock(catchBlocks[i], true)))
} }
myResult = TryStatement(getConverter().blockToBlock(statement?.getTryBlock(), true), myResult = TryStatement(getConverter().blockToBlock(statement?.getTryBlock(), true),
catches, getConverter().blockToBlock(statement?.getFinallyBlock(), true)) catches, getConverter().blockToBlock(statement?.getFinallyBlock(), true))
} }
public override fun visitWhileStatement(statement: PsiWhileStatement?): Unit { public override fun visitWhileStatement(statement: PsiWhileStatement?): Unit {
var condition: PsiExpression? = statement?.getCondition() var condition: PsiExpression? = statement?.getCondition()
val expression: Expression = (if (condition != null && condition?.getType() != null) val expression: Expression = (if (condition != null && condition?.getType() != null)
this.getConverter().expressionToExpression(condition, condition?.getType()) this.getConverter().expressionToExpression(condition, condition?.getType())
else else
getConverter().expressionToExpression(condition)) getConverter().expressionToExpression(condition))
myResult = WhileStatement(expression, getConverter().statementToStatement(statement?.getBody())) myResult = WhileStatement(expression, getConverter().statementToStatement(statement?.getBody()))
} }
public override fun visitReturnStatement(statement: PsiReturnStatement?): Unit { public override fun visitReturnStatement(statement: PsiReturnStatement?): Unit {
val returnValue: PsiExpression? = statement?.getReturnValue() val returnValue: PsiExpression? = statement?.getReturnValue()
val methodReturnType: PsiType? = getConverter().getMethodReturnType() val methodReturnType: PsiType? = getConverter().getMethodReturnType()
val expression: Expression = (if (returnValue != null && methodReturnType != null) val expression: Expression = (if (returnValue != null && methodReturnType != null)
this.getConverter().expressionToExpression(returnValue, methodReturnType) this.getConverter().expressionToExpression(returnValue, methodReturnType)
else else
getConverter().expressionToExpression(returnValue)) getConverter().expressionToExpression(returnValue))
myResult = ReturnStatement(expression) myResult = ReturnStatement(expression)
} }
class object { class object {
private open fun isPlusPlusExpression(psiElement: PsiElement): Boolean { private open fun isPlusPlusExpression(psiElement: PsiElement): Boolean {
return (psiElement is PsiPostfixExpression && psiElement.getOperationTokenType() == JavaTokenType.PLUSPLUS) || return (psiElement is PsiPostfixExpression && psiElement.getOperationTokenType() == JavaTokenType.PLUSPLUS) ||
(psiElement is PsiPrefixExpression && psiElement.getOperationTokenType() == JavaTokenType.PLUSPLUS) (psiElement is PsiPrefixExpression && psiElement.getOperationTokenType() == JavaTokenType.PLUSPLUS)
} }
private fun containsBreak(slice: List<PsiElement?>) = slice.any { it is PsiBreakStatement } private fun containsBreak(slice: List<PsiElement?>) = slice.any { it is PsiBreakStatement }
private open fun getAllToNextBreak(allStatements: List<PsiElement>, start: Int): List<PsiElement> { private open fun getAllToNextBreak(allStatements: List<PsiElement>, start: Int): List<PsiElement> {
val result = ArrayList<PsiElement>() val result = ArrayList<PsiElement>()
for (i in start..allStatements.size() - 1) { for (i in start..allStatements.size() - 1) {
val s = allStatements.get(i) val s = allStatements.get(i)
if (s is PsiBreakStatement || s is PsiReturnStatement) { if (s is PsiBreakStatement || s is PsiReturnStatement) {
return result return result
} }
if (!(s is PsiSwitchLabelStatement)) { if (!(s is PsiSwitchLabelStatement)) {
result.add(s) result.add(s)
} }
} }
return result return result
} }
private open fun splitToCases(body: PsiCodeBlock?): List<List<PsiElement>> { private open fun splitToCases(body: PsiCodeBlock?): List<List<PsiElement>> {
val cases = ArrayList<List<PsiElement>>() val cases = ArrayList<List<PsiElement>>()
var currentCaseStatements = ArrayList<PsiElement>() var currentCaseStatements = ArrayList<PsiElement>()
var isFirst: Boolean = true var isFirst: Boolean = true
if (body != null) { if (body != null) {
for (s in body.getChildren()) { for (s in body.getChildren()) {
if (s !is PsiStatement && s !is PsiComment) continue if (s !is PsiStatement && s !is PsiComment) continue
if (s is PsiSwitchLabelStatement) { if (s is PsiSwitchLabelStatement) {
if (isFirst) { if (isFirst) {
isFirst = false isFirst = false
} }
else { else {
cases.add(currentCaseStatements) cases.add(currentCaseStatements)
currentCaseStatements = arrayList() currentCaseStatements = arrayList()
} }
} }
currentCaseStatements.add(s) currentCaseStatements.add(s)
} }
cases.add(currentCaseStatements) cases.add(currentCaseStatements)
} }
return cases return cases
} }
} }
} }
@@ -1,26 +1,26 @@
package org.jetbrains.jet.j2k.visitors package org.jetbrains.jet.j2k.visitors
import com.intellij.psi.* import com.intellij.psi.*
import java.util.HashSet import java.util.HashSet
public open class SuperVisitor(): JavaRecursiveElementVisitor() { public open class SuperVisitor(): JavaRecursiveElementVisitor() {
public val resolvedSuperCallParameters: HashSet<PsiExpressionList> = hashSet() public val resolvedSuperCallParameters: HashSet<PsiExpressionList> = hashSet()
public override fun visitMethodCallExpression(expression: PsiMethodCallExpression?): Unit { public override fun visitMethodCallExpression(expression: PsiMethodCallExpression?): Unit {
if (expression != null && isSuper(expression.getMethodExpression())) { if (expression != null && isSuper(expression.getMethodExpression())) {
resolvedSuperCallParameters.add(expression.getArgumentList()) resolvedSuperCallParameters.add(expression.getArgumentList())
} }
} }
class object { class object {
open fun isSuper(r: PsiReference): Boolean { open fun isSuper(r: PsiReference): Boolean {
if (r.getCanonicalText().equals("super")) { if (r.getCanonicalText().equals("super")) {
val baseConstructor: PsiElement? = r.resolve() val baseConstructor: PsiElement? = r.resolve()
if (baseConstructor != null && baseConstructor is PsiMethod && baseConstructor.isConstructor()) { if (baseConstructor != null && baseConstructor is PsiMethod && baseConstructor.isConstructor()) {
return true return true
} }
} }
return false return false
} }
} }
} }
@@ -1,33 +1,33 @@
package org.jetbrains.jet.j2k.visitors package org.jetbrains.jet.j2k.visitors
import com.intellij.psi.* import com.intellij.psi.*
import org.jetbrains.annotations.Nullable import org.jetbrains.annotations.Nullable
import java.util.LinkedHashSet import java.util.LinkedHashSet
public open class ThisVisitor(): JavaRecursiveElementVisitor() { public open class ThisVisitor(): JavaRecursiveElementVisitor() {
private val myResolvedConstructors = LinkedHashSet<PsiMethod>() private val myResolvedConstructors = LinkedHashSet<PsiMethod>()
public override fun visitReferenceExpression(expression: PsiReferenceExpression?): Unit { public override fun visitReferenceExpression(expression: PsiReferenceExpression?): Unit {
for (r : PsiReference? in expression?.getReferences()!!) { for (r : PsiReference? in expression?.getReferences()!!) {
if (r?.getCanonicalText() == "this") { if (r?.getCanonicalText() == "this") {
val res: PsiElement? = r?.resolve() val res: PsiElement? = r?.resolve()
if (res is PsiMethod && res.isConstructor()) { if (res is PsiMethod && res.isConstructor()) {
myResolvedConstructors.add(res) myResolvedConstructors.add(res)
} }
} }
} }
} }
public open fun getPrimaryConstructor(): PsiMethod? { public open fun getPrimaryConstructor(): PsiMethod? {
if (myResolvedConstructors.size() > 0) { if (myResolvedConstructors.size() > 0) {
val first: PsiMethod = myResolvedConstructors.iterator().next() val first: PsiMethod = myResolvedConstructors.iterator().next()
for (m in myResolvedConstructors) for (m in myResolvedConstructors)
if (m.hashCode() != first.hashCode()) { if (m.hashCode() != first.hashCode()) {
return null return null
} }
return first return first
} }
return null return null
} }
} }
+162 -162
View File
@@ -1,162 +1,162 @@
package org.jetbrains.jet.j2k.visitors package org.jetbrains.jet.j2k.visitors
import com.intellij.psi.* import com.intellij.psi.*
import com.intellij.psi.impl.source.PsiClassReferenceType import com.intellij.psi.impl.source.PsiClassReferenceType
import org.jetbrains.jet.j2k.Converter import org.jetbrains.jet.j2k.Converter
import org.jetbrains.jet.j2k.J2KConverterFlags import org.jetbrains.jet.j2k.J2KConverterFlags
import org.jetbrains.jet.j2k.ast.* import org.jetbrains.jet.j2k.ast.*
import org.jetbrains.jet.j2k.ast.types.* import org.jetbrains.jet.j2k.ast.types.*
import java.util.LinkedList import java.util.LinkedList
import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.util.text.StringUtil
public open class TypeVisitor(private val myConverter : Converter) : PsiTypeVisitor<Type>() { public open class TypeVisitor(private val myConverter : Converter) : PsiTypeVisitor<Type>() {
private var myResult : Type = EmptyType() private var myResult : Type = EmptyType()
public open fun getResult() : Type { public open fun getResult() : Type {
return myResult return myResult
} }
public override fun visitPrimitiveType(primitiveType: PsiPrimitiveType?) : Type { public override fun visitPrimitiveType(primitiveType: PsiPrimitiveType?) : Type {
val name : String = primitiveType?.getCanonicalText()!! val name : String = primitiveType?.getCanonicalText()!!
if (name == "void") { if (name == "void") {
myResult = PrimitiveType(Identifier("Unit")) myResult = PrimitiveType(Identifier("Unit"))
} }
else if (Node.PRIMITIVE_TYPES.contains(name)) { else if (Node.PRIMITIVE_TYPES.contains(name)) {
myResult = PrimitiveType(Identifier(StringUtil.capitalize(name))) myResult = PrimitiveType(Identifier(StringUtil.capitalize(name)))
} }
else { else {
myResult = PrimitiveType(Identifier(name)) myResult = PrimitiveType(Identifier(name))
} }
return myResult return myResult
} }
public override fun visitArrayType(arrayType: PsiArrayType?) : Type { public override fun visitArrayType(arrayType: PsiArrayType?) : Type {
if (myResult is EmptyType) { if (myResult is EmptyType) {
myResult = ArrayType(myConverter.typeToType(arrayType?.getComponentType()), true) myResult = ArrayType(myConverter.typeToType(arrayType?.getComponentType()), true)
} }
return myResult return myResult
} }
public override fun visitClassType(classType : PsiClassType?) : Type { public override fun visitClassType(classType : PsiClassType?) : Type {
if (classType == null) return myResult if (classType == null) return myResult
val identifier : Identifier = constructClassTypeIdentifier(classType) val identifier : Identifier = constructClassTypeIdentifier(classType)
val resolvedClassTypeParams : List<Type> = createRawTypesForResolvedReference(classType) val resolvedClassTypeParams : List<Type> = createRawTypesForResolvedReference(classType)
if (classType.getParameterCount() == 0 && resolvedClassTypeParams.size() > 0) { if (classType.getParameterCount() == 0 && resolvedClassTypeParams.size() > 0) {
myResult = ClassType(identifier, resolvedClassTypeParams, true) myResult = ClassType(identifier, resolvedClassTypeParams, true)
} }
else { else {
myResult = ClassType(identifier, myConverter.typesToTypeList(classType.getParameters()), true) myResult = ClassType(identifier, myConverter.typesToTypeList(classType.getParameters()), true)
} }
return myResult return myResult
} }
private fun constructClassTypeIdentifier(classType : PsiClassType) : Identifier { private fun constructClassTypeIdentifier(classType : PsiClassType) : Identifier {
val psiClass : PsiClass? = classType.resolve() val psiClass : PsiClass? = classType.resolve()
if (psiClass != null) { if (psiClass != null) {
val qualifiedName: String? = psiClass.getQualifiedName() val qualifiedName: String? = psiClass.getQualifiedName()
if (qualifiedName != null) { if (qualifiedName != null) {
if (!qualifiedName.equals("java.lang.Object") && myConverter.hasFlag(J2KConverterFlags.FULLY_QUALIFIED_TYPE_NAMES)) { if (!qualifiedName.equals("java.lang.Object") && myConverter.hasFlag(J2KConverterFlags.FULLY_QUALIFIED_TYPE_NAMES)) {
return Identifier(qualifiedName) return Identifier(qualifiedName)
} }
if (qualifiedName.equals(CommonClassNames.JAVA_LANG_ITERABLE)) { if (qualifiedName.equals(CommonClassNames.JAVA_LANG_ITERABLE)) {
return Identifier(CommonClassNames.JAVA_LANG_ITERABLE) return Identifier(CommonClassNames.JAVA_LANG_ITERABLE)
} }
if (qualifiedName.equals(CommonClassNames.JAVA_UTIL_ITERATOR)) { if (qualifiedName.equals(CommonClassNames.JAVA_UTIL_ITERATOR)) {
return Identifier(CommonClassNames.JAVA_UTIL_ITERATOR) return Identifier(CommonClassNames.JAVA_UTIL_ITERATOR)
} }
} }
} }
val classTypeName = createQualifiedName(classType) val classTypeName = createQualifiedName(classType)
if (classTypeName.isEmpty()) { if (classTypeName.isEmpty()) {
return Identifier(getClassTypeName(classType)) return Identifier(getClassTypeName(classType))
} }
return Identifier(classTypeName) return Identifier(classTypeName)
} }
private fun createRawTypesForResolvedReference(classType : PsiClassType) : List<Type> { private fun createRawTypesForResolvedReference(classType : PsiClassType) : List<Type> {
val typeParams = LinkedList<Type>() val typeParams = LinkedList<Type>()
if (classType is PsiClassReferenceType) { if (classType is PsiClassReferenceType) {
val reference : PsiJavaCodeReferenceElement? = (classType as PsiClassReferenceType).getReference() val reference : PsiJavaCodeReferenceElement? = (classType as PsiClassReferenceType).getReference()
val resolve : PsiElement? = reference?.resolve() val resolve : PsiElement? = reference?.resolve()
if (resolve is PsiClass) { if (resolve is PsiClass) {
for (p : PsiTypeParameter? in (resolve as PsiClass).getTypeParameters()) { for (p : PsiTypeParameter? in (resolve as PsiClass).getTypeParameters()) {
val superTypes = p!!.getSuperTypes() val superTypes = p!!.getSuperTypes()
val boundType : Type = (if (superTypes.size > 0) val boundType : Type = (if (superTypes.size > 0)
ClassType(Identifier(getClassTypeName(superTypes[0]!!)), ClassType(Identifier(getClassTypeName(superTypes[0]!!)),
myConverter.typesToTypeList(superTypes[0]!!.getParameters()), myConverter.typesToTypeList(superTypes[0]!!.getParameters()),
true) true)
else else
StarProjectionType()) StarProjectionType())
typeParams.add(boundType) typeParams.add(boundType)
} }
} }
} }
return typeParams return typeParams
} }
public override fun visitWildcardType(wildcardType : PsiWildcardType?) : Type { public override fun visitWildcardType(wildcardType : PsiWildcardType?) : Type {
if (wildcardType!!.isExtends()) { if (wildcardType!!.isExtends()) {
myResult = OutProjectionType(myConverter.typeToType(wildcardType!!.getExtendsBound())) myResult = OutProjectionType(myConverter.typeToType(wildcardType!!.getExtendsBound()))
} }
else else
if (wildcardType!!.isSuper()) { if (wildcardType!!.isSuper()) {
myResult = InProjectionType(myConverter.typeToType(wildcardType?.getSuperBound())) myResult = InProjectionType(myConverter.typeToType(wildcardType?.getSuperBound()))
} }
else { else {
myResult = StarProjectionType() myResult = StarProjectionType()
} }
return myResult return myResult
} }
public override fun visitEllipsisType(ellipsisType : PsiEllipsisType?) : Type { public override fun visitEllipsisType(ellipsisType : PsiEllipsisType?) : Type {
myResult = VarArg(myConverter.typeToType(ellipsisType?.getComponentType())) myResult = VarArg(myConverter.typeToType(ellipsisType?.getComponentType()))
return myResult return myResult
} }
class object { class object {
private fun createQualifiedName(classType : PsiClassType) : String { private fun createQualifiedName(classType : PsiClassType) : String {
if (classType is PsiClassReferenceType) if (classType is PsiClassReferenceType)
{ {
val reference : PsiJavaCodeReferenceElement? = (classType as PsiClassReferenceType).getReference() val reference : PsiJavaCodeReferenceElement? = (classType as PsiClassReferenceType).getReference()
if (reference != null && reference.isQualified()) { if (reference != null && reference.isQualified()) {
var result : String = Identifier(reference.getReferenceName()!!).toKotlin() var result : String = Identifier(reference.getReferenceName()!!).toKotlin()
var qualifier : PsiElement? = reference.getQualifier() var qualifier : PsiElement? = reference.getQualifier()
while (qualifier != null) while (qualifier != null)
{ {
val p : PsiJavaCodeReferenceElement = (qualifier as PsiJavaCodeReferenceElement) val p : PsiJavaCodeReferenceElement = (qualifier as PsiJavaCodeReferenceElement)
result = Identifier(p.getReferenceName()!!).toKotlin() + "." + result result = Identifier(p.getReferenceName()!!).toKotlin() + "." + result
qualifier = p.getQualifier() qualifier = p.getQualifier()
} }
return result return result
} }
} }
return "" return ""
} }
private fun getClassTypeName(classType : PsiClassType) : String { private fun getClassTypeName(classType : PsiClassType) : String {
var canonicalTypeStr : String? = classType.getCanonicalText() var canonicalTypeStr : String? = classType.getCanonicalText()
return when(canonicalTypeStr) { return when(canonicalTypeStr) {
CommonClassNames.JAVA_LANG_OBJECT -> "Any" CommonClassNames.JAVA_LANG_OBJECT -> "Any"
CommonClassNames.JAVA_LANG_BYTE -> "Byte" CommonClassNames.JAVA_LANG_BYTE -> "Byte"
CommonClassNames.JAVA_LANG_CHARACTER -> "Char" CommonClassNames.JAVA_LANG_CHARACTER -> "Char"
CommonClassNames.JAVA_LANG_DOUBLE -> "Double" CommonClassNames.JAVA_LANG_DOUBLE -> "Double"
CommonClassNames.JAVA_LANG_FLOAT -> "Float" CommonClassNames.JAVA_LANG_FLOAT -> "Float"
CommonClassNames.JAVA_LANG_INTEGER -> "Int" CommonClassNames.JAVA_LANG_INTEGER -> "Int"
CommonClassNames.JAVA_LANG_LONG -> "Long" CommonClassNames.JAVA_LANG_LONG -> "Long"
CommonClassNames.JAVA_LANG_SHORT -> "Short" CommonClassNames.JAVA_LANG_SHORT -> "Short"
CommonClassNames.JAVA_LANG_BOOLEAN -> "Boolean" CommonClassNames.JAVA_LANG_BOOLEAN -> "Boolean"
else -> (if (classType.getClassName() != null) else -> (if (classType.getClassName() != null)
classType.getClassName()!! classType.getClassName()!!
else else
classType.getCanonicalText())!! classType.getCanonicalText())!!
} }
} }
} }
} }
@@ -1,178 +1,178 @@
/* /*
* Copyright 2010-2012 JetBrains s.r.o. * Copyright 2010-2012 JetBrains s.r.o.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.jetbrains.jet.j2k; package org.jetbrains.jet.j2k;
import com.intellij.core.JavaCoreProjectEnvironment; import com.intellij.core.JavaCoreProjectEnvironment;
import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiJavaFile; import com.intellij.psi.PsiJavaFile;
import junit.framework.Assert; import junit.framework.Assert;
import junit.framework.Test; import junit.framework.Test;
import junit.framework.TestCase; import junit.framework.TestCase;
import junit.framework.TestSuite; import junit.framework.TestSuite;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
/** /**
* @author ignatov * @author ignatov
*/ */
public class StandaloneJavaToKotlinConverterTest extends TestCase { public class StandaloneJavaToKotlinConverterTest extends TestCase {
private final String myDataPath; private final String myDataPath;
private final String myName; private final String myName;
@NotNull @NotNull
private final static JavaCoreProjectEnvironment myJavaCoreEnvironment = JavaToKotlinTranslator.setUpJavaCoreEnvironment(); private final static JavaCoreProjectEnvironment myJavaCoreEnvironment = JavaToKotlinTranslator.setUpJavaCoreEnvironment();
public StandaloneJavaToKotlinConverterTest(String dataPath, String name) { public StandaloneJavaToKotlinConverterTest(String dataPath, String name) {
myDataPath = dataPath; myDataPath = dataPath;
myName = name; myName = name;
} }
@Override @Override
protected void runTest() throws Throwable { protected void runTest() throws Throwable {
Converter converter = new Converter(); Converter converter = new Converter();
String javaPath = "tests/testData/" + getTestFilePath(); String javaPath = "tests/testData/" + getTestFilePath();
String kotlinPath = javaPath.replace(".jav", ".kt"); String kotlinPath = javaPath.replace(".jav", ".kt");
final File kotlinFile = new File(kotlinPath); final File kotlinFile = new File(kotlinPath);
if (!kotlinFile.exists()) { if (!kotlinFile.exists()) {
FileUtil.writeToFile(kotlinFile, ""); FileUtil.writeToFile(kotlinFile, "");
} }
final String expected = StringUtil.convertLineSeparators(FileUtil.loadFile(kotlinFile)); final String expected = StringUtil.convertLineSeparators(FileUtil.loadFile(kotlinFile));
final File javaFile = new File(javaPath); final File javaFile = new File(javaPath);
final String javaCode = FileUtil.loadFile(javaFile); final String javaCode = FileUtil.loadFile(javaFile);
String actual = ""; String actual = "";
String parentFileName = javaFile.getParentFile().getName(); String parentFileName = javaFile.getParentFile().getName();
if (parentFileName.equals("expression")) { if (parentFileName.equals("expression")) {
actual = expressionToKotlin(converter, javaCode); actual = expressionToKotlin(converter, javaCode);
} }
else if (parentFileName.equals("statement")) { else if (parentFileName.equals("statement")) {
actual = statementToKotlin(converter, javaCode); actual = statementToKotlin(converter, javaCode);
} }
else if (parentFileName.equals("method")) { else if (parentFileName.equals("method")) {
actual = methodToKotlin(converter, javaCode); actual = methodToKotlin(converter, javaCode);
} }
else if (parentFileName.equals("class")) { else if (parentFileName.equals("class")) {
actual = fileToKotlin(converter, javaCode); actual = fileToKotlin(converter, javaCode);
} }
else if (parentFileName.equals("file")) { else if (parentFileName.equals("file")) {
actual = fileToKotlin(converter, javaCode); actual = fileToKotlin(converter, javaCode);
} }
else if (parentFileName.equals("comp")) actual = fileToFileWithCompatibilityImport(javaCode); else if (parentFileName.equals("comp")) actual = fileToFileWithCompatibilityImport(javaCode);
actual = StringUtil.convertLineSeparators(actual); actual = StringUtil.convertLineSeparators(actual);
assert !actual.isEmpty() : "Specify what is it: file, class, method, statement or expression: " + javaPath + " parent: " + parentFileName; assert !actual.isEmpty() : "Specify what is it: file, class, method, statement or expression: " + javaPath + " parent: " + parentFileName;
final File tmp = new File(kotlinPath + ".tmp"); final File tmp = new File(kotlinPath + ".tmp");
if (!expected.equals(actual)) FileUtil.writeToFile(tmp, actual); if (!expected.equals(actual)) FileUtil.writeToFile(tmp, actual);
if (expected.equals(actual) && tmp.exists()) //noinspection ResultOfMethodCallIgnored if (expected.equals(actual) && tmp.exists()) //noinspection ResultOfMethodCallIgnored
{ {
tmp.delete(); tmp.delete();
} }
Assert.assertEquals(expected, actual); Assert.assertEquals(expected, actual);
} }
@NotNull @NotNull
String getTestFilePath() { String getTestFilePath() {
return myDataPath + "/" + myName + ".jav"; return myDataPath + "/" + myName + ".jav";
} }
@NotNull @NotNull
@Override @Override
public String getName() { public String getName() {
return "test_" + myName; return "test_" + myName;
} }
@NotNull @NotNull
public static Test suite() { public static Test suite() {
TestSuite suite = new TestSuite(); TestSuite suite = new TestSuite();
// suite.addTest(new StandaloneJavaToKotlinConverterTest("ast/class/file", "kt-639")); // suite.addTest(new StandaloneJavaToKotlinConverterTest("ast/class/file", "kt-639"));
suite.addTest(TestCaseBuilder.suiteForDirectory("tests/testData", "/ast", new TestCaseBuilder.NamedTestFactory() { suite.addTest(TestCaseBuilder.suiteForDirectory("tests/testData", "/ast", new TestCaseBuilder.NamedTestFactory() {
@NotNull @NotNull
@Override @Override
public Test createTest(@NotNull String dataPath, @NotNull String name) { public Test createTest(@NotNull String dataPath, @NotNull String name) {
return new StandaloneJavaToKotlinConverterTest(dataPath, name); return new StandaloneJavaToKotlinConverterTest(dataPath, name);
} }
})); }));
return suite; return suite;
} }
@NotNull @NotNull
private static String fileToFileWithCompatibilityImport(@NotNull String text) { private static String fileToFileWithCompatibilityImport(@NotNull String text) {
return JavaToKotlinTranslator.generateKotlinCodeWithCompatibilityImport(text); return JavaToKotlinTranslator.generateKotlinCodeWithCompatibilityImport(text);
} }
@NotNull @NotNull
private String fileToKotlin(Converter converter, @NotNull String text) { private String fileToKotlin(Converter converter, @NotNull String text) {
return generateKotlinCode(converter, JavaToKotlinTranslator.createFile(myJavaCoreEnvironment, text)); return generateKotlinCode(converter, JavaToKotlinTranslator.createFile(myJavaCoreEnvironment, text));
} }
@NotNull @NotNull
private static String generateKotlinCode(@NotNull Converter converter, @Nullable PsiFile file) { private static String generateKotlinCode(@NotNull Converter converter, @Nullable PsiFile file) {
if (file != null && file instanceof PsiJavaFile) { if (file != null && file instanceof PsiJavaFile) {
JavaToKotlinTranslator.setClassIdentifiers(converter, file); JavaToKotlinTranslator.setClassIdentifiers(converter, file);
return prettify(converter.elementToKotlin(file)); return prettify(converter.elementToKotlin(file));
} }
return ""; return "";
} }
@NotNull @NotNull
private String methodToKotlin(Converter converter, String text) throws IOException { private String methodToKotlin(Converter converter, String text) throws IOException {
String result = fileToKotlin(converter, "final class C {" + text + "}") String result = fileToKotlin(converter, "final class C {" + text + "}")
.replaceAll("class C\\(\\) \\{", ""); .replaceAll("class C\\(\\) \\{", "");
result = result.substring(0, result.lastIndexOf("}")); result = result.substring(0, result.lastIndexOf("}"));
return prettify(result); return prettify(result);
} }
@NotNull @NotNull
private String statementToKotlin(Converter converter, String text) throws Exception { private String statementToKotlin(Converter converter, String text) throws Exception {
String result = methodToKotlin(converter, "void main() {" + text + "}"); String result = methodToKotlin(converter, "void main() {" + text + "}");
int pos = result.lastIndexOf("}"); int pos = result.lastIndexOf("}");
result = result.substring(0, pos).replaceFirst("fun main\\(\\) : Unit \\{", ""); result = result.substring(0, pos).replaceFirst("fun main\\(\\) : Unit \\{", "");
return prettify(result); return prettify(result);
} }
@NotNull @NotNull
private String expressionToKotlin(Converter converter, String code) throws Exception { private String expressionToKotlin(Converter converter, String code) throws Exception {
String result = statementToKotlin(converter, "Object o =" + code + "}"); String result = statementToKotlin(converter, "Object o =" + code + "}");
result = result.replaceFirst("var o : Any\\? =", ""); result = result.replaceFirst("var o : Any\\? =", "");
return prettify(result); return prettify(result);
} }
@NotNull @NotNull
private static String prettify(@Nullable String code) { private static String prettify(@Nullable String code) {
if (code == null) { if (code == null) {
return ""; return "";
} }
return code return code
.trim() .trim()
.replaceAll("\r\n", "\n") .replaceAll("\r\n", "\n")
.replaceAll(" \n", "\n") .replaceAll(" \n", "\n")
.replaceAll("\n ", "\n") .replaceAll("\n ", "\n")
.replaceAll("\n+", "\n") .replaceAll("\n+", "\n")
.replaceAll(" +", " ") .replaceAll(" +", " ")
.trim() .trim()
; ;
} }
} }
@@ -1,110 +1,110 @@
/* /*
* Copyright 2010-2012 JetBrains s.r.o. * Copyright 2010-2012 JetBrains s.r.o.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.jetbrains.jet.j2k; package org.jetbrains.jet.j2k;
import com.intellij.openapi.application.PathManager; import com.intellij.openapi.application.PathManager;
import junit.framework.Test; import junit.framework.Test;
import junit.framework.TestSuite; import junit.framework.TestSuite;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.io.File; import java.io.File;
import java.io.FileFilter; import java.io.FileFilter;
import java.io.FilenameFilter; import java.io.FilenameFilter;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
/** /**
* @author ignatov * @author ignatov
*/ */
abstract class TestCaseBuilder { abstract class TestCaseBuilder {
@NotNull @NotNull
private static final FilenameFilter emptyFilter = new FilenameFilter() { private static final FilenameFilter emptyFilter = new FilenameFilter() {
@Override @Override
public boolean accept(File file, String name) { public boolean accept(File file, String name) {
return true; return true;
} }
}; };
@NotNull @NotNull
public static String getTestDataPathBase() { public static String getTestDataPathBase() {
return "testData"; return "testData";
} }
public static String getHomeDirectory() { public static String getHomeDirectory() {
return new File(PathManager.getResourceRoot(TestCaseBuilder.class, "/org/jetbrains/jet/TestCaseBuilder.class")).getParentFile().getParentFile().getParent(); return new File(PathManager.getResourceRoot(TestCaseBuilder.class, "/org/jetbrains/jet/TestCaseBuilder.class")).getParentFile().getParentFile().getParent();
} }
public interface NamedTestFactory { public interface NamedTestFactory {
@NotNull @NotNull
Test createTest(@NotNull String dataPath, @NotNull String name); Test createTest(@NotNull String dataPath, @NotNull String name);
} }
@NotNull @NotNull
public static TestSuite suiteForDirectory(String baseDataDir, @NotNull final String dataPath, @NotNull NamedTestFactory factory) { public static TestSuite suiteForDirectory(String baseDataDir, @NotNull final String dataPath, @NotNull NamedTestFactory factory) {
return suiteForDirectory(baseDataDir, dataPath, true, emptyFilter, factory); return suiteForDirectory(baseDataDir, dataPath, true, emptyFilter, factory);
} }
@NotNull @NotNull
private static TestSuite suiteForDirectory(String baseDataDir, @NotNull final String dataPath, boolean recursive, @NotNull final FilenameFilter filter, @NotNull NamedTestFactory factory) { private static TestSuite suiteForDirectory(String baseDataDir, @NotNull final String dataPath, boolean recursive, @NotNull final FilenameFilter filter, @NotNull NamedTestFactory factory) {
TestSuite suite = new TestSuite(dataPath); TestSuite suite = new TestSuite(dataPath);
final String extensionJava = ".jav"; final String extensionJava = ".jav";
final FilenameFilter extensionFilter = new FilenameFilter() { final FilenameFilter extensionFilter = new FilenameFilter() {
@Override @Override
public boolean accept(File dir, @NotNull String name) { public boolean accept(File dir, @NotNull String name) {
return name.endsWith(extensionJava); return name.endsWith(extensionJava);
} }
}; };
FilenameFilter resultFilter; FilenameFilter resultFilter;
if (filter != emptyFilter) { if (filter != emptyFilter) {
resultFilter = new FilenameFilter() { resultFilter = new FilenameFilter() {
@Override @Override
public boolean accept(File file, String s) { public boolean accept(File file, String s) {
return extensionFilter.accept(file, s) && filter.accept(file, s); return extensionFilter.accept(file, s) && filter.accept(file, s);
} }
}; };
} }
else { else {
resultFilter = extensionFilter; resultFilter = extensionFilter;
} }
File dir = new File(baseDataDir + dataPath); File dir = new File(baseDataDir + dataPath);
FileFilter dirFilter = new FileFilter() { FileFilter dirFilter = new FileFilter() {
@Override @Override
public boolean accept(@NotNull File pathname) { public boolean accept(@NotNull File pathname) {
return pathname.isDirectory(); return pathname.isDirectory();
} }
}; };
if (recursive) { if (recursive) {
File[] files = dir.listFiles(dirFilter); File[] files = dir.listFiles(dirFilter);
assert files != null : dir; assert files != null : dir;
List<File> subdirs = Arrays.asList(files); List<File> subdirs = Arrays.asList(files);
Collections.sort(subdirs); Collections.sort(subdirs);
for (File subdir : subdirs) { for (File subdir : subdirs) {
suite.addTest(suiteForDirectory(baseDataDir, dataPath + "/" + subdir.getName(), recursive, filter, factory)); suite.addTest(suiteForDirectory(baseDataDir, dataPath + "/" + subdir.getName(), recursive, filter, factory));
} }
} }
List<File> files = Arrays.asList(dir.listFiles(resultFilter)); List<File> files = Arrays.asList(dir.listFiles(resultFilter));
Collections.sort(files); Collections.sort(files);
for (File file : files) { for (File file : files) {
String fileName = file.getName(); String fileName = file.getName();
assert fileName != null; assert fileName != null;
suite.addTest(factory.createTest(dataPath, fileName.substring(0, fileName.length() - extensionJava.length()))); suite.addTest(factory.createTest(dataPath, fileName.substring(0, fileName.length() - extensionJava.length())));
} }
return suite; return suite;
} }
} }
@@ -1,29 +1,29 @@
package test; package test;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
public class Test { public class Test {
@NotNull String myStr = "String2"; @NotNull String myStr = "String2";
public Test(@NotNull String str) { public Test(@NotNull String str) {
myStr = str; myStr = str;
} }
public void sout(@NotNull String str) { public void sout(@NotNull String str) {
System.out.println(str); System.out.println(str);
} }
@NotNull @NotNull
public String dummy(@NotNull String str) { public String dummy(@NotNull String str) {
return str; return str;
} }
public void test() { public void test() {
sout("String"); sout("String");
@NotNull String test = "String2"; @NotNull String test = "String2";
sout(test); sout(test);
sout(dummy(test)); sout(dummy(test));
new Test(test); new Test(test);
} }
} }
@@ -1,20 +1,20 @@
package test package test
public open class Test(str : String) { public open class Test(str : String) {
var myStr : String? = "String2" var myStr : String? = "String2"
public open fun sout(str : String) : Unit { public open fun sout(str : String) : Unit {
System.out?.println(str) System.out?.println(str)
} }
public open fun dummy(str : String) : String { public open fun dummy(str : String) : String {
return str return str
} }
public open fun test() : Unit { public open fun test() : Unit {
sout("String") sout("String")
var test : String = "String2" var test : String = "String2"
sout(test) sout(test)
sout(dummy(test)) sout(dummy(test))
Test(test) Test(test)
} }
{ {
myStr = str myStr = str
} }
} }
@@ -1,6 +1,6 @@
open class Test() { open class Test() {
var str : String? = null var str : String? = null
{ {
str = "Ola" str = "Ola"
} }
} }
@@ -1,8 +1,8 @@
open class Test() { open class Test() {
var str : String? = null var str : String? = null
class object { class object {
{ {
str = "Ola" str = "Ola"
} }
} }
} }
@@ -1,4 +1,4 @@
var a : Double = 0 var a : Double = 0
var b : Double = 0 var b : Double = 0
var c : Double = 0 var c : Double = 0
var ds : DoubleArray? = doubleArray((a).toDouble(), (b).toDouble(), (c).toDouble()) var ds : DoubleArray? = doubleArray((a).toDouble(), (b).toDouble(), (c).toDouble())
@@ -1,4 +1,4 @@
var a : Int = 0 var a : Int = 0
var b : Int = 0 var b : Int = 0
var c : Int = 0 var c : Int = 0
var `is` : IntArray? = intArray(a, b, c) var `is` : IntArray? = intArray(a, b, c)
@@ -1,2 +1,2 @@
fun fromArrayToCollection(a : Array<Foo?>?) : Unit { fun fromArrayToCollection(a : Array<Foo?>?) : Unit {
} }
@@ -1,9 +1,9 @@
import java.util.BitSet; import java.util.BitSet;
class Foo { class Foo {
void foo(BitSet o) { void foo(BitSet o) {
BitSet o2 = o; BitSet o2 = o;
int foo = 0; int foo = 0;
foo = o2.size(); foo = o2.size();
} }
} }
@@ -1,8 +1,8 @@
import java.util.BitSet import java.util.BitSet
open class Foo() { open class Foo() {
open fun foo(o : BitSet?) : Unit { open fun foo(o : BitSet?) : Unit {
var o2 : BitSet? = o var o2 : BitSet? = o
var foo : Int = 0 var foo : Int = 0
foo = o2?.size()!! foo = o2?.size()!!
} }
} }
+6 -6
View File
@@ -1,7 +1,7 @@
package demo package demo
open class Test() { open class Test() {
open fun test() : Unit { open fun test() : Unit {
var i : Int? = Integer.valueOf(100) var i : Int? = Integer.valueOf(100)
var s : Short? = Short.valueOf(100) var s : Short? = Short.valueOf(100)
} }
} }
@@ -1,10 +1,10 @@
open class Library() { open class Library() {
class object { class object {
val ourOut : java.io.PrintStream? = null val ourOut : java.io.PrintStream? = null
} }
} }
open class User() { open class User() {
open fun main() : Unit { open fun main() : Unit {
Library.ourOut?.print() Library.ourOut?.print()
} }
} }
@@ -1,15 +1,15 @@
open class Library() { open class Library() {
class object { class object {
open fun call() : Unit { open fun call() : Unit {
} }
open fun getString() : String? { open fun getString() : String? {
return "" return ""
} }
} }
} }
open class User() { open class User() {
open fun main() : Unit { open fun main() : Unit {
Library.call() Library.call()
Library.getString()?.isEmpty() Library.getString()?.isEmpty()
} }
} }
@@ -1,16 +1,16 @@
open class Library() { open class Library() {
open fun call() : Unit { open fun call() : Unit {
} }
open fun getString() : String? { open fun getString() : String? {
return "" return ""
} }
} }
open class User() { open class User() {
open fun main() : Unit { open fun main() : Unit {
var lib : Library? = Library() var lib : Library? = Library()
lib?.call() lib?.call()
lib?.getString()?.isEmpty() lib?.getString()?.isEmpty()
Library().call() Library().call()
Library().getString()?.isEmpty() Library().getString()?.isEmpty()
} }
} }
@@ -1,8 +1,8 @@
open class Library() { open class Library() {
public val myString : String? = null public val myString : String? = null
} }
open class User() { open class User() {
open fun main() : Unit { open fun main() : Unit {
Library.myString?.isEmpty() Library.myString?.isEmpty()
} }
} }
@@ -1,6 +1,6 @@
abstract class A() { abstract class A() {
abstract fun callme() : Unit abstract fun callme() : Unit
open fun callmetoo() : Unit { open fun callmetoo() : Unit {
print("This is a concrete method.") print("This is a concrete method.")
} }
} }
@@ -1,10 +1,10 @@
abstract class Shape() { abstract class Shape() {
public var color : String? = null public var color : String? = null
public open fun setColor(c : String?) : Unit { public open fun setColor(c : String?) : Unit {
color = c color = c
} }
public open fun getColor() : String? { public open fun getColor() : String? {
return color return color
} }
public abstract fun area() : Double public abstract fun area() : Double
} }
+1 -1
View File
@@ -1,2 +1,2 @@
open class Test() { open class Test() {
} }
@@ -1,8 +1,8 @@
class T() { class T() {
fun main() : Unit { fun main() : Unit {
} }
fun i() : Int { fun i() : Int {
} }
fun s() : String? { fun s() : String? {
} }
} }
@@ -1,4 +1,4 @@
class T() { class T() {
var a : String? = "abc" var a : String? = "abc"
var b : Int = 10 var b : Int = 10
} }
@@ -1,5 +1,5 @@
class T() { class T() {
var a : String? = null var a : String? = null
var b : String? = null var b : String? = null
var c : String? = "abc" var c : String? = "abc"
} }
+1 -1
View File
@@ -1,2 +1,2 @@
class A() { class A() {
} }
@@ -1,2 +1,2 @@
class A() : Base(), I { class A() : Base(), I {
} }
@@ -1,2 +1,2 @@
class A() : Base(), I0, I1, I2 { class A() : Base(), I0, I1, I2 {
} }
+1 -1
View File
@@ -1,2 +1,2 @@
class Test() { class Test() {
} }
@@ -1,2 +1,2 @@
class Entry<K, V>() { class Entry<K, V>() {
} }
@@ -1,4 +1,4 @@
class A() { class A() {
class B() { class B() {
} }
} }
@@ -1,6 +1,6 @@
class S() { class S() {
class object { class object {
open class Inner() { open class Inner() {
} }
} }
} }
@@ -1,2 +1,2 @@
open class Test() { open class Test() {
} }
@@ -1,8 +1,8 @@
class S() { class S() {
fun sB() : Boolean { fun sB() : Boolean {
return true return true
} }
class object { class object {
var myI : Int = 10 var myI : Int = 10
} }
} }
@@ -1,7 +1,7 @@
class S() { class S() {
class object { class object {
fun staticF() : Boolean { fun staticF() : Boolean {
return true return true
} }
} }
} }
@@ -1,10 +1,10 @@
class S() { class S() {
fun sB() : Boolean { fun sB() : Boolean {
return true return true
} }
class object { class object {
fun sI() : Int { fun sI() : Int {
return 1 return 1
} }
} }
} }
@@ -1,2 +1,2 @@
private open class Test() { private open class Test() {
} }
@@ -1,2 +1,2 @@
protected open class Test() { protected open class Test() {
} }
@@ -1,2 +1,2 @@
public open class Test() { public open class Test() {
} }
@@ -1,2 +1,2 @@
class A() : Base() { class A() : Base() {
} }
@@ -1,10 +1,10 @@
class S() { class S() {
class object { class object {
fun sB() : Boolean { fun sB() : Boolean {
return true return true
} }
fun sI() : Int { fun sI() : Int {
return 1 return 1
} }
} }
} }
+21 -21
View File
@@ -1,22 +1,22 @@
package demo package demo
import java.util.HashMap import java.util.HashMap
open class Test() { open class Test() {
class object { class object {
open fun init() : Test { open fun init() : Test {
val __ = Test() val __ = Test()
return __ return __
} }
open fun init(s : String?) : Test { open fun init(s : String?) : Test {
val __ = Test() val __ = Test()
return __ return __
} }
} }
} }
open class User() { open class User() {
open fun main() : Unit { open fun main() : Unit {
var m : HashMap<Any?, Any?>? = HashMap(1) var m : HashMap<Any?, Any?>? = HashMap(1)
var m2 : HashMap<Any?, Any?>? = HashMap(10) var m2 : HashMap<Any?, Any?>? = HashMap(10)
var t1 : Test? = Test.init() var t1 : Test? = Test.init()
var t2 : Test? = Test.init("") var t2 : Test? = Test.init("")
} }
} }

Some files were not shown because too many files have changed in this diff Show More