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