Support compiling common KMP code
baconz opened this issue · comments
I would like to be able to compile code as common module sources
so that I can test compilation of @JsExport
annotated classes. I tried messing with the paths of the modules, but could not find a way to convince the compiler that my code is in the common module.
As an example, you can try compiling something simple like:
@JsExport
fun add(a: Double, b: Double): Double {
return a + b
}
You will get a compiler error along the lines of:
Declaration annotated with '@OptionalExpectation' can only be used in common module sources
This test runs fine for me:
@Test
fun `foos`() {
val result = defaultCompilerConfig().apply {
sources = listOf(SourceFile.kotlin("kSource.kt", """
import kotlin.js.ExperimentalJsExport
@ExperimentalJsExport
fun add(a: Double, b: Double): Double {
return a + b
}
""".trimIndent()))
}.compile()
assertThat(result.exitCode).isEqualTo(ExitCode.OK)
}
where is your @JsExport
annotation coming from? I could only find @ExperimentalJsExport
.
It is in kotlin.js
. I can repro the error using your test:
@Test
fun `foos`() {
val result = KotlinCompilation().apply {
sources = listOf(
SourceFile.kotlin(
"kSource.kt",
"""
import kotlin.js.JsExport
@JsExport
fun add(a: Double, b: Double): Double {
return a + b
}
""".trimIndent()
)
)
}.compile()
assertEquals(KotlinCompilation.ExitCode.OK, result.exitCode)
}
Yields:
e: file:///var/folders/nb/4mjn36pj1k1dvs2wtrm4xkjr0000gn/T/Kotlin-Compilation6662340746301164020/sources/kSource.kt:1:18 Declaration annotated with '@OptionalExpectation' can only be used in common module sources
e: file:///var/folders/nb/4mjn36pj1k1dvs2wtrm4xkjr0000gn/T/Kotlin-Compilation6662340746301164020/sources/kSource.kt:3:2 Declaration annotated with '@OptionalExpectation' can only be used in common module sources
@JsExport
is there: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.js/-js-export/ (and source code is here)
I see, there is a new experimental option -Xcommon-sources
that tells the compiler which sources are supposed to be from the common module. "common sources" paths have to appear both in -Xcommon-sources
and the list of regular sources (free arguments to kotlinc). This requires some refactoring in SourceFile.new
because the files are written on-demand and the path is not known at the point where that compiler option has to be set. I'm working on it, but until then you may write the files to disk yourself to get an absolute path, use SourceFile.fromPath
instead and set the -Xcommon-sources
option manually via KotlinCompilation.kotlincArguments
.