Skip to content

Commit c734e71

Browse files
authored
Merge pull request #519 from thisisthepy/feat/191-native-consumer
Plugin: link and ship libpython for Kotlin/Native desktop consumers (SPEC L-9c, #191)
2 parents 646b152 + bf6cd51 commit c734e71

18 files changed

Lines changed: 829 additions & 19 deletions

File tree

‎.github/workflows/desktop.yml‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,27 @@ jobs:
4444
# Using --console=plain so logs are readable in GitHub Actions
4545
run: ./gradlew :python-multiplatform:desktopTest --console=plain
4646

47+
# SPEC L-9c (#191): a macosArm64 consumer linked and packaged only by the bindings plugin. The test
48+
# task runs with the staged PYTHONHOME; the release executable then runs with none, from another
49+
# directory, so python-multiplatform-home beside it is the only prefix it can find.
50+
- name: Desktop native consumer (macosArm64), host test
51+
run: ./gradlew :python-multiplatform-gradle-plugin-fixtures:desktop-native-consumer:macosArm64Test --rerun --console=plain
52+
53+
- name: Desktop native consumer (macosArm64), packaged executable
54+
run: |
55+
set -euo pipefail
56+
./gradlew :python-multiplatform-gradle-plugin-fixtures:desktop-native-consumer:linkReleaseExecutableMacosArm64 --console=plain
57+
DIR=python-multiplatform-gradle-plugin/fixtures/desktop-native-consumer/build/bin/macosArm64/releaseExecutable
58+
test -d "$DIR/python-multiplatform-home" || { echo "::error::no python-multiplatform-home beside the executable"; exit 1; }
59+
LINE=$(cd "$RUNNER_TEMP" && env -u PYTHONHOME "$GITHUB_WORKSPACE/$DIR/desktop-native-consumer.kexe" | grep DESKTOP_NATIVE_PROBE)
60+
echo "$LINE"
61+
test "$LINE" = "DESKTOP_NATIVE_PROBE stdlib=ok ext=ok ft=ok"
62+
63+
# #191: Python draws material3 composables on Kotlin/Native (macosArm64) through the fork's walked
64+
# klibs; Text and Button go through the B3 compiler plugin, whose unrewritten marker would throw.
65+
- name: Compose on Kotlin/Native (macosArm64), host test
66+
run: ./gradlew :python-multiplatform-compose:fixtures:compose-native:macosArm64Test --rerun --console=plain
67+
4768
plugin-unit:
4869
# The Gradle plugin's own unit tests (#403). Only its fixtures ran in CI before, so plugin
4970
# unit tests were never executed (leader decision 2026-11-13). Linux: the tests use fake
@@ -117,6 +138,27 @@ jobs:
117138
- name: Run Linux x86_64 Kotlin/Native Tests
118139
run: ./gradlew :python-multiplatform:linuxX64Test --rerun --console=plain
119140

141+
# SPEC L-9c (#191): a linuxX64 consumer linked and packaged only by the bindings plugin. The test
142+
# task runs with the staged PYTHONHOME; the release executable then runs with none, from another
143+
# directory, so python-multiplatform-home beside it is the only prefix it can find.
144+
- name: Desktop native consumer (linuxX64), host test
145+
run: ./gradlew :python-multiplatform-gradle-plugin-fixtures:desktop-native-consumer:linuxX64Test --rerun --console=plain
146+
147+
- name: Desktop native consumer (linuxX64), packaged executable
148+
run: |
149+
set -euo pipefail
150+
./gradlew :python-multiplatform-gradle-plugin-fixtures:desktop-native-consumer:linkReleaseExecutableLinuxX64 --console=plain
151+
DIR=python-multiplatform-gradle-plugin/fixtures/desktop-native-consumer/build/bin/linuxX64/releaseExecutable
152+
test -d "$DIR/python-multiplatform-home" || { echo "::error::no python-multiplatform-home beside the executable"; exit 1; }
153+
LINE=$(cd "$RUNNER_TEMP" && env -u PYTHONHOME "$GITHUB_WORKSPACE/$DIR/desktop-native-consumer.kexe" | grep DESKTOP_NATIVE_PROBE)
154+
echo "$LINE"
155+
test "$LINE" = "DESKTOP_NATIVE_PROBE stdlib=ok ext=ok ft=ok"
156+
157+
# #191: Python draws material3 composables on Kotlin/Native (linuxX64) through the fork's walked
158+
# klibs; Text and Button go through the B3 compiler plugin, whose unrewritten marker would throw.
159+
- name: Compose on Kotlin/Native (linuxX64), host test
160+
run: ./gradlew :python-multiplatform-compose:fixtures:compose-native:linuxX64Test --rerun --console=plain
161+
120162
# The Compose host's linuxX64 target (#386): compiled here, since only the fork publishes the
121163
# Compose UI klibs for linuxX64.
122164
- name: Compile the Compose host for Linux x86_64 Kotlin/Native

‎docs/SPEC.md‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,29 @@ fail, then implement.
131131
old prefixes are re-extracted, and the packaged copy fails the build on any 0-byte `libpython*`.
132132
`Status: implemented` -- `PM/desktopTest/.../ffi/DesktopJarLibrariesTest.kt`, `ExtractLibraryCacheTest.kt`,
133133
`GP/StagedPrefixLinksTest.kt`.
134+
- **L-9c** (#191) Kotlin/Native desktop consumers (`macosArm64`, `linuxX64`). Leader decision 2026-10-25 on #191
135+
(item 3): "K/N CPython: libpython is shipped beside the executable (dynamic)". At run time (in
136+
`desktopNativeMain`, `DesktopNativePythonHome`), before `Py_Initialize`, a desktop native binary takes the first
137+
of: `PYTHONHOME` from the environment (CPython reads it itself); `<directory of the executable>/python-multiplatform-home`
138+
when that directory exists; `<directory of the executable>/../Resources/python-multiplatform-home` (a macOS `.app`).
139+
For a consumer applying the Gradle plugin, for each such target the plugin:
140+
1. registers `stagePythonHome<Target>` (L-9's staging, for that target's platform `macos-aarch64` or
141+
`linux-x86_64`, whatever the host), in the same per-machine cache;
142+
2. links every executable and test binary of the target against the staged `libpython<X.Y>t`
143+
(`-L<prefix>/lib -lpython<X.Y>t`), with the run-time search path
144+
`@executable_path/python-multiplatform-home/lib` (macOS) or `$ORIGIN/python-multiplatform-home/lib` (Linux), and,
145+
for debug and test binaries only, also the staged prefix's own `lib` (so a build path never ends up in a
146+
release binary); the link tasks depend on the staging;
147+
3. gives the target's host test task (`<target>Test`) `PYTHONHOME=<staged prefix>`, unless `PYTHONHOME` is
148+
already set (L-9's rule);
149+
4. after linking each executable, copies the packaged prefix (L-9's includes and excludes) to
150+
`<the executable's output directory>/python-multiplatform-home`, unless `packagePythonHome` is false.
151+
On Windows (`mingwX64`, SPEC P-1a) the rule differs where the loader does: binaries link the import library
152+
`<prefix>/libs/python3XYt.lib` and carry no search path; packaging puts the prefix's `*.dll` (the interpreter
153+
and the MSVC runtime) beside the executable, where Windows looks, and `Lib/` and `DLLs/` into
154+
`python-multiplatform-home`; `mingwX64Test` also gets the staged prefix on `PATH`.
155+
The library's own klib carries no libpython link option; a consumer that does not apply the plugin links it
156+
itself. `Status: draft` (#191), `GP/DesktopNativeConsumerWiringTest.kt`.
134157
- **L-10** Desktop: the library uses no JDK module beyond `java.base`, so it runs on a `jlink`ed
135158
runtime such as the one Compose Desktop's `createDistributable` bundles (issue #77). In particular
136159
native memory is reached through `java.lang.foreign`, never `sun.misc.Unsafe` (module

‎docs/design/klib-composable-and-defaults.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,6 @@ Let's check how Kotlin compiles default arguments when calling a function from K
202202
**Not verified, open (agent notes):**
203203

204204
1. **Plugin order.** The rewrite needs Compose's `IrGenerationExtension` to have run first, and the compiler offers no ordering API. The extension does not assume: a marker whose wrapped callee has no `$default` parameter stops the compilation with a message naming the cause. Which order the two plugins get in a real Kotlin/Native compilation has not been observed.
205-
2. **No run.** Nothing here has been executed: no unit test of the IR rewrite, no klib with `Text` compiled through it, no device or CI run. The modules compile (`:python-multiplatform-compiler-plugin:compileKotlin`, the Gradle plugin's `compileKotlin` and `compileTestKotlin`).
205+
2. **No run yet; first compile against real klibs (2026-11-22, #191).** `python-multiplatform-compose/fixtures/compose-native` walks the fork's material3, foundation.layout and ui.graphics klibs for linuxX64 (136 marker calls in the generated material3 fragment) and compiles for linuxX64 and macosArm64 with the compiler plugin on the classpath. A clean compile does not show the rewrite ran: the extension fails the compilation only when it runs before Compose's plugin, and K/N does not print its LOGGING line (`rewrote N __pympDefaultCall call(s)`) under Gradle `--info`. Its host test (`NativeComposableRenderTest`: Python `Text`, `Button` rendered with `ImageComposeScene`) runs in desktop.yml on Linux and macOS; an unrewritten marker throws there.
206206
3. **Which configuration konanc reads.** `kotlinNativeCompilerPluginClasspath` is assumed to be the one Kotlin/Native compilations use in KGP 2.4.20-Beta2; only the name's presence in the jar was checked.
207207
4. **Type inference of `__pympOmitted()`** against an overloaded or generic callee has not been compiled against a real Compose klib.
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
/**
2+
* #191: the composable claim of `:python-multiplatform-compose:fixtures:compose`, on Kotlin/Native
3+
* desktop (macosArm64, linuxX64).
4+
*
5+
* The fork's Compose klibs are walked by `KlibScanner` (the walker's klib half) into the shared
6+
* `nativeMain`. `Text` and `Button` declare more than 6 defaulted parameters, so their bindings go
7+
* through the consumer compiler plugin (`docs/design/klib-composable-and-defaults.md` B3, owner
8+
* decision 2026-11-19 on #191), which rewrites each marked call to the lowered `$default` symbol. The
9+
* host test renders Python's composition with `ImageComposeScene`, so a binding the compiler plugin
10+
* did not reach fails at its first call (the marker throws) rather than drawing something.
11+
*
12+
* Linking and `PYTHONHOME` come from the bindings plugin (SPEC L-9c).
13+
*/
14+
plugins {
15+
alias(libs.plugins.kotlin.multiplatform)
16+
alias(libs.plugins.jetpack.compose)
17+
alias(libs.plugins.compose.compiler)
18+
id("org.thisisthepy.python.multiplatform.bindings")
19+
}
20+
21+
kotlin {
22+
applyDefaultHierarchyTemplate()
23+
24+
macosArm64()
25+
linuxX64 {
26+
// Skiko's linuxX64 klib uses Fontconfig but declares no linker option for it (its own native
27+
// samples add these), so a test binary missed every Fc* symbol (batch run 44973431716). The
28+
// host's libfontconfig is newer than Kotlin/Native's sysroot glibc, so its own undefined
29+
// versioned references are left to the dynamic loader.
30+
binaries.all {
31+
linkerOpts("-L/usr/lib/x86_64-linux-gnu", "-l:libfontconfig.so.1", "--allow-shlib-undefined")
32+
}
33+
}
34+
35+
sourceSets {
36+
val commonMain by getting {
37+
dependencies {
38+
implementation(projects.pythonMultiplatform)
39+
implementation(projects.pythonMultiplatformCompose)
40+
implementation(compose.runtime)
41+
implementation(compose.foundation)
42+
implementation(compose.material3)
43+
implementation(compose.ui)
44+
}
45+
}
46+
val commonTest by getting {
47+
dependencies {
48+
implementation(libs.kotlin.test)
49+
}
50+
}
51+
}
52+
}
53+
54+
pythonBindings {
55+
role.set("app")
56+
processor.set(projects.pythonMultiplatformKsp)
57+
58+
// One walked configuration per module (ROADMAP §16f #1): linuxX64's klibs, generated into the
59+
// shared `nativeMain`, which macosArm64 compiles too (the fork publishes the same API for both).
60+
artifactConfiguration.set("linuxX64CompileKlibraries")
61+
artifactSourceSet.set("nativeMain")
62+
artifactIncludePackages.set(
63+
listOf(
64+
"androidx.compose.material3",
65+
"androidx.compose.foundation.layout",
66+
"androidx.compose.ui.graphics",
67+
),
68+
)
69+
compilerPlugin.set(project(":python-multiplatform-compiler-plugin"))
70+
}
71+
72+
// A failing host test prints its whole exception, message and Python error included: Gradle's default
73+
// short format printed only "PyException at null:-1" (batch run 44973431716).
74+
tasks.withType<AbstractTestTask>().configureEach {
75+
testLogging {
76+
events("failed")
77+
exceptionFormat = org.gradle.api.tasks.testing.logging.TestExceptionFormat.FULL
78+
showCauses = true
79+
showStackTraces = true
80+
}
81+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package fixture.composenative
2+
3+
import androidx.compose.runtime.Composable
4+
import androidx.compose.runtime.remember
5+
import python.multiplatform.compose.PythonCallableArena
6+
import python.multiplatform.compose.withPythonComposer
7+
import python.multiplatform.ffi.Python3
8+
import python.multiplatform.ffi.pythonx.PythonCallables
9+
10+
/**
11+
* Runs [source] as Python inside this composition, with the composer and a callable scope the
12+
* composition owns: the same entry point `:python-multiplatform-compose:fixtures:compose` uses on the
13+
* JVM (its `PythonComposition.kt`), here in common native code.
14+
*/
15+
@Composable
16+
fun PythonComposition(source: String) {
17+
val arena = remember { PythonCallableArena() }
18+
withPythonComposer {
19+
PythonCallables.withScope(arena.scope) {
20+
Python3.exec(source)
21+
}
22+
}
23+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
package fixture.composenative
2+
3+
import androidx.compose.ui.ImageComposeScene
4+
import androidx.compose.ui.unit.Density
5+
import org.jetbrains.skia.Bitmap
6+
import python.multiplatform.ffi.Python3
7+
import python.multiplatform.ffi.exceptions.PyException
8+
import python.multiplatform.ffi.pythonx.PythonxAdapter
9+
import python.multiplatform.ffi.upcall.UpcallBootstrap
10+
import python.multiplatform.generated.artifacts.ArtifactTable
11+
import python.multiplatform.reflection.UpcallTable
12+
import kotlin.test.AfterTest
13+
import kotlin.test.BeforeTest
14+
import kotlin.test.Test
15+
import kotlin.test.assertEquals
16+
import kotlin.test.assertTrue
17+
18+
/**
19+
* #191 on Kotlin/Native desktop: Python draws material3 composables whose bindings come from the
20+
* walked klibs. `Text` (about 15 defaulted parameters) and `Button` (8) are past B1's limit of 6, so
21+
* each call is the B3 compiler plugin's rewrite; if the plugin did not run, the marker function in
22+
* the generated fragment throws on the first call and these tests fail with its message.
23+
*/
24+
class NativeComposableRenderTest {
25+
26+
@BeforeTest
27+
fun install() {
28+
Python3.initialize(silent = true)
29+
UpcallTable.clear()
30+
UpcallTable.install(ArtifactTable.fragments)
31+
check(UpcallBootstrap.publishToGlobals()) { "UpcallBootstrap.publishToGlobals() failed" }
32+
PythonxAdapter.install(setOf("androidx.compose.ui.unit.Dp"))
33+
}
34+
35+
@AfterTest
36+
fun cleanup() {
37+
UpcallTable.clear()
38+
}
39+
40+
@Test
41+
fun pythonDrawsAMaterial3TextThroughTheCompilerPlugin() {
42+
val drawn = inkOf("from androidx.compose.material3 import Text\nText('hi')")
43+
val blank = inkOf("pass")
44+
println("compose-native render: Text('hi') -> $drawn px, empty body -> $blank px")
45+
assertEquals(0, blank, "an empty composition must draw nothing, or the measurement is not measuring")
46+
assertTrue(drawn > 0, "Text('hi') drew nothing")
47+
}
48+
49+
@Test
50+
fun moreTextIsMoreInk() {
51+
val short = inkOf("from androidx.compose.material3 import Text\nText('hi')")
52+
val long = inkOf("from androidx.compose.material3 import Text\nText('hi hi hi hi hi')")
53+
assertTrue(long > short, "expected more ink for more text: $short vs $long")
54+
}
55+
56+
@Test
57+
fun aButtonWithAPythonContentLambdaDraws() {
58+
val drawn = inkOf(
59+
"from androidx.compose.material3 import Button, Text\n" +
60+
"Button(onClick=lambda: None, content=lambda: Text('ok'))",
61+
)
62+
assertTrue(drawn > 0, "Button(...) drew nothing")
63+
}
64+
65+
private fun inkOf(body: String): Int {
66+
val scene = ImageComposeScene(width = 200, height = 60, density = Density(1f)) {
67+
PythonComposition(body)
68+
}
69+
try {
70+
val image = try {
71+
scene.render()
72+
} catch (e: PyException) {
73+
throw AssertionError("Python raised ${e.type?.name}: ${e.message}, running:\n$body", e)
74+
}
75+
val bitmap = Bitmap.makeFromImage(image)
76+
var ink = 0
77+
for (y in 0 until bitmap.height) {
78+
for (x in 0 until bitmap.width) {
79+
if (bitmap.getColor(x, y) != 0) ink++
80+
}
81+
}
82+
return ink
83+
} finally {
84+
scene.close()
85+
}
86+
}
87+
}

‎python-multiplatform-gradle-plugin/compiler-plugin/src/main/kotlin/python/multiplatform/compiler/PythonDefaultCallPlugin.kt‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ package python.multiplatform.compiler
55
import org.jetbrains.kotlin.backend.common.extensions.IrGenerationExtension
66
import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext
77
import org.jetbrains.kotlin.compiler.plugin.CompilerPluginRegistrar
8+
import org.jetbrains.kotlin.config.reportLog
89
import org.jetbrains.kotlin.config.CompilerConfiguration
910
import org.jetbrains.kotlin.descriptors.InlineClassRepresentation
1011
import org.jetbrains.kotlin.ir.IrElement
@@ -49,7 +50,7 @@ class PythonDefaultCallRegistrar : CompilerPluginRegistrar() {
4950
override val supportsK2: Boolean get() = true
5051

5152
override fun ExtensionStorage.registerExtensions(configuration: CompilerConfiguration) {
52-
IrGenerationExtension.registerExtension(PythonDefaultCallExtension())
53+
IrGenerationExtension.registerExtension(PythonDefaultCallExtension { configuration.reportLog(it) })
5354
}
5455
}
5556

@@ -64,15 +65,26 @@ class PythonDefaultCallRegistrar : CompilerPluginRegistrar() {
6465
* extension checks instead of assuming: a marker whose callee has no `$default` parameter is a
6566
* compilation error naming the cause.
6667
*/
67-
internal class PythonDefaultCallExtension : IrGenerationExtension {
68+
internal class PythonDefaultCallExtension(
69+
private val log: (String) -> Unit = {},
70+
) : IrGenerationExtension {
6871
override fun generate(moduleFragment: IrModuleFragment, pluginContext: IrPluginContext) {
69-
moduleFragment.transformChildrenVoid(DefaultCallRewriter())
72+
val rewriter = DefaultCallRewriter()
73+
moduleFragment.transformChildrenVoid(rewriter)
74+
// Evidence in a build log (`--info`) that this extension ran in a compilation and what it did:
75+
// a clean compile alone cannot tell "rewritten" from "never invoked".
76+
if (rewriter.rewritten > 0) {
77+
log("python-multiplatform defaults: rewrote ${rewriter.rewritten} $DEFAULT_CALL_MARKER call(s) in ${moduleFragment.name}")
78+
}
7079
}
7180
}
7281

7382
@OptIn(UnsafeDuringIrConstructionAPI::class)
7483
private class DefaultCallRewriter : IrElementTransformerVoid() {
7584

85+
/** How many marker calls this pass replaced. */
86+
var rewritten: Int = 0
87+
7688
override fun visitCall(expression: IrCall): IrExpression {
7789
val name = expression.symbol.owner.name.asString()
7890
if (name == OMITTED_MARKER) return zeroValueOf(expression.type, expression.startOffset, expression.endOffset)
@@ -95,6 +107,7 @@ private class DefaultCallRewriter : IrElementTransformerVoid() {
95107
?: IrConstImpl.int(expression.startOffset, expression.endOffset, parameter.type, 0)
96108
maskIndex += 1
97109
}
110+
rewritten += 1
98111
// The marker is gone; what it wrapped stands in its place. Visited afterwards so the
99112
// `__pympOmitted()` arguments inside it are replaced too.
100113
return wrapped.transform(this, null)

0 commit comments

Comments
 (0)