Skip to content

Commit dd9067f

Browse files
authored
Merge pull request #484 from thisisthepy/feat/164-ksp-walker-suspend-fn
Feat: expose top-level suspend function-typed parameters in KSP and ArtifactScanner (#164)
2 parents 7a79766 + f534c58 commit dd9067f

8 files changed

Lines changed: 199 additions & 48 deletions

File tree

‎python-multiplatform-gradle-plugin/src/main/kotlin/python/multiplatform/gradle/artifact/ArtifactScanner.kt‎

Lines changed: 82 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import kotlin.metadata.isSuspend
1212
import kotlin.metadata.isValue
1313
import kotlin.metadata.isVar
1414
import kotlin.metadata.jvm.KotlinClassMetadata
15+
import kotlin.metadata.jvm.annotations
1516
import kotlin.metadata.jvm.fieldSignature
1617
import kotlin.metadata.jvm.getterSignature
1718
import kotlin.metadata.jvm.setterSignature
@@ -1930,10 +1931,7 @@ internal object ArtifactScanner {
19301931
val declared = kotlinClassifierNameOf(type) ?: return null
19311932
if (!declared.startsWith(KOTLIN_FUNCTION_PREFIX)) return null
19321933
if (type.isSuspend) {
1933-
return FunctionSlot(
1934-
declineReason = "a suspend function-typed parameter ($declared): its compiled shape takes a " +
1935-
"Continuation and answers COROUTINE_SUSPENDED, which no Python callable can do",
1936-
)
1934+
return suspendFunctionSlot(type, declared, classpath)
19371935
}
19381936
val name = functionSlotTypeName(type, declared, descriptor)
19391937
?: return FunctionSlot(
@@ -1960,6 +1958,86 @@ internal object ArtifactScanner {
19601958
return FunctionSlot(typeName = name, boundary = BoundaryType("OBJECT", "(%s as $rendered)", "(%s)"))
19611959
}
19621960

1961+
/**
1962+
* A `suspend` function-typed parameter (SPEC U-5a; #164 item 7): on the JVM, Kotlin metadata
1963+
* records `suspend (A1, ..., AN) -> R` as `kotlin.Function(N+1)<A1, ..., AN, Continuation<R>, Any?>`
1964+
* with `type.isSuspend == true`.
1965+
*
1966+
* Supported for non-extension `suspend` function types of arities `0..5` (matching
1967+
* `PythonCallables.newSuspendFunction`). Extension `suspend` function types (`suspend R.() -> T`,
1968+
* marked by `@kotlin.ExtensionFunctionType`) are declined with a reason.
1969+
*/
1970+
private fun suspendFunctionSlot(type: KmType, declared: String, classpath: ArtifactClasspath): FunctionSlot {
1971+
if (type.annotations.any { it.className == EXTENSION_FUNCTION_TYPE_ANNOTATION }) {
1972+
return FunctionSlot(
1973+
declineReason = "a suspend extension function-typed parameter ($declared): receiver-carrying suspend lambdas are not supported yet",
1974+
)
1975+
}
1976+
val jvmArity = declared.removePrefix(KOTLIN_FUNCTION_PREFIX).toIntOrNull()
1977+
val arguments = type.arguments
1978+
if (jvmArity == null || arguments.size != jvmArity + 1) {
1979+
return FunctionSlot(
1980+
declineReason = "a suspend function-typed parameter ($declared): unexpected type argument count ${arguments.size}",
1981+
)
1982+
}
1983+
// On JVM metadata, a suspend function type `suspend (A1, ..., AN) -> R` is stored as
1984+
// `Function(N+1)<A1, ..., AN, kotlin.coroutines.Continuation<R>, kotlin.Any?>`: the second-to-last
1985+
// type argument is `Continuation<R>` and the last is `Any?`. Unwrap `Continuation<R>` to
1986+
// recover the true Kotlin parameter list `(A1, ..., AN)` and return type `R`.
1987+
val continuationType = arguments.getOrNull(arguments.size - 2)?.type
1988+
val isLoweredContinuation = continuationType != null &&
1989+
kotlinClassifierNameOf(continuationType) == CONTINUATION_CLASS_NAME &&
1990+
continuationType.arguments.size == 1
1991+
val logicalArgProjections: List<kotlin.metadata.KmTypeProjection>
1992+
val logicalRetProjection: kotlin.metadata.KmTypeProjection
1993+
if (isLoweredContinuation) {
1994+
logicalArgProjections = arguments.dropLast(2)
1995+
logicalRetProjection = continuationType!!.arguments[0]
1996+
} else {
1997+
logicalArgProjections = arguments.dropLast(1)
1998+
logicalRetProjection = arguments.last()
1999+
}
2000+
val logicalArity = logicalArgProjections.size
2001+
if (logicalArity !in 0..MAX_SUSPEND_FUNCTION_ARITY) {
2002+
return FunctionSlot(
2003+
declineReason = "a suspend function-typed parameter ($declared): only arities 0..$MAX_SUSPEND_FUNCTION_ARITY are supported",
2004+
)
2005+
}
2006+
val logicalProjections = logicalArgProjections + logicalRetProjection
2007+
val classifierNames = logicalProjections.map { projection ->
2008+
val argType = projection.type ?: return FunctionSlot(
2009+
declineReason = "a suspend function-typed parameter ($declared): a type argument is a star projection",
2010+
)
2011+
kotlinClassifierNameOf(argType) ?: return FunctionSlot(
2012+
declineReason = "a suspend function-typed parameter ($declared): a type argument has no name a proxy could be built over",
2013+
)
2014+
}
2015+
val renderedTypes = logicalProjections.map { projection ->
2016+
if (projection.variance != KmVariance.INVARIANT) {
2017+
return FunctionSlot(
2018+
declineReason = "a suspend function-typed parameter ($declared): use-site variance is not supported",
2019+
)
2020+
}
2021+
val argType = projection.type ?: return FunctionSlot(
2022+
declineReason = "a suspend function-typed parameter ($declared): a type argument is a star projection",
2023+
)
2024+
renderKotlinSourceType(argType, classpath, depth = 1) ?: return FunctionSlot(
2025+
declineReason = "a suspend function-typed parameter ($declared): some part of its signature is not a nameable public type",
2026+
)
2027+
}
2028+
val slotName = "kotlin.coroutines.SuspendFunction$logicalArity(" +
2029+
classifierNames.dropLast(1).joinToString(",") + ")" + FUNCTION_RETURNS + classifierNames.last()
2030+
val renderedArgs = renderedTypes.dropLast(1).joinToString(", ")
2031+
val renderedRet = renderedTypes.last()
2032+
val nullableSuffix = if (type.isNullable) "?" else ""
2033+
val castTarget = "(suspend ($renderedArgs) -> $renderedRet)$nullableSuffix"
2034+
return FunctionSlot(typeName = slotName, boundary = BoundaryType("OBJECT", "(%s as $castTarget)", "(%s)"))
2035+
}
2036+
2037+
private const val MAX_SUSPEND_FUNCTION_ARITY = 5
2038+
private const val EXTENSION_FUNCTION_TYPE_ANNOTATION = "kotlin/ExtensionFunctionType"
2039+
private const val CONTINUATION_CLASS_NAME = "kotlin.coroutines.Continuation"
2040+
19632041
/**
19642042
* A parameter typed as a **functional interface** (issue #216): a Java interface with one abstract
19652043
* method (`java.lang.Runnable`) or a Kotlin `fun interface`, whose method returns `Unit` and which is

‎python-multiplatform-gradle-plugin/src/test/kotlin/python/multiplatform/gradle/artifact/DeclarationModelTest.kt‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -133,19 +133,22 @@ class DeclarationModelTest {
133133
*/
134134
@Test
135135
fun aDeclinedDeclarationStaysVisibleWithItsReason() {
136-
val declined = fixtureDeclarations().single { it.simpleName == "withSuspendCallback" }
136+
val declined = fixtureDeclarations().single { it.simpleName == "withSuspendExtensionCallback" }
137137
assertNull(declined.bindingName, "the binder declined it, and that is the fact being kept")
138138
val reason = assertNotNull(declined.declineReason)
139139
assertTrue("suspend" in reason, reason)
140-
assertEquals("kotlin.Function1", declined.parameters.single().type.qualifiedName)
140+
assertEquals("kotlin.Function2", declined.parameters.single().type.qualifiedName)
141141

142-
// The half that moved. A plain `() -> Unit` binds now, and the *model* still spells its
143-
// parameter with the declared classifier: the signature grammar is the binding's answer
144-
// (`ArtifactCallable.paramTypeNames`), not the stub's.
142+
// The halves that moved: both a plain `() -> Unit` and a non-extension `suspend () -> Unit`
143+
// bind now (SPEC U-5a; #164 item 7).
145144
val bound = fixtureDeclarations().single { it.simpleName == "withCallback" }
146145
assertEquals("fixture.artifactvalueclass.withCallback", bound.bindingName)
147146
assertNull(bound.declineReason)
148147
assertEquals("kotlin.Function0", bound.parameters.single().type.qualifiedName)
148+
149+
val boundSuspend = fixtureDeclarations().single { it.simpleName == "withSuspendCallback" }
150+
assertEquals("fixture.artifactvalueclass.withSuspendCallback", boundSuspend.bindingName)
151+
assertNull(boundSuspend.declineReason)
149152
}
150153

151154
/** `suspend` is declined by both producers and §3.1 says it must not be stubbed. It is still in

‎python-multiplatform-gradle-plugin/src/test/kotlin/python/multiplatform/gradle/artifact/valueclassfixture/ValueClassFixtures.kt‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -99,17 +99,17 @@ fun withCallback(action: () -> Unit): Int {
9999
}
100100

101101
/**
102-
* The function-typed shape that is still declined, and not for want of a *name*: its slot is
103-
* describable and its arity checks out.
104-
*
105-
* A `suspend` lambda's compiled type is `Function1<Continuation<Unit>, Any?>`, it answers
106-
* `COROUTINE_SUSPENDED` rather than a value, and Kotlin will not let source assign a `Function1` to a
107-
* `suspend` function type at all. `Modifier.pointerInput` is the real-world case -- the one
108-
* `a179b747`'s open note named beside `clickable`, and the one that turns out to be a different limit
109-
* from the one that note was about.
102+
* A non-extension `suspend` function-typed parameter: binds now through `ArtifactScanner.suspendFunctionSlot`
103+
* (SPEC U-5a; #164 item 7).
110104
*/
111105
fun withSuspendCallback(action: suspend () -> Unit): Int = if (action === action) 1 else 0
112106

107+
/**
108+
* The function-typed shape that is still declined: a receiver-carrying `suspend` extension lambda
109+
* (`suspend String.() -> Unit`, the `Modifier.pointerInput` shape).
110+
*/
111+
fun withSuspendExtensionCallback(action: suspend String.() -> Unit): Int = if (action === action) 1 else 0
112+
113113
/**
114114
* `kotlin.time.Duration.getInWholeSeconds-impl(J)J`'s exact shape: a value class with a *public*
115115
* constructor and accessor (unlike `Duration`'s own `internal` one), but where the mangled method is

‎python-multiplatform-ksp/fixtures/app/src/desktopTest/kotlin/fixture/app/GeneratedSuspendTest.kt‎

Lines changed: 22 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -229,9 +229,17 @@ class GeneratedSuspendTest {
229229
// (`grep "has a type with no exposable classifier" build output`) rather than the old silence.
230230

231231
@Test
232-
fun aSuspendingFunctionTypeHasNoEntryAsATopLevelPropertyParameterOrReturn() {
232+
fun aSuspendingFunctionTypeIsExposedAsAParameterAndRejectedAsPropertyOrReturn() {
233+
// SPEC U-5a (#164 item 7): top-level `suspend` function-typed parameters (arities 0..5)
234+
// are now exposed with `kotlin.coroutines.SuspendFunctionN(Args)->Ret` metadata, while
235+
// properties and return types remain excluded with a KSP warning.
233236
assertFalse(UpcallTable.resolve("fixture.library.suspendingHandler").isValid)
234-
assertFalse(UpcallTable.resolve("fixture.library.runsHandler").isValid)
237+
assertTrue(UpcallTable.resolve("fixture.library.runsHandler").isValid)
238+
val entry = UpcallTable.callable(UpcallTable.resolve("fixture.library.runsHandler"))
239+
assertEquals(
240+
"kotlin.coroutines.SuspendFunction1(kotlin.Long)->kotlin.Long",
241+
entry.paramTypeNames[0],
242+
)
235243
assertFalse(UpcallTable.resolve("fixture.library.makeHandler").isValid)
236244
}
237245

@@ -247,27 +255,25 @@ class GeneratedSuspendTest {
247255
}
248256

249257
@Test
250-
fun aNullableSuspendingFunctionTypeHasNoEntry() {
258+
fun aNullableSuspendingFunctionTypeHasNoEntryAsProperty() {
251259
assertFalse(UpcallTable.resolve("fixture.library.nullableHandler").isValid)
252260
}
253261

254262
@Test
255-
fun aTypealiasForASuspendingFunctionTypeHasNoEntryEitherSideOfTheAlias() {
256-
// Measured, not assumed: `KSType.isSuspendFunctionType` answers `false` for the
257-
// alias-typed `KSType` itself (`KSType.declaration` is the `KSTypeAlias`, not the
258-
// expansion), so `isExposableType` has to expand one level of `typealias` before asking.
259-
// Without that expansion, `runsAliasedHandler`'s cast would target
260-
// `fixture.library.LongHandler` -- a real, source-declared classifier this time, since the
261-
// `typealias` is itself a declaration in this compilation -- and it would have passed
262-
// every check while remaining exactly as uncallable underneath.
263+
fun aTypealiasForASuspendingFunctionTypeIsExposedAsAParameterAndRejectedAsAProperty() {
263264
assertFalse(UpcallTable.resolve("fixture.library.aliasedHandler").isValid)
264-
assertFalse(UpcallTable.resolve("fixture.library.runsAliasedHandler").isValid)
265+
assertTrue(UpcallTable.resolve("fixture.library.runsAliasedHandler").isValid)
266+
val entry = UpcallTable.callable(UpcallTable.resolve("fixture.library.runsAliasedHandler"))
267+
assertEquals(
268+
"kotlin.coroutines.SuspendFunction1(kotlin.Long)->kotlin.Long",
269+
entry.paramTypeNames[0],
270+
)
265271
}
266272

267273
@Test
268-
fun aSuspendingFunctionTypeHasNoEntryAsAMemberPropertyParameterOrReturn() {
274+
fun aSuspendingFunctionTypeIsExposedAsAMemberParameterAndRejectedAsPropertyOrReturn() {
269275
assertFalse(UpcallTable.resolve("fixture.library.SuspendingService.handler").isValid)
270-
assertFalse(UpcallTable.resolve("fixture.library.SuspendingService.runsHandlerMember").isValid)
276+
assertTrue(UpcallTable.resolve("fixture.library.SuspendingService.runsHandlerMember").isValid)
271277
assertFalse(UpcallTable.resolve("fixture.library.SuspendingService.makesHandlerMember").isValid)
272278
}
273279

@@ -280,13 +286,8 @@ class GeneratedSuspendTest {
280286
}
281287

282288
@Test
283-
fun aSuspendingFunctionTypeHasNoEntryAsAPrimaryConstructorParameter() {
284-
// The primary constructor does not route through
285-
// `BindingPolicy.isExposedMemberFunction`/`isExposedTopLevelFunction` the way every other
286-
// function entry does -- `FragmentScanner` selects it directly -- so this is the one
287-
// location that needed its own, separate call to `hasExposableTypes` rather than
288-
// inheriting the check through a shared gate.
289-
assertFalse(UpcallTable.resolve("fixture.library.ValueHandler.<init>").isValid)
289+
fun aSuspendingFunctionTypeIsExposedAsAPrimaryConstructorParameterWhileItsPropertyStaysExcluded() {
290+
assertTrue(UpcallTable.resolve("fixture.library.ValueHandler.<init>").isValid)
290291
assertFalse(UpcallTable.resolve("fixture.library.ValueHandler.f").isValid)
291292
}
292293

‎python-multiplatform-ksp/src/main/kotlin/python/multiplatform/ksp/BindingPolicy.kt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -237,7 +237,7 @@ object BindingPolicy {
237237
* has nothing behind it.
238238
*/
239239
fun hasExposableTypes(function: KSFunctionDeclaration): Boolean =
240-
function.parameters.all { isExposableType(it.type) } &&
240+
function.parameters.all { isExposableParameterType(it.type) } &&
241241
(function.returnType?.let { isExposableType(it) } ?: true)
242242

243243
/** [hasExposableTypes] for a property's own type. */

‎python-multiplatform-ksp/src/main/kotlin/python/multiplatform/ksp/FragmentScanner.kt‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -389,7 +389,7 @@ class FragmentScanner(private val excludePackages: List<String>, private val log
389389
}
390390

391391
private fun constructorEntry(classQualifiedName: String, ctor: KSFunctionDeclaration): CallableEntryModel {
392-
val paramShapes = ctor.parameters.map { it.type.toShape() }
392+
val paramShapes = ctor.parameters.map { it.type.toShape(allowTopLevelSuspendFunction = true) }
393393
val argExprs = paramShapes.mapIndexed { i, shape -> castExpression(shape, "args[$i]") }
394394
return CallableEntryModel(
395395
name = "$classQualifiedName.<init>",
@@ -399,7 +399,7 @@ class FragmentScanner(private val excludePackages: List<String>, private val log
399399
kind = "CONSTRUCTOR",
400400
lambdaBody = "{ args -> $classQualifiedName(${argExprs.joinToString(", ")}) }",
401401
paramNames = paramNamesOf(ctor.parameters),
402-
paramTypeNames = paramShapes.map { it.rendered },
402+
paramTypeNames = paramShapes.map { it.slotTypeName },
403403
// The class being built, not a `TypeShape` -- there is no return-type usage to derive
404404
// one from. `PythonProxySource.renderClass`'s own comment records that a CONSTRUCTOR
405405
// result is never wrapped by this gate anyway (`self._pm_handle` is set directly), so
@@ -412,7 +412,7 @@ class FragmentScanner(private val excludePackages: List<String>, private val log
412412
}
413413

414414
private fun memberFunctionEntry(classQualifiedName: String, function: KSFunctionDeclaration): CallableEntryModel {
415-
val paramShapes = function.parameters.map { it.type.toShape() }
415+
val paramShapes = function.parameters.map { it.type.toShape(allowTopLevelSuspendFunction = true) }
416416
val returnShape = function.returnType?.toShape() ?: TypeShape("kotlin.Unit", false)
417417
// args[0] is the receiver; declared parameters start at args[1].
418418
val argExprs = paramShapes.mapIndexed { i, shape -> castExpression(shape, "args[${i + 1}]") }
@@ -431,7 +431,7 @@ class FragmentScanner(private val excludePackages: List<String>, private val log
431431
// a `<receiver>` slot the way an [python.multiplatform.reflection.ExposedCallable
432432
// .isExtension] entry would.
433433
paramNames = paramNamesOf(function.parameters),
434-
paramTypeNames = paramShapes.map { it.rendered },
434+
paramTypeNames = paramShapes.map { it.slotTypeName },
435435
returnTypeName = returnShape.rendered,
436436
paramHasDefault = paramHasDefaultOf(function.parameters),
437437
)
@@ -447,7 +447,7 @@ class FragmentScanner(private val excludePackages: List<String>, private val log
447447
callPrefix: String,
448448
function: KSFunctionDeclaration,
449449
): CallableEntryModel {
450-
val paramShapes = function.parameters.map { it.type.toShape() }
450+
val paramShapes = function.parameters.map { it.type.toShape(allowTopLevelSuspendFunction = true) }
451451
val returnShape = function.returnType?.toShape() ?: TypeShape("kotlin.Unit", false)
452452
val argExprs = paramShapes.mapIndexed { i, shape -> castExpression(shape, "args[$i]") }
453453
val callExpr = "$callPrefix.${function.simpleName.asString()}(${argExprs.joinToString(", ")})"
@@ -460,7 +460,7 @@ class FragmentScanner(private val excludePackages: List<String>, private val log
460460
lambdaBody = functionBody(function, wrapReturnExpression(returnShape, callExpr)),
461461
isSuspend = BindingPolicy.isSuspending(function),
462462
paramNames = paramNamesOf(function.parameters),
463-
paramTypeNames = paramShapes.map { it.rendered },
463+
paramTypeNames = paramShapes.map { it.slotTypeName },
464464
returnTypeName = returnShape.rendered,
465465
paramHasDefault = paramHasDefaultOf(function.parameters),
466466
)

0 commit comments

Comments
 (0)