├── .gitignore ├── playground ├── .gitignore ├── core │ ├── src │ │ └── commonMain │ │ │ └── kotlin │ │ │ └── core │ │ │ └── Greeter.kt │ └── build.gradle.kts ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradle.properties ├── libB │ ├── src │ │ └── commonMain │ │ │ └── kotlin │ │ │ └── LibAGreeter.kt │ └── build.gradle.kts ├── app │ ├── src │ │ ├── commonTest │ │ │ └── kotlin │ │ │ │ └── CommonTest.kt │ │ └── commonMain │ │ │ └── kotlin │ │ │ └── Main.kt │ └── build.gradle.kts ├── libA │ ├── build.gradle.kts │ └── src │ │ └── commonMain │ │ └── kotlin │ │ └── LibAGreeter.kt ├── kotlinx-spi-playground.iml ├── build.gradle.kts ├── settings.gradle.kts ├── gradlew.bat └── gradlew ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── kotlinx-spi-compiler ├── src │ └── main │ │ └── kotlin │ │ └── org │ │ └── jetbrains │ │ └── kotlinx │ │ └── spi │ │ └── ksp │ │ ├── fqNames.kt │ │ ├── ServiceDeclaration.kt │ │ ├── genreateSource.kt │ │ ├── compileJvm.kt │ │ ├── compileNative.kt │ │ ├── main.kt │ │ ├── readClassFile.kt │ │ └── readKlib.kt └── build.gradle.kts ├── kotlinx-spi-runtime ├── src │ └── commonMain │ │ └── kotlin │ │ └── ServiceLoader.kt └── build.gradle.kts ├── kotlinx-spi-gradle-plugin ├── src │ └── main │ │ └── kotlin │ │ └── org │ │ └── jetbrains │ │ └── kotlinx │ │ └── spi │ │ └── gradle │ │ ├── utils.kt │ │ ├── spiCompilerClasspath.kt │ │ └── SpiGradlePlugin.kt └── build.gradle.kts ├── kotlinx-spi-core ├── src │ └── commonMain │ │ └── kotlin │ │ └── org │ │ └── jetbrains │ │ └── kotlinx │ │ └── spi │ │ ├── Service.kt │ │ └── loader.kt └── build.gradle.kts ├── settings.gradle.kts ├── ReadMe.md ├── gradlew.bat └── gradlew /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | .idea 3 | .kotlin 4 | **/build -------------------------------------------------------------------------------- /playground/.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | .kotlin 3 | .idea 4 | **/build 5 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sellmair/kotlinx-spi/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /playground/core/src/commonMain/kotlin/core/Greeter.kt: -------------------------------------------------------------------------------- 1 | package core 2 | 3 | interface Greeter { 4 | fun greet() 5 | } -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | org.gradle.jvmargs=-Xmx2g -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 2 | -------------------------------------------------------------------------------- /playground/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sellmair/kotlinx-spi/HEAD/playground/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /playground/core/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | kotlin("multiplatform") 3 | } 4 | 5 | kotlin { 6 | jvm() 7 | macosX64() 8 | macosArm64() 9 | } -------------------------------------------------------------------------------- /kotlinx-spi-compiler/src/main/kotlin/org/jetbrains/kotlinx/spi/ksp/fqNames.kt: -------------------------------------------------------------------------------- 1 | package org.jetbrains.kotlinx.spi.ksp 2 | 3 | internal const val SPI_SERVICE_ANNOTATION_FQN = "org/jetbrains/kotlinx/spi/Service" -------------------------------------------------------------------------------- /kotlinx-spi-runtime/src/commonMain/kotlin/ServiceLoader.kt: -------------------------------------------------------------------------------- 1 | package _KOTLINX_SPI_MODULE 2 | 3 | import kotlin.reflect.KClass 4 | 5 | fun loadService(service: KClass): Sequence { 6 | return emptySequence() 7 | } 8 | -------------------------------------------------------------------------------- /playground/gradle.properties: -------------------------------------------------------------------------------- 1 | org.gradle.jvmargs=-Xmx2g -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 2 | ksp.useKSP2=true 3 | kotlin.native.home=/Users/sebastiansellmair/JetBrainsProjects/kotlin/kotlin-native/dist -------------------------------------------------------------------------------- /playground/libB/src/commonMain/kotlin/LibAGreeter.kt: -------------------------------------------------------------------------------- 1 | import core.Greeter 2 | import org.jetbrains.kotlinx.spi.Service 3 | 4 | @Service(Greeter::class) 5 | object LibB : Greeter { 6 | override fun greet() { 7 | println("Hello from **LIB B**") 8 | } 9 | } -------------------------------------------------------------------------------- /kotlinx-spi-compiler/src/main/kotlin/org/jetbrains/kotlinx/spi/ksp/ServiceDeclaration.kt: -------------------------------------------------------------------------------- 1 | package org.jetbrains.kotlinx.spi.ksp 2 | 3 | import org.jetbrains.kotlin.name.FqName 4 | 5 | data class ServiceDeclaration(val service: FqName, val implementation: FqName, val ordinal: Int) -------------------------------------------------------------------------------- /kotlinx-spi-gradle-plugin/src/main/kotlin/org/jetbrains/kotlinx/spi/gradle/utils.kt: -------------------------------------------------------------------------------- 1 | package org.jetbrains.kotlinx.spi.gradle 2 | 3 | import java.util.* 4 | 5 | val String.capitalized get() = replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() } -------------------------------------------------------------------------------- /playground/app/src/commonTest/kotlin/CommonTest.kt: -------------------------------------------------------------------------------- 1 | import core.Greeter 2 | import org.jetbrains.kotlinx.spi.loadService 3 | import kotlin.test.Test 4 | 5 | 6 | class CommonTest { 7 | @Test 8 | fun testGreeting() { 9 | loadService().forEach { it.greet() } 10 | } 11 | } -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /kotlinx-spi-core/src/commonMain/kotlin/org/jetbrains/kotlinx/spi/Service.kt: -------------------------------------------------------------------------------- 1 | package org.jetbrains.kotlinx.spi 2 | 3 | import kotlin.reflect.KClass 4 | 5 | @Target(AnnotationTarget.CLASS) 6 | @Retention(AnnotationRetention.BINARY) 7 | @Repeatable 8 | annotation class Service(val target: KClass<*>, val ordinal: Int = 0) 9 | -------------------------------------------------------------------------------- /playground/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /playground/libA/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | kotlin("multiplatform") 3 | } 4 | 5 | kotlin { 6 | jvm() 7 | macosX64() 8 | macosArm64() 9 | 10 | sourceSets.commonMain.dependencies { 11 | implementation("org.jetbrains.kotlinx:kotlinx-spi-core:1.0.0-SNAPSHOT") 12 | implementation(project(":core")) 13 | } 14 | } -------------------------------------------------------------------------------- /playground/libB/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | kotlin("multiplatform") 3 | } 4 | 5 | kotlin { 6 | jvm() 7 | macosX64() 8 | macosArm64() 9 | 10 | sourceSets.commonMain.dependencies { 11 | implementation("org.jetbrains.kotlinx:kotlinx-spi-core:1.0.0-SNAPSHOT") 12 | implementation(project(":core")) 13 | } 14 | } -------------------------------------------------------------------------------- /playground/kotlinx-spi-playground.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /playground/app/src/commonMain/kotlin/Main.kt: -------------------------------------------------------------------------------- 1 | import core.Greeter 2 | import org.jetbrains.kotlinx.spi.Service 3 | import org.jetbrains.kotlinx.spi.loadService 4 | 5 | @Service(Greeter::class) 6 | object RootGreeter : Greeter { 7 | override fun greet() { 8 | println("Hello from root") 9 | } 10 | } 11 | 12 | fun main() { 13 | loadService().forEach { it.greet() } 14 | } 15 | -------------------------------------------------------------------------------- /kotlinx-spi-core/src/commonMain/kotlin/org/jetbrains/kotlinx/spi/loader.kt: -------------------------------------------------------------------------------- 1 | package org.jetbrains.kotlinx.spi 2 | 3 | import kotlin.reflect.KClass 4 | 5 | 6 | inline fun loadService(): Sequence { 7 | return loadService(T::class) 8 | } 9 | 10 | @PublishedApi 11 | internal fun loadService(service: KClass): Sequence { 12 | return _KOTLINX_SPI_MODULE.loadService(service) 13 | } -------------------------------------------------------------------------------- /kotlinx-spi-compiler/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | kotlin("jvm") 3 | `maven-publish` 4 | } 5 | 6 | publishing { 7 | publications.create("maven") { 8 | from(components["java"]) 9 | } 10 | } 11 | 12 | dependencies { 13 | implementation(kotlin("compiler-embeddable:2.0.20")) 14 | implementation("org.jetbrains.kotlinx:kotlinx-metadata-jvm:0.9.0") 15 | implementation("org.ow2.asm:asm:9.7") 16 | } 17 | -------------------------------------------------------------------------------- /playground/build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.jetbrains.kotlin.gradle.dsl.KotlinNativeCompilerOptions 2 | import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSetTree 3 | import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinMetadataTarget 4 | import org.jetbrains.kotlin.gradle.plugin.mpp.NativeBuildType 5 | 6 | plugins { 7 | kotlin("multiplatform") version "2.0.20" apply false 8 | id("org.jetbrains.kotlinx.spi") version "1.0.0-SNAPSHOT" apply false 9 | } 10 | -------------------------------------------------------------------------------- /kotlinx-spi-gradle-plugin/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | `java-gradle-plugin` 3 | `kotlin-dsl` 4 | `maven-publish` 5 | } 6 | 7 | dependencies { 8 | compileOnly(kotlin("gradle-plugin:2.0.20")) 9 | } 10 | 11 | gradlePlugin { 12 | plugins { 13 | create("org.jetbrains.kotlinx.spi") { 14 | id = "org.jetbrains.kotlinx.spi" 15 | implementationClass = "org.jetbrains.kotlinx.spi.gradle.SpiGradlePlugin" 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /playground/libA/src/commonMain/kotlin/LibAGreeter.kt: -------------------------------------------------------------------------------- 1 | import core.Greeter 2 | import org.jetbrains.kotlinx.spi.Service 3 | 4 | @Service(Greeter::class, ordinal = 10) 5 | object LibAGreeter : Greeter { 6 | override fun greet() { 7 | println("Hello from libA") 8 | } 9 | } 10 | 11 | @Service(Greeter::class, ordinal = 10) 12 | internal object LibAInternalGreeter : Greeter { 13 | override fun greet() { 14 | println("Hello from libA internals") 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /kotlinx-spi-runtime/build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget 2 | 3 | plugins { 4 | kotlin("multiplatform") 5 | `maven-publish` 6 | } 7 | 8 | kotlin { 9 | jvm() 10 | macosX64() 11 | macosArm64() 12 | 13 | targets.withType().configureEach { 14 | compilations.getByName("main").compileTaskProvider.configure { 15 | compilerOptions.moduleName.set("kotlinx.spi.runtime") 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /playground/settings.gradle.kts: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | includeBuild("..") 3 | 4 | repositories { 5 | gradlePluginPortal() 6 | mavenCentral() 7 | 8 | mavenLocal { 9 | mavenContent { 10 | includeGroupByRegex("org.jetbrains.kotlinx.*") 11 | } 12 | } 13 | } 14 | } 15 | 16 | dependencyResolutionManagement { 17 | repositories { 18 | mavenCentral() 19 | mavenLocal { 20 | mavenContent { 21 | includeGroup("org.jetbrains.kotlinx") 22 | } 23 | } 24 | } 25 | } 26 | 27 | includeBuild("..") 28 | 29 | include(":core") 30 | include(":libA") 31 | include(":libB") 32 | include(":app") -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | @file:Suppress("UnstableApiUsage") 2 | 3 | pluginManagement { 4 | repositories { 5 | mavenCentral() 6 | gradlePluginPortal() 7 | } 8 | } 9 | 10 | dependencyResolutionManagement { 11 | repositories { 12 | mavenCentral() 13 | maven("https://maven.pkg.jetbrains.space/kotlin/p/kotlin/kotlin-ide-plugin-dependencies") 14 | maven("https://packages.jetbrains.team/maven/p/ij/intellij-dependencies") 15 | } 16 | } 17 | 18 | gradle.lifecycle.beforeProject { 19 | version = "1.0.0-SNAPSHOT" 20 | group = "org.jetbrains.kotlinx" 21 | } 22 | 23 | include(":kotlinx-spi-core") 24 | include(":kotlinx-spi-runtime") 25 | include(":kotlinx-spi-compiler") 26 | include(":kotlinx-spi-gradle-plugin") 27 | -------------------------------------------------------------------------------- /kotlinx-spi-gradle-plugin/src/main/kotlin/org/jetbrains/kotlinx/spi/gradle/spiCompilerClasspath.kt: -------------------------------------------------------------------------------- 1 | package org.jetbrains.kotlinx.spi.gradle 2 | 3 | import org.gradle.api.Project 4 | import org.gradle.api.artifacts.Configuration 5 | import org.gradle.kotlin.dsl.dependencies 6 | 7 | private const val SPI_COMPILER_CLASSPATH_CONFIGURATION_NAME = "_spiCompilerClasspath" 8 | 9 | internal fun Project.createSpiCompilerClasspathConfiguration(): Configuration { 10 | return configurations.create(SPI_COMPILER_CLASSPATH_CONFIGURATION_NAME) { 11 | isCanBeConsumed = false 12 | isCanBeResolved = true 13 | project.dependencies { 14 | this@create("org.jetbrains.kotlinx:kotlinx-spi-compiler:1.0.0-SNAPSHOT") 15 | } 16 | } 17 | } 18 | 19 | internal fun Project.getSpiCompilerClasspathConfiguration(): Configuration { 20 | return configurations.getByName(SPI_COMPILER_CLASSPATH_CONFIGURATION_NAME) 21 | } -------------------------------------------------------------------------------- /playground/app/build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.jetbrains.kotlin.gradle.plugin.mpp.NativeBuildType 2 | 3 | plugins { 4 | kotlin("multiplatform") 5 | id("org.jetbrains.kotlinx.spi") 6 | } 7 | 8 | kotlin { 9 | jvm() 10 | macosArm64() 11 | 12 | macosArm64().binaries.executable { 13 | entryPoint = "main" 14 | } 15 | 16 | sourceSets.commonMain.dependencies { 17 | implementation("org.jetbrains.kotlinx:kotlinx-spi-core:1.0.0-SNAPSHOT") 18 | implementation(project(":core")) 19 | implementation(project(":libA")) 20 | } 21 | 22 | sourceSets.commonTest.dependencies { 23 | implementation(kotlin("test")) 24 | runtimeOnly(project(":libB")) 25 | } 26 | } 27 | 28 | tasks.register("macosRun") { 29 | dependsOn(kotlin.macosArm64().binaries.getExecutable(NativeBuildType.DEBUG).linkTaskProvider) 30 | val file = kotlin.macosArm64().binaries.getExecutable(NativeBuildType.DEBUG).outputFile 31 | inputs.files(file) 32 | commandLine(file.absolutePath) 33 | } 34 | -------------------------------------------------------------------------------- /kotlinx-spi-compiler/src/main/kotlin/org/jetbrains/kotlinx/spi/ksp/genreateSource.kt: -------------------------------------------------------------------------------- 1 | package org.jetbrains.kotlinx.spi.ksp 2 | 3 | import org.jetbrains.kotlin.name.FqName 4 | 5 | internal fun generateServiceLoaderSourceCode(declarations: List): String { 6 | val bindings = declarations.groupBy { it.service } 7 | 8 | val serviceLoader = """ 9 | package _KOTLINX_SPI_MODULE 10 | 11 | import kotlin.reflect.KClass 12 | 13 | private val services = mapOf>( 14 | ${bindings.entries.joinToString { (service, impls) -> renderBinding(service, impls) }} 15 | ) 16 | 17 | fun loadService(service: KClass): Sequence { 18 | val qualifiedName = service.qualifiedName ?: return emptySequence() 19 | return services[qualifiedName]?.asSequence()?.let { it as Sequence } ?: emptySequence() 20 | } 21 | 22 | """.trimIndent() 23 | 24 | return serviceLoader 25 | } 26 | 27 | private fun renderBinding(service: FqName, declarations: List): String { 28 | val implementations = declarations.sortedBy { it.ordinal }.map { it.implementation } 29 | return """ 30 | "${service.asString()}" to listOf(${implementations.joinToString { it.asString() }}), 31 | """.trimIndent() 32 | } 33 | 34 | -------------------------------------------------------------------------------- /kotlinx-spi-compiler/src/main/kotlin/org/jetbrains/kotlinx/spi/ksp/compileJvm.kt: -------------------------------------------------------------------------------- 1 | package org.jetbrains.kotlinx.spi.ksp 2 | 3 | import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments 4 | import org.jetbrains.kotlin.cli.common.messages.MessageRenderer 5 | import org.jetbrains.kotlin.cli.common.messages.PrintingMessageCollector 6 | import org.jetbrains.kotlin.cli.jvm.K2JVMCompiler 7 | import org.jetbrains.kotlin.config.Services 8 | import org.jetbrains.kotlin.incremental.classpathAsList 9 | import org.jetbrains.kotlin.incremental.destinationAsFile 10 | import java.nio.file.Path 11 | import kotlin.io.path.absolute 12 | import kotlin.io.path.absolutePathString 13 | 14 | fun compileJvm( 15 | source: Path, 16 | classpath: List, 17 | output: Path, 18 | ) { 19 | val arguments = K2JVMCompilerArguments() 20 | arguments.moduleName = "kotlinx.spi.runtime" 21 | arguments.classpathAsList = classpath.map { it.absolute().toFile() }.toList() 22 | arguments.destinationAsFile = output.toFile() 23 | arguments.freeArgs = listOf(source.absolutePathString()) 24 | arguments.friendPaths = classpath.map { it.absolutePathString() }.toTypedArray() 25 | arguments.noStdlib = true 26 | K2JVMCompiler().exec( 27 | PrintingMessageCollector(System.err, MessageRenderer.GRADLE_STYLE, true), 28 | Services.EMPTY, 29 | arguments 30 | ) 31 | } -------------------------------------------------------------------------------- /kotlinx-spi-compiler/src/main/kotlin/org/jetbrains/kotlinx/spi/ksp/compileNative.kt: -------------------------------------------------------------------------------- 1 | package org.jetbrains.kotlinx.spi.ksp 2 | 3 | import org.jetbrains.kotlin.cli.common.arguments.K2NativeCompilerArguments 4 | import org.jetbrains.kotlin.compilerRunner.toArgumentStrings 5 | import org.jetbrains.kotlin.konan.target.CompilerOutputKind 6 | import org.jetbrains.kotlin.konan.target.KonanTarget 7 | import java.io.File 8 | import java.net.URLClassLoader 9 | import java.nio.file.Path 10 | import kotlin.io.path.absolutePathString 11 | import kotlin.io.path.exists 12 | import kotlin.io.path.name 13 | 14 | fun compileNative( 15 | source: Path, 16 | classpath: List, 17 | output: Path, 18 | konanHome: Path, 19 | konanTarget: KonanTarget 20 | ) { 21 | val args = K2NativeCompilerArguments() 22 | val filteredClasspath = classpath.filter { it.exists() } 23 | 24 | args.moduleName = "kotlinx.spi.runtime" 25 | args.nostdlib = true 26 | args.libraries = filteredClasspath.map { it.absolutePathString() }.toTypedArray() 27 | args.friendModules = filteredClasspath.joinToString(File.pathSeparator) { it.absolutePathString() } 28 | args.freeArgs = listOf(source.absolutePathString()) 29 | args.target = konanTarget.name 30 | args.produce = CompilerOutputKind.LIBRARY.name 31 | args.outputName = output.absolutePathString() 32 | args.includeBinaries 33 | 34 | val konanJar = konanHome.resolve("konan/lib/kotlin-native-compiler-embeddable.jar") 35 | val trove4jJar = konanHome.resolve("konan/lib/trove4j.jar") 36 | val konanClassLoader = URLClassLoader( 37 | arrayOf(konanJar.toUri().toURL(), trove4jJar.toUri().toURL()), 38 | ClassLoader.getPlatformClassLoader() 39 | ) 40 | 41 | val main = konanClassLoader.loadClass("org.jetbrains.kotlin.cli.utilities.MainKt") 42 | val arguments = (listOf("konanc") + args.toArgumentStrings()) 43 | 44 | main.getDeclaredMethod("main", Array::class.java).invoke(null, arguments.toTypedArray()) 45 | } -------------------------------------------------------------------------------- /kotlinx-spi-core/build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.gradle.internal.impldep.org.apache.tools.zip.ZipFile 2 | import org.gradle.kotlin.dsl.support.unzipTo 3 | import org.gradle.kotlin.dsl.support.zipTo 4 | import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeCompilation 5 | import org.jetbrains.kotlin.gradle.tasks.KotlinNativeCompile 6 | import java.util.zip.ZipEntry 7 | import java.util.zip.ZipOutputStream 8 | 9 | plugins { 10 | kotlin("multiplatform") 11 | `maven-publish` 12 | } 13 | 14 | kotlin { 15 | jvm() 16 | macosX64() 17 | macosArm64() 18 | 19 | sourceSets.commonMain.dependencies { 20 | implementation(project(":kotlinx-spi-runtime")) 21 | } 22 | 23 | tasks.withType().configureEach { 24 | /* Patch the manifest */ 25 | if (properties.contains("patch.manifest")) 26 | doLast { 27 | val klib = outputFile.get() 28 | val unzipped = klib.parentFile.resolve("unzipped") 29 | unzipTo(unzipped, klib) 30 | if (!unzipped.resolve("default/targets").exists()) { 31 | error("DOES NOT EXIST?") 32 | } 33 | klib.delete() 34 | 35 | val manifest = unzipped.resolve("default/manifest") 36 | manifest.writeText( 37 | manifest.readText() 38 | .replace("depends=stdlib org.jetbrains.kotlinx\\:kotlinx-spi-compiletime", "depends=stdlib") 39 | ) 40 | 41 | ZipOutputStream(klib.outputStream()).use { out -> 42 | unzipped.walkTopDown().forEach { file -> 43 | if (file.isDirectory) { 44 | out.putNextEntry(ZipEntry(file.relativeTo(unzipped).path + "/")) 45 | out.closeEntry() 46 | } 47 | 48 | if (file.isFile) { 49 | out.putNextEntry(ZipEntry(file.relativeTo(unzipped).path)) 50 | file.inputStream().use { input -> input.copyTo(out) } 51 | out.closeEntry() 52 | } 53 | } 54 | } 55 | } 56 | } 57 | } 58 | 59 | -------------------------------------------------------------------------------- /ReadMe.md: -------------------------------------------------------------------------------- 1 | # kotlinx.spi: Static, Kotlin Multiplatform ServiceLoader replacement 2 | ## Demo: https://youtu.be/hMk04PjVh9M 3 | This prototype acts as a 'Proof of Concept' and is not yet endorsed by JetBrains or Kotlin by any means. 4 | 5 | ## Motivation 6 | Java's ServiceLoader is a pretty popular implementation of a generic 'Service Provider Interface.' 7 | This ServiceLoader (and similar mechanisms), however, have the following problems: 8 | - They do not support Kotlin/Native 9 | - Reflection or IO at runtime might be undesirable for some applications 10 | - Reflection might be unsafe 11 | 12 | This spi implementation, whilst also being multiplatform, is fully static. 13 | All services will be known at compile time; The corresponding IR or ByteCode will be generated to 14 | link them. 15 | 16 | Note: This does not mean that the services have to be visible to the currently compiled module. 17 | Each 'execution' gets associated with their own 'spi compilation' and will be provided the module at runtime. 18 | 19 | ## Implementation 20 | Code gets compiled against the `kotlinx.spi.runtime` module which, by default, returns an empty sequence 21 | of services. However, when the `kotlinx.spi` plugin is applied to a project, then each 'executable' 22 | will get assigned its own compilation of a *real* `kotlinx.spi.runtime`. 23 | 24 | e.g. when running `jvmRun`, this execution will have its associated compilation `:compileKotlinSpiJvmMain` 25 | which will look at the runtime classpath and generated the necessary links. 26 | 27 | ### Kotlin Native Implementation 28 | The Kotlin/Native implementation requires one additional change to the `KotlinLibraryResolver` in order 29 | to replace the `kotlinx.spi.runtime` module with a 'real' one. See the commit in kotlin/sellmair/spi. 30 | 31 | ## Try: playground 32 | This kotlinx.spi implementation requires a small change in the Kotlin/Native compiler which can be found in the 33 | `sellmair/spi` branch of Kotlin. The K/N compiler needs to be built first and provided in the 34 | `gradle.properties` file. 35 | 36 | Run jvm/main 37 | ```shell 38 | cd playground 39 | ./gradlew :app:jvmRun -DmainClass=MainKt 40 | ``` 41 | 42 | Run jvm/test 43 | ```shell 44 | cd playground 45 | ./gradlew :app:jvmTest --rerun -i 46 | ``` 47 | 48 | Run macosArm64/main 49 | ```shell 50 | cd playground 51 | ./gradlew :app:macosRun 52 | ``` -------------------------------------------------------------------------------- /kotlinx-spi-compiler/src/main/kotlin/org/jetbrains/kotlinx/spi/ksp/main.kt: -------------------------------------------------------------------------------- 1 | @file:JvmName("SpiCompiler") 2 | @file:OptIn(UnstableMetadataApi::class) 3 | 4 | package org.jetbrains.kotlinx.spi.ksp 5 | 6 | 7 | import kotlinx.metadata.jvm.UnstableMetadataApi 8 | import org.jetbrains.kotlin.konan.target.KonanTarget 9 | import org.jetbrains.kotlin.library.ToolingSingleFileKlibResolveStrategy 10 | import org.jetbrains.kotlin.library.resolveSingleFileKlib 11 | import java.nio.file.Path 12 | import kotlin.io.path.* 13 | import org.jetbrains.kotlin.konan.file.File as KonanFile 14 | 15 | data class Arguments( 16 | val output: Path, 17 | val classpath: List, 18 | val konanTarget: KonanTarget?, 19 | val konanHome: Path?, 20 | ) 21 | 22 | 23 | fun main(args: Array) { 24 | val arguments = args.toList().listIterator() 25 | 26 | var output = "build/spi" 27 | val classpath = mutableListOf() 28 | var konanTarget: String? = null 29 | var konanHome: String? = null 30 | 31 | while (arguments.hasNext()) { 32 | when (val arg = arguments.next()) { 33 | "--output" -> output = arguments.next() 34 | "--konan-target" -> konanTarget = arguments.next() 35 | "--konan-home" -> konanHome = arguments.next() 36 | else -> classpath += arg 37 | } 38 | } 39 | 40 | val parsed = Arguments( 41 | output = Path(output), 42 | classpath = classpath.map { Path(it) }, 43 | konanTarget = konanTarget?.let { KonanTarget.predefinedTargets[it]!! }, 44 | konanHome = konanHome?.let { Path(it) }, 45 | ) 46 | 47 | compile(parsed) 48 | } 49 | 50 | fun compile(arguments: Arguments) { 51 | val services: List = arguments.classpath.flatMap { binary -> 52 | if (!binary.exists()) return@flatMap emptyList() 53 | 54 | if (binary.extension == "klib") { 55 | val resolvedKlib = resolveSingleFileKlib(KonanFile(binary), strategy = ToolingSingleFileKlibResolveStrategy) 56 | return@flatMap readLibrary(resolvedKlib) 57 | } 58 | 59 | if (binary.extension == "jar") { 60 | return@flatMap readJar(binary) 61 | } 62 | 63 | if (binary.isDirectory()) { 64 | return@flatMap readDirectory(binary) 65 | } 66 | 67 | emptyList() 68 | } 69 | println("Found services: $services") 70 | 71 | 72 | val serviceLoaderCode = generateServiceLoaderSourceCode(services) 73 | val serviceLoaderFile = arguments.output.resolveSibling("source/ServiceLoader.kt") 74 | serviceLoaderFile.createParentDirectories() 75 | serviceLoaderFile.writeText(serviceLoaderCode) 76 | 77 | if (arguments.konanTarget != null) { 78 | compileNative( 79 | serviceLoaderFile, 80 | arguments.classpath, 81 | arguments.output, 82 | arguments.konanHome!!, 83 | arguments.konanTarget 84 | ) 85 | } else { 86 | compileJvm(serviceLoaderFile, arguments.classpath, arguments.output) 87 | } 88 | } 89 | 90 | 91 | 92 | 93 | -------------------------------------------------------------------------------- /kotlinx-spi-compiler/src/main/kotlin/org/jetbrains/kotlinx/spi/ksp/readClassFile.kt: -------------------------------------------------------------------------------- 1 | package org.jetbrains.kotlinx.spi.ksp 2 | 3 | import org.jetbrains.kotlin.name.ClassId 4 | import org.jetbrains.kotlin.name.FqName 5 | import org.objectweb.asm.AnnotationVisitor 6 | import org.objectweb.asm.ClassReader 7 | import org.objectweb.asm.ClassVisitor 8 | import org.objectweb.asm.Opcodes 9 | import org.objectweb.asm.Type 10 | import java.nio.file.Path 11 | import java.util.zip.ZipEntry 12 | import java.util.zip.ZipFile 13 | import kotlin.io.path.* 14 | import kotlin.streams.asSequence 15 | 16 | 17 | internal fun readJar(file: Path): Set { 18 | return ZipFile(file.toFile()).use { zip -> 19 | zip.stream().asSequence() 20 | .filter { it.name.endsWith(".class") } 21 | .flatMap { zip.readClassFile(it) } 22 | .toSet() 23 | } 24 | } 25 | 26 | 27 | internal fun ZipFile.readClassFile(entry: ZipEntry): Sequence { 28 | return readClassFile(getInputStream(entry).use { input -> input.readBytes() }) 29 | } 30 | 31 | @OptIn(ExperimentalPathApi::class) 32 | internal fun readDirectory(directory: Path): Set { 33 | return directory.walk() 34 | .filter { it.name.endsWith(".class") && it.isRegularFile() } 35 | .flatMap { current -> 36 | readClassFile(current.readBytes()) 37 | } 38 | .toSet() 39 | } 40 | 41 | internal fun readClassFile(clazz: ByteArray): Sequence { 42 | val reader = ClassReader(clazz) 43 | val visitor = ClassVisitorImpl() 44 | reader.accept(visitor, /* parsingOptions = */ 0) 45 | return visitor.declarations.asSequence() 46 | } 47 | 48 | private class ClassVisitorImpl : ClassVisitor(Opcodes.ASM9) { 49 | private var className: String? = null 50 | val declarations = mutableListOf() 51 | 52 | override fun visit( 53 | version: Int, 54 | access: Int, 55 | name: String?, 56 | signature: String?, 57 | superName: String?, 58 | interfaces: Array? 59 | ) { 60 | className = name 61 | } 62 | 63 | override fun visitAnnotation(descriptor: String?, visible: Boolean): AnnotationVisitor? { 64 | if (descriptor == "L$SPI_SERVICE_ANNOTATION_FQN;") { 65 | return AnnotationVisitorImpl { ordinal, service -> 66 | declarations.add(ServiceDeclaration(FqName(service), ClassId.fromString(className!!).asSingleFqName(), ordinal)) 67 | } 68 | } 69 | return null 70 | } 71 | } 72 | 73 | private class AnnotationVisitorImpl( 74 | val finished: (ordinal: Int, service: String) -> Unit 75 | ) : AnnotationVisitor(Opcodes.ASM9) { 76 | 77 | var ordinal = 0 78 | 79 | var service: String? = null 80 | 81 | override fun visit(name: String?, value: Any?) { 82 | if (name == "ordinal" && value is Int) { 83 | ordinal = value 84 | } 85 | 86 | if (name == "target") { 87 | service = (value as Type).className 88 | } 89 | } 90 | 91 | override fun visitEnd() { 92 | finished(ordinal, service!!) 93 | } 94 | } -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 1>&2 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 48 | echo. 1>&2 49 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 50 | echo location of your Java installation. 1>&2 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 1>&2 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 62 | echo. 1>&2 63 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 64 | echo location of your Java installation. 1>&2 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /playground/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 1>&2 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 48 | echo. 1>&2 49 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 50 | echo location of your Java installation. 1>&2 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 1>&2 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 62 | echo. 1>&2 63 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 64 | echo location of your Java installation. 1>&2 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /kotlinx-spi-compiler/src/main/kotlin/org/jetbrains/kotlinx/spi/ksp/readKlib.kt: -------------------------------------------------------------------------------- 1 | package org.jetbrains.kotlinx.spi.ksp 2 | 3 | import org.jetbrains.kotlin.library.KotlinLibrary 4 | import org.jetbrains.kotlin.library.metadata.KlibMetadataProtoBuf 5 | import org.jetbrains.kotlin.library.metadata.parseModuleHeader 6 | import org.jetbrains.kotlin.library.metadata.parsePackageFragment 7 | import org.jetbrains.kotlin.metadata.ProtoBuf 8 | import org.jetbrains.kotlin.metadata.deserialization.NameResolverImpl 9 | import org.jetbrains.kotlin.metadata.deserialization.getExtensionOrNull 10 | import org.jetbrains.kotlin.name.ClassId 11 | import org.jetbrains.kotlin.name.FqName 12 | import java.nio.file.Path 13 | import kotlin.io.path.Path 14 | 15 | 16 | internal fun readLibrary(library: KotlinLibrary): Set { 17 | val headerProto = parseModuleHeader(library.moduleHeaderData) 18 | 19 | val packageMetadataSequence = headerProto.packageFragmentNameList.asSequence().flatMap { packageFragmentName -> 20 | library.packageMetadataParts(packageFragmentName).asSequence().map { packageMetadataPart -> 21 | library.packageMetadata(packageFragmentName, packageMetadataPart) 22 | } 23 | } 24 | 25 | return packageMetadataSequence.flatMap { packageMetadata -> 26 | val packageFragmentProto = parsePackageFragment(packageMetadata) 27 | val context = PackageFragmentReadingContext(library, packageFragmentProto) 28 | context.readServices(packageFragmentProto) 29 | }.toSet() 30 | } 31 | 32 | @Suppress("CONTEXT_RECEIVERS_DEPRECATED") 33 | internal fun PackageFragmentReadingContext.readServices(fragment: ProtoBuf.PackageFragment): Set { 34 | return fragment.class_List.flatMap { classProto -> 35 | val classId = ClassId.fromString(nameResolver.getQualifiedClassName(classProto.fqName)) 36 | if (classId.isNestedClass) return@flatMap emptyList() 37 | classProto.getExtension(KlibMetadataProtoBuf.classAnnotation).mapNotNull { annotation -> 38 | val name = nameResolver.getQualifiedClassName(annotation.id) 39 | if (name != SPI_SERVICE_ANNOTATION_FQN) return@mapNotNull null 40 | val service = nameResolver.getQualifiedClassName(annotation.argumentList[0].value.classId) 41 | val ordinal = annotation.argumentList.getOrNull(1)?.value?.intValue?.toInt() 42 | ServiceDeclaration( 43 | ClassId.fromString(service).asSingleFqName(), 44 | classId.asSingleFqName(), ordinal ?: 0 45 | ) 46 | } 47 | }.toSet() 48 | } 49 | 50 | internal fun PackageFragmentReadingContext( 51 | library: KotlinLibrary, 52 | packageFragmentProto: ProtoBuf.PackageFragment, 53 | ): PackageFragmentReadingContext { 54 | val nameResolver = NameResolverImpl(packageFragmentProto.strings, packageFragmentProto.qualifiedNames) 55 | val packageFqName = packageFragmentProto.`package`.getExtensionOrNull(KlibMetadataProtoBuf.packageFqName) 56 | ?.let { packageFqNameStringIndex -> nameResolver.getPackageFqName(packageFqNameStringIndex) } ?: "" 57 | return PackageFragmentReadingContext(Path(library.libraryFile.path), FqName(packageFqName), nameResolver) 58 | } 59 | 60 | internal class PackageFragmentReadingContext( 61 | val libraryPath: Path, 62 | val packageFqName: FqName, 63 | val nameResolver: NameResolverImpl, 64 | ) -------------------------------------------------------------------------------- /kotlinx-spi-gradle-plugin/src/main/kotlin/org/jetbrains/kotlinx/spi/gradle/SpiGradlePlugin.kt: -------------------------------------------------------------------------------- 1 | package org.jetbrains.kotlinx.spi.gradle 2 | 3 | import org.gradle.api.DefaultTask 4 | import org.gradle.api.Plugin 5 | import org.gradle.api.Project 6 | import org.gradle.api.file.ConfigurableFileCollection 7 | import org.gradle.api.file.FileCollection 8 | import org.gradle.api.provider.Provider 9 | import org.gradle.api.tasks.* 10 | import org.gradle.kotlin.dsl.exclude 11 | import org.gradle.kotlin.dsl.support.serviceOf 12 | import org.gradle.kotlin.dsl.withType 13 | import org.gradle.process.ExecOperations 14 | import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension 15 | import org.jetbrains.kotlin.gradle.dsl.KotlinProjectExtension 16 | import org.jetbrains.kotlin.gradle.dsl.kotlinExtension 17 | import org.jetbrains.kotlin.gradle.plugin.KotlinBasePlugin 18 | import org.jetbrains.kotlin.gradle.plugin.KotlinCompilation 19 | import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinMetadataTarget 20 | import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeCompilation 21 | import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget 22 | import org.jetbrains.kotlin.gradle.targets.jvm.KotlinJvmTarget 23 | import javax.inject.Inject 24 | 25 | @Suppress("unused") // Defined by FQN 26 | class SpiGradlePlugin : Plugin { 27 | override fun apply(project: Project) { 28 | project.createSpiCompilerClasspathConfiguration() 29 | 30 | project.plugins.withType().configureEach { 31 | project.kotlinExtension.setupSpi() 32 | } 33 | } 34 | } 35 | 36 | private fun KotlinProjectExtension.setupSpi() { 37 | this as KotlinMultiplatformExtension 38 | this.targets.all target@{ 39 | if (this is KotlinMetadataTarget) return@target 40 | 41 | this.compilations.all compilation@{ 42 | val spiCompile = registerSpiCompileTask() 43 | 44 | if (this@target is KotlinJvmTarget) { 45 | project.configurations.getByName(runtimeDependencyConfigurationName!!) 46 | .exclude("org.jetbrains.kotlinx", "kotlinx-spi-runtime") 47 | 48 | if (compilationName == "main") { 49 | @Suppress("OPT_IN_USAGE") 50 | this@target.mainRun { 51 | classpath(project.files({ spiCompile.get().outputFiles }).builtBy(spiCompile)) 52 | } 53 | } 54 | 55 | if (compilationName == "test") { 56 | this@target.testRuns.getByName("test") testRun@{ 57 | this@testRun.executionTask.configure { 58 | classpath += project.files(spiCompile.map { it.outputFiles }) 59 | } 60 | } 61 | } 62 | } 63 | 64 | if (this@target is KotlinNativeTarget) { 65 | this@target.binaries.all binary@{ 66 | if (this.compilation != this@compilation) return@binary 67 | 68 | linkTaskProvider.configure { 69 | libraries.setFrom(project.files({ 70 | project.files( 71 | spiCompile.get().outputFiles, 72 | this@compilation.compileDependencyFiles 73 | ) 74 | }).builtBy(spiCompile)) 75 | } 76 | } 77 | 78 | } 79 | 80 | compileTaskProvider.configure { 81 | finalizedBy(spiCompile) 82 | } 83 | } 84 | } 85 | } 86 | 87 | private fun KotlinCompilation<*>.registerSpiCompileTask(): TaskProvider { 88 | return project.tasks.register( 89 | "compileKotlinSpi${this.target.name.capitalized}${this.name.capitalized}", 90 | SpiCompileTask::class.java, 91 | this 92 | ) 93 | } 94 | 95 | private open class SpiCompileTask @Inject constructor( 96 | compilation: KotlinCompilation<*> 97 | ) : DefaultTask() { 98 | private val spiDirectory = project.layout.buildDirectory.dir("spi") 99 | 100 | @get:Internal 101 | val outputFiles: ConfigurableFileCollection = project.files({ 102 | spiDirectory.map { dir -> 103 | if (compilation is KotlinNativeCompilation) dir.asFile.resolve("${compilation.target.name}/${compilation.name}/$compilation.klib") 104 | else dir.asFile.resolve("${compilation.target.name}/${compilation.name}/jar") 105 | } 106 | }).builtBy(path) 107 | 108 | init { 109 | if (compilation is KotlinNativeCompilation) { 110 | outputs.file(project.provider { outputFiles.singleFile }) 111 | } else { 112 | outputs.dir(project.provider { outputFiles.singleFile }) 113 | } 114 | } 115 | 116 | 117 | private val exec = project.serviceOf() 118 | 119 | @get:Input 120 | @get:Optional 121 | val debug: Provider = project.providers.gradleProperty("spi.debug") 122 | 123 | @InputFiles 124 | val inputFiles: FileCollection = 125 | project.files({ compilation.runtimeDependencyFiles ?: compilation.compileDependencyFiles }) 126 | .filter { file -> !file.startsWith(spiDirectory.get().asFile) } 127 | .plus(project.files({ compilation.output.allOutputs })) 128 | 129 | 130 | @Classpath 131 | val compilerClasspath: FileCollection = project.getSpiCompilerClasspathConfiguration() 132 | 133 | @get:Input 134 | @get:Optional 135 | protected val konanTarget: String? = (compilation as? KotlinNativeCompilation)?.konanTarget?.name 136 | 137 | @get:Input 138 | @get:Optional 139 | protected val konanHome: Provider = project.provider { 140 | if (compilation !is KotlinNativeCompilation) return@provider null 141 | compilation.compileTaskProvider.get().konanHome.get() 142 | } 143 | 144 | @TaskAction 145 | fun generate() { 146 | exec.javaexec { 147 | this.debug = this@SpiCompileTask.debug.orNull == "true" 148 | this.classpath = compilerClasspath 149 | this.mainClass.set("org.jetbrains.kotlinx.spi.ksp.SpiCompiler") 150 | this.args("--output", outputFiles.singleFile.absolutePath) 151 | if (konanTarget != null) this.args("--konan-target", konanTarget) 152 | if (konanHome.isPresent) this.args("--konan-home", konanHome.get()) 153 | this.args(inputFiles.map { it.absolutePath }) 154 | } 155 | } 156 | } 157 | 158 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 87 | APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit 88 | 89 | # Use the maximum available, or set MAX_FD != -1 to use that value. 90 | MAX_FD=maximum 91 | 92 | warn () { 93 | echo "$*" 94 | } >&2 95 | 96 | die () { 97 | echo 98 | echo "$*" 99 | echo 100 | exit 1 101 | } >&2 102 | 103 | # OS specific support (must be 'true' or 'false'). 104 | cygwin=false 105 | msys=false 106 | darwin=false 107 | nonstop=false 108 | case "$( uname )" in #( 109 | CYGWIN* ) cygwin=true ;; #( 110 | Darwin* ) darwin=true ;; #( 111 | MSYS* | MINGW* ) msys=true ;; #( 112 | NONSTOP* ) nonstop=true ;; 113 | esac 114 | 115 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 116 | 117 | 118 | # Determine the Java command to use to start the JVM. 119 | if [ -n "$JAVA_HOME" ] ; then 120 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 121 | # IBM's JDK on AIX uses strange locations for the executables 122 | JAVACMD=$JAVA_HOME/jre/sh/java 123 | else 124 | JAVACMD=$JAVA_HOME/bin/java 125 | fi 126 | if [ ! -x "$JAVACMD" ] ; then 127 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 128 | 129 | Please set the JAVA_HOME variable in your environment to match the 130 | location of your Java installation." 131 | fi 132 | else 133 | JAVACMD=java 134 | if ! command -v java >/dev/null 2>&1 135 | then 136 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | fi 142 | 143 | # Increase the maximum file descriptors if we can. 144 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 145 | case $MAX_FD in #( 146 | max*) 147 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 148 | # shellcheck disable=SC2039,SC3045 149 | MAX_FD=$( ulimit -H -n ) || 150 | warn "Could not query maximum file descriptor limit" 151 | esac 152 | case $MAX_FD in #( 153 | '' | soft) :;; #( 154 | *) 155 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 156 | # shellcheck disable=SC2039,SC3045 157 | ulimit -n "$MAX_FD" || 158 | warn "Could not set maximum file descriptor limit to $MAX_FD" 159 | esac 160 | fi 161 | 162 | # Collect all arguments for the java command, stacking in reverse order: 163 | # * args from the command line 164 | # * the main class name 165 | # * -classpath 166 | # * -D...appname settings 167 | # * --module-path (only if needed) 168 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 169 | 170 | # For Cygwin or MSYS, switch paths to Windows format before running java 171 | if "$cygwin" || "$msys" ; then 172 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 173 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 174 | 175 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 176 | 177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 178 | for arg do 179 | if 180 | case $arg in #( 181 | -*) false ;; # don't mess with options #( 182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 183 | [ -e "$t" ] ;; #( 184 | *) false ;; 185 | esac 186 | then 187 | arg=$( cygpath --path --ignore --mixed "$arg" ) 188 | fi 189 | # Roll the args list around exactly as many times as the number of 190 | # args, so each arg winds up back in the position where it started, but 191 | # possibly modified. 192 | # 193 | # NB: a `for` loop captures its iteration list before it begins, so 194 | # changing the positional parameters here affects neither the number of 195 | # iterations, nor the values presented in `arg`. 196 | shift # remove old arg 197 | set -- "$@" "$arg" # push replacement arg 198 | done 199 | fi 200 | 201 | 202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 204 | 205 | # Collect all arguments for the java command: 206 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 207 | # and any embedded shellness will be escaped. 208 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 209 | # treated as '${Hostname}' itself on the command line. 210 | 211 | set -- \ 212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 213 | -classpath "$CLASSPATH" \ 214 | org.gradle.wrapper.GradleWrapperMain \ 215 | "$@" 216 | 217 | # Stop when "xargs" is not available. 218 | if ! command -v xargs >/dev/null 2>&1 219 | then 220 | die "xargs is not available" 221 | fi 222 | 223 | # Use "xargs" to parse quoted args. 224 | # 225 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 226 | # 227 | # In Bash we could simply go: 228 | # 229 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 230 | # set -- "${ARGS[@]}" "$@" 231 | # 232 | # but POSIX shell has neither arrays nor command substitution, so instead we 233 | # post-process each arg (as a line of input to sed) to backslash-escape any 234 | # character that might be a shell metacharacter, then use eval to reverse 235 | # that process (while maintaining the separation between arguments), and wrap 236 | # the whole thing up as a single "set" statement. 237 | # 238 | # This will of course break if any of these variables contains a newline or 239 | # an unmatched quote. 240 | # 241 | 242 | eval "set -- $( 243 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 244 | xargs -n1 | 245 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 246 | tr '\n' ' ' 247 | )" '"$@"' 248 | 249 | exec "$JAVACMD" "$@" 250 | -------------------------------------------------------------------------------- /playground/gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 87 | APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit 88 | 89 | # Use the maximum available, or set MAX_FD != -1 to use that value. 90 | MAX_FD=maximum 91 | 92 | warn () { 93 | echo "$*" 94 | } >&2 95 | 96 | die () { 97 | echo 98 | echo "$*" 99 | echo 100 | exit 1 101 | } >&2 102 | 103 | # OS specific support (must be 'true' or 'false'). 104 | cygwin=false 105 | msys=false 106 | darwin=false 107 | nonstop=false 108 | case "$( uname )" in #( 109 | CYGWIN* ) cygwin=true ;; #( 110 | Darwin* ) darwin=true ;; #( 111 | MSYS* | MINGW* ) msys=true ;; #( 112 | NONSTOP* ) nonstop=true ;; 113 | esac 114 | 115 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 116 | 117 | 118 | # Determine the Java command to use to start the JVM. 119 | if [ -n "$JAVA_HOME" ] ; then 120 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 121 | # IBM's JDK on AIX uses strange locations for the executables 122 | JAVACMD=$JAVA_HOME/jre/sh/java 123 | else 124 | JAVACMD=$JAVA_HOME/bin/java 125 | fi 126 | if [ ! -x "$JAVACMD" ] ; then 127 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 128 | 129 | Please set the JAVA_HOME variable in your environment to match the 130 | location of your Java installation." 131 | fi 132 | else 133 | JAVACMD=java 134 | if ! command -v java >/dev/null 2>&1 135 | then 136 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | fi 142 | 143 | # Increase the maximum file descriptors if we can. 144 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 145 | case $MAX_FD in #( 146 | max*) 147 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 148 | # shellcheck disable=SC2039,SC3045 149 | MAX_FD=$( ulimit -H -n ) || 150 | warn "Could not query maximum file descriptor limit" 151 | esac 152 | case $MAX_FD in #( 153 | '' | soft) :;; #( 154 | *) 155 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 156 | # shellcheck disable=SC2039,SC3045 157 | ulimit -n "$MAX_FD" || 158 | warn "Could not set maximum file descriptor limit to $MAX_FD" 159 | esac 160 | fi 161 | 162 | # Collect all arguments for the java command, stacking in reverse order: 163 | # * args from the command line 164 | # * the main class name 165 | # * -classpath 166 | # * -D...appname settings 167 | # * --module-path (only if needed) 168 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 169 | 170 | # For Cygwin or MSYS, switch paths to Windows format before running java 171 | if "$cygwin" || "$msys" ; then 172 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 173 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 174 | 175 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 176 | 177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 178 | for arg do 179 | if 180 | case $arg in #( 181 | -*) false ;; # don't mess with options #( 182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 183 | [ -e "$t" ] ;; #( 184 | *) false ;; 185 | esac 186 | then 187 | arg=$( cygpath --path --ignore --mixed "$arg" ) 188 | fi 189 | # Roll the args list around exactly as many times as the number of 190 | # args, so each arg winds up back in the position where it started, but 191 | # possibly modified. 192 | # 193 | # NB: a `for` loop captures its iteration list before it begins, so 194 | # changing the positional parameters here affects neither the number of 195 | # iterations, nor the values presented in `arg`. 196 | shift # remove old arg 197 | set -- "$@" "$arg" # push replacement arg 198 | done 199 | fi 200 | 201 | 202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 204 | 205 | # Collect all arguments for the java command: 206 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 207 | # and any embedded shellness will be escaped. 208 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 209 | # treated as '${Hostname}' itself on the command line. 210 | 211 | set -- \ 212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 213 | -classpath "$CLASSPATH" \ 214 | org.gradle.wrapper.GradleWrapperMain \ 215 | "$@" 216 | 217 | # Stop when "xargs" is not available. 218 | if ! command -v xargs >/dev/null 2>&1 219 | then 220 | die "xargs is not available" 221 | fi 222 | 223 | # Use "xargs" to parse quoted args. 224 | # 225 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 226 | # 227 | # In Bash we could simply go: 228 | # 229 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 230 | # set -- "${ARGS[@]}" "$@" 231 | # 232 | # but POSIX shell has neither arrays nor command substitution, so instead we 233 | # post-process each arg (as a line of input to sed) to backslash-escape any 234 | # character that might be a shell metacharacter, then use eval to reverse 235 | # that process (while maintaining the separation between arguments), and wrap 236 | # the whole thing up as a single "set" statement. 237 | # 238 | # This will of course break if any of these variables contains a newline or 239 | # an unmatched quote. 240 | # 241 | 242 | eval "set -- $( 243 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 244 | xargs -n1 | 245 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 246 | tr '\n' ' ' 247 | )" '"$@"' 248 | 249 | exec "$JAVACMD" "$@" 250 | --------------------------------------------------------------------------------