|
1 | 1 | package org.javacs.kt.j2k
|
2 | 2 |
|
3 |
| -import java.util.Arrays |
4 |
| -import com.intellij.psi.* |
5 |
| -import com.intellij.lang.java.JavaLanguage |
6 | 3 | import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
|
7 |
| -import org.jetbrains.kotlin.j2k.JavaToKotlinConverter |
8 | 4 | import org.jetbrains.kotlin.j2k.JavaToKotlinTranslator
|
9 |
| -import org.jetbrains.kotlin.j2k.ConverterSettings |
10 |
| -import org.jetbrains.kotlin.j2k.EmptyJavaToKotlinServices |
11 | 5 | import org.javacs.kt.LOG
|
12 | 6 |
|
13 |
| -/** |
14 |
| - * Source: https://github.com/JetBrains/kotlin-web-demo/blob/master/versions/1.2.50/src/main/java/org/jetbrains/webdemo/kotlin/impl/converter/WebDemoJavaToKotlinConverter.kt |
15 |
| - * Licensed under Apache License, Version 2.0 |
16 |
| - */ |
17 |
| - |
18 |
| -/** Converts a Java code snippet to Kotlin */ |
19 | 7 | fun convertJavaToKotlin(environment: KotlinCoreEnvironment, javaCode: String): String {
|
20 | 8 | LOG.info("Converting to Kotlin: $javaCode")
|
21 |
| - |
22 |
| - val project = environment.project |
23 |
| - val converter = JavaToKotlinConverter( |
24 |
| - project, |
25 |
| - ConverterSettings.defaultSettings, |
26 |
| - EmptyJavaToKotlinServices |
27 |
| - ) |
28 |
| - val instance = PsiElementFactory.SERVICE.getInstance(project) |
29 |
| - val javaFile = PsiFileFactory.getInstance(project) |
30 |
| - .createFileFromText("snippet.java", JavaLanguage.INSTANCE, javaCode) |
31 |
| - |
32 |
| - var inputElements: List<PsiElement>? = if (javaFile.children.any { it is PsiClass}) listOf<PsiElement>(javaFile) else null |
33 |
| - |
34 |
| - if (inputElements == null) { |
35 |
| - val psiClass = instance.createClassFromText(javaCode, javaFile) |
36 |
| - var errorsFound = false |
37 |
| - for (element in psiClass.children) { |
38 |
| - if (element is PsiErrorElement) { |
39 |
| - errorsFound = true |
40 |
| - } |
41 |
| - } |
42 |
| - |
43 |
| - if (!errorsFound) { |
44 |
| - inputElements = Arrays.asList(*psiClass.children) |
45 |
| - } |
46 |
| - } |
47 |
| - |
48 |
| - if (inputElements == null) { |
49 |
| - val codeBlock = instance.createCodeBlockFromText(javaCode, javaFile) |
50 |
| - val childrenWithoutBraces = Arrays.copyOfRange(codeBlock.children, 1, codeBlock.children.size - 1) |
51 |
| - inputElements = Arrays.asList(*childrenWithoutBraces) |
52 |
| - } |
53 |
| - |
54 |
| - val resultFormConverter = converter.elementsToKotlin(inputElements!!).results |
55 |
| - var textResult = "" |
56 |
| - resultFormConverter |
57 |
| - .asSequence() |
58 |
| - .filterNotNull() |
59 |
| - .forEach { textResult += it.text + "\n" } |
60 |
| - |
61 |
| - return JavaToKotlinTranslator.prettify(textResult) |
| 9 | + return JavaToKotlinTranslator.generateKotlinCode(javaCode, environment.project) |
62 | 10 | }
|
0 commit comments