|
| 1 | +package org.javacs.kt.externalsources |
| 2 | + |
| 3 | +import java.nio.file.Files |
| 4 | +import java.nio.file.Path |
| 5 | +import org.javacs.kt.LOG |
| 6 | +import org.javacs.kt.util.KotlinLSException |
| 7 | +import org.javacs.kt.util.replaceExtensionWith |
| 8 | +import org.javacs.kt.util.withCustomStdout |
| 9 | +import org.jetbrains.java.decompiler.main.decompiler.ConsoleDecompiler |
| 10 | + |
| 11 | +class FernFlowerDecompiler : Decompiler { |
| 12 | + private val outputDir: Path by lazy { |
| 13 | + Files.createTempDirectory("fernflowerOut").also { |
| 14 | + Runtime.getRuntime().addShutdownHook(Thread { it.toFile().deleteRecursively() }) |
| 15 | + } |
| 16 | + } |
| 17 | + |
| 18 | + private val decompilerOptions = |
| 19 | + arrayOf( |
| 20 | + "-iec=1", // Include entire classpath for better context |
| 21 | + "-jpr=1", // Include parameter names in method signatures |
| 22 | + ) |
| 23 | + |
| 24 | + override fun decompileClass(compiledClass: Path): Path { |
| 25 | + return decompile(compiledClass, ".java") |
| 26 | + } |
| 27 | + |
| 28 | + override fun decompileJar(compiledJar: Path): Path { |
| 29 | + return decompile(compiledJar, ".jar") |
| 30 | + } |
| 31 | + |
| 32 | + private fun decompile(input: Path, extension: String): Path { |
| 33 | + LOG.info("Decompiling ${input.fileName} using FernFlower...") |
| 34 | + |
| 35 | + val args = decompilerOptions + arrayOf(input.toString(), outputDir.toString()) |
| 36 | + |
| 37 | + withCustomStdout(LOG.outStream) { ConsoleDecompiler.main(args) } |
| 38 | + |
| 39 | + val outName = input.fileName.replaceExtensionWith(extension) |
| 40 | + val outPath = outputDir.resolve(outName) |
| 41 | + if (!Files.exists(outPath)) { |
| 42 | + throw KotlinLSException( |
| 43 | + "Could not decompile ${input.fileName}: FernFlower did not generate sources at $outName" |
| 44 | + ) |
| 45 | + } |
| 46 | + return outPath |
| 47 | + } |
| 48 | +} |
0 commit comments