From d1720c10a1d5437daf97ed412a67b4baab81920d Mon Sep 17 00:00:00 2001 From: Elie Gambache Date: Fri, 16 Oct 2026 17:02:38 +0300 Subject: [PATCH 1/5] JVM targets, primitive arrays and sealed value hierarchies MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - A Kotlin Multiplatform module's jvm() target runs the façades in its own JVM: nja-client gets a jvm target whose transport calls the server's dispatcher on the calling thread (callbacks served back on it, as on iOS without JNI); the plugin puts the façades on the target's runtime class path and checks that their proxies have a package of their own (njaFacade.clientPackage), as both are on it. - IntArray, LongArray, FloatArray and DoubleArray cross the bridge as a count and their elements. - A sealed interface or class whose nested cases are all data classes or objects travels by value (its case, then the case's fields), copied verbatim like a data class; value types now reference each other by name, so they may be recursive (a sealed value holding a list of itself, through a data class...). - examples/calculator: a jvm target running the same suites, the proxies in their own packages, tests for the arrays and the sealed values. Signed-off-by: Elie Gambache --- examples/calculator-facade/build.gradle.kts | 2 + .../kotlin/com/example/calculator/Arrays.kt | 28 +++++++ .../com/example/calculator/SealedValues.kt | 58 ++++++++++++++ examples/calculator/build.gradle.kts | 2 + .../{ => client}/TortureSupport.android.kt | 4 +- .../example/calculator/client/ArraysTest.kt | 59 ++++++++++++++ .../{ => client}/AsyncCallbackTest.kt | 2 +- .../{ => client}/AsyncCollectionTest.kt | 2 +- .../calculator/{ => client}/AsyncCoreTest.kt | 2 +- .../{ => client}/AsyncDataClassEnumTest.kt | 2 +- .../{ => client}/AsyncInheritanceTest.kt | 2 +- .../{ => client}/AsyncSuspendFlowTest.kt | 2 +- .../{ => client}/BufferTortureTest.kt | 2 +- .../{ => client}/ByteArrayEverywhereTest.kt | 2 +- .../calculator/{ => client}/CallbackTest.kt | 2 +- .../{ => client}/CollectionPropertyTest.kt | 2 +- .../calculator/{ => client}/CollectionTest.kt | 2 +- .../calculator/{ => client}/CoreTest.kt | 2 +- .../{ => client}/CoroutineCrossFeatureTest.kt | 2 +- .../calculator/{ => client}/DataClassTest.kt | 2 +- .../{ => client}/DcCollectionFieldTest.kt | 2 +- .../calculator/{ => client}/EdgeCaseTest.kt | 2 +- .../calculator/{ => client}/EnumTest.kt | 2 +- .../{ => client}/ExtensionFunctionTest.kt | 2 +- .../{ => client}/FlowByteArrayTest.kt | 2 +- .../{ => client}/FlowCollectionTest.kt | 2 +- .../{ => client}/FlowDataClassTest.kt | 2 +- .../calculator/{ => client}/FlowTest.kt | 2 +- .../{ => client}/InheritanceEdgeCaseTest.kt | 2 +- .../{ => client}/InheritanceTest.kt | 2 +- .../calculator/{ => client}/InterfaceTest.kt | 2 +- .../{ => client}/LambdaReturnTest.kt | 2 +- .../{ => client}/ListDataClassParamTest.kt | 2 +- .../{ => client}/LoadAndConcurrencyTest.kt | 2 +- .../{ => client}/LoadInheritanceTest.kt | 2 +- .../calculator/{ => client}/MonkeyTest.kt | 2 +- .../{ => client}/NestedClassTest.kt | 2 +- .../{ => client}/NestedCollectionTest.kt | 2 +- .../{ => client}/NestedDataClassTest.kt | 2 +- .../calculator/{ => client}/NjaTortureTest.kt | 16 ++-- .../{ => client}/NullableCallbackTest.kt | 2 +- .../calculator/{ => client}/NullableTest.kt | 2 +- .../calculator/{ => client}/ObjectTest.kt | 2 +- .../{ => client}/RuntimeTortureTest.kt | 2 +- .../{ => client}/SealedClassTest.kt | 2 +- .../calculator/client/SealedValuesTest.kt | 49 ++++++++++++ .../calculator/{ => client}/SmokeTest.kt | 2 +- .../{ => client}/SuspendBasicTest.kt | 2 +- .../{ => client}/SuspendCollectionTest.kt | 2 +- .../{ => client}/SuspendCrossFeatureTest.kt | 2 +- .../{ => client}/SuspendDataClassTest.kt | 2 +- .../{ => client}/SuspendEdgeCaseTest.kt | 2 +- .../{ => client}/SuspendHeavyTest.kt | 2 +- .../calculator/{ => client}/TortureSupport.kt | 5 +- .../{ => client}/ValueTypeParityTest.kt | 2 +- .../{ => client}/ValueTypeTortureTest.kt | 2 +- .../{ => client}/TortureSupport.ios.kt | 4 +- .../calculator/client/TortureSupport.jvm.kt | 48 +++++++++++ examples/torture-facade/build.gradle.kts | 1 + .../nucleusframework/nja/plugin/NjaPlugin.kt | 35 +++++++- .../nja/plugin/analysis/ParseModel.kt | 2 + .../nja/plugin/analysis/PsiSourceParser.kt | 32 +++++++- .../nja/plugin/analysis/SymbolTable.kt | 79 ++++++++++++++----- .../nja/plugin/codegen/ClientGenerator.kt | 34 +++++++- .../nja/plugin/codegen/Codec.kt | 17 +++- .../nja/plugin/codegen/ServerGenerator.kt | 30 +++++++ .../nucleusframework/nja/plugin/ir/ApiIR.kt | 40 ++++++++++ .../plugin/tasks/GenerateNjaBridgesTask.kt | 10 ++- runtime/client/build.gradle.kts | 10 ++- .../kotlin/dev/nucleusframework/nja/Wire.kt | 57 +++++++++++++ .../dev/nucleusframework/nja/Platform.jvm.kt | 40 ++++++++++ .../dev/nucleusframework/nja/server/Wire.kt | 57 +++++++++++++ 72 files changed, 730 insertions(+), 83 deletions(-) create mode 100644 examples/calculator-facade/src/main/kotlin/com/example/calculator/Arrays.kt create mode 100644 examples/calculator-facade/src/main/kotlin/com/example/calculator/SealedValues.kt rename examples/calculator/src/androidDeviceTest/kotlin/com/example/calculator/{ => client}/TortureSupport.android.kt (94%) create mode 100644 examples/calculator/src/commonTest/kotlin/com/example/calculator/client/ArraysTest.kt rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/AsyncCallbackTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/AsyncCollectionTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/AsyncCoreTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/AsyncDataClassEnumTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/AsyncInheritanceTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/AsyncSuspendFlowTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/BufferTortureTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/ByteArrayEverywhereTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/CallbackTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/CollectionPropertyTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/CollectionTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/CoreTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/CoroutineCrossFeatureTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/DataClassTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/DcCollectionFieldTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/EdgeCaseTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/EnumTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/ExtensionFunctionTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/FlowByteArrayTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/FlowCollectionTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/FlowDataClassTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/FlowTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/InheritanceEdgeCaseTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/InheritanceTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/InterfaceTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/LambdaReturnTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/ListDataClassParamTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/LoadAndConcurrencyTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/LoadInheritanceTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/MonkeyTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/NestedClassTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/NestedCollectionTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/NestedDataClassTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/NjaTortureTest.kt (95%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/NullableCallbackTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/NullableTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/ObjectTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/RuntimeTortureTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/SealedClassTest.kt (99%) create mode 100644 examples/calculator/src/commonTest/kotlin/com/example/calculator/client/SealedValuesTest.kt rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/SmokeTest.kt (96%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/SuspendBasicTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/SuspendCollectionTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/SuspendCrossFeatureTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/SuspendDataClassTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/SuspendEdgeCaseTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/SuspendHeavyTest.kt (99%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/TortureSupport.kt (96%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/ValueTypeParityTest.kt (98%) rename examples/calculator/src/commonTest/kotlin/com/example/calculator/{ => client}/ValueTypeTortureTest.kt (99%) rename examples/calculator/src/iosTest/kotlin/com/example/calculator/{ => client}/TortureSupport.ios.kt (97%) create mode 100644 examples/calculator/src/jvmTest/kotlin/com/example/calculator/client/TortureSupport.jvm.kt create mode 100644 runtime/client/src/jvmMain/kotlin/dev/nucleusframework/nja/Platform.jvm.kt diff --git a/examples/calculator-facade/build.gradle.kts b/examples/calculator-facade/build.gradle.kts index 6cb3ebf..159b982 100644 --- a/examples/calculator-facade/build.gradle.kts +++ b/examples/calculator-facade/build.gradle.kts @@ -10,6 +10,8 @@ kotlin { njaFacade { libName = "calculator" + // Apart from the façade's: the JVM target has both on its class path + clientPackage = "com.example.calculator.client" } dependencies { diff --git a/examples/calculator-facade/src/main/kotlin/com/example/calculator/Arrays.kt b/examples/calculator-facade/src/main/kotlin/com/example/calculator/Arrays.kt new file mode 100644 index 0000000..5d7a4cc --- /dev/null +++ b/examples/calculator-facade/src/main/kotlin/com/example/calculator/Arrays.kt @@ -0,0 +1,28 @@ +package com.example.calculator + +/** A vector and its ids, primitive arrays inside a data class. */ +data class Embedding(val ids: LongArray, val values: FloatArray, val label: String) + +/** Primitive arrays crossing the bridge: as parameters, results, nullables, in data classes and in callbacks. */ +class ArrayOps { + fun sumInts(values: IntArray): Long = values.fold(0L) { sum, v -> sum + v } + + fun reverseLongs(values: LongArray): LongArray = values.reversedArray() + + fun scale(values: FloatArray, factor: Float): FloatArray = FloatArray(values.size) { values[it] * factor } + + fun squares(count: Int): DoubleArray = DoubleArray(count) { (it * it).toDouble() } + + fun sizeOf(values: LongArray?): Int = values?.size ?: -1 + + fun maybe(present: Boolean): IntArray? = if (present) intArrayOf(1, 2, 3) else null + + fun normalize(embedding: Embedding): Embedding { + val norm = kotlin.math.sqrt(embedding.values.fold(0.0) { s, v -> s + v * v }).toFloat() + return embedding.copy(values = FloatArray(embedding.values.size) { embedding.values[it] / norm }, label = embedding.label + "/n") + } + + fun mapThroughApp(values: DoubleArray, transform: (DoubleArray) -> DoubleArray): DoubleArray = transform(values) + + fun bits(): FloatArray = floatArrayOf(Float.NaN, Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY, -0.0f, Float.MIN_VALUE, Float.MAX_VALUE) +} diff --git a/examples/calculator-facade/src/main/kotlin/com/example/calculator/SealedValues.kt b/examples/calculator-facade/src/main/kotlin/com/example/calculator/SealedValues.kt new file mode 100644 index 0000000..09fcd51 --- /dev/null +++ b/examples/calculator-facade/src/main/kotlin/com/example/calculator/SealedValues.kt @@ -0,0 +1,58 @@ +package com.example.calculator + +/** A sealed value hierarchy: figures travel by value, nested in one another. */ +sealed interface Figure { + data class Circle(val radius: Double) : Figure + + data class Rect(val width: Double, val height: Double) : Figure + + data class Group(val name: String, val children: List
, val anchor: Figure? = null) : Figure + + data object Empty : Figure +} + +/** A data class holding a sealed value: the recursion goes through it too. */ +data class Layer(val shape: Figure, val tags: Set) + +/** A sealed class of values. */ +sealed class Op { + data class Add(val a: Long, val b: Long) : Op() + + data class Sum(val values: LongArray) : Op() + + data object Noop : Op() +} + +class Geometry { + fun area(shape: Figure): Double = when (shape) { + is Figure.Circle -> Math.PI * shape.radius * shape.radius + is Figure.Rect -> shape.width * shape.height + is Figure.Group -> shape.children.sumOf { area(it) } + Figure.Empty -> 0.0 + } + + fun scale(shape: Figure, factor: Double): Figure = when (shape) { + is Figure.Circle -> Figure.Circle(shape.radius * factor) + is Figure.Rect -> Figure.Rect(shape.width * factor, shape.height * factor) + is Figure.Group -> shape.copy(children = shape.children.map { scale(it, factor) }, anchor = shape.anchor?.let { scale(it, factor) }) + Figure.Empty -> Figure.Empty + } + + fun flatten(shape: Figure): List
= if (shape is Figure.Group) shape.children.flatMap { flatten(it) } else listOf(shape) + + fun nested(depth: Int): Figure = if (depth == 0) Figure.Empty else Figure.Group("level $depth", listOf(nested(depth - 1), Figure.Circle(depth.toDouble()))) + + fun depth(shape: Figure): Int = if (shape is Figure.Group) 1 + (shape.children.maxOfOrNull { depth(it) } ?: 0) else 0 + + fun layerArea(layer: Layer): Double = area(layer.shape) * layer.tags.size + + fun maybe(present: Boolean): Figure? = if (present) Figure.Rect(2.0, 3.0) else null + + fun eval(op: Op): Long = when (op) { + is Op.Add -> op.a + op.b + is Op.Sum -> op.values.sum() + Op.Noop -> 0 + } + + fun viaApp(shape: Figure, transform: (Figure) -> Figure): Figure = transform(shape) +} diff --git a/examples/calculator/build.gradle.kts b/examples/calculator/build.gradle.kts index cd2a6e8..df23c75 100644 --- a/examples/calculator/build.gradle.kts +++ b/examples/calculator/build.gradle.kts @@ -16,6 +16,8 @@ kotlin { } iosSimulatorArm64() iosArm64() + // The desktop: the façades in this JVM, the same suites + jvm() compilerOptions { optIn.add("kotlin.concurrent.atomics.ExperimentalAtomicApi") diff --git a/examples/calculator/src/androidDeviceTest/kotlin/com/example/calculator/TortureSupport.android.kt b/examples/calculator/src/androidDeviceTest/kotlin/com/example/calculator/client/TortureSupport.android.kt similarity index 94% rename from examples/calculator/src/androidDeviceTest/kotlin/com/example/calculator/TortureSupport.android.kt rename to examples/calculator/src/androidDeviceTest/kotlin/com/example/calculator/client/TortureSupport.android.kt index e36d876..7bd5550 100644 --- a/examples/calculator/src/androidDeviceTest/kotlin/com/example/calculator/TortureSupport.android.kt +++ b/examples/calculator/src/androidDeviceTest/kotlin/com/example/calculator/client/TortureSupport.android.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client actual class Thread actual constructor(body: () -> Unit) { // A JVM-like 8 MB stack, as the iOS threads (deep JVM <-> app nesting recurses on both sides) @@ -30,6 +30,8 @@ internal actual fun platformGc() { internal actual fun platformGetenv(name: String): String? = java.lang.System.getenv(name) +internal actual fun hostJvmVersion(): String? = null + private val missing: String? get() = java.lang.System.getProperty("nja.missing.property") internal actual fun appFaultStorm(count: Int): Int { diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/ArraysTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/ArraysTest.kt new file mode 100644 index 0000000..22289e4 --- /dev/null +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/ArraysTest.kt @@ -0,0 +1,59 @@ +package com.example.calculator.client + +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertNull + +class ArraysTest { + private val ops = ArrayOps() + + @Test + fun `primitive arrays go both ways`() { + assertEquals(6L, ops.sumInts(intArrayOf(1, 2, 3))) + assertEquals(0L, ops.sumInts(IntArray(0))) + assertContentEquals(longArrayOf(Long.MAX_VALUE, 0, Long.MIN_VALUE), ops.reverseLongs(longArrayOf(Long.MIN_VALUE, 0, Long.MAX_VALUE))) + assertContentEquals(floatArrayOf(2f, -4f), ops.scale(floatArrayOf(1f, -2f), 2f)) + assertContentEquals(doubleArrayOf(0.0, 1.0, 4.0, 9.0), ops.squares(4)) + } + + @Test + fun `large arrays`() { + val ids = LongArray(200_000) { it * 3L } + assertContentEquals(ids.reversedArray(), ops.reverseLongs(ids)) + assertEquals(200_000, ops.squares(200_000).size) + } + + @Test + fun `nullable arrays`() { + assertEquals(-1, ops.sizeOf(null)) + assertEquals(2, ops.sizeOf(longArrayOf(1, 2))) + assertNull(ops.maybe(false)) + assertContentEquals(intArrayOf(1, 2, 3), ops.maybe(true)) + } + + @Test + fun `arrays in a data class`() { + val normalized = ops.normalize(Embedding(longArrayOf(7, 8), floatArrayOf(3f, 4f), "v")) + assertContentEquals(longArrayOf(7, 8), normalized.ids) + assertContentEquals(floatArrayOf(0.6f, 0.8f), normalized.values) + assertEquals("v/n", normalized.label) + } + + @Test + fun `arrays through a callback`() { + assertContentEquals(doubleArrayOf(2.0, 4.0), ops.mapThroughApp(doubleArrayOf(1.0, 2.0)) { a -> DoubleArray(a.size) { a[it] * 2 } }) + } + + @Test + fun `float bits survive`() { + val bits = ops.bits() + assertEquals(6, bits.size) + assert(bits[0].isNaN()) { "NaN" } + assertEquals(Float.POSITIVE_INFINITY, bits[1]) + assertEquals(Float.NEGATIVE_INFINITY, bits[2]) + assertEquals((-0.0f).toRawBits(), bits[3].toRawBits()) + assertEquals(Float.MIN_VALUE, bits[4]) + assertEquals(Float.MAX_VALUE, bits[5]) + } +} diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/AsyncCallbackTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/AsyncCallbackTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/AsyncCallbackTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/AsyncCallbackTest.kt index fb6b2f9..5691ed7 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/AsyncCallbackTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/AsyncCallbackTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlin.test.Test import kotlin.test.assertEquals diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/AsyncCollectionTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/AsyncCollectionTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/AsyncCollectionTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/AsyncCollectionTest.kt index 69c1f22..44420de 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/AsyncCollectionTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/AsyncCollectionTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlin.test.Test import kotlin.test.assertEquals diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/AsyncCoreTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/AsyncCoreTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/AsyncCoreTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/AsyncCoreTest.kt index e82c292..36d6e1c 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/AsyncCoreTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/AsyncCoreTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlin.test.Test import kotlin.test.assertEquals diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/AsyncDataClassEnumTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/AsyncDataClassEnumTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/AsyncDataClassEnumTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/AsyncDataClassEnumTest.kt index dd59911..b68b490 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/AsyncDataClassEnumTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/AsyncDataClassEnumTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlin.test.Test import kotlin.test.assertEquals diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/AsyncInheritanceTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/AsyncInheritanceTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/AsyncInheritanceTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/AsyncInheritanceTest.kt index 5b6b58a..f19111d 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/AsyncInheritanceTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/AsyncInheritanceTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlin.test.Test import kotlin.test.assertEquals diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/AsyncSuspendFlowTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/AsyncSuspendFlowTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/AsyncSuspendFlowTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/AsyncSuspendFlowTest.kt index 515f2df..5a5a2f1 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/AsyncSuspendFlowTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/AsyncSuspendFlowTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlin.test.Test import kotlin.test.assertEquals diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/BufferTortureTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/BufferTortureTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/BufferTortureTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/BufferTortureTest.kt index bb66b2f..f560cbd 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/BufferTortureTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/BufferTortureTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlinx.coroutines.runBlocking import kotlin.random.Random diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/ByteArrayEverywhereTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/ByteArrayEverywhereTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/ByteArrayEverywhereTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/ByteArrayEverywhereTest.kt index 0dad707..b6c2d05 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/ByteArrayEverywhereTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/ByteArrayEverywhereTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlin.test.Test import kotlin.test.assertEquals diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/CallbackTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/CallbackTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/CallbackTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/CallbackTest.kt index 2d7b588..2eac38c 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/CallbackTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/CallbackTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import dev.nucleusframework.nja.JvmException diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/CollectionPropertyTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/CollectionPropertyTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/CollectionPropertyTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/CollectionPropertyTest.kt index 9235b49..77c5f39 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/CollectionPropertyTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/CollectionPropertyTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlin.test.Test import kotlin.test.assertEquals diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/CollectionTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/CollectionTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/CollectionTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/CollectionTest.kt index bd76d84..ecd12d2 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/CollectionTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/CollectionTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlin.test.Test import kotlin.test.assertEquals diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/CoreTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/CoreTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/CoreTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/CoreTest.kt index 3512e84..460f89c 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/CoreTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/CoreTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import dev.nucleusframework.nja.JvmException diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/CoroutineCrossFeatureTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/CoroutineCrossFeatureTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/CoroutineCrossFeatureTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/CoroutineCrossFeatureTest.kt index ca6514f..eff27fc 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/CoroutineCrossFeatureTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/CoroutineCrossFeatureTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlin.test.Test import kotlin.test.assertEquals diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/DataClassTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/DataClassTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/DataClassTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/DataClassTest.kt index a34422d..ad72930 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/DataClassTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/DataClassTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import dev.nucleusframework.nja.JvmException diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/DcCollectionFieldTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/DcCollectionFieldTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/DcCollectionFieldTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/DcCollectionFieldTest.kt index 7d70f7a..823efe6 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/DcCollectionFieldTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/DcCollectionFieldTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlin.test.Test import kotlin.test.assertEquals diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/EdgeCaseTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/EdgeCaseTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/EdgeCaseTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/EdgeCaseTest.kt index cce7e14..fac1b4a 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/EdgeCaseTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/EdgeCaseTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import dev.nucleusframework.nja.JvmException diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/EnumTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/EnumTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/EnumTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/EnumTest.kt index 9395235..77f6fcb 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/EnumTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/EnumTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlin.test.Test import kotlin.test.assertEquals diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/ExtensionFunctionTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/ExtensionFunctionTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/ExtensionFunctionTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/ExtensionFunctionTest.kt index b9d71d7..5546461 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/ExtensionFunctionTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/ExtensionFunctionTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlin.test.Test import kotlin.test.assertEquals diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/FlowByteArrayTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/FlowByteArrayTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/FlowByteArrayTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/FlowByteArrayTest.kt index 3f3fa66..750d543 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/FlowByteArrayTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/FlowByteArrayTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlin.test.Test import kotlin.test.assertEquals diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/FlowCollectionTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/FlowCollectionTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/FlowCollectionTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/FlowCollectionTest.kt index 620a147..eb7f918 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/FlowCollectionTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/FlowCollectionTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlin.test.Test import kotlin.test.assertEquals diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/FlowDataClassTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/FlowDataClassTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/FlowDataClassTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/FlowDataClassTest.kt index f74bce2..223c65f 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/FlowDataClassTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/FlowDataClassTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import dev.nucleusframework.nja.JvmException diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/FlowTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/FlowTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/FlowTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/FlowTest.kt index 1fdad3e..1086476 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/FlowTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/FlowTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import dev.nucleusframework.nja.JvmException diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/InheritanceEdgeCaseTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/InheritanceEdgeCaseTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/InheritanceEdgeCaseTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/InheritanceEdgeCaseTest.kt index d11b25d..b6c6a26 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/InheritanceEdgeCaseTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/InheritanceEdgeCaseTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlin.test.Test import kotlin.test.assertEquals diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/InheritanceTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/InheritanceTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/InheritanceTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/InheritanceTest.kt index e5e65ee..dc0f4be 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/InheritanceTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/InheritanceTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlin.test.Test import kotlin.math.PI diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/InterfaceTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/InterfaceTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/InterfaceTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/InterfaceTest.kt index 40b5958..c054124 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/InterfaceTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/InterfaceTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlin.test.Test import kotlin.test.assertEquals diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/LambdaReturnTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/LambdaReturnTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/LambdaReturnTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/LambdaReturnTest.kt index 5b8feb2..df7f7a2 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/LambdaReturnTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/LambdaReturnTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlin.test.Test import kotlin.test.assertEquals diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/ListDataClassParamTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/ListDataClassParamTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/ListDataClassParamTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/ListDataClassParamTest.kt index 6d60980..c6445aa 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/ListDataClassParamTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/ListDataClassParamTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlin.test.Test import kotlin.test.assertEquals diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/LoadAndConcurrencyTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/LoadAndConcurrencyTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/LoadAndConcurrencyTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/LoadAndConcurrencyTest.kt index a69eb8e..8213290 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/LoadAndConcurrencyTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/LoadAndConcurrencyTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlin.test.Test import kotlin.test.assertEquals diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/LoadInheritanceTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/LoadInheritanceTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/LoadInheritanceTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/LoadInheritanceTest.kt index a2deed1..35395b3 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/LoadInheritanceTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/LoadInheritanceTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlin.test.Test import kotlin.test.assertEquals diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/MonkeyTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/MonkeyTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/MonkeyTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/MonkeyTest.kt index ad802ef..7462e10 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/MonkeyTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/MonkeyTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import dev.nucleusframework.nja.JvmException diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/NestedClassTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/NestedClassTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/NestedClassTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/NestedClassTest.kt index 90e6107..26d070b 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/NestedClassTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/NestedClassTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlin.test.Test import kotlin.test.assertEquals diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/NestedCollectionTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/NestedCollectionTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/NestedCollectionTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/NestedCollectionTest.kt index 0f1bccf..780e949 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/NestedCollectionTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/NestedCollectionTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlin.test.Test import kotlin.test.assertEquals diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/NestedDataClassTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/NestedDataClassTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/NestedDataClassTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/NestedDataClassTest.kt index 5e853f7..62442df 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/NestedDataClassTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/NestedDataClassTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlin.test.Test import kotlin.test.assertEquals diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/NjaTortureTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/NjaTortureTest.kt similarity index 95% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/NjaTortureTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/NjaTortureTest.kt index c845b87..68e97d7 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/NjaTortureTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/NjaTortureTest.kt @@ -1,7 +1,7 @@ -package com.example.calculator +package com.example.calculator.client -import com.example.torture.JvmTorture -import com.example.torture.Node +import com.example.torture.client.JvmTorture +import com.example.torture.client.Node import dev.nucleusframework.nja.JvmException import dev.nucleusframework.nja.NjaInternal import dev.nucleusframework.nja.NjaRuntime @@ -35,8 +35,14 @@ class NjaTortureTest { fun `the JVM is the expected one`() { val vm = jvm.vm() println("NJA torture on ${vm.name} ${vm.version} (${vm.os}/${vm.arch}, ${vm.processors} cpus)") - assertTrue(vm.version.startsWith("27"), "$vm") - assertTrue(vm.name.contains("Server") || vm.name.contains("Zero"), "$vm") + val host = hostJvmVersion() + if (host != null) { + // A JVM target: the façades run in the tests' own JVM + assertEquals(host, vm.version, "$vm") + } else { + assertTrue(vm.version.startsWith("27"), "$vm") + assertTrue(vm.name.contains("Server") || vm.name.contains("Zero"), "$vm") + } } @Test diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/NullableCallbackTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/NullableCallbackTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/NullableCallbackTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/NullableCallbackTest.kt index ec6c4c9..6cdec86 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/NullableCallbackTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/NullableCallbackTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlin.test.Test import kotlin.test.assertEquals diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/NullableTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/NullableTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/NullableTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/NullableTest.kt index c838f4f..a72ed6d 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/NullableTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/NullableTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlin.test.Test import kotlin.test.assertEquals diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/ObjectTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/ObjectTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/ObjectTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/ObjectTest.kt index 8a5eeb5..f9d1675 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/ObjectTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/ObjectTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlin.test.Test import kotlin.test.assertEquals diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/RuntimeTortureTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/RuntimeTortureTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/RuntimeTortureTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/RuntimeTortureTest.kt index 1e5e1fb..63952a6 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/RuntimeTortureTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/RuntimeTortureTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/SealedClassTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/SealedClassTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/SealedClassTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/SealedClassTest.kt index 5391560..fce56fa 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/SealedClassTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/SealedClassTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlin.test.Test import kotlin.test.assertEquals diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/SealedValuesTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/SealedValuesTest.kt new file mode 100644 index 0000000..65c7564 --- /dev/null +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/SealedValuesTest.kt @@ -0,0 +1,49 @@ +package com.example.calculator.client + +import kotlin.math.PI +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertSame + +class SealedValuesTest { + private val geometry = Geometry() + + @Test + fun `each case goes both ways`() { + assertEquals(PI * 4, geometry.area(Figure.Circle(2.0)), 1e-9) + assertEquals(6.0, geometry.area(Figure.Rect(2.0, 3.0))) + assertEquals(0.0, geometry.area(Figure.Empty)) + assertEquals(Figure.Rect(4.0, 6.0), geometry.scale(Figure.Rect(2.0, 3.0), 2.0)) + assertSame(Figure.Empty, geometry.scale(Figure.Empty, 2.0)) + } + + @Test + fun `nested and recursive values`() { + val group = Figure.Group("g", listOf(Figure.Rect(1.0, 1.0), Figure.Group("inner", listOf(Figure.Rect(2.0, 2.0)))), anchor = Figure.Circle(1.0)) + assertEquals(5.0, geometry.area(group)) + assertEquals( + Figure.Group("g", listOf(Figure.Rect(2.0, 2.0), Figure.Group("inner", listOf(Figure.Rect(4.0, 4.0)))), anchor = Figure.Circle(2.0)), + geometry.scale(group, 2.0), + ) + assertEquals(listOf(Figure.Rect(1.0, 1.0), Figure.Rect(2.0, 2.0)), geometry.flatten(group)) + val deep = geometry.nested(200) + assertEquals(200, geometry.depth(deep)) + assertEquals(deep, geometry.scale(geometry.scale(deep, 1.0), 1.0)) + } + + @Test + fun `in a data class, nullable, through a callback`() { + assertEquals(12.0, geometry.layerArea(Layer(Figure.Rect(2.0, 3.0), setOf("a", "b")))) + assertNull(geometry.maybe(false)) + assertEquals(Figure.Rect(2.0, 3.0), geometry.maybe(true)) + assertEquals(Figure.Circle(9.0), geometry.viaApp(Figure.Circle(3.0)) { s -> Figure.Circle((s as Figure.Circle).radius * 3) }) + } + + @Test + fun `a sealed class`() { + assertEquals(5L, geometry.eval(Op.Add(2, 3))) + assertEquals(10L, geometry.eval(Op.Sum(longArrayOf(1, 2, 3, 4)))) + assertEquals(0L, geometry.eval(Op.Noop)) + } +} diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/SmokeTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/SmokeTest.kt similarity index 96% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/SmokeTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/SmokeTest.kt index 5635555..9658897 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/SmokeTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/SmokeTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import dev.nucleusframework.nja.JvmException diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/SuspendBasicTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/SuspendBasicTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/SuspendBasicTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/SuspendBasicTest.kt index 69db75b..433264f 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/SuspendBasicTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/SuspendBasicTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import dev.nucleusframework.nja.JvmException diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/SuspendCollectionTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/SuspendCollectionTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/SuspendCollectionTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/SuspendCollectionTest.kt index 4ee3572..ede59e8 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/SuspendCollectionTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/SuspendCollectionTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlin.test.Test import kotlin.test.assertEquals diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/SuspendCrossFeatureTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/SuspendCrossFeatureTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/SuspendCrossFeatureTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/SuspendCrossFeatureTest.kt index 990c077..2fd6903 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/SuspendCrossFeatureTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/SuspendCrossFeatureTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlin.test.Test import kotlin.test.assertEquals diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/SuspendDataClassTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/SuspendDataClassTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/SuspendDataClassTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/SuspendDataClassTest.kt index a78a573..db630af 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/SuspendDataClassTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/SuspendDataClassTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlin.test.Test import kotlin.test.assertEquals diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/SuspendEdgeCaseTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/SuspendEdgeCaseTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/SuspendEdgeCaseTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/SuspendEdgeCaseTest.kt index ca7f02e..f68181d 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/SuspendEdgeCaseTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/SuspendEdgeCaseTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlin.test.Test import kotlin.test.assertEquals diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/SuspendHeavyTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/SuspendHeavyTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/SuspendHeavyTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/SuspendHeavyTest.kt index c3d85d6..03dcc33 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/SuspendHeavyTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/SuspendHeavyTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import dev.nucleusframework.nja.JvmException diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/TortureSupport.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/TortureSupport.kt similarity index 96% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/TortureSupport.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/TortureSupport.kt index 9f85cd0..cba10ba 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/TortureSupport.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/TortureSupport.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlin.concurrent.atomics.AtomicBoolean import kotlin.concurrent.atomics.AtomicInt @@ -33,6 +33,9 @@ internal expect fun platformGc() internal expect fun platformGetenv(name: String): String? +/** On a JVM target, the version of the JVM the tests (and so the façades) run in; on the mobile ones, null (jdk-mobile). */ +internal expect fun hostJvmVersion(): String? + object System { private val origin = TimeSource.Monotonic.markNow() diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/ValueTypeParityTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/ValueTypeParityTest.kt similarity index 98% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/ValueTypeParityTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/ValueTypeParityTest.kt index df20e07..fa71f6e 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/ValueTypeParityTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/ValueTypeParityTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlin.test.Test import kotlin.test.assertEquals diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/ValueTypeTortureTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/ValueTypeTortureTest.kt similarity index 99% rename from examples/calculator/src/commonTest/kotlin/com/example/calculator/ValueTypeTortureTest.kt rename to examples/calculator/src/commonTest/kotlin/com/example/calculator/client/ValueTypeTortureTest.kt index 0611fcd..6dad65d 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/ValueTypeTortureTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/ValueTypeTortureTest.kt @@ -1,4 +1,4 @@ -package com.example.calculator +package com.example.calculator.client import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async diff --git a/examples/calculator/src/iosTest/kotlin/com/example/calculator/TortureSupport.ios.kt b/examples/calculator/src/iosTest/kotlin/com/example/calculator/client/TortureSupport.ios.kt similarity index 97% rename from examples/calculator/src/iosTest/kotlin/com/example/calculator/TortureSupport.ios.kt rename to examples/calculator/src/iosTest/kotlin/com/example/calculator/client/TortureSupport.ios.kt index e118852..7d208e2 100644 --- a/examples/calculator/src/iosTest/kotlin/com/example/calculator/TortureSupport.ios.kt +++ b/examples/calculator/src/iosTest/kotlin/com/example/calculator/client/TortureSupport.ios.kt @@ -1,6 +1,6 @@ @file:OptIn(ExperimentalForeignApi::class, ExperimentalNativeApi::class, NativeRuntimeApi::class) -package com.example.calculator +package com.example.calculator.client import kotlinx.cinterop.COpaquePointer import kotlinx.cinterop.ExperimentalForeignApi @@ -111,6 +111,8 @@ internal actual fun platformGc() = GC.collect() internal actual fun platformGetenv(name: String): String? = getenv(name)?.toKString() +internal actual fun hostJvmVersion(): String? = null + internal actual fun appFaultStorm(count: Int): Int { var caught = 0 val holder: Any? = if (count < 0) "never" else null diff --git a/examples/calculator/src/jvmTest/kotlin/com/example/calculator/client/TortureSupport.jvm.kt b/examples/calculator/src/jvmTest/kotlin/com/example/calculator/client/TortureSupport.jvm.kt new file mode 100644 index 0000000..d90234a --- /dev/null +++ b/examples/calculator/src/jvmTest/kotlin/com/example/calculator/client/TortureSupport.jvm.kt @@ -0,0 +1,48 @@ +package com.example.calculator.client + +actual class Thread actual constructor(body: () -> Unit) { + // A JVM-like 8 MB stack, as the iOS threads (deep JVM <-> app nesting recurses on both sides) + private val thread = java.lang.Thread(null, body, "test", 8L * 1024 * 1024) + + actual fun start() = thread.start() + actual fun join() = thread.join() + actual fun join(millis: Long): Boolean { + thread.join(millis) + return !thread.isAlive + } + + actual companion object { + actual fun sleep(millis: Long) = java.lang.Thread.sleep(millis) + actual fun sleep(millis: Long, nanos: Int) = java.lang.Thread.sleep(millis, nanos) + actual fun yield() = java.lang.Thread.yield() + } +} + +actual class WeakReference actual constructor(referent: T) { + private val reference = java.lang.ref.WeakReference(referent) + actual fun get(): T? = reference.get() +} + +internal actual fun platformGc() { + Runtime.getRuntime().gc() + java.lang.System.runFinalization() +} + +internal actual fun platformGetenv(name: String): String? = java.lang.System.getenv(name) + +internal actual fun hostJvmVersion(): String? = Runtime.version().toString() + +private val missing: String? get() = java.lang.System.getProperty("nja.missing.property") + +internal actual fun appFaultStorm(count: Int): Int { + var caught = 0 + repeat(count) { + try { + // A platform-typed receiver: no Kotlin null check, HotSpot's compiled code faults on the null (its own SIGSEGV) + java.lang.System.getProperty("nja.missing.property").length + } catch (e: NullPointerException) { + caught++ + } + } + return caught + (if (missing == null) 0 else 0) +} diff --git a/examples/torture-facade/build.gradle.kts b/examples/torture-facade/build.gradle.kts index efed688..a92bbe9 100644 --- a/examples/torture-facade/build.gradle.kts +++ b/examples/torture-facade/build.gradle.kts @@ -11,6 +11,7 @@ kotlin { njaFacade { libName = "torture" + clientPackage = "com.example.torture.client" } dependencies { diff --git a/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/NjaPlugin.kt b/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/NjaPlugin.kt index 3de7984..5867b99 100644 --- a/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/NjaPlugin.kt +++ b/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/NjaPlugin.kt @@ -5,6 +5,7 @@ import com.android.build.api.variant.AndroidComponentsExtension import com.android.build.api.variant.HasDeviceTests import dev.nucleusframework.nja.plugin.tasks.NjaAndroidLinkTask import dev.nucleusframework.nja.plugin.tasks.NjaAndroidRuntimeTask +import dev.nucleusframework.nja.plugin.tasks.PACKAGES_FILE import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.artifacts.Configuration @@ -21,6 +22,7 @@ import org.jetbrains.kotlin.gradle.plugin.KotlinPlatformType import org.jetbrains.kotlin.gradle.plugin.mpp.Executable import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget import org.jetbrains.kotlin.gradle.plugin.mpp.TestExecutable +import org.jetbrains.kotlin.gradle.targets.jvm.KotlinJvmTarget import org.jetbrains.kotlin.konan.target.Family import org.jetbrains.kotlin.konan.target.KonanTarget import java.io.File @@ -46,8 +48,9 @@ abstract class NjaExtension(private val project: Project) { } /** - * Applied to a Kotlin Multiplatform module (Android and/or iOS): its common code gets the façades' proxies, and its - * binaries the JVM: on Android HotSpot, in the app's process next to ART; on iOS Zero, linked into the app. + * Applied to a Kotlin Multiplatform module (Android, iOS, the JVM): its common code gets the façades' proxies, and its + * binaries the JVM: on Android HotSpot, in the app's process next to ART; on iOS Zero, linked into the app; on a JVM + * target the app's own JVM, the façades on its class path. */ class NjaPlugin : Plugin { override fun apply(project: Project) { @@ -72,6 +75,7 @@ class NjaPlugin : Plugin { kotlin.targets.withType(KotlinNativeTarget::class.java).configureEach { if (konanTarget.family == Family.IOS) configureIos(project, extension, classPath.get(), this) } + kotlin.targets.withType(KotlinJvmTarget::class.java).configureEach { configureJvm(project, this, facades, clientSources.get()) } } listOf("com.android.kotlin.multiplatform.library", "com.android.application", "com.android.library").forEach { id -> project.pluginManager.withPlugin(id) { configureAndroid(project, extension, classPath.get()) } @@ -139,6 +143,33 @@ class NjaPlugin : Plugin { ?: throw IllegalStateException("NJA: no NDK found (set ANDROID_NDK_HOME)") } + /** + * A JVM target runs the façades in its own JVM: they go on its runtime class path only (its code sees the proxies, + * not the façades), so the proxies need a package of their own, checked before it compiles. + */ + private fun configureJvm(project: Project, target: KotlinJvmTarget, facades: Configuration, clientSources: Configuration) { + val main = target.compilations.getByName("main") + project.configurations.getByName(main.defaultSourceSet.runtimeOnlyConfigurationName).extendsFrom(facades) + // The client sources' directories (built by the façades' generation tasks) + val sourceDirs = project.files(clientSources) + val check = project.tasks.register("checkNja${target.name.replaceFirstChar(Char::uppercase)}ClientPackages") { + description = "Checks that the façades' proxies have packages of their own, apart from the façades'." + inputs.files(sourceDirs) + doLast { + for (file in sourceDirs.files.map { File(it, PACKAGES_FILE) }.filter { it.isFile }) { + val packages = Properties().apply { file.reader().use { load(it) } } + val client = packages.getProperty("client") + val facade = packages.getProperty("facade").orEmpty().split(',').filter { it.isNotEmpty() } + check(client !in facade) { + "NJA: the proxies of a façade used on the JVM need a package of their own (both are on its class path): " + + "set njaFacade.clientPackage, not $client" + } + } + } + } + project.tasks.named(main.compileKotlinTaskName) { dependsOn(check) } + } + private fun configureIos(project: Project, extension: NjaExtension, classPath: Configuration, target: KotlinNativeTarget) { val dirName = when (target.konanTarget) { KonanTarget.IOS_SIMULATOR_ARM64 -> "ios-simulator-aarch64" diff --git a/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/analysis/ParseModel.kt b/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/analysis/ParseModel.kt index 7ead798..d36153e 100644 --- a/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/analysis/ParseModel.kt +++ b/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/analysis/ParseModel.kt @@ -5,6 +5,7 @@ import dev.nucleusframework.nja.plugin.ir.ApiDataClass import dev.nucleusframework.nja.plugin.ir.ApiEnum import dev.nucleusframework.nja.plugin.ir.ApiFunction import dev.nucleusframework.nja.plugin.ir.ApiInterface +import dev.nucleusframework.nja.plugin.ir.ApiSealedValue import java.io.Serializable import java.security.MessageDigest @@ -17,6 +18,7 @@ data class FileFragment( /** Keyed by function name, or `Receiver.name` for extension functions. */ val functions: List>, val interfaces: List, + val sealedValues: List = emptyList(), ) : Serializable data class CachedSourceFile( val contentHash: String, diff --git a/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/analysis/PsiSourceParser.kt b/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/analysis/PsiSourceParser.kt index 6940ad1..eb5c935 100644 --- a/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/analysis/PsiSourceParser.kt +++ b/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/analysis/PsiSourceParser.kt @@ -10,6 +10,7 @@ import dev.nucleusframework.nja.plugin.ir.ApiInterface import dev.nucleusframework.nja.plugin.ir.ApiModule import dev.nucleusframework.nja.plugin.ir.ApiParam import dev.nucleusframework.nja.plugin.ir.ApiProperty +import dev.nucleusframework.nja.plugin.ir.ApiSealedValue import dev.nucleusframework.nja.plugin.ir.ApiSourceDecl import dev.nucleusframework.nja.plugin.ir.ApiType import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreApplicationEnvironment @@ -135,7 +136,9 @@ class PsiSourceParser { val name = decl.name ?: continue val fq = if (parentFq != null) "$parentFq.$name" else if (pkg.isNotEmpty()) "$pkg.$name" else name + val cases = sealedValueCases(decl) when { + cases != null -> decls += PrescanDecl(name, fq, DeclKind.SEALED_VALUE, cases = cases) decl.isEnum() -> decls += PrescanDecl(name, fq, DeclKind.ENUM) decl.isData() -> decls += PrescanDecl(name, fq, DeclKind.DATA_CLASS, dataParams(decl)) decl.isInterface() -> decls += PrescanDecl(name, fq, DeclKind.INTERFACE) @@ -150,6 +153,24 @@ class PsiSourceParser { return decls } + /** + * The cases of a sealed value hierarchy: a sealed interface or class whose nested declarations are all data + * classes or objects (a companion aside), at least one; null for any other declaration. + */ + private fun sealedValueCases(decl: KtClass): List? { + if (!decl.hasModifier(KtTokens.SEALED_KEYWORD)) return null + val cases = mutableListOf() + for (nested in decl.declarations) { + when { + nested is KtObjectDeclaration && nested.isCompanion() -> continue + nested is KtObjectDeclaration -> cases += SealedCaseSyntax(nested.name ?: return null, isObject = true, params = null) + nested is KtClass && nested.isData() -> cases += SealedCaseSyntax(nested.name ?: return null, isObject = false, params = dataParams(nested)) + nested is KtClass -> return null + } + } + return cases.ifEmpty { null } + } + private fun dataParams(ktClass: KtClass): List? = ktClass.primaryConstructor?.valueParameters?.map { param -> DataParamSyntax(param.name, param.hasValOrVar(), param.typeReference.toSyntax()) @@ -163,11 +184,16 @@ class PsiSourceParser { val enums = mutableListOf() val functions = mutableListOf>() val interfaces = mutableListOf() + val sealedValues = mutableListOf() fun processDeclarations(declarations: List, parentSimpleName: String?, isTopLevel: Boolean) { for (decl in declarations) { if (decl.isPrivateOrInternal()) continue + val sealed = (decl as? KtClass)?.name?.let { scope.sealedValue(it) } when { + decl is KtClass && sealed != null -> sealedValues += ApiSealedValue( + decl.name!!, sealed.first, sealed.second, source = sourceDecl(decl, imports), + ) decl is KtClass && decl.isEnum() -> parseEnum(decl, pkg, scope) ?.copy(source = sourceDecl(decl, imports)) ?.let { enums += it } @@ -211,7 +237,7 @@ class PsiSourceParser { } } processDeclarations(ktFile.declarations.toList(), null, true) - return FileFragment(pkg, classes, dataClasses, enums, functions, interfaces) + return FileFragment(pkg, classes, dataClasses, enums, functions, interfaces, sealedValues) } /** Merges per-file fragments in source order; the first declaration of a given FQ name wins. */ @@ -221,6 +247,7 @@ class PsiSourceParser { val enumMap = LinkedHashMap() val functionMap = LinkedHashMap() val interfaceMap = LinkedHashMap() + val sealedMap = LinkedHashMap() val packages = LinkedHashSet() for (fragment in fragments) { @@ -230,6 +257,7 @@ class PsiSourceParser { fragment.enums.forEach { enumMap.putIfAbsent(it.fqName, it) } fragment.functions.forEach { (key, fn) -> functionMap.putIfAbsent(key, fn) } fragment.interfaces.forEach { interfaceMap.putIfAbsent(it.fqName, it) } + fragment.sealedValues.forEach { sealedMap.putIfAbsent(it.fqName, it) } } // Ensure common data classes are present even if only defined in commonMain @@ -240,7 +268,7 @@ class PsiSourceParser { return ApiModule( libName, packages, classMap.values.toList(), dataClassMap.values.toList(), - enumMap.values.toList(), functionMap.values.toList(), interfaceMap.values.toList(), + enumMap.values.toList(), functionMap.values.toList(), interfaceMap.values.toList(), sealedMap.values.toList(), ) } diff --git a/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/analysis/SymbolTable.kt b/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/analysis/SymbolTable.kt index 5d007a7..c4fd247 100644 --- a/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/analysis/SymbolTable.kt +++ b/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/analysis/SymbolTable.kt @@ -1,6 +1,7 @@ package dev.nucleusframework.nja.plugin.analysis import dev.nucleusframework.nja.plugin.ir.ApiParam +import dev.nucleusframework.nja.plugin.ir.ApiSealedCase import dev.nucleusframework.nja.plugin.ir.ApiType import java.io.Serializable @@ -15,22 +16,32 @@ sealed interface TypeSyntax : Serializable { data object Unsupported : TypeSyntax } -enum class DeclKind { ENUM, DATA_CLASS, INTERFACE, CLASS } +enum class DeclKind { ENUM, DATA_CLASS, INTERFACE, CLASS, SEALED_VALUE } /** A primary-constructor parameter of a data class, kept unresolved until the global symbol table exists. */ data class DataParamSyntax(val name: String?, val isProperty: Boolean, val type: TypeSyntax?) : Serializable -/** A type declaration discovered by the prescan phase. [dataParams] is null when there is no primary constructor. */ +/** A case of a sealed value hierarchy: a nested data class ([params]) or object ([isObject]). */ +data class SealedCaseSyntax(val name: String, val isObject: Boolean, val params: List?) : Serializable + +/** + * A type declaration discovered by the prescan phase. [dataParams] is null when there is no primary constructor; + * [cases] are those of a sealed value hierarchy. + */ data class PrescanDecl( val name: String, val fqName: String, val kind: DeclKind, val dataParams: List? = null, + val cases: List? = null, ) : Serializable /** Resolved data class: FQ name + resolved fields. */ typealias ResolvedDataClass = Pair> +/** Resolved sealed value hierarchy: FQ name + its cases. */ +typealias ResolvedSealedValue = Pair> + /** * Everything the symbol table knows about a simple name. Per-file parse results record the * [SymbolInfo] of every name they looked up; a cached result stays valid as long as those @@ -42,6 +53,7 @@ data class SymbolInfo( val interfaceFq: String?, val classFq: String?, val isCommonDataClass: Boolean, + val sealedValue: ResolvedSealedValue? = null, ) : Serializable /** Name-based lookups used to resolve [TypeSyntax] into [ApiType]. */ @@ -50,6 +62,7 @@ interface TypeScope { fun dataClass(name: String): ResolvedDataClass? fun interfaceFq(name: String): String? fun classFq(name: String): String? + fun sealedValue(name: String): ResolvedSealedValue? = null } /** Global symbol table built from the prescan results of all source files, in merge order. */ @@ -59,6 +72,7 @@ class SymbolTable private constructor( private val interfaces: Map, private val classes: Map, val commonDataClassNames: Set, + val sealedValues: Map = emptyMap(), ) { fun info(name: String): SymbolInfo? { @@ -68,6 +82,7 @@ class SymbolTable private constructor( interfaceFq = interfaces[name], classFq = classes[name], isCommonDataClass = name in commonDataClassNames, + sealedValue = sealedValues[name], ) return info.takeUnless { it == UNKNOWN } } @@ -81,6 +96,7 @@ class SymbolTable private constructor( val interfaces = LinkedHashMap() val classes = LinkedHashMap() val rawDataClasses = LinkedHashMap() + val rawSealed = LinkedHashMap() val commonDataClassNames = LinkedHashSet() for ((decls, isCommon) in files) { @@ -91,37 +107,56 @@ class SymbolTable private constructor( DeclKind.DATA_CLASS -> rawDataClasses[decl.name] = decl DeclKind.INTERFACE -> interfaces[decl.name] = decl.fqName DeclKind.CLASS -> classes[decl.name] = decl.fqName + DeclKind.SEALED_VALUE -> rawSealed[decl.name] = decl } } if (isCommon) commonDataClassNames += rawDataClasses.keys - dataClassesBefore } - // Resolve data class fields iteratively (a data class may nest another one) + // Value types (data classes, sealed value hierarchies) may nest one another, recursively: resolve them all + // assuming every candidate is one (types reference them by name), drop those with an unresolvable field, + // and again until none drops. Those dropped are exported as regular classes + val valueData = rawDataClasses.keys.toMutableSet() + val valueSealed = rawSealed.keys.toMutableSet() val dataClasses = LinkedHashMap() - val scope = object : TypeScope { - override fun enumFq(name: String) = enums[name] - override fun dataClass(name: String) = dataClasses[name] - override fun interfaceFq(name: String): String? = null - override fun classFq(name: String) = classes[name] - } - var changed = true - while (changed) { - changed = false - for ((name, decl) in rawDataClasses) { - if (name in dataClasses) continue - val fields = resolveDataClassFields(decl.dataParams, scope) ?: continue - dataClasses[name] = decl.fqName to fields - changed = true + val sealedValues = LinkedHashMap() + while (true) { + val scope = object : TypeScope { + override fun enumFq(name: String) = enums[name] + override fun dataClass(name: String) = if (name in valueData) rawDataClasses.getValue(name).fqName to emptyList() else null + override fun sealedValue(name: String) = if (name in valueSealed) rawSealed.getValue(name).fqName to emptyList() else null + override fun interfaceFq(name: String): String? = null + override fun classFq(name: String) = classes[name] } + dataClasses.clear() + sealedValues.clear() + for (name in valueData) { + val decl = rawDataClasses.getValue(name) + resolveDataClassFields(decl.dataParams, scope)?.let { dataClasses[name] = decl.fqName to it } + } + for (name in valueSealed) { + val decl = rawSealed.getValue(name) + resolveCases(decl, scope)?.let { sealedValues[name] = decl.fqName to it } + } + val dropped = valueData.retainAll(dataClasses.keys) or valueSealed.retainAll(sealedValues.keys) + if (!dropped) break } - // Unresolvable data classes are exported as regular classes for ((name, decl) in rawDataClasses) { if (name !in dataClasses) classes[name] = decl.fqName } + for ((name, decl) in rawSealed) { + if (name !in sealedValues) interfaces[name] = decl.fqName + } - return SymbolTable(enums, dataClasses, interfaces, classes, commonDataClassNames) + return SymbolTable(enums, dataClasses, interfaces, classes, commonDataClassNames, sealedValues) } + private fun resolveCases(decl: PrescanDecl, scope: TypeScope): List? = + decl.cases?.map { case -> + val fields = if (case.isObject) emptyList() else resolveDataClassFields(case.params, scope) ?: return null + ApiSealedCase(case.name, "${decl.fqName}.${case.name}", case.isObject, fields) + }?.ifEmpty { null } + private fun resolveDataClassFields(params: List?, scope: TypeScope): List? { params ?: return null val fields = mutableListOf() @@ -151,6 +186,7 @@ class RecordingScope(private val table: SymbolTable) : TypeScope { override fun dataClass(name: String) = info(name)?.dataClass override fun interfaceFq(name: String) = info(name)?.interfaceFq override fun classFq(name: String) = info(name)?.classFq + override fun sealedValue(name: String) = info(name)?.sealedValue fun isCommonDataClass(name: String) = info(name)?.isCommonDataClass == true } @@ -178,7 +214,7 @@ object TypeResolver { private fun resolveFunction(type: TypeSyntax.Function, scope: TypeScope): ApiType? { val paramTypes = type.params.mapNotNull { resolve(it, scope) } val returnType = resolve(type.returnType, scope) ?: ApiType.UNIT - fun ok(t: ApiType) = t in CALLBACK_PRIMITIVES || t == ApiType.BYTE_ARRAY || t is ApiType.DATA_CLASS || + fun ok(t: ApiType) = t in CALLBACK_PRIMITIVES || t in ApiType.ARRAYS || t is ApiType.DATA_CLASS || t is ApiType.SEALED_VALUE || t is ApiType.ENUM || t is ApiType.OBJECT || t is ApiType.INTERFACE || t is ApiType.LIST || t is ApiType.SET || t is ApiType.MAP if (paramTypes.any { !ok(it) } || !(ok(returnType) || returnType == ApiType.UNIT)) return null @@ -192,12 +228,15 @@ object TypeResolver { "Int" -> ApiType.INT; "Long" -> ApiType.LONG; "Double" -> ApiType.DOUBLE; "Float" -> ApiType.FLOAT "Boolean" -> ApiType.BOOLEAN; "Byte" -> ApiType.BYTE; "Short" -> ApiType.SHORT "String" -> ApiType.STRING; "ByteArray" -> ApiType.BYTE_ARRAY; "Unit" -> ApiType.UNIT + "IntArray" -> ApiType.INT_ARRAY; "LongArray" -> ApiType.LONG_ARRAY + "FloatArray" -> ApiType.FLOAT_ARRAY; "DoubleArray" -> ApiType.DOUBLE_ARRAY "List", "MutableList" -> if (typeArgs.size == 1) ApiType.LIST(typeArgs[0]) else null "Set", "MutableSet" -> if (typeArgs.size == 1) ApiType.SET(typeArgs[0]) else null "Map", "MutableMap" -> if (typeArgs.size == 2) ApiType.MAP(typeArgs[0], typeArgs[1]) else null "Flow" -> if (typeArgs.size == 1) ApiType.FLOW(typeArgs[0]) else null else -> scope.enumFq(name)?.let { ApiType.ENUM(it, name) } ?: scope.dataClass(name)?.let { ApiType.DATA_CLASS(it.first, name, it.second) } + ?: scope.sealedValue(name)?.let { ApiType.SEALED_VALUE(it.first, name) } ?: scope.interfaceFq(name)?.let { ApiType.INTERFACE(it, name) } ?: scope.classFq(name)?.let { ApiType.OBJECT(it, name) } } diff --git a/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/codegen/ClientGenerator.kt b/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/codegen/ClientGenerator.kt index 4b8053a..bafecb3 100644 --- a/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/codegen/ClientGenerator.kt +++ b/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/codegen/ClientGenerator.kt @@ -4,6 +4,8 @@ import dev.nucleusframework.nja.plugin.ir.ApiClass import dev.nucleusframework.nja.plugin.ir.ApiFunction import dev.nucleusframework.nja.plugin.ir.ApiInterface import dev.nucleusframework.nja.plugin.ir.ApiProperty +import dev.nucleusframework.nja.plugin.ir.ApiSealedCase +import dev.nucleusframework.nja.plugin.ir.ApiSealedValue import dev.nucleusframework.nja.plugin.ir.ApiSourceDecl import dev.nucleusframework.nja.plugin.ir.ApiType @@ -45,6 +47,7 @@ class ClientGenerator(private val model: ApiModel, private val libName: String, model.module.interfaces.forEach { files["$dir/${it.simpleName}.kt"] = file { appendInterface(it) } } model.module.dataClasses.forEach { dc -> dc.source?.let { files["$dir/${dc.simpleName}.kt"] = valueType(it) } } model.module.enums.forEach { e -> e.source?.let { files["$dir/${e.simpleName}.kt"] = valueType(it) } } + model.module.sealedValues.forEach { v -> v.source?.let { files["$dir/${v.simpleName}.kt"] = valueType(it) } } files["$dir/$moduleObject.kt"] = file { appendModule() } return files } @@ -61,7 +64,7 @@ class ClientGenerator(private val model: ApiModel, private val libName: String, body() } - /** A value type (data class or enum) exactly as the façade declares it. */ + /** A value type (data class, enum, sealed value hierarchy) exactly as the façade declares it. */ private fun valueType(source: ApiSourceDecl): String = buildString { appendLine("// Generated by NJA from the $libName façade. Do not modify.") appendLine("package $packageName") @@ -292,6 +295,7 @@ class ClientGenerator(private val model: ApiModel, private val libName: String, dc.fields.forEach { f -> appendLine(" ${esc(f.name)} = ${codec.decode(f.type, "r")},") } appendLine(")") } + for (v in model.module.sealedValues) appendSealedCodec(v, v.simpleName, "njaS: CallScope") { "${v.simpleName}.${it.name}" } // The JVM's lambdas, by signature for ((key, invoke) in model.invokers) { @@ -305,4 +309,32 @@ class ClientGenerator(private val model: ApiModel, private val libName: String, appendLine("}") } } + + // Its case's index, then the case's fields + private fun StringBuilder.appendSealedCodec(v: ApiSealedValue, type: String, extra: String, caseName: (ApiSealedCase) -> String) { + appendLine() + appendLine("internal fun nja_write_${v.simpleName}(w: WireWriter, value: $type, $extra) {") + appendLine(" when (value) {") + v.cases.forEachIndexed { i, case -> + appendLine(" is ${caseName(case)} -> {") + appendLine(" w.writeInt($i)") + case.fields.forEach { f -> appendLine(" ${codec.encode(f.type, "value.${esc(f.name)}", "w")}") } + appendLine(" }") + } + appendLine(" }") + appendLine("}") + appendLine() + appendLine("internal fun nja_read_${v.simpleName}(r: WireReader): $type = when (val njaCase = r.readInt()) {") + v.cases.forEachIndexed { i, case -> + if (case.isObject) { + appendLine(" $i -> ${caseName(case)}") + } else { + appendLine(" $i -> ${caseName(case)}(") + case.fields.forEach { f -> appendLine(" ${esc(f.name)} = ${codec.decode(f.type, "r")},") } + appendLine(" )") + } + } + appendLine(" else -> throw IllegalStateException(\"NJA: unknown case \$njaCase of $type\")") + appendLine("}") + } } diff --git a/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/codegen/Codec.kt b/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/codegen/Codec.kt index 2a0b67c..9b08cb6 100644 --- a/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/codegen/Codec.kt +++ b/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/codegen/Codec.kt @@ -26,9 +26,14 @@ class Codec(private val model: ApiModel, private val side: Side) { ApiType.SHORT -> "$w.writeShort($value)" ApiType.STRING -> "$w.writeString($value)" ApiType.BYTE_ARRAY -> "$w.writeBytes($value)" + ApiType.INT_ARRAY -> "$w.writeInts($value)" + ApiType.LONG_ARRAY -> "$w.writeLongs($value)" + ApiType.FLOAT_ARRAY -> "$w.writeFloats($value)" + ApiType.DOUBLE_ARRAY -> "$w.writeDoubles($value)" ApiType.UNIT -> "Unit" is ApiType.ENUM -> "$w.writeInt($value.ordinal)" is ApiType.DATA_CLASS -> if (side == Side.CLIENT) "nja_write_${t.simpleName}($w, $value, njaS)" else "nja_write_${t.simpleName}($w, $value)" + is ApiType.SEALED_VALUE -> if (side == Side.CLIENT) "nja_write_${t.simpleName}($w, $value, njaS)" else "nja_write_${t.simpleName}($w, $value)" is ApiType.OBJECT, is ApiType.INTERFACE -> encodeObject(value, w, nullable = false) is ApiType.LIST -> "writeList($w, $value) { w$d, e$d -> ${encode(t.elementType, "e$d", "w$d", d + 1)} }" is ApiType.SET -> "writeList($w, $value) { w$d, e$d -> ${encode(t.elementType, "e$d", "w$d", d + 1)} }" @@ -40,7 +45,8 @@ class Codec(private val model: ApiModel, private val side: Side) { } private fun encodeNullable(inner: ApiType, value: String, w: String, d: Int): String = when (inner) { - ApiType.STRING, ApiType.BYTE_ARRAY, is ApiType.LIST, is ApiType.SET, is ApiType.MAP -> encode(inner, value, w, d) + ApiType.STRING, ApiType.BYTE_ARRAY, ApiType.INT_ARRAY, ApiType.LONG_ARRAY, ApiType.FLOAT_ARRAY, ApiType.DOUBLE_ARRAY, + is ApiType.LIST, is ApiType.SET, is ApiType.MAP -> encode(inner, value, w, d) is ApiType.ENUM -> "$w.writeInt($value?.ordinal ?: -1)" is ApiType.OBJECT, is ApiType.INTERFACE -> encodeObject(value, w, nullable = true) is ApiType.FUNCTION -> encodeFunction(inner, value, w, d, nullable = true) @@ -77,9 +83,14 @@ class Codec(private val model: ApiModel, private val side: Side) { ApiType.SHORT -> "$r.readShort()" ApiType.STRING -> "$r.readString()!!" ApiType.BYTE_ARRAY -> "$r.readBytes()!!" + ApiType.INT_ARRAY -> "$r.readInts()!!" + ApiType.LONG_ARRAY -> "$r.readLongs()!!" + ApiType.FLOAT_ARRAY -> "$r.readFloats()!!" + ApiType.DOUBLE_ARRAY -> "$r.readDoubles()!!" ApiType.UNIT -> "Unit" is ApiType.ENUM -> "${type(t)}.entries[$r.readInt()]" is ApiType.DATA_CLASS -> "nja_read_${t.simpleName}($r)" + is ApiType.SEALED_VALUE -> "nja_read_${t.simpleName}($r)" is ApiType.OBJECT, is ApiType.INTERFACE -> decodeObject(t, r, nullable = false) is ApiType.LIST -> "readList($r) { r$d -> ${decode(t.elementType, "r$d", d + 1)} }!!" is ApiType.SET -> "readSet($r) { r$d -> ${decode(t.elementType, "r$d", d + 1)} }!!" @@ -92,6 +103,10 @@ class Codec(private val model: ApiModel, private val side: Side) { private fun decodeNullable(inner: ApiType, r: String, d: Int): String = when (inner) { ApiType.STRING -> "$r.readString()" ApiType.BYTE_ARRAY -> "$r.readBytes()" + ApiType.INT_ARRAY -> "$r.readInts()" + ApiType.LONG_ARRAY -> "$r.readLongs()" + ApiType.FLOAT_ARRAY -> "$r.readFloats()" + ApiType.DOUBLE_ARRAY -> "$r.readDoubles()" is ApiType.LIST -> "readList($r) { r$d -> ${decode(inner.elementType, "r$d", d + 1)} }" is ApiType.SET -> "readSet($r) { r$d -> ${decode(inner.elementType, "r$d", d + 1)} }" is ApiType.MAP -> "readMap($r, { r$d -> ${decode(inner.keyType, "r$d", d + 1)} }, { r$d -> ${decode(inner.valueType, "r$d", d + 1)} })" diff --git a/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/codegen/ServerGenerator.kt b/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/codegen/ServerGenerator.kt index 9ea6a4c..2bb9269 100644 --- a/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/codegen/ServerGenerator.kt +++ b/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/codegen/ServerGenerator.kt @@ -2,6 +2,7 @@ package dev.nucleusframework.nja.plugin.codegen import dev.nucleusframework.nja.plugin.ir.ApiFunction import dev.nucleusframework.nja.plugin.ir.ApiParam +import dev.nucleusframework.nja.plugin.ir.ApiSealedValue import dev.nucleusframework.nja.plugin.ir.ApiType /** @@ -147,6 +148,35 @@ class ServerGenerator(private val model: ApiModel, private val libName: String) dc.fields.forEach { f -> appendLine(" ${esc(f.name)} = ${codec.decode(f.type, "r")},") } appendLine(")") } + for (v in model.module.sealedValues) appendSealedCodec(v) + } + + // A sealed value: its case's index, then the case's fields + private fun StringBuilder.appendSealedCodec(v: ApiSealedValue) { + appendLine() + appendLine("internal fun nja_write_${v.simpleName}(w: WireWriter, value: ${v.fqName}) {") + appendLine(" when (value) {") + v.cases.forEachIndexed { i, case -> + appendLine(" is ${case.fqName} -> {") + appendLine(" w.writeInt($i)") + case.fields.forEach { f -> appendLine(" ${codec.encode(f.type, "value.${esc(f.name)}", "w")}") } + appendLine(" }") + } + appendLine(" }") + appendLine("}") + appendLine() + appendLine("internal fun nja_read_${v.simpleName}(r: WireReader): ${v.fqName} = when (val njaCase = r.readInt()) {") + v.cases.forEachIndexed { i, case -> + if (case.isObject) { + appendLine(" $i -> ${case.fqName}") + } else { + appendLine(" $i -> ${case.fqName}(") + case.fields.forEach { f -> appendLine(" ${esc(f.name)} = ${codec.decode(f.type, "r")},") } + appendLine(" )") + } + } + appendLine(" else -> throw IllegalStateException(\"NJA: unknown case \$njaCase of ${v.fqName}\")") + appendLine("}") } companion object { diff --git a/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/ir/ApiIR.kt b/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/ir/ApiIR.kt index 561b8d4..82d1749 100644 --- a/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/ir/ApiIR.kt +++ b/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/ir/ApiIR.kt @@ -10,6 +10,26 @@ data class ApiModule( val enums: List, val functions: List, val interfaces: List = emptyList(), + val sealedValues: List = emptyList(), +) : Serializable + +/** + * A sealed value hierarchy: a sealed interface or class whose cases, nested in it, are all data classes or objects. + * It travels by value (its case, then the case's fields), copied verbatim to the app like a data class. + */ +data class ApiSealedValue( + val simpleName: String, + val fqName: String, + val cases: List, + val source: ApiSourceDecl? = null, +) : Serializable + +/** A case of an [ApiSealedValue]: [name] nested in it, an object or a data class with [fields]. */ +data class ApiSealedCase( + val name: String, + val fqName: String, + val isObject: Boolean, + val fields: List, ) : Serializable data class ApiDataClass( @@ -111,12 +131,22 @@ sealed class ApiType : Serializable { data class NULLABLE(val inner: ApiType) : ApiType() data class FUNCTION(val paramTypes: List, val returnType: ApiType) : ApiType() data class DATA_CLASS(val fqName: String, val simpleName: String, val fields: List) : ApiType() + data class SEALED_VALUE(val fqName: String, val simpleName: String) : ApiType() data object BYTE_ARRAY : ApiType() + data object INT_ARRAY : ApiType() + data object LONG_ARRAY : ApiType() + data object FLOAT_ARRAY : ApiType() + data object DOUBLE_ARRAY : ApiType() data class LIST(val elementType: ApiType) : ApiType() data class SET(val elementType: ApiType) : ApiType() data class MAP(val keyType: ApiType, val valueType: ApiType) : ApiType() data class FLOW(val elementType: ApiType) : ApiType() + companion object { + /** The arrays, encoded as a count and their elements: nullable like strings, with no wrapper. */ + val ARRAYS: Set get() = setOf(BYTE_ARRAY, INT_ARRAY, LONG_ARRAY, FLOAT_ARRAY, DOUBLE_ARRAY) + } + /** Preserves singleton identity when deserialized from the incremental cache. */ protected fun readResolve(): Any = when (this) { INT -> INT @@ -129,6 +159,10 @@ sealed class ApiType : Serializable { STRING -> STRING UNIT -> UNIT BYTE_ARRAY -> BYTE_ARRAY + INT_ARRAY -> INT_ARRAY + LONG_ARRAY -> LONG_ARRAY + FLOAT_ARRAY -> FLOAT_ARRAY + DOUBLE_ARRAY -> DOUBLE_ARRAY else -> this } @@ -150,7 +184,12 @@ sealed class ApiType : Serializable { is NULLABLE -> if (inner is FUNCTION) "(${inner.clientName})?" else "${inner.clientName}?" is FUNCTION -> "(${paramTypes.joinToString(", ") { it.clientName }}) -> ${returnType.clientName}" is DATA_CLASS -> simpleName + is SEALED_VALUE -> simpleName BYTE_ARRAY -> "ByteArray" + INT_ARRAY -> "IntArray" + LONG_ARRAY -> "LongArray" + FLOAT_ARRAY -> "FloatArray" + DOUBLE_ARRAY -> "DoubleArray" is LIST -> "List<${elementType.clientName}>" is SET -> "Set<${elementType.clientName}>" is MAP -> "Map<${keyType.clientName}, ${valueType.clientName}>" @@ -164,6 +203,7 @@ sealed class ApiType : Serializable { is INTERFACE -> fqName is ENUM -> fqName is DATA_CLASS -> fqName + is SEALED_VALUE -> fqName is NULLABLE -> if (inner is FUNCTION) "(${inner.serverName})?" else "${inner.serverName}?" is FUNCTION -> "(${paramTypes.joinToString(", ") { it.serverName }}) -> ${returnType.serverName}" is LIST -> "List<${elementType.serverName}>" diff --git a/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/tasks/GenerateNjaBridgesTask.kt b/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/tasks/GenerateNjaBridgesTask.kt index c027530..fb0cca1 100644 --- a/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/tasks/GenerateNjaBridgesTask.kt +++ b/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/tasks/GenerateNjaBridgesTask.kt @@ -89,7 +89,12 @@ abstract class GenerateNjaBridgesTask : DefaultTask() { val model = ApiModel(module) val clientPackage = parameters.clientPackage.get().ifEmpty { module.packages.firstOrNull().orEmpty() } write(parameters.serverDir.get().asFile, ServerGenerator(model, libName).generate()) - write(parameters.clientDir.get().asFile, ClientGenerator(model, libName, clientPackage).generate()) + // The packages, for a JVM consumer's check: its class path holds both the façade and the proxies + val packages = "client=$clientPackage\nfacade=${module.packages.joinToString(",")}\n" + write( + parameters.clientDir.get().asFile, + ClientGenerator(model, libName, clientPackage).generate() + (PACKAGES_FILE to packages), + ) logger.lifecycle( "nja: $libName: ${module.classes.size} classes, ${module.interfaces.size} interfaces, " + "${module.dataClasses.size} data classes, ${module.enums.size} enums, ${model.members.size} members", @@ -106,3 +111,6 @@ abstract class GenerateNjaBridgesTask : DefaultTask() { } } } + +/** The client sources' packages file: `client=`, `facade=,...`. */ +internal const val PACKAGES_FILE = "nja-packages.properties" diff --git a/runtime/client/build.gradle.kts b/runtime/client/build.gradle.kts index 6f6086e..007d44a 100644 --- a/runtime/client/build.gradle.kts +++ b/runtime/client/build.gradle.kts @@ -11,6 +11,10 @@ kotlin { minSdk = 29 } + // A JVM app (the desktop): the façades run in its own JVM (see Platform.jvm.kt) + jvm() + jvmToolchain(25) + listOf(iosArm64(), iosSimulatorArm64()).forEach { target -> target.compilations.getByName("main").cinterops.create("jni") { definitionFile.set(project.file("src/nativeInterop/cinterop/jni.def")) @@ -28,6 +32,10 @@ kotlin { commonMain.dependencies { api(libs.kotlinx.coroutines.core) } + jvmMain.dependencies { + // The dispatcher the façades run behind, in the app's JVM + implementation(project(":nja-server")) + } } } @@ -35,7 +43,7 @@ mavenPublishing { coordinates("dev.nucleusframework.nja", project.name, project.version.toString()) pom { name.set("Nucleus JVM Access client") - description.set("The part of Nucleus JVM Access running in the app (Android, iOS): starts the JVM and calls the façades") + description.set("The part of Nucleus JVM Access running in the app (Android, iOS, the JVM): starts the JVM and calls the façades") url.set("https://github.com/NucleusFramework/NucleusJvmAccess") licenses { license { diff --git a/runtime/client/src/commonMain/kotlin/dev/nucleusframework/nja/Wire.kt b/runtime/client/src/commonMain/kotlin/dev/nucleusframework/nja/Wire.kt index 8d65c77..4e877a6 100644 --- a/runtime/client/src/commonMain/kotlin/dev/nucleusframework/nja/Wire.kt +++ b/runtime/client/src/commonMain/kotlin/dev/nucleusframework/nja/Wire.kt @@ -94,6 +94,35 @@ class WireWriter(capacity: Int = 256) { size += value.size } + /** Primitive arrays: their count (-1 for null), then their elements as [writeInt]... writes them. */ + fun writeInts(value: IntArray?) { + if (value == null) return writeInt(-1) + writeInt(value.size) + ensure(4 * value.size) + for (v in value) writeInt(v) + } + + fun writeLongs(value: LongArray?) { + if (value == null) return writeInt(-1) + writeInt(value.size) + ensure(8 * value.size) + for (v in value) writeLong(v) + } + + fun writeFloats(value: FloatArray?) { + if (value == null) return writeInt(-1) + writeInt(value.size) + ensure(4 * value.size) + for (v in value) writeFloat(v) + } + + fun writeDoubles(value: DoubleArray?) { + if (value == null) return writeInt(-1) + writeInt(value.size) + ensure(8 * value.size) + for (v in value) writeDouble(v) + } + fun writeRaw(value: ByteArray, offset: Int = 0, length: Int = value.size - offset) { ensure(length) value.copyInto(buffer, size, offset, offset + length) @@ -161,6 +190,34 @@ class WireReader(private val buffer: ByteArray, private var position: Int = 0, p return value } + fun readInts(): IntArray? { + val length = readInt() + if (length < 0) return null + check(4 * length) + return IntArray(length) { readInt() } + } + + fun readLongs(): LongArray? { + val length = readInt() + if (length < 0) return null + check(8 * length) + return LongArray(length) { readLong() } + } + + fun readFloats(): FloatArray? { + val length = readInt() + if (length < 0) return null + check(4 * length) + return FloatArray(length) { readFloat() } + } + + fun readDoubles(): DoubleArray? { + val length = readInt() + if (length < 0) return null + check(8 * length) + return DoubleArray(length) { readDouble() } + } + private fun check(count: Int) { if (count < 0 || position + count > limit) throw IllegalStateException("NJA: read past the end of the message") } diff --git a/runtime/client/src/jvmMain/kotlin/dev/nucleusframework/nja/Platform.jvm.kt b/runtime/client/src/jvmMain/kotlin/dev/nucleusframework/nja/Platform.jvm.kt new file mode 100644 index 0000000..f8a025a --- /dev/null +++ b/runtime/client/src/jvmMain/kotlin/dev/nucleusframework/nja/Platform.jvm.kt @@ -0,0 +1,40 @@ +package dev.nucleusframework.nja + +import dev.nucleusframework.nja.server.Link +import dev.nucleusframework.nja.server.NjaServer +import java.lang.ref.Cleaner +import java.util.concurrent.locks.ReentrantLock + +internal actual class NjaLock actual constructor() { + private val lock = ReentrantLock() + actual fun lock() = lock.lock() + actual fun unlock() = lock.unlock() +} + +private val scopes = ThreadLocal.withInitial { ArrayList(4) } + +internal actual fun currentScopes(): ArrayList = scopes.get()!! + +internal actual fun className(e: Throwable): String = e.javaClass.name + +internal actual fun startDaemon(name: String, body: () -> Unit) { + Thread(body, name).apply { isDaemon = true }.start() +} + +private val cleaner = Cleaner.create() + +internal actual fun createCleaner(ref: JvmRef): Any = Any().also { token -> cleaner.register(token) { ref.close() } } + +internal actual fun startTransport(): Transport = JvmTransport + +/** + * A JVM app (the desktop): the façades run in this very JVM, on its class path, so a call is a plain call into the + * server's dispatcher on the calling thread, and a callback a plain call back into the app's, as on iOS without JNI. + * The messages are still encoded: the app sees the same proxies as on the mobile platforms. + */ +private object JvmTransport : Transport { + private val link = Link { request -> NjaRuntime.serveCallback(request) } + + override fun transact(message: ByteArray, length: Int): ByteArray = + NjaServer.handle(if (length == message.size) message else message.copyOf(length), link) +} diff --git a/runtime/server/src/main/kotlin/dev/nucleusframework/nja/server/Wire.kt b/runtime/server/src/main/kotlin/dev/nucleusframework/nja/server/Wire.kt index a94afde..58cc8ce 100644 --- a/runtime/server/src/main/kotlin/dev/nucleusframework/nja/server/Wire.kt +++ b/runtime/server/src/main/kotlin/dev/nucleusframework/nja/server/Wire.kt @@ -94,6 +94,35 @@ class WireWriter(capacity: Int = 256) { size += value.size } + /** Primitive arrays: their count (-1 for null), then their elements as [writeInt]... writes them. */ + fun writeInts(value: IntArray?) { + if (value == null) return writeInt(-1) + writeInt(value.size) + ensure(4 * value.size) + for (v in value) writeInt(v) + } + + fun writeLongs(value: LongArray?) { + if (value == null) return writeInt(-1) + writeInt(value.size) + ensure(8 * value.size) + for (v in value) writeLong(v) + } + + fun writeFloats(value: FloatArray?) { + if (value == null) return writeInt(-1) + writeInt(value.size) + ensure(4 * value.size) + for (v in value) writeFloat(v) + } + + fun writeDoubles(value: DoubleArray?) { + if (value == null) return writeInt(-1) + writeInt(value.size) + ensure(8 * value.size) + for (v in value) writeDouble(v) + } + fun writeRaw(value: ByteArray, offset: Int = 0, length: Int = value.size - offset) { ensure(length) value.copyInto(buffer, size, offset, offset + length) @@ -161,6 +190,34 @@ class WireReader(private val buffer: ByteArray, private var position: Int = 0, p return value } + fun readInts(): IntArray? { + val length = readInt() + if (length < 0) return null + check(4 * length) + return IntArray(length) { readInt() } + } + + fun readLongs(): LongArray? { + val length = readInt() + if (length < 0) return null + check(8 * length) + return LongArray(length) { readLong() } + } + + fun readFloats(): FloatArray? { + val length = readInt() + if (length < 0) return null + check(4 * length) + return FloatArray(length) { readFloat() } + } + + fun readDoubles(): DoubleArray? { + val length = readInt() + if (length < 0) return null + check(8 * length) + return DoubleArray(length) { readDouble() } + } + private fun check(count: Int) { if (count < 0 || position + count > limit) throw IllegalStateException("NJA: read past the end of the message") } From d3e64191211eaa80137e3f676a2d3e75368f97d2 Mon Sep 17 00:00:00 2001 From: Elie Gambache Date: Fri, 16 Oct 2026 17:12:40 +0300 Subject: [PATCH 2/5] =?UTF-8?q?AutoCloseable=20fa=C3=A7ades,=20and=20only?= =?UTF-8?q?=20the=20public=20API?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - A façade's close() is the proxy's: it calls the JVM object's close(), then releases it, once (it was generated as a member hiding JvmObject's). - Private and internal declarations are left out of the symbol table, private constructor properties out of the API, and a class whose constructor is private, internal or takes what can't cross the bridge isn't constructible from the app (its constructor's unsupported parameters were dropped). Signed-off-by: Elie Gambache --- .../com/example/calculator/Resources.kt | 30 ++++++++++++++++ .../calculator/client/ResourcesTest.kt | 36 +++++++++++++++++++ .../nja/plugin/analysis/PsiSourceParser.kt | 7 ++-- .../nja/plugin/codegen/ClientGenerator.kt | 12 +++++++ .../nja/plugin/codegen/Model.kt | 2 +- .../nucleusframework/nja/plugin/ir/ApiIR.kt | 2 ++ 6 files changed, 85 insertions(+), 4 deletions(-) create mode 100644 examples/calculator-facade/src/main/kotlin/com/example/calculator/Resources.kt create mode 100644 examples/calculator/src/commonTest/kotlin/com/example/calculator/client/ResourcesTest.kt diff --git a/examples/calculator-facade/src/main/kotlin/com/example/calculator/Resources.kt b/examples/calculator-facade/src/main/kotlin/com/example/calculator/Resources.kt new file mode 100644 index 0000000..3d0b6c7 --- /dev/null +++ b/examples/calculator-facade/src/main/kotlin/com/example/calculator/Resources.kt @@ -0,0 +1,30 @@ +package com.example.calculator + +import java.util.concurrent.atomic.AtomicInteger + +/** A JVM resource: closing its proxy closes it, once. */ +class Resource(val name: String) : AutoCloseable { + @Volatile private var open = true + + fun isOpen(): Boolean = open + + override fun close() { + if (open) closes.incrementAndGet() + open = false + } + + companion object { + private val closes = AtomicInteger() + + fun closeCount(): Int = closes.get() + } +} + +/** A class the app gets from a factory only: its constructor is internal, its state private. */ +class Ticket internal constructor(private val secret: Long, val label: String) { + fun check(guess: Long): Boolean = guess == secret +} + +class TicketOffice { + fun issue(label: String): Ticket = Ticket(label.length * 7L, label) +} diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/ResourcesTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/ResourcesTest.kt new file mode 100644 index 0000000..67d10f4 --- /dev/null +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/ResourcesTest.kt @@ -0,0 +1,36 @@ +package com.example.calculator.client + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class ResourcesTest { + @Test + fun `closing the proxy closes the JVM object, once`() { + val before = Resource.closeCount() + val resource = Resource("r") + assertTrue(resource.isOpen()) + resource.close() + assertEquals(before + 1, Resource.closeCount()) + resource.close() + assertEquals(before + 1, Resource.closeCount()) + assertFailsWith { resource.isOpen() } + } + + @Test + fun `use closes it`() { + val before = Resource.closeCount() + Resource("u").use { assertTrue(it.isOpen()) } + assertEquals(before + 1, Resource.closeCount()) + } + + @Test + fun `an internal constructor stays the JVM's`() { + val ticket = TicketOffice().issue("abc") + assertEquals("abc", ticket.label) + assertTrue(ticket.check(21)) + assertFalse(ticket.check(1)) + } +} diff --git a/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/analysis/PsiSourceParser.kt b/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/analysis/PsiSourceParser.kt index eb5c935..70ac6a1 100644 --- a/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/analysis/PsiSourceParser.kt +++ b/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/analysis/PsiSourceParser.kt @@ -132,7 +132,7 @@ class PsiSourceParser { fun visit(declarations: List, parentFq: String?) { for (decl in declarations) { - if (decl !is KtClass) continue + if (decl !is KtClass || decl.isPrivateOrInternal()) continue val name = decl.name ?: continue val fq = if (parentFq != null) "$parentFq.$name" else if (pkg.isNotEmpty()) "$pkg.$name" else name @@ -288,8 +288,8 @@ class PsiSourceParser { val type = resolveType(param.typeReference, scope) ?: return@mapNotNull null ApiParam(pName, type, hasDefault = param.hasDefaultValue()) } - // Constructor val/var params are properties — collect them for getter/setter generation - val ctorProperties = rawCtorParams.filter { it.hasValOrVar() }.mapNotNull { param -> + // Constructor val/var params are properties — collect them for getter/setter generation (the public ones) + val ctorProperties = rawCtorParams.filter { it.hasValOrVar() && !it.isPrivateOrInternal() }.mapNotNull { param -> val pName = param.name ?: return@mapNotNull null val type = resolveType(param.typeReference, scope) ?: return@mapNotNull null ApiProperty(pName, type, param.isMutable) @@ -370,6 +370,7 @@ class PsiSourceParser { isOpen = isOpen, isAbstract = isAbstract, isSealed = isSealed, superClass = superClass, interfaces = implementedInterfaces, sealedSubclasses = sealedSubclasses, isCommon = isCommon, + isConstructible = ktClass.primaryConstructor?.isPrivateOrInternal() != true && ctorParams.size == rawCtorParams.size, ) } diff --git a/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/codegen/ClientGenerator.kt b/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/codegen/ClientGenerator.kt index bafecb3..fc485d4 100644 --- a/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/codegen/ClientGenerator.kt +++ b/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/codegen/ClientGenerator.kt @@ -206,6 +206,18 @@ class ClientGenerator(private val model: ApiModel, private val libName: String, private fun StringBuilder.appendFunction(fn: ApiFunction, member: Member, indent: String, receiver: String?, modifiers: String) { val params = fn.params.joinToString(", ") { "${esc(it.name)}: ${model.clientType(it.type)}" } val returnType = fn.returnType + // close() (an AutoCloseable's): the JVM object's own, then the proxy's, which releases it; once + if (receiver != null && fn.name == "close" && fn.params.isEmpty() && returnType == ApiType.UNIT && !fn.isSuspend && !fn.isExtension) { + appendLine("${indent}override fun close() {") + appendLine("$indent if (njaRef.isClosed) return") + appendLine("$indent try {") + appendLine("$indent $receiver.use { njaH -> NjaRuntime.call($module, ${member.id}, { njaW, njaS -> njaW.writeLong(njaH) }) { _, _ -> } }") + appendLine("$indent } finally {") + appendLine("$indent super.close()") + appendLine("$indent }") + appendLine("$indent}") + return + } val extension = if (fn.isExtension) "${model.clientType(fn.receiverType!!)}." else "" val head = "$indent$modifiers${if (fn.isSuspend) "suspend " else ""}fun $extension${esc(fn.name)}($params): ${model.clientType(returnType)}" val leading = buildList { diff --git a/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/codegen/Model.kt b/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/codegen/Model.kt index 55d9dbe..ff09275 100644 --- a/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/codegen/Model.kt +++ b/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/codegen/Model.kt @@ -57,7 +57,7 @@ class ApiModel(val module: ApiModule) { } for (cls in module.classes) { val owner = Owner.Instance(cls.fqName, cls.simpleName) - if (!cls.isAbstract && !cls.isSealed) { + if (!cls.isAbstract && !cls.isSealed && cls.isConstructible) { val params = cls.constructor.params val trailingDefaults = params.reversed().takeWhile { it.hasDefault }.size for (drop in 0..trailingDefaults) add { Member.Constructor(it, cls, params.dropLast(drop)) } diff --git a/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/ir/ApiIR.kt b/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/ir/ApiIR.kt index 82d1749..604d40a 100644 --- a/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/ir/ApiIR.kt +++ b/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/ir/ApiIR.kt @@ -73,6 +73,8 @@ data class ApiClass( val interfaces: List = emptyList(), val sealedSubclasses: List = emptyList(), val isCommon: Boolean = false, + /** Whether the app may construct it: a public constructor whose parameters all cross the bridge. */ + val isConstructible: Boolean = true, ) : Serializable data class ApiEnumEntry( From 9df807e0d3da8ee7392fe4822da75c0b8e48b813 Mon Sep 17 00:00:00 2001 From: Elie Gambache Date: Fri, 16 Oct 2026 17:19:41 +0300 Subject: [PATCH 3/5] Default arguments, and functions whose types can't cross left out MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A method's (or a companion's) trailing parameters with default values get overloads, as constructors do: the app leaves them out, the JVM applies the façade's defaults. A function with a parameter or a result that can't cross the bridge is left out (the parameter was dropped, the result taken for Unit). Signed-off-by: Elie Gambache --- .../nja/plugin/analysis/PsiSourceParser.kt | 24 +++++++++++++------ 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/analysis/PsiSourceParser.kt b/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/analysis/PsiSourceParser.kt index 70ac6a1..533ac52 100644 --- a/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/analysis/PsiSourceParser.kt +++ b/plugin-build/plugin/src/main/kotlin/dev/nucleusframework/nja/plugin/analysis/PsiSourceParser.kt @@ -347,7 +347,7 @@ class PsiSourceParser { when (decl) { is KtNamedFunction -> { if (decl.name?.startsWith("_") == true) continue - parseFunction(decl, scope)?.let { methods.add(it) } + parseFunction(decl, scope)?.let { methods.addAll(it.withDefaultOverloads()) } } is KtProperty -> { val propName = decl.name ?: continue @@ -358,7 +358,7 @@ class PsiSourceParser { for (cd in decl.declarations) { if (cd.isPrivateOrInternal()) continue when (cd) { - is KtNamedFunction -> parseFunction(cd, scope)?.let { companionMethods.add(it) } + is KtNamedFunction -> parseFunction(cd, scope)?.let { companionMethods.addAll(it.withDefaultOverloads()) } is KtProperty -> parseProperty(cd, scope)?.let { companionProperties.add(it) } } } @@ -435,17 +435,27 @@ class PsiSourceParser { ApiEnumEntry(entryName, args) } + /** + * The function and, as for constructors, one overload per trailing parameter with a default value: the app calls + * the one it needs, and the JVM applies the façade's defaults. + */ + private fun ApiFunction.withDefaultOverloads(): List { + val trailingDefaults = params.reversed().takeWhile { it.hasDefault }.size + return (0..trailingDefaults).map { drop -> if (drop == 0) this else copy(params = params.dropLast(drop)) } + } + private fun parseFunction(fn: KtNamedFunction, scope: RecordingScope): ApiFunction? { val name = fn.name ?: return null if (name == "init") return null val isSuspend = fn.hasModifier(KtTokens.SUSPEND_KEYWORD) val isOverride = fn.hasModifier(KtTokens.OVERRIDE_KEYWORD) - val params = fn.valueParameters.mapNotNull { param -> - val pName = param.name ?: return@mapNotNull null - val type = resolveType(param.typeReference, scope) ?: return@mapNotNull null - ApiParam(pName, type) + // Left out when a parameter or the result can't cross the bridge + val params = fn.valueParameters.map { param -> + val pName = param.name ?: return null + val type = resolveType(param.typeReference, scope) ?: return null + ApiParam(pName, type, hasDefault = param.hasDefaultValue()) } - val returnType = fn.typeReference?.let { resolveType(it, scope) } ?: ApiType.UNIT + val returnType = fn.typeReference?.let { resolveType(it, scope) ?: return null } ?: ApiType.UNIT // Extension function detection val receiverTypeRef = fn.receiverTypeReference From 556aa6c15ad56885201a1bc2d05216bcfbdb0dc7 Mon Sep 17 00:00:00 2001 From: Elie Gambache Date: Fri, 16 Oct 2026 17:20:08 +0300 Subject: [PATCH 4/5] examples: default arguments Signed-off-by: Elie Gambache --- .../main/kotlin/com/example/calculator/SealedValues.kt | 3 +++ .../com/example/calculator/client/SealedValuesTest.kt | 8 ++++++++ 2 files changed, 11 insertions(+) diff --git a/examples/calculator-facade/src/main/kotlin/com/example/calculator/SealedValues.kt b/examples/calculator-facade/src/main/kotlin/com/example/calculator/SealedValues.kt index 09fcd51..010b893 100644 --- a/examples/calculator-facade/src/main/kotlin/com/example/calculator/SealedValues.kt +++ b/examples/calculator-facade/src/main/kotlin/com/example/calculator/SealedValues.kt @@ -55,4 +55,7 @@ class Geometry { } fun viaApp(shape: Figure, transform: (Figure) -> Figure): Figure = transform(shape) + + /** Default arguments: the app may leave out the trailing ones, the JVM fills them in. */ + fun describe(shape: Figure, decimals: Int = 1, unit: String = "u²"): String = String.format(java.util.Locale.ROOT, "%.${decimals}f %s", area(shape), unit) } diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/SealedValuesTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/SealedValuesTest.kt index 65c7564..ec9441a 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/SealedValuesTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/SealedValuesTest.kt @@ -40,6 +40,14 @@ class SealedValuesTest { assertEquals(Figure.Circle(9.0), geometry.viaApp(Figure.Circle(3.0)) { s -> Figure.Circle((s as Figure.Circle).radius * 3) }) } + @Test + fun `default arguments`() { + val rect = Figure.Rect(2.0, 3.0) + assertEquals("6.0 u²", geometry.describe(rect)) + assertEquals("6.000 u²", geometry.describe(rect, 3)) + assertEquals("6 m²", geometry.describe(rect, 0, "m²")) + } + @Test fun `a sealed class`() { assertEquals(5L, geometry.eval(Op.Add(2, 3))) From 2424e2fa8ad74e9a70fa469aa178ee6c5cd87981 Mon Sep 17 00:00:00 2001 From: Elie Gambache Date: Fri, 16 Oct 2026 17:48:03 +0300 Subject: [PATCH 5/5] Document the JVM targets, arrays, sealed values and default arguments The test names also have to be valid DEX and Kotlin/Native names (no comma, no apostrophe). Signed-off-by: Elie Gambache --- README.md | 37 +++++++++++++------ .../calculator/client/ResourcesTest.kt | 4 +- .../calculator/client/SealedValuesTest.kt | 2 +- 3 files changed, 29 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 0fc91bf..c0eac59 100644 --- a/README.md +++ b/README.md @@ -24,13 +24,18 @@ your iOS and Android code calls as if it were local. ## How it works -| | iOS | Android | -|---|---|---| -| JVM | Zero (jdk-mobile's interpreter: iOS forbids JIT) | HotSpot server VM (C2 JIT) | -| Where | Linked into the app (`libjvm.a`, static) | `libnja.so`: HotSpot + the JDK's natives + the bridge, loaded by ART | -| Calls | JNI from the calling Kotlin/Native thread (attached on first use, detached when it ends) | Handed from the ART thread to a HotSpot thread paired with it (futex channel, spin-then-sleep) | -| Callbacks (JVM → app) | JNI upcall on the same thread | The answer of the channel, served on the ART thread; nested calls recurse on the same pair | -| Fallback process | none | none | +| | iOS | Android | JVM (desktop) | +|---|---|---|---| +| JVM | Zero (jdk-mobile's interpreter: iOS forbids JIT) | HotSpot server VM (C2 JIT) | The app's own | +| Where | Linked into the app (`libjvm.a`, static) | `libnja.so`: HotSpot + the JDK's natives + the bridge, loaded by ART | The façades on the app's class path | +| Calls | JNI from the calling Kotlin/Native thread (attached on first use, detached when it ends) | Handed from the ART thread to a HotSpot thread paired with it (futex channel, spin-then-sleep) | A plain call into the dispatcher, on the calling thread | +| Callbacks (JVM → app) | JNI upcall on the same thread | The answer of the channel, served on the ART thread; nested calls recurse on the same pair | A plain call back, on the same thread | +| Fallback process | none | none | none | + +**A JVM target** (`jvm()`, a desktop app) sees the same proxies as the mobile ones, with the façades in its own JVM: +the plugin puts them on the target's runtime class path, and the messages are still encoded (the app's code is the +same everywhere). Both the façades and their proxies being on that class path, the proxies need a package of their own: +set `njaFacade { clientPackage = "…" }` (the plugin checks it before the JVM target compiles). **One process on Android.** ART and HotSpot can't share a *thread* (both keep their state in TLS and guard zones on the stack), but they can share a *process*: @@ -100,21 +105,27 @@ Kotlin binaries (`-force_load` of jdk-mobile's static libraries, `-export_dynami The façade's public API, parsed from its sources with Kotlin PSI: `Int`, `Long`, `Double`, `Float`, `Boolean`, `Byte`, `Short`, `String` (length-prefixed UTF-8: NUL included), `ByteArray`, -enums (verbatim, bodies included), data classes (verbatim), classes (proxies, `AutoCloseable`, released on `close()` or -when collected), open/abstract/sealed classes and interfaces (hierarchy mirrored, objects wrapped in their most specific +`IntArray`, `LongArray`, `FloatArray`, `DoubleArray`, enums (verbatim, bodies included), data classes (verbatim), sealed +value hierarchies (a sealed interface or class whose nested cases are all data classes or objects: verbatim, by value, +recursive ones included), classes (proxies, released on `close()` or when collected; an `AutoCloseable`'s `close()` +closes the JVM object, then releases it), default arguments (overloads: the JVM applies the defaults), open/abstract/sealed classes and interfaces (hierarchy mirrored, objects wrapped in their most specific exported type), nested classes (`Outer_Inner`), companion objects, extension and top-level functions, nullable types, `List`/`Set`/`Map` (nested), lambdas as parameters (callbacks, valid during the call, exceptions rethrown as themselves) and as return values (JVM lambdas the app calls), `suspend` functions (cancellable both ways) and `Flow` (credit-based backpressure). +Private and internal declarations stay the JVM's, as does a constructor that is private, internal, or takes what can't +cross; a function whose parameters or result can't cross is left out. + JVM exceptions arrive as `JvmException` (with the JVM class name, message and stack); exceptions an app callback throws come back out of the call as themselves. A closed proxy fails with `IllegalStateException`; `close()` releases the JVM object once the calls using it are done (receiver *and* arguments are leased). ## Tests -`examples/calculator` runs a suite of 1,977 tests (types, callbacks, suspend, flows, inheritance, load, concurrency, -monkey and torture tests) against a calculator façade, on iOS and on Android, from `commonTest`, plus NJA's own +`examples/calculator` runs a suite of 2,008 tests (types, arrays, sealed values, callbacks, suspend, flows, inheritance, +load, concurrency, monkey and torture tests) against a calculator façade, on iOS, on Android and on the JVM, from +`commonTest`, plus NJA's own torture suite (`NjaTortureTest`): JVM null checks and stack overflows on 16 threads while the app faults and collects, JIT deoptimization storms, 300-level JVM ↔ app nesting, callbacks invoked from the wrong JVM thread, thread churn (1,000 threads, no JVM thread leak), 24–48 MB payloads, 100k handles released by close and by collection, @@ -128,6 +139,10 @@ cancellation storms, 200k-element flows, a 20 s chaos soak on 24 threads. ./gradlew :examples:calculator:connectedAndroidDeviceTest ``` +```bash +./gradlew :examples:calculator:jvmTest +``` + ## Performance See [BENCHMARKS.md](BENCHMARKS.md). In short, on Android NJA's HotSpot runs Jackson and Commons Math 1.8–7.8× faster diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/ResourcesTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/ResourcesTest.kt index 67d10f4..67211dc 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/ResourcesTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/ResourcesTest.kt @@ -8,7 +8,7 @@ import kotlin.test.assertTrue class ResourcesTest { @Test - fun `closing the proxy closes the JVM object, once`() { + fun `closing the proxy closes the JVM object once`() { val before = Resource.closeCount() val resource = Resource("r") assertTrue(resource.isOpen()) @@ -27,7 +27,7 @@ class ResourcesTest { } @Test - fun `an internal constructor stays the JVM's`() { + fun `an internal constructor stays on the JVM`() { val ticket = TicketOffice().issue("abc") assertEquals("abc", ticket.label) assertTrue(ticket.check(21)) diff --git a/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/SealedValuesTest.kt b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/SealedValuesTest.kt index ec9441a..96aa054 100644 --- a/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/SealedValuesTest.kt +++ b/examples/calculator/src/commonTest/kotlin/com/example/calculator/client/SealedValuesTest.kt @@ -33,7 +33,7 @@ class SealedValuesTest { } @Test - fun `in a data class, nullable, through a callback`() { + fun `in a data class or nullable or through a callback`() { assertEquals(12.0, geometry.layerArea(Layer(Figure.Rect(2.0, 3.0), setOf("a", "b")))) assertNull(geometry.maybe(false)) assertEquals(Figure.Rect(2.0, 3.0), geometry.maybe(true))