[build] joint (step 1)

(cherry picked from commit 7d0775f7e69ab900200bcf1fa78b94d68e6bd4f6)
This commit is contained in:
Vasily Levchenko
2020-11-12 10:25:57 +01:00
parent cc9573a9a0
commit c85c3ac123
59 changed files with 822 additions and 637 deletions
+85
View File
@@ -81,12 +81,15 @@ extra["intellijReleaseType"] = when {
else -> "releases" else -> "releases"
} }
extra["versions.androidDxSources"] = "5.0.0_r2"
extra["customDepsOrg"] = "kotlin.build" extra["customDepsOrg"] = "kotlin.build"
repositories { repositories {
jcenter() jcenter()
maven("https://jetbrains.bintray.com/intellij-third-party-dependencies/") maven("https://jetbrains.bintray.com/intellij-third-party-dependencies/")
maven("https://maven.pkg.jetbrains.space/kotlin/p/kotlin/kotlin-dependencies") maven("https://maven.pkg.jetbrains.space/kotlin/p/kotlin/kotlin-dependencies")
maven("https://kotlin.bintray.com/kotlinx")
maven("https://kotlin.bintray.com/kotlin-dev")
gradlePluginPortal() gradlePluginPortal()
extra["bootstrapKotlinRepo"]?.let { extra["bootstrapKotlinRepo"]?.let {
@@ -94,6 +97,21 @@ repositories {
} }
} }
sourceSets["main"].withConvention(org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet::class) {
kotlin.srcDir("src/main/kotlin")
kotlin.srcDir("src/generated/kotlin")
kotlin.srcDir("src/to_bootstrap/kotlin")
kotlin.srcDir("../kotlin-native/shared/src/library/kotlin")
kotlin.srcDir("../kotlin-native/shared/src/main/kotlin")
kotlin.srcDir("../kotlin-native/build-tools/src/main/kotlin")
kotlin.srcDir("../kotlin-native/build-tools/src/tmp/kotlin")
kotlin.srcDir("../kotlin-native/tools/kotlin-native-gradle-plugin/src/main/kotlin")
}
tasks.validatePlugins.configure {
enabled = false
}
dependencies { dependencies {
implementation(kotlin("stdlib", embeddedKotlinVersion)) implementation(kotlin("stdlib", embeddedKotlinVersion))
implementation("org.jetbrains.kotlin:kotlin-gradle-plugin:${project.bootstrapKotlinVersion}") implementation("org.jetbrains.kotlin:kotlin-gradle-plugin:${project.bootstrapKotlinVersion}")
@@ -113,6 +131,26 @@ dependencies {
implementation("org.gradle:test-retry-gradle-plugin:1.1.9") implementation("org.gradle:test-retry-gradle-plugin:1.1.9")
implementation("com.gradle.enterprise:test-distribution-gradle-plugin:1.2.1") implementation("com.gradle.enterprise:test-distribution-gradle-plugin:1.2.1")
compileOnly(gradleApi())
val kotlinVersion = project.bootstrapKotlinVersion
val ktorVersion = "1.2.1"
val slackApiVersion = "1.2.0"
val metadataVersion = "0.0.1-dev-10"
implementation("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion")
implementation("org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion")
implementation("org.jetbrains.kotlin:kotlin-reflect:$kotlinVersion")
implementation("com.ullink.slack:simpleslackapi:$slackApiVersion")
implementation("io.ktor:ktor-client-auth:$ktorVersion")
implementation("io.ktor:ktor-client-core:$ktorVersion")
implementation("io.ktor:ktor-client-cio:$ktorVersion")
api("org.jetbrains.kotlin:kotlin-native-utils:$kotlinVersion")
implementation("org.jetbrains.kotlinx:kotlinx-metadata-klib:$metadataVersion")
} }
samWithReceiver { samWithReceiver {
@@ -134,6 +172,14 @@ tasks.withType<KotlinCompile>().configureEach {
} }
tasks["build"].dependsOn(":prepare-deps:build") tasks["build"].dependsOn(":prepare-deps:build")
sourceSets["main"].withConvention(org.gradle.api.tasks.GroovySourceSet::class) {
groovy.srcDir("../kotlin-native/build-tools/src/main/groovy")
}
tasks.named("compileGroovy", GroovyCompile::class.java) {
classpath += project.files(tasks.named("compileKotlin", org.jetbrains.kotlin.gradle.tasks.KotlinCompile::class.java))
dependsOn(tasks.named("compileKotlin"))
}
allprojects { allprojects {
tasks.register("checkBuild") tasks.register("checkBuild")
@@ -142,3 +188,42 @@ allprojects {
apply(from = "$rootDir/../gradle/cacheRedirector.gradle.kts") apply(from = "$rootDir/../gradle/cacheRedirector.gradle.kts")
} }
} }
gradlePlugin {
plugins {
create("benchmarkPlugin") {
id = "benchmarking"
implementationClass = "org.jetbrains.kotlin.benchmark.KotlinNativeBenchmarkingPlugin"
}
create("compileBenchmarking") {
id = "compile-benchmarking"
implementationClass = "org.jetbrains.kotlin.benchmark.CompileBenchmarkingPlugin"
}
create("swiftBenchmarking") {
id = "swift-benchmarking"
implementationClass = "org.jetbrains.kotlin.benchmark.SwiftBenchmarkingPlugin"
}
create("compileToBitcode") {
id = "compile-to-bitcode"
implementationClass = "org.jetbrains.kotlin.bitcode.CompileToBitcodePlugin"
}
create("runtimeTesting") {
id = "runtime-testing"
implementationClass = "org.jetbrains.kotlin.testing.native.RuntimeTestingPlugin"
}
create("konan") {
id = "konan"
implementationClass = "org.jetbrains.kotlin.gradle.plugin.konan.KonanPlugin"
}
// We bundle a shaded version of kotlinx-serialization plugin
create("kotlinx-serialization-native") {
id = "kotlinx-serialization-native"
implementationClass = "shadow.org.jetbrains.kotlinx.serialization.gradle.SerializationGradleSubplugin"
}
create("org.jetbrains.kotlin.konan") {
id = "org.jetbrains.kotlin.konan"
implementationClass = "org.jetbrains.kotlin.gradle.plugin.konan.KonanPlugin"
}
}
}
@@ -0,0 +1,14 @@
/*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.konan
internal val currentCompilerVersion: CompilerVersion =
CompilerVersionImpl(
MetaVersion.DEV, 1, 4,
30, -1, -1)
val CompilerVersion.Companion.CURRENT: CompilerVersion
get() = currentCompilerVersion
@@ -0,0 +1,84 @@
/*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.*
import java.io.File
import java.io.FileNotFoundException
import java.io.PrintWriter
import java.util.regex.Pattern
open class VersionGenerator: DefaultTask() {
@OutputDirectory
fun getVersionSourceDirectory(): File {
return getProject().file("build/generated")
}
@OutputFile
open fun getVersionFile(): File? {
return getProject().file(getVersionSourceDirectory().path + "/src/generated/org/jetbrains/kotlin/konan/CompilerVersionGenerated.kt")
}
@Input
open fun getKonanVersion(): String? {
return getProject().getProperties().get("konanVersion").toString()
}
// TeamCity passes all configuration parameters into a build script as project properties.
// Thus we can use them here instead of environment variables.
@Optional
@Input
open fun getBuildNumber(): String? {
val property: Any = getProject().findProperty("build.number") ?: return null
return property.toString()
}
@Input
open fun getMeta(): String {
val konanMetaVersionProperty: Any = getProject().getProperties().get("konanMetaVersion") ?: return "MetaVersion.DEV"
return "MetaVersion." + konanMetaVersionProperty.toString().toUpperCase()
}
private val versionPattern = Pattern.compile(
"^(\\d+)\\.(\\d+)(?:\\.(\\d+))?(?:-M(\\p{Digit}))?(?:-(\\p{Alpha}\\p{Alnum}*))?(?:-(\\d+))?$"
)
@TaskAction
open fun generateVersion() {
val matcher = versionPattern.matcher(getKonanVersion())
require(matcher.matches()) { "Cannot parse Kotlin/Native version: \$konanVersion" }
val major = matcher.group(1).toInt()
val minor = matcher.group(2).toInt()
val maintenanceStr = matcher.group(3)
val maintenance = maintenanceStr?.toInt() ?: 0
val milestoneStr = matcher.group(4)
val milestone = milestoneStr?.toInt() ?: -1
val buildNumber = getBuildNumber()
getProject().getLogger().info("BUILD_NUMBER: " + getBuildNumber())
var build = -1
if (buildNumber != null) {
val buildNumberSplit = buildNumber.split("-".toRegex()).toTypedArray()
build = buildNumberSplit[buildNumberSplit.size - 1].toInt() // //7-dev-buildcount
}
try {
PrintWriter(getVersionFile()).use { printWriter ->
printWriter.println(
"""package org.jetbrains.kotlin.konan
internal val currentCompilerVersion: CompilerVersion =
CompilerVersionImpl(${getMeta()}, $major, $minor,
$maintenance, $milestone, $build)
val CompilerVersion.Companion.CURRENT: CompilerVersion
get() = currentCompilerVersion"""
)
}
} catch (e: FileNotFoundException) {
throw IllegalStateException(e)
}
}
}
+5 -11
View File
@@ -20,8 +20,7 @@ buildscript {
apply from: "$rootBuildDirectory/gradle/kotlinGradlePlugin.gradle" apply from: "$rootBuildDirectory/gradle/kotlinGradlePlugin.gradle"
dependencies { dependencies {
classpath "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion" classpath "org.jetbrains.kotlin:kotlin-stdlib:${project.bootstrapKotlinVersion}"
classpath "org.jetbrains.kotlin:kotlin-native-shared:$konanVersion"
} }
} }
apply plugin: 'kotlin' apply plugin: 'kotlin'
@@ -32,7 +31,7 @@ apply plugin: 'cpp'
import org.jetbrains.kotlin.konan.target.ClangArgs import org.jetbrains.kotlin.konan.target.ClangArgs
final Project libclangextProject = project(":libclangext") final Project libclangextProject = project(":kotlin-native:libclangext")
final String libclangextTask = libclangextProject.path + ":build" final String libclangextTask = libclangextProject.path + ":build"
File libclangextDir = new File(libclangextProject.buildDir, "libs/clangext/static") File libclangextDir = new File(libclangextProject.buildDir, "libs/clangext/static")
final boolean libclangextIsEnabled = libclangextProject.isEnabled final boolean libclangextIsEnabled = libclangextProject.isEnabled
@@ -46,7 +45,7 @@ if (isWindows()) {
List<String> cflags = [ List<String> cflags = [
"-I$llvmDir/include", "-I$llvmDir/include",
"-I${project(":libclangext").projectDir.absolutePath + "/src/main/include"}" "-I${project(":kotlin-native:libclangext").projectDir.absolutePath}/src/main/include"
]*.toString() ]*.toString()
List<String> ldflags = ["$llvmDir/$libclang", "-L$libclangextDir.absolutePath", "-lclangext"]*.toString() List<String> ldflags = ["$llvmDir/$libclang", "-L$libclangextDir.absolutePath", "-lclangext"]*.toString()
@@ -111,15 +110,10 @@ sourceSets {
} }
} }
repositories {
maven {
url buildKotlinCompilerRepo
}
}
dependencies { dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion" compile project(":kotlin-stdlib")
compile project(':Interop:Runtime') compile project(':kotlin-native:Interop:Runtime')
} }
task nativelibs(type: Copy) { task nativelibs(type: Copy) {
+1 -1
View File
@@ -15,6 +15,6 @@
*/ */
buildscript { buildscript {
apply from: "$rootDir/gradle/kotlinGradlePlugin.gradle" apply from: "$rootDir/kotlin-native/gradle/kotlinGradlePlugin.gradle"
} }
+6 -13
View File
@@ -23,8 +23,7 @@ buildscript {
apply from: "$rootBuildDirectory/gradle/kotlinGradlePlugin.gradle" apply from: "$rootBuildDirectory/gradle/kotlinGradlePlugin.gradle"
dependencies { dependencies {
classpath "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion" classpath "org.jetbrains.kotlin:kotlin-stdlib:${project.bootstrapKotlinVersion}"
classpath "org.jetbrains.kotlin:kotlin-native-shared:$konanVersion"
} }
} }
import org.jetbrains.kotlin.konan.target.ClangArgs import org.jetbrains.kotlin.konan.target.ClangArgs
@@ -38,9 +37,9 @@ model {
include '**/*.c' include '**/*.c'
} }
binaries.all { binaries.all {
def host = rootProject.ext.hostName def host = rootProject.project(":kotlin-native").ext.hostName
def hostLibffiDir = rootProject.ext.get("${host}LibffiDir") def hostLibffiDir = rootProject.project(":kotlin-native").ext.get("${host}LibffiDir")
cCompiler.args hostPlatform.clang.hostCompilerArgsForJni cCompiler.args hostPlatform.clang.hostCompilerArgsForJni
cCompiler.args "-I$hostLibffiDir/include" cCompiler.args "-I$hostLibffiDir/include"
@@ -59,16 +58,10 @@ model {
} }
} }
repositories {
maven {
url buildKotlinCompilerRepo
}
}
dependencies { dependencies {
compile project(":utilities:basic-utils") compile project(":kotlin-native:utilities:basic-utils")
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion" compile project(":kotlin-stdlib")
compile "org.jetbrains.kotlin:kotlin-reflect:$kotlinVersion" compile project(":kotlin-reflect")
} }
sourceSets.main.kotlin.srcDirs += "src/jvm/kotlin" sourceSets.main.kotlin.srcDirs += "src/jvm/kotlin"
@@ -15,7 +15,7 @@
*/ */
buildscript { buildscript {
apply from: "$rootDir/gradle/kotlinGradlePlugin.gradle" apply from: "$rootDir/kotlin-native/gradle/kotlinGradlePlugin.gradle"
} }
apply plugin: 'kotlin' apply plugin: 'kotlin'
@@ -23,25 +23,19 @@ apply plugin: 'application'
mainClassName = "org.jetbrains.kotlin.native.interop.gen.jvm.MainKt" mainClassName = "org.jetbrains.kotlin.native.interop.gen.jvm.MainKt"
repositories {
maven {
url buildKotlinCompilerRepo
}
}
dependencies { dependencies {
implementation project(":Interop:Indexer") implementation project(":kotlin-native:Interop:Indexer")
implementation project(":utilities:basic-utils") implementation project(":kotlin-native:utilities:basic-utils")
api project(path: ":endorsedLibraries:kotlinx.cli", configuration: "jvmRuntimeElements") api project(path: ":kotlin-native:endorsedLibraries:kotlinx.cli", configuration: "jvmRuntimeElements")
api "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion" api project(":kotlin-stdlib")
api "org.jetbrains.kotlin:kotlin-compiler:$kotlinVersion" api project(":kotlin-compiler")
api "org.jetbrains.kotlin:kotlin-native-shared:$konanVersion" api project(":kotlinx-metadata-klib")
api "org.jetbrains.kotlinx:kotlinx-metadata-klib:$metadataVersion"
testImplementation "junit:junit:4.12" testImplementation "junit:junit:4.12"
testImplementation "org.jetbrains.kotlin:kotlin-test-junit:$buildKotlinVersion" testImplementation project(":kotlin-test:kotlin-test-junit")
testImplementation "org.jetbrains.kotlin:kotlin-test:$buildKotlinVersion"
} }
compileKotlin { compileKotlin {
+26 -27
View File
@@ -6,7 +6,7 @@ import org.jetbrains.kotlin.konan.target.HostManager
* that can be found in the LICENSE file. * that can be found in the LICENSE file.
*/ */
buildscript { buildscript {
apply from: "$rootDir/gradle/kotlinGradlePlugin.gradle" apply from: "../../kotlin-native/gradle/kotlinGradlePlugin.gradle"
apply plugin: 'project-report' apply plugin: 'project-report'
dependencies { dependencies {
@@ -24,7 +24,7 @@ apply plugin: "maven-publish"
// (gets applied to this project and all its subprojects) // (gets applied to this project and all its subprojects)
allprojects { allprojects {
repositories { repositories {
maven { url buildKotlinCompilerRepo } maven { url project.bootstrapKotlinRepo }
} }
} }
@@ -87,22 +87,23 @@ task renamePackage {
kotlinNativeInterop { kotlinNativeInterop {
llvm { llvm {
dependsOn ":llvmDebugInfoC:debugInfoStaticLibrary"
dependsOn ":llvmCoverageMappingC:coverageMappingStaticLibrary" dependsOn ":kotlin-native:llvmDebugInfoC:debugInfoStaticLibrary"
dependsOn ":kotlin-native:llvmCoverageMappingC:coverageMappingStaticLibrary"
defFile 'llvm.def' defFile 'llvm.def'
if (!project.parent.convention.plugins.platformInfo.isWindows()) if (!project.parent.convention.plugins.platformInfo.isWindows())
compilerOpts "-fPIC" compilerOpts "-fPIC"
compilerOpts "-I$llvmDir/include", "-I${project(':llvmDebugInfoC').projectDir}/src/main/include", "-I${project(':llvmCoverageMappingC').projectDir}/src/main/include" compilerOpts "-I$llvmDir/include", "-I${rootProject.project(':kotlin-native:llvmDebugInfoC').projectDir}/src/main/include", "-I${rootProject.project(':kotlin-native:llvmCoverageMappingC').projectDir}/src/main/include"
linkerOpts "-L$llvmDir/lib", "-L${project(':llvmDebugInfoC').buildDir}/libs/debugInfo/static", "-L${project(':llvmCoverageMappingC').buildDir}/libs/coverageMapping/static" linkerOpts "-L$llvmDir/lib", "-L${rootProject.project(':kotlin-native:llvmDebugInfoC').buildDir}/libs/debugInfo/static", "-L${rootProject.project(':kotlin-native:llvmCoverageMappingC').buildDir}/libs/coverageMapping/static"
} }
hash { // TODO: copy-pasted from ':common:compileHash' hash { // TODO: copy-pasted from ':common:compileHash'
if (!project.parent.convention.plugins.platformInfo.isWindows()) { if (!rootProject.project(":kotlin-native").convention.plugins.platformInfo.isWindows()) {
compilerOpts '-fPIC' compilerOpts '-fPIC'
linkerOpts '-fPIC' linkerOpts '-fPIC'
} }
linker 'clang++' linker 'clang++'
linkOutputs ":common:${hostName}Hash" linkOutputs ":kotlin-native:common:${hostName}Hash"
headers fileTree('../common/src/hash/headers') { headers fileTree('../common/src/hash/headers') {
include '**/*.h' include '**/*.h'
@@ -118,7 +119,7 @@ kotlinNativeInterop {
linkerOpts '-fPIC' linkerOpts '-fPIC'
} }
linker 'clang++' linker 'clang++'
linkOutputs ":common:${hostName}Files" linkOutputs ":kotlin-native:common:${hostName}Files"
headers fileTree('../common/src/files/headers') { headers fileTree('../common/src/files/headers') {
include '**/*.h' include '**/*.h'
@@ -150,27 +151,25 @@ configurations {
dependencies { dependencies {
trove4j_jar "org.jetbrains.intellij.deps:trove4j:1.0.20181211@jar" trove4j_jar "org.jetbrains.intellij.deps:trove4j:1.0.20181211@jar"
kotlin_compiler_jar "$kotlinCompilerModule@jar" kotlin_compiler_jar project(":kotlin-compiler")
kotlin_stdlib_jar "$kotlinStdLibModule@jar" kotlin_stdlib_jar project(":kotlin-stdlib")
kotlin_reflect_jar "$kotlinReflectModule@jar" kotlin_reflect_jar project(":kotlin-reflect")
kotlin_script_runtime_jar "$kotlinScriptRuntimeModule@jar" kotlin_script_runtime_jar project(":kotlin-script-runtime")
[kotlinCommonStdlibModule, kotlinTestCommonModule, kotlinTestAnnotationsCommonModule].each { [kotlinCommonStdlibModule, kotlinTestCommonModule, kotlinTestAnnotationsCommonModule].each {
kotlinCommonSources(it) { transitive = false } kotlinCommonSources(it) { transitive = false }
} }
compilerCompile project(":utilities:basic-utils") compilerCompile project(":kotlin-native:utilities:basic-utils")
compilerCompile "com.google.protobuf:protobuf-java:${protobufVersion}" compilerCompile "com.google.protobuf:protobuf-java:${protobufVersion}"
compilerCompile kotlinCompilerModule compilerCompile project(":kotlin-compiler")
compilerCompile kotlinNativeInterop['llvm'].configuration compilerCompile kotlinNativeInterop['llvm'].configuration
compilerCompile kotlinNativeInterop['hash'].configuration compilerCompile kotlinNativeInterop['hash'].configuration
compilerCompile kotlinNativeInterop['files'].configuration compilerCompile kotlinNativeInterop['files'].configuration
compilerCompile "org.jetbrains.kotlin:kotlin-native-shared:$konanVersion"
cli_bcCompile kotlinCompilerModule cli_bcCompile project(":kotlin-compiler")
cli_bcCompile "org.jetbrains.kotlin:kotlin-native-shared:$konanVersion"
cli_bcCompile sourceSets.compiler.output cli_bcCompile sourceSets.compiler.output
bc_frontendCompile kotlinCompilerModule bc_frontendCompile kotlinCompilerModule
@@ -193,10 +192,10 @@ task unzipStdlibSources(type: CopyCommonSources) {
} }
final List<File> stdLibSrc = [ final List<File> stdLibSrc = [
project(':Interop:Runtime').file('src/main/kotlin'), project(':kotlin-native:Interop:Runtime').file('src/main/kotlin'),
project(':Interop:Runtime').file('src/native/kotlin'), project(':kotlin-native:Interop:Runtime').file('src/native/kotlin'),
project(':Interop:JsRuntime').file('src/main/kotlin'), project(':kotlin-native:Interop:JsRuntime').file('src/main/kotlin'),
project(':runtime').file('src/main/kotlin') project(':kotlin-native:runtime').file('src/main/kotlin')
] ]
// These files are built before the 'dist' is complete, // These files are built before the 'dist' is complete,
@@ -211,7 +210,7 @@ targetList.each { target ->
if (target != "wasm32") defaultArgs += '-g' if (target != "wasm32") defaultArgs += '-g'
def konanArgs = [*defaultArgs, def konanArgs = [*defaultArgs,
'-target', target, '-target', target,
"-Xruntime=${project(':runtime').file('build/bitcode/main/' + target + '/runtime.bc')}", "-Xruntime=${project(':kotlin-native:runtime').file('build/bitcode/main/' + target + '/runtime.bc')}",
*project.globalBuildArgs] *project.globalBuildArgs]
task("${target}Stdlib", type: JavaExec) { task("${target}Stdlib", type: JavaExec) {
@@ -222,7 +221,7 @@ targetList.each { target ->
} }
jvmArgs = konanJvmArgs jvmArgs = konanJvmArgs
args = [*konanArgs, args = [*konanArgs,
'-output', project(':runtime').file("build/${target}Stdlib"), '-output', project(':kotlin-native:runtime').file("build/${target}Stdlib"),
'-produce', 'library', '-module-name', 'stdlib', '-XXLanguage:+AllowContractsForCustomFunctions', '-produce', 'library', '-module-name', 'stdlib', '-XXLanguage:+AllowContractsForCustomFunctions',
'-Xmulti-platform', '-Xopt-in=kotlin.RequiresOptIn', '-Xinline-classes', '-Xmulti-platform', '-Xopt-in=kotlin.RequiresOptIn', '-Xinline-classes',
'-Xopt-in=kotlin.contracts.ExperimentalContracts', '-Xopt-in=kotlin.contracts.ExperimentalContracts',
@@ -233,11 +232,11 @@ targetList.each { target ->
*stdLibSrc] *stdLibSrc]
stdLibSrc.forEach { inputs.dir(it) } stdLibSrc.forEach { inputs.dir(it) }
inputs.dir(commonSrc) inputs.dir(commonSrc)
outputs.dir(project(':runtime').file("build/${target}Stdlib")) outputs.dir(project(':kotlin-native:runtime').file("build/${target}Stdlib"))
dependsOn 'unzipStdlibSources' dependsOn 'unzipStdlibSources'
dependsOn ":runtime:${target}Runtime" dependsOn ":kotlin-native:runtime:${target}Runtime"
dependsOn ":distCompiler" dependsOn ":kotlin-native:distCompiler"
} }
} }
@@ -164,7 +164,7 @@ class NamedNativeInteropConfig implements Named {
this.project = project this.project = project
this.flavor = flavor this.flavor = flavor
def platformManager = project.rootProject.ext.platformManager def platformManager = project.project(":kotlin-native").ext.platformManager
def targetManager = platformManager.targetManager(target) def targetManager = platformManager.targetManager(target)
this.target = targetManager.targetName this.target = targetManager.targetName
@@ -189,7 +189,7 @@ class NamedNativeInteropConfig implements Named {
interopStubs.kotlin.srcDirs generatedSrcDir interopStubs.kotlin.srcDirs generatedSrcDir
project.dependencies { project.dependencies {
add interopStubs.getCompileConfigurationName(), project(path: ':Interop:Runtime') add interopStubs.getCompileConfigurationName(), project(path: ':kotlin-native:Interop:Runtime')
} }
this.configuration.extendsFrom project.configurations[interopStubs.runtimeConfigurationName] this.configuration.extendsFrom project.configurations[interopStubs.runtimeConfigurationName]
@@ -202,8 +202,8 @@ class NamedNativeInteropConfig implements Named {
jvmArgs '-ea' jvmArgs '-ea'
systemProperties "java.library.path" : project.files( systemProperties "java.library.path" : project.files(
new File(project.findProject(":Interop:Indexer").buildDir, "nativelibs"), new File(project.findProject(":kotlin-native:Interop:Indexer").buildDir, "nativelibs"),
new File(project.findProject(":Interop:Runtime").buildDir, "nativelibs") new File(project.findProject(":kotlin-native:Interop:Runtime").buildDir, "nativelibs")
).asPath ).asPath
// Set the konan.home property because we run the cinterop tool not from a distribution jar // Set the konan.home property because we run the cinterop tool not from a distribution jar
// so it will not be able to determine this path by itself. // so it will not be able to determine this path by itself.
@@ -298,7 +298,7 @@ class NativeInteropPlugin implements Plugin<Project> {
void apply(Project prj) { void apply(Project prj) {
prj.extensions.add("kotlinNativeInterop", new NativeInteropExtension(prj)) prj.extensions.add("kotlinNativeInterop", new NativeInteropExtension(prj))
def runtimeNativeLibsDir = new File(prj.findProject(':Interop:Runtime').buildDir, 'nativelibs') def runtimeNativeLibsDir = new File(prj.findProject(':kotlin-native:Interop:Runtime').buildDir, 'nativelibs')
def nativeLibsDir = new File(prj.buildDir, "nativelibs") def nativeLibsDir = new File(prj.buildDir, "nativelibs")
@@ -307,8 +307,8 @@ class NativeInteropPlugin implements Plugin<Project> {
} }
prj.dependencies { prj.dependencies {
interopStubGenerator project(path: ":Interop:StubGenerator") interopStubGenerator project(path: ":kotlin-native:Interop:StubGenerator")
interopStubGenerator project(path: ":endorsedLibraries:kotlinx.cli", configuration: "jvmRuntimeElements") interopStubGenerator project(path: ":kotlin-native:endorsedLibraries:kotlinx.cli", configuration: "jvmRuntimeElements")
} }
} }
} }
@@ -31,7 +31,7 @@ fun configureCacheTesting(project: Project): CacheTesting? {
val compilerArgs = listOf("-Xcached-library=$stdlib,$cacheFile") val compilerArgs = listOf("-Xcached-library=$stdlib,$cacheFile")
val buildCacheTask = project.tasks.create("buildStdlibCache", Exec::class.java) { val buildCacheTask = project.tasks.create("buildStdlibCache", Exec::class.java) {
it.doFirst { doFirst {
cacheDir.mkdirs() cacheDir.mkdirs()
} }
@@ -42,10 +42,10 @@ fun configureCacheTesting(project: Project): CacheTesting? {
"distCompiler" "distCompiler"
).map { task -> project.rootProject.tasks.getByName(task) } ).map { task -> project.rootProject.tasks.getByName(task) }
it.dependsOn(tasks) dependsOn(tasks)
} }
it.commandLine( commandLine(
"$dist/bin/konanc", "$dist/bin/konanc",
"-p", cacheKind.visibleName, "-p", cacheKind.visibleName,
"-o", "$cacheDir/stdlib-cache", "-o", "$cacheDir/stdlib-cache",
@@ -158,7 +158,7 @@ open class CompareDistributionSignatures : DefaultTask() {
val oldKlibSignatures = getKlibSignatures(old).toSet() val oldKlibSignatures = getKlibSignatures(old).toSet()
return CompareDiff( return CompareDiff(
newKlibSignatures - oldKlibSignatures, newKlibSignatures - oldKlibSignatures,
oldKlibSignatures - newKlibSignatures, oldKlibSignatures - newKlibSignatures
) )
} }
@@ -96,9 +96,9 @@ fun mergeCompilationDatabases(project: Project, name: String, paths: List<String
} }
task task
} }
return project.tasks.create(name, MergeCompilationDatabases::class.java) { task -> return project.tasks.create(name, MergeCompilationDatabases::class.java) {
task.dependsOn(subtasks) dependsOn(subtasks)
task.inputFiles.addAll(subtasks.map { it.outputFile }) inputFiles.addAll(subtasks.map { it.outputFile })
} }
} }
@@ -120,10 +120,10 @@ fun createCompilationDatabasesFromCompileToBitcodeTasks(project: Project, name:
task.objDir) task.objDir)
} }
for ((target, tasks) in compdbTasks) { for ((target, tasks) in compdbTasks) {
project.tasks.create("${target}${name}", MergeCompilationDatabases::class.java) { task -> project.tasks.create("${target}${name}", MergeCompilationDatabases::class.java) {
task.dependsOn(tasks) dependsOn(tasks)
task.inputFiles.addAll(tasks.map { it.outputFile }) inputFiles.addAll(tasks.map { it.outputFile })
task.outputFile = File(File(project.buildDir, target), "compile_commands.json") outputFile = File(File(project.buildDir, target), "compile_commands.json")
} }
} }
} }
@@ -67,12 +67,12 @@ open class CopyCommonSources : DefaultTask() {
val fileTree = if (isFile) project.zipTree(this) else project.fileTree(this) val fileTree = if (isFile) project.zipTree(this) else project.fileTree(this)
project.copy { project.copy {
it.from(fileTree) from(fileTree)
it.includeEmptyDirs = false includeEmptyDirs = false
it.include("generated/**/*.kt") include("generated/**/*.kt")
it.include("kotlin/**/*.kt") include("kotlin/**/*.kt")
it.include("kotlin.test/*.kt") include("kotlin.test/*.kt")
it.into(destinationDir) into(destinationDir)
} }
} }
} }
@@ -16,14 +16,14 @@ open class CopySamples : Copy() {
private fun configureReplacements() { private fun configureReplacements() {
from(samplesDir) { from(samplesDir) {
it.exclude("**/*.gradle.kts") exclude("**/*.gradle.kts")
it.exclude("**/*.gradle") exclude("**/*.gradle")
it.exclude("**/gradle.properties") exclude("**/gradle.properties")
} }
from(samplesDir) { from(samplesDir) {
it.include("**/*.gradle") include("**/*.gradle")
it.include("**/*.gradle.kts") include("**/*.gradle.kts")
it.filter { line -> filter { line ->
replacements.forEach { (repo, replacement) -> replacements.forEach { (repo, replacement) ->
if (line.contains(repo)) { if (line.contains(repo)) {
return@filter line.replace(repo, replacement) return@filter line.replace(repo, replacement)
@@ -33,14 +33,14 @@ open class CopySamples : Copy() {
} }
} }
from(samplesDir) { from(samplesDir) {
it.include("**/gradle.properties") include("**/gradle.properties")
val kotlinVersion = project.property("kotlinVersion") as? String val kotlinVersion = project.property("kotlinVersion") as? String
?: throw IllegalArgumentException("Property kotlinVersion should be specified in the root project") ?: throw IllegalArgumentException("Property kotlinVersion should be specified in the root project")
val kotlinCompilerRepo = project.property("kotlinCompilerRepo") as? String val kotlinCompilerRepo = project.property("kotlinCompilerRepo") as? String
?: throw IllegalArgumentException("Property kotlinCompilerRepo should be specified in the root project") ?: throw IllegalArgumentException("Property kotlinCompilerRepo should be specified in the root project")
it.filter { line -> filter { line ->
when { when {
line.startsWith("kotlin_version") -> "kotlin_version=$kotlinVersion" line.startsWith("kotlin_version") -> "kotlin_version=$kotlinVersion"
line.startsWith("#kotlinCompilerRepo") || line.startsWith("kotlinCompilerRepo") -> line.startsWith("#kotlinCompilerRepo") || line.startsWith("kotlinCompilerRepo") ->
@@ -63,6 +63,6 @@ open class CopySamples : Copy() {
"https://dl.bintray.com/kotlin/ktor" to "https://cache-redirector.jetbrains.com/dl.bintray.com/kotlin/ktor", "https://dl.bintray.com/kotlin/ktor" to "https://cache-redirector.jetbrains.com/dl.bintray.com/kotlin/ktor",
"https://plugins.gradle.org/m2" to "https://cache-redirector.jetbrains.com/plugins.gradle.org/m2", "https://plugins.gradle.org/m2" to "https://cache-redirector.jetbrains.com/plugins.gradle.org/m2",
"mavenCentral()" to "maven { setUrl(\"https://cache-redirector.jetbrains.com/maven-central\") }", "mavenCentral()" to "maven { setUrl(\"https://cache-redirector.jetbrains.com/maven-central\") }",
"jcenter()" to "maven { setUrl(\"https://cache-redirector.jetbrains.com/jcenter\") }", "jcenter()" to "maven { setUrl(\"https://cache-redirector.jetbrains.com/jcenter\") }"
) )
} }
@@ -28,7 +28,7 @@ import org.jetbrains.kotlin.konan.file.*
class ExecClang(private val project: Project) { class ExecClang(private val project: Project) {
private val platformManager = project.rootProject.findProperty("platformManager") as PlatformManager private val platformManager = project.project(":kotlin-native").findProperty("platformManager") as PlatformManager
private fun konanArgs(target: KonanTarget): List<String> { private fun konanArgs(target: KonanTarget): List<String> {
return platformManager.platform(target).clang.clangArgsForKonanSources.asList() return platformManager.platform(target).clang.clangArgsForKonanSources.asList()
@@ -108,11 +108,9 @@ class ExecClang(private val project: Project) {
} }
fun execToolchainClang(target: KonanTarget, action: Action<in ExecSpec>): ExecResult { fun execToolchainClang(target: KonanTarget, action: Action<in ExecSpec>): ExecResult {
val extendedAction = Action<ExecSpec> { execSpec -> val extendedAction = Action<ExecSpec> {
action.execute(execSpec) action.execute(this)
execSpec.apply { executable = resolveToolchainExecutable(target, executable)
executable = resolveToolchainExecutable(target, executable)
}
} }
return project.exec(extendedAction) return project.exec(extendedAction)
} }
@@ -128,16 +126,14 @@ class ExecClang(private val project: Project) {
} }
private fun execClang(defaultArgs: List<String>, action: Action<in ExecSpec>): ExecResult { private fun execClang(defaultArgs: List<String>, action: Action<in ExecSpec>): ExecResult {
val extendedAction = Action<ExecSpec> { execSpec -> val extendedAction = Action<ExecSpec> {
action.execute(execSpec) action.execute(this)
execSpec.apply { executable = resolveExecutable(executable)
executable = resolveExecutable(executable)
val hostPlatform = project.findProperty("hostPlatform") as Platform val hostPlatform = project.findProperty("hostPlatform") as Platform
environment["PATH"] = project.files(hostPlatform.clang.clangPaths).asPath + environment["PATH"] = project.files(hostPlatform.clang.clangPaths).asPath +
java.io.File.pathSeparator + environment["PATH"] java.io.File.pathSeparator + environment["PATH"]
args = args + defaultArgs args = args + defaultArgs
}
} }
return project.exec(extendedAction) return project.exec(extendedAction)
} }
@@ -58,15 +58,13 @@ fun create(project: Project): ExecutorService {
sshExecutor(project) sshExecutor(project)
} else when (testTarget) { } else when (testTarget) {
KonanTarget.WASM32 -> object : ExecutorService { KonanTarget.WASM32 -> object : ExecutorService {
override fun execute(action: Action<in ExecSpec>): ExecResult? = project.exec { execSpec -> override fun execute(action: Action<in ExecSpec>): ExecResult? = project.exec {
action.execute(execSpec) action.execute(this)
with(execSpec) { val exe = executable
val exe = executable val d8 = "$absoluteTargetToolchain/bin/d8"
val d8 = "$absoluteTargetToolchain/bin/d8" val launcherJs = "$executable.js"
val launcherJs = "$executable.js" this.executable = d8
executable = d8 this.args = listOf("--expose-wasm", launcherJs, "--", exe) + args
args = listOf("--expose-wasm", launcherJs, "--", exe) + args
}
} }
} }
@@ -102,11 +100,11 @@ fun runProcess(executor: (Action<in ExecSpec>) -> ExecResult?,
val errStream = ByteArrayOutputStream() val errStream = ByteArrayOutputStream()
val execResult = executor(Action { val execResult = executor(Action {
it.executable = executable this.executable = executable
it.args = args.toList() this.args = args.toList()
it.standardOutput = outStream this.standardOutput = outStream
it.errorOutput = errStream this.errorOutput = errStream
it.isIgnoreExitValue = true this.isIgnoreExitValue = true
}) })
checkNotNull(execResult) checkNotNull(execResult)
@@ -135,12 +133,12 @@ fun runProcessWithInput(executor: (Action<in ExecSpec>) -> ExecResult?,
val inStream = ByteArrayInputStream(input.toByteArray()) val inStream = ByteArrayInputStream(input.toByteArray())
val execResult = executor(Action { val execResult = executor(Action {
it.executable = executable this.executable = executable
it.args = args.toList() this.args = args.toList()
it.standardOutput = outStream this.standardOutput = outStream
it.errorOutput = errStream this.errorOutput = errStream
it.isIgnoreExitValue = true this.isIgnoreExitValue = true
it.standardInput = inStream this.standardInput = inStream
}) })
checkNotNull(execResult) checkNotNull(execResult)
@@ -166,10 +164,10 @@ val Project.executor: ExecutorService
*/ */
fun ExecutorService.add(actionParameter: Action<in ExecSpec>) = object : ExecutorService { fun ExecutorService.add(actionParameter: Action<in ExecSpec>) = object : ExecutorService {
override fun execute(action: Action<in ExecSpec>): ExecResult? = override fun execute(action: Action<in ExecSpec>): ExecResult? =
this@add.execute { this@add.execute(Action {
action.execute(it) action.execute(this)
actionParameter.execute(it) actionParameter.execute(this)
} })
} }
/** /**
@@ -206,25 +204,24 @@ private fun emulatorExecutor(project: Project, target: KonanTarget) = object : E
?: error("$target does not support emulation!") ?: error("$target does not support emulation!")
val absoluteTargetSysRoot = configurables.absoluteTargetSysRoot val absoluteTargetSysRoot = configurables.absoluteTargetSysRoot
override fun execute(action: Action<in ExecSpec>): ExecResult? = project.exec { execSpec -> override fun execute(action: Action<in ExecSpec>): ExecResult? = project.exec {
action.execute(execSpec) action.execute(this)
with(execSpec) {
val exe = executable val exe = executable
// TODO: Move these to konan.properties when when it will be possible // TODO: Move these to konan.properties when when it will be possible
// to represent absolute path there. // to represent absolute path there.
val qemuSpecificArguments = listOf("-L", absoluteTargetSysRoot) val qemuSpecificArguments = listOf("-L", absoluteTargetSysRoot)
val targetSpecificArguments = when (target) { val targetSpecificArguments = when (target) {
KonanTarget.LINUX_MIPS32, KonanTarget.LINUX_MIPS32,
KonanTarget.LINUX_MIPSEL32 -> { KonanTarget.LINUX_MIPSEL32 -> {
// This is to workaround an endianess issue. // This is to workaround an endianess issue.
// See https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=731082 for details. // See https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=731082 for details.
listOf("$absoluteTargetSysRoot/lib/ld.so.1", "--inhibit-cache") listOf("$absoluteTargetSysRoot/lib/ld.so.1", "--inhibit-cache")
}
else -> emptyList()
} }
executable = configurables.absoluteEmulatorExecutable else -> emptyList()
args = qemuSpecificArguments + targetSpecificArguments + exe + args
} }
executable = configurables.absoluteEmulatorExecutable
args = qemuSpecificArguments + targetSpecificArguments + exe + args
} }
} }
@@ -251,8 +248,8 @@ private fun simulator(project: Project): ExecutorService = object : ExecutorServ
} }
val out = ByteArrayOutputStream() val out = ByteArrayOutputStream()
val result = project.exec { val result = project.exec {
it.commandLine("/usr/bin/xcrun", "--find", "simctl", "--sdk", sdk) commandLine("/usr/bin/xcrun", "--find", "simctl", "--sdk", sdk)
it.standardOutput = out standardOutput = out
} }
result.assertNormalExitValue() result.assertNormalExitValue()
out.toString("UTF-8").trim() out.toString("UTF-8").trim()
@@ -272,10 +269,10 @@ private fun simulator(project: Project): ExecutorService = object : ExecutorServ
else -> error("${target.architecture} can't be used in simulator.") else -> error("${target.architecture} can't be used in simulator.")
}.toTypedArray() }.toTypedArray()
override fun execute(action: Action<in ExecSpec>): ExecResult? = project.exec { execSpec -> override fun execute(action: Action<in ExecSpec>): ExecResult? = project.exec {
action.execute(execSpec) action.execute(this)
// Starting Xcode 11 `simctl spawn` requires explicit `--standalone` flag. // Starting Xcode 11 `simctl spawn` requires explicit `--standalone` flag.
with(execSpec) { commandLine = listOf(simctl, "spawn", "--standalone", *archSpecification, device, executable) + args } commandLine = listOf(simctl, "spawn", "--standalone", *archSpecification, device, executable) + args
} }
} }
@@ -303,14 +300,12 @@ private fun sshExecutor(project: Project): ExecutorService = object : ExecutorSe
var execFile: String? = null var execFile: String? = null
createRemoteDir() createRemoteDir()
val execResult = project.exec { execSpec -> val execResult = project.exec {
action.execute(execSpec) action.execute(this)
with(execSpec) { upload(executable)
upload(executable) this.executable = "$remoteDir/${File(executable).name}"
executable = "$remoteDir/${File(executable).name}" execFile = executable
execFile = executable commandLine = arrayListOf("$sshHome/ssh") + sshArgs + remote + commandLine
commandLine = arrayListOf("$sshHome/ssh") + sshArgs + remote + commandLine
}
} }
cleanup(execFile!!) cleanup(execFile!!)
return execResult return execResult
@@ -318,19 +313,19 @@ private fun sshExecutor(project: Project): ExecutorService = object : ExecutorSe
private fun createRemoteDir() { private fun createRemoteDir() {
project.exec { project.exec {
it.commandLine = arrayListOf("$sshHome/ssh") + sshArgs + remote + "mkdir" + "-p" + remoteDir commandLine = arrayListOf("$sshHome/ssh") + sshArgs + remote + "mkdir" + "-p" + remoteDir
} }
} }
private fun upload(fileName: String) { private fun upload(fileName: String) {
project.exec { project.exec {
it.commandLine = arrayListOf("$sshHome/scp") + sshArgs + fileName + "$remote:$remoteDir" commandLine = arrayListOf("$sshHome/scp") + sshArgs + fileName + "$remote:$remoteDir"
} }
} }
private fun cleanup(fileName: String) { private fun cleanup(fileName: String) {
project.exec { project.exec {
it.commandLine = arrayListOf("$sshHome/ssh") + sshArgs + remote + "rm" + fileName commandLine = arrayListOf("$sshHome/ssh") + sshArgs + remote + "rm" + fileName
} }
} }
} }
@@ -364,12 +359,12 @@ private fun deviceLauncher(project: Project) = object : ExecutorService {
var savedOut: OutputStream? = null var savedOut: OutputStream? = null
val out = ByteArrayOutputStream() val out = ByteArrayOutputStream()
result = project.exec { execSpec: ExecSpec -> result = project.exec {
action.execute(execSpec) action.execute(this)
execSpec.executable = "lldb" executable = "lldb"
execSpec.args = commands + "-b" + "-o" + "command script import ${pythonScript()}" + args = commands + "-b" + "-o" + "command script import ${pythonScript()}" +
"-o" + ("process launch" + "-o" + ("process launch" +
(execSpec.args.takeUnless { it.isEmpty() } (args.takeUnless { it.isEmpty() }
?.let { " -- ${it.joinToString(" ")}" } ?.let { " -- ${it.joinToString(" ")}" }
?: "")) + ?: "")) +
"-o" + "get_exit_code" + "-o" + "get_exit_code" +
@@ -378,8 +373,8 @@ private fun deviceLauncher(project: Project) = object : ExecutorService {
// A test task that uses project.exec { } sets the stdOut to parse the result, // A test task that uses project.exec { } sets the stdOut to parse the result,
// but the test executable is being run under debugger that has its own output mixed with the // but the test executable is being run under debugger that has its own output mixed with the
// output from the test. Save the stdOut from the test to write the parsed output to it. // output from the test. Save the stdOut from the test to write the parsed output to it.
savedOut = execSpec.standardOutput savedOut = this.standardOutput
execSpec.standardOutput = out standardOutput = out
} }
out.toString() out.toString()
.also { if (project.verboseTest) println(it) } .also { if (project.verboseTest) println(it) }
@@ -430,7 +425,7 @@ private fun deviceLauncher(project: Project) = object : ExecutorService {
absolutePath absolutePath
} }
private fun kill() = project.exec { it.commandLine(idb, "kill") } private fun kill() = project.exec { commandLine(idb, "kill") }
private inline fun tryUntilTrue(times: Int = 3, f: () -> Boolean) { private inline fun tryUntilTrue(times: Int = 3, f: () -> Boolean) {
for (i in 1..times) { for (i in 1..times) {
@@ -445,8 +440,8 @@ private fun deviceLauncher(project: Project) = object : ExecutorService {
// So relaunch `list-targets` again. // So relaunch `list-targets` again.
tryUntilTrue { tryUntilTrue {
project.exec { project.exec {
it.commandLine(idb, "list-targets", "--json") commandLine(idb, "list-targets", "--json")
it.standardOutput = out standardOutput = out
}.assertNormalExitValue() }.assertNormalExitValue()
out.toString().trim().isNotEmpty() out.toString().trim().isNotEmpty()
} }
@@ -469,11 +464,11 @@ private fun deviceLauncher(project: Project) = object : ExecutorService {
lateinit var result: ExecResult lateinit var result: ExecResult
tryUntilTrue { tryUntilTrue {
result = project.exec { result = project.exec {
it.workingDir = xcProject.toFile() workingDir = xcProject.toFile()
it.commandLine = listOf(idb, "install", "--udid", udid, bundlePath) commandLine = listOf(idb, "install", "--udid", udid, bundlePath)
it.standardOutput = out standardOutput = out
it.errorOutput = out errorOutput = out
it.isIgnoreExitValue = true isIgnoreExitValue = true
} }
println(out.toString()) println(out.toString())
result.exitValue == 0 result.exitValue == 0
@@ -485,11 +480,11 @@ private fun deviceLauncher(project: Project) = object : ExecutorService {
val out = ByteArrayOutputStream() val out = ByteArrayOutputStream()
project.exec { project.exec {
it.workingDir = xcProject.toFile() workingDir = xcProject.toFile()
it.commandLine = listOf(idb, "uninstall", "--udid", udid, bundleID) commandLine = listOf(idb, "uninstall", "--udid", udid, bundleID)
it.standardOutput = out standardOutput = out
it.errorOutput = out errorOutput = out
it.isIgnoreExitValue = true isIgnoreExitValue = true
} }
println(out.toString()) println(out.toString())
} }
@@ -498,11 +493,11 @@ private fun deviceLauncher(project: Project) = object : ExecutorService {
val out = ByteArrayOutputStream() val out = ByteArrayOutputStream()
val result = project.exec { val result = project.exec {
it.workingDir = xcProject.toFile() workingDir = xcProject.toFile()
it.commandLine = listOf(idb, "debugserver", "start", "--udid", udid, bundleID) commandLine = listOf(idb, "debugserver", "start", "--udid", udid, bundleID)
it.standardOutput = out standardOutput = out
it.errorOutput = out errorOutput = out
it.isIgnoreExitValue = true isIgnoreExitValue = true
} }
check(result.exitValue == 0) { "Failed to start debug server: $out" } check(result.exitValue == 0) { "Failed to start debug server: $out" }
return out.toString() return out.toString()
@@ -570,9 +565,9 @@ fun KonanTestExecutable.configureXcodeBuild() {
val xcode = listOf("/usr/bin/xcrun", "-sdk", sdk, "xcodebuild") val xcode = listOf("/usr/bin/xcrun", "-sdk", sdk, "xcodebuild")
val out = ByteArrayOutputStream() val out = ByteArrayOutputStream()
val result = project.exec { val result = project.exec {
it.workingDir = xcProject.toFile() workingDir = xcProject.toFile()
it.commandLine = xcode + elements.toList() commandLine = xcode + elements.toList()
it.standardOutput = out standardOutput = out
} }
println(out.toString("UTF-8")) println(out.toString("UTF-8"))
result.assertNormalExitValue() result.assertNormalExitValue()
@@ -90,7 +90,7 @@ open class FrameworkTest : DefaultTask(), KonanTestExecutable {
fun Language.filesFrom(dir: String): FileTree = project.fileTree(dir) { fun Language.filesFrom(dir: String): FileTree = project.fileTree(dir) {
// include only files with the language extension // include only files with the language extension
it.include("*${this.extension}") include("*${this@filesFrom.extension}")
} }
fun List<String>.toFiles(language: Language): List<File> = fun List<String>.toFiles(language: Language): List<File> =
@@ -222,8 +222,8 @@ open class FrameworkTest : DefaultTask(), KonanTestExecutable {
private fun runTest(executorService: ExecutorService, testExecutable: Path, args: List<String> = emptyList()) { private fun runTest(executorService: ExecutorService, testExecutable: Path, args: List<String> = emptyList()) {
val (stdOut, stdErr, exitCode) = runProcess( val (stdOut, stdErr, exitCode) = runProcess(
executor = { executorService.add(Action { executor = { executorService.add(Action {
it.environment = buildEnvironment() environment = buildEnvironment()
it.workingDir = Paths.get(testOutput).toFile() workingDir = Paths.get(testOutput).toFile()
}).execute(it) }, }).execute(it) },
executable = testExecutable.toString(), executable = testExecutable.toString(),
args = args) args = args)
@@ -464,18 +464,18 @@ open class KonanDynamicTest : KonanStandaloneTest() {
val isOpt = flagsContain("-opt") val isOpt = flagsContain("-opt")
val isDebug = flagsContain("-g") val isDebug = flagsContain("-g")
val execResult = plugin.execKonanClang(project.testTarget) { val execResult = plugin.execKonanClang(project.testTarget, Action<ExecSpec> {
it.workingDir = File(outputDirectory) workingDir = File(outputDirectory)
it.executable = clangTool executable = clangTool
it.args = listOf(processCSource(), args = listOf(processCSource(),
"-c", "-c",
"-o", "$executable.o", "-o", "${this@KonanDynamicTest.executable}.o",
"-I", artifactsDir "-I", artifactsDir
) + clangFlags ) + clangFlags
it.standardOutput = log standardOutput = log
it.errorOutput = log errorOutput = log
it.isIgnoreExitValue = true isIgnoreExitValue = true
} })
log.toString("UTF-8").also { log.toString("UTF-8").also {
project.file("$executable.compilation.log").writeText(it) project.file("$executable.compilation.log").writeText(it)
println(it) println(it)
@@ -484,7 +484,7 @@ open class KonanDynamicTest : KonanStandaloneTest() {
val linker = project.platformManager.platform(project.testTarget).linker val linker = project.platformManager.platform(project.testTarget).linker
val commands = linker.finalLinkCommands( val commands = linker.finalLinkCommands(
objectFiles = listOf("$executable.o"), objectFiles = listOf("${this@KonanDynamicTest.executable}.o"),
executable = executable, executable = executable,
libraries = listOf("-l$name"), libraries = listOf("-l$name"),
linkerArgs = listOf("-L", artifactsDir, "-rpath", artifactsDir), linkerArgs = listOf("-L", artifactsDir, "-rpath", artifactsDir),
@@ -50,9 +50,9 @@ open class MetadataComparisonTest : DefaultTask() {
val sourcecodeLibrary = cinterop(project.file(defFile), Mode.SOURCECODE) val sourcecodeLibrary = cinterop(project.file(defFile), Mode.SOURCECODE)
compareKlibMetadata(CInteropComparisonConfig(), sourcecodeLibrary.absolutePath, metadataLibrary.absolutePath).let { result -> compareKlibMetadata(CInteropComparisonConfig(), sourcecodeLibrary.absolutePath, metadataLibrary.absolutePath).let { result ->
if (result is MetadataCompareResult.Fail) { if (result is MetadataCompareResult.Fail) {
val message = StringBuilder().also { val message = buildString {
expandFail(result, it::appendln) expandFail(result, {x:String -> appendln(x)})
}.toString() }
throw TestFailedException(message) throw TestFailedException(message)
} }
} }
@@ -89,7 +89,7 @@ open class RunJvmTask: JavaExec() {
).removePrefix("[").removeSuffix("]") ).removePrefix("[").removeSuffix("]")
).jsonObject ).jsonObject
val modifiedBenchmarkReport = JsonObject(HashMap(benchmarkReport.content).apply { val modifiedBenchmarkReport = JsonObject(HashMap(benchmarkReport.content).apply {
put("repeat", JsonLiteral(i)) put("repeat", JsonLiteral(i) as JsonElement)
put("warmup", JsonLiteral(warmupCount)) put("warmup", JsonLiteral(warmupCount))
}) })
result.add(modifiedBenchmarkReport.toString()) result.add(modifiedBenchmarkReport.toString())
@@ -59,22 +59,22 @@ open class RunKotlinNativeTask @Inject constructor(private val linkTask: Task,
val useCset = project.findProperty("useCset")?.toString()?.toBoolean() ?: false val useCset = project.findProperty("useCset")?.toString()?.toBoolean() ?: false
project.exec { project.exec {
if (useCset) { if (useCset) {
it.executable = "cset" executable = "cset"
it.args("shield", "--exec", "--", executable) args("shield", "--exec", "--", executable)
} else { } else {
it.executable = executable this.executable = executable
} }
it.args(argumentsList) args(argumentsList)
it.args("-f", benchmark) args("-f", benchmark)
// Logging with application should be done only in case it controls running benchmarks itself. // Logging with application should be done only in case it controls running benchmarks itself.
// Although it's a responsibility of gradle task. // Although it's a responsibility of gradle task.
if (verbose && repeatingType == BenchmarkRepeatingType.INTERNAL) { if (verbose && repeatingType == BenchmarkRepeatingType.INTERNAL) {
it.args("-v") args("-v")
} }
it.args("-w", warmupCount.toString()) args("-w", warmupCount.toString())
it.args("-r", repeatCount.toString()) args("-r", repeatCount.toString())
it.standardOutput = output standardOutput = output
} }
return output.toString().substringAfter("[").removeSuffix("]") return output.toString().substringAfter("[").removeSuffix("]")
} }
@@ -104,9 +104,9 @@ open class RunKotlinNativeTask @Inject constructor(private val linkTask: Task,
fun run() { fun run() {
val output = ByteArrayOutputStream() val output = ByteArrayOutputStream()
project.exec { project.exec {
it.executable = executable executable = executable
it.args("list") args("list")
it.standardOutput = output standardOutput = output
} }
val benchmarks = output.toString().lines() val benchmarks = output.toString().lines()
val filterArgs = filter.splitCommaSeparatedOption("-f") val filterArgs = filter.splitCommaSeparatedOption("-f")
@@ -333,16 +333,16 @@ fun Project.buildStaticLibrary(cSources: Collection<File>, output: File, objDir:
objDir.mkdirs() objDir.mkdirs()
exec { exec {
it.commandLine(platform.clang.clangC( commandLine(platform.clang.clangC(
"-c", "-c",
*cSources.map { it.absolutePath }.toTypedArray() *cSources.map { it.absolutePath }.toTypedArray()
)) ))
it.workingDir(objDir) workingDir(objDir)
} }
output.parentFile.mkdirs() output.parentFile.mkdirs()
exec { exec {
it.commandLine( commandLine(
"${platform.configurables.absoluteLlvmHome}/bin/llvm-ar", "${platform.configurables.absoluteLlvmHome}/bin/llvm-ar",
"-rc", "-rc",
output, output,
@@ -125,7 +125,7 @@ abstract class BenchmarkingPlugin: Plugin<Project> {
protected open fun Project.configureSourceSets(kotlinVersion: String) { protected open fun Project.configureSourceSets(kotlinVersion: String) {
with(kotlin.sourceSets) { with(kotlin.sourceSets) {
commonMain.dependencies { commonMain.dependencies {
implementation("org.jetbrains.kotlin:kotlin-stdlib-common:$kotlinStdlibVersion") implementation(project(":kotlin-stdlib-common"))
} }
project.configurations.getByName(nativeMain.implementationConfigurationName).apply { project.configurations.getByName(nativeMain.implementationConfigurationName).apply {
@@ -134,7 +134,7 @@ abstract class BenchmarkingPlugin: Plugin<Project> {
} }
repositories.maven { repositories.maven {
it.setUrl(kotlinStdlibRepo) setUrl(kotlinStdlibRepo)
} }
additionalConfigurations(this@configureSourceSets) additionalConfigurations(this@configureSourceSets)
@@ -215,10 +215,10 @@ abstract class BenchmarkingPlugin: Plugin<Project> {
protected open fun Project.configureKonanJsonTask(nativeTarget: KotlinNativeTarget): Task { protected open fun Project.configureKonanJsonTask(nativeTarget: KotlinNativeTarget): Task {
return tasks.create("konanJsonReport") { return tasks.create("konanJsonReport") {
it.group = BENCHMARKING_GROUP group = BENCHMARKING_GROUP
it.description = "Builds the benchmarking report for Kotlin/Native." description = "Builds the benchmarking report for Kotlin/Native."
it.doLast { doLast {
val applicationName = benchmark.applicationName val applicationName = benchmark.applicationName
val benchContents = buildDir.resolve(nativeBenchResults).readText() val benchContents = buildDir.resolve(nativeBenchResults).readText()
val nativeCompileTime = if (benchmark.compileTasks.isEmpty()) getNativeCompileTime(project, applicationName) val nativeCompileTime = if (benchmark.compileTasks.isEmpty()) getNativeCompileTime(project, applicationName)
@@ -41,11 +41,11 @@ open class CompileBenchmarkingPlugin : Plugin<Project> {
private fun Project.configureUtilityTasks() { private fun Project.configureUtilityTasks() {
tasks.create("configureBuild") { tasks.create("configureBuild") {
it.doLast { mkdir(buildDir) } doLast { mkdir(buildDir) }
} }
tasks.create("clean", Delete::class.java) { tasks.create("clean", Delete::class.java) {
it.delete(buildDir) delete(buildDir)
} }
} }
@@ -53,11 +53,11 @@ open class CompileBenchmarkingPlugin : Plugin<Project> {
benchmarkExtension: CompileBenchmarkExtension benchmarkExtension: CompileBenchmarkExtension
): Unit = with(benchmarkExtension) { ): Unit = with(benchmarkExtension) {
// Aggregate task. // Aggregate task.
val konanRun = tasks.create("konanRun") { task -> val konanRun = tasks.create("konanRun") {
task.dependsOn("configureBuild") dependsOn("configureBuild")
task.group = BenchmarkingPlugin.BENCHMARKING_GROUP group = BenchmarkingPlugin.BENCHMARKING_GROUP
task.description = "Runs the compile only benchmark for Kotlin/Native." description = "Runs the compile only benchmark for Kotlin/Native."
} }
// Compile tasks. // Compile tasks.
@@ -112,16 +112,16 @@ open class CompileBenchmarkingPlugin : Plugin<Project> {
private fun Project.configureJvmRun() { private fun Project.configureJvmRun() {
val jvmRun = tasks.create("jvmRun") { val jvmRun = tasks.create("jvmRun") {
it.group = BenchmarkingPlugin.BENCHMARKING_GROUP group = BenchmarkingPlugin.BENCHMARKING_GROUP
it.description = "Runs the compile only benchmark for Kotlin/JVM." description = "Runs the compile only benchmark for Kotlin/JVM."
it.doLast { println("JVM run isn't supported") } doLast { println("JVM run isn't supported") }
} }
tasks.create("jvmJsonReport") { tasks.create("jvmJsonReport") {
it.group = BenchmarkingPlugin.BENCHMARKING_GROUP group = BenchmarkingPlugin.BENCHMARKING_GROUP
it.description = "Builds the benchmarking report for Kotlin/Native." description = "Builds the benchmarking report for Kotlin/Native."
it.doLast { println("JVM run isn't supported") } doLast { println("JVM run isn't supported") }
jvmRun.finalizedBy(it) jvmRun.finalizedBy(this)
} }
} }
@@ -37,10 +37,10 @@ open class KotlinNativeBenchmarkExtension @Inject constructor(project: Project)
open class KotlinNativeBenchmarkingPlugin: BenchmarkingPlugin() { open class KotlinNativeBenchmarkingPlugin: BenchmarkingPlugin() {
override fun Project.configureJvmJsonTask(jvmRun: Task): Task { override fun Project.configureJvmJsonTask(jvmRun: Task): Task {
return tasks.create("jvmJsonReport") { return tasks.create("jvmJsonReport") {
it.group = BENCHMARKING_GROUP group = BENCHMARKING_GROUP
it.description = "Builds the benchmarking report for Kotlin/JVM." description = "Builds the benchmarking report for Kotlin/JVM."
it.doLast { doLast {
val applicationName = benchmark.applicationName val applicationName = benchmark.applicationName
val jarPath = (tasks.getByName("jvmJar") as Jar).archiveFile.get().asFile val jarPath = (tasks.getByName("jvmJar") as Jar).archiveFile.get().asFile
val jvmCompileTime = getJvmCompileTime(project, applicationName) val jvmCompileTime = getJvmCompileTime(project, applicationName)
@@ -58,28 +58,28 @@ open class KotlinNativeBenchmarkingPlugin: BenchmarkingPlugin() {
buildDir.resolve(jvmJson).writeText(output) buildDir.resolve(jvmJson).writeText(output)
} }
jvmRun.finalizedBy(it) jvmRun.finalizedBy(this)
} }
} }
override fun Project.configureJvmTask(): Task { override fun Project.configureJvmTask(): Task {
return tasks.create("jvmRun", RunJvmTask::class.java) { task -> return tasks.create("jvmRun", RunJvmTask::class.java) {
task.dependsOn("jvmJar") dependsOn("jvmJar")
val mainCompilation = kotlin.jvm().compilations.getByName("main") val mainCompilation = kotlin.jvm().compilations.getByName("main")
val runtimeDependencies = configurations.getByName(mainCompilation.runtimeDependencyConfigurationName) val runtimeDependencies = configurations.getByName(mainCompilation.runtimeDependencyConfigurationName)
task.classpath(files(mainCompilation.output.allOutputs, runtimeDependencies)) classpath(files(mainCompilation.output.allOutputs, runtimeDependencies))
task.main = "MainKt" main = "MainKt"
task.group = BENCHMARKING_GROUP group = BENCHMARKING_GROUP
task.description = "Runs the benchmark for Kotlin/JVM." description = "Runs the benchmark for Kotlin/JVM."
// Specify settings configured by a user in the benchmark extension. // Specify settings configured by a user in the benchmark extension.
afterEvaluate { afterEvaluate {
task.args("-p", "${benchmark.applicationName}::") args("-p", "${benchmark.applicationName}::")
task.warmupCount = jvmWarmup warmupCount = jvmWarmup
task.repeatCount = attempts repeatCount = attempts
task.outputFileName = buildDir.resolve(jvmBenchResults).absolutePath outputFileName = buildDir.resolve(jvmBenchResults).absolutePath
task.repeatingType = benchmark.repeatingType repeatingType = benchmark.repeatingType
} }
} }
} }
@@ -131,7 +131,7 @@ open class KotlinNativeBenchmarkingPlugin: BenchmarkingPlugin() {
private fun Project.configureJVMTarget() { private fun Project.configureJVMTarget() {
kotlin.jvm { kotlin.jvm {
compilations.all { compilations.all {
it.compileKotlinTask.kotlinOptions { compileKotlinTask.kotlinOptions {
jvmTarget = "1.8" jvmTarget = "1.8"
suppressWarnings = true suppressWarnings = true
freeCompilerArgs = project.benchmark.compilerOpts + project.compilerArgs freeCompilerArgs = project.benchmark.compilerOpts + project.compilerArgs
@@ -28,13 +28,13 @@ open class SwiftBenchmarkingPlugin : BenchmarkingPlugin() {
override fun Project.configureJvmJsonTask(jvmRun: Task): Task { override fun Project.configureJvmJsonTask(jvmRun: Task): Task {
return tasks.create("jvmJsonReport") { return tasks.create("jvmJsonReport") {
logger.info("JVM run is unsupported") logger.info("JVM run is unsupported")
jvmRun.finalizedBy(it) jvmRun.finalizedBy(this)
} }
} }
override fun Project.configureJvmTask(): Task { override fun Project.configureJvmTask(): Task {
return tasks.create("jvmRun") { task -> return tasks.create("jvmRun") {
task.doLast { doLast {
logger.info("JVM run is unsupported") logger.info("JVM run is unsupported")
} }
} }
@@ -79,9 +79,9 @@ open class SwiftBenchmarkingPlugin : BenchmarkingPlugin() {
val nativeTarget = kotlin.targets.getByName(NATIVE_TARGET_NAME) as KotlinNativeTarget val nativeTarget = kotlin.targets.getByName(NATIVE_TARGET_NAME) as KotlinNativeTarget
// Build executable from swift code. // Build executable from swift code.
framework = nativeTarget.binaries.getFramework(nativeFrameworkName, benchmark.buildType) framework = nativeTarget.binaries.getFramework(nativeFrameworkName, benchmark.buildType)
tasks.create("buildSwift") { task -> tasks.create("buildSwift") {
task.dependsOn(framework.linkTaskName) dependsOn(framework.linkTaskName)
task.doLast { doLast {
val frameworkParentDirPath = framework.outputDirectory.absolutePath val frameworkParentDirPath = framework.outputDirectory.absolutePath
val options = listOf("-O", "-wmo", "-Xlinker", "-rpath", "-Xlinker", frameworkParentDirPath, "-F", frameworkParentDirPath) val options = listOf("-O", "-wmo", "-Xlinker", "-rpath", "-Xlinker", frameworkParentDirPath, "-F", frameworkParentDirPath)
compileSwift(project, nativeTarget.konanTarget, benchmark.swiftSources, options, compileSwift(project, nativeTarget.konanTarget, benchmark.swiftSources, options,
@@ -20,7 +20,7 @@ open class CompileToBitcode @Inject constructor(
val srcRoot: File, val srcRoot: File,
val folderName: String, val folderName: String,
val target: String, val target: String,
val outputGroup: String, val outputGroup: String
) : DefaultTask() { ) : DefaultTask() {
enum class Language { enum class Language {
@@ -35,7 +35,7 @@ open class CompileToBitcode @Inject constructor(
"**/*Test.cpp", "**/*Test.cpp",
"**/*TestSupport.cpp", "**/*TestSupport.cpp",
"**/*Test.mm", "**/*Test.mm",
"**/*TestSupport.mm", "**/*TestSupport.mm"
) )
var includeFiles: List<String> = listOf( var includeFiles: List<String> = listOf(
"**/*.cpp", "**/*.cpp",
@@ -103,8 +103,8 @@ open class CompileToBitcode @Inject constructor(
get() { get() {
return srcDirs.flatMap { srcDir -> return srcDirs.flatMap { srcDir ->
project.fileTree(srcDir) { project.fileTree(srcDir) {
it.include(includeFiles) include(includeFiles)
it.exclude(excludeFiles) exclude(excludeFiles)
}.files }.files
} }
} }
@@ -143,7 +143,7 @@ open class CompileToBitcode @Inject constructor(
Language.C -> arrayOf("**/.h") Language.C -> arrayOf("**/.h")
Language.CPP -> arrayOf("**/*.h", "**/*.hpp") Language.CPP -> arrayOf("**/*.h", "**/*.hpp")
} }
it.include(*includePatterns) include(*includePatterns)
}.files }.files
} }
} }
@@ -158,18 +158,18 @@ open class CompileToBitcode @Inject constructor(
val plugin = project.convention.getPlugin(ExecClang::class.java) val plugin = project.convention.getPlugin(ExecClang::class.java)
plugin.execKonanClang(target) { plugin.execKonanClang(target) {
it.workingDir = objDir workingDir = objDir
it.executable = executable executable = executable
it.args = compilerFlags + inputFiles.map { it.absolutePath } args = compilerFlags + inputFiles.map { it.absolutePath }
} }
project.exec { project.exec {
val llvmDir = project.findProperty("llvmDir") val llvmDir = project.findProperty("llvmDir")
it.executable = "$llvmDir/bin/llvm-link" executable = "$llvmDir/bin/llvm-link"
it.args = listOf("-o", outFile.absolutePath) + linkerArgs + args = listOf("-o", outFile.absolutePath) + linkerArgs +
inputFiles.map { project.fileTree(objDir) {
bitcodeFileForInputFile(it).absolutePath include("**/*.bc")
} }.files.map { it.absolutePath }
} }
} }
} }
@@ -38,7 +38,7 @@ open class CompileToBitcodePlugin: Plugin<Project> {
open class CompileToBitcodeExtension @Inject constructor(val project: Project) { open class CompileToBitcodeExtension @Inject constructor(val project: Project) {
private val targetList = with(project) { private val targetList = with(project) {
provider { (rootProject.property("targetList") as? List<*>)?.filterIsInstance<String>() ?: emptyList() } // TODO: Can we make it better? provider { (rootProject.project(":kotlin-native").property("targetList") as? List<*>)?.filterIsInstance<String>() ?: emptyList() } // TODO: Can we make it better?
} }
fun create( fun create(
@@ -48,7 +48,7 @@ open class CompileToBitcodeExtension @Inject constructor(val project: Project) {
configurationBlock: CompileToBitcode.() -> Unit = {} configurationBlock: CompileToBitcode.() -> Unit = {}
) { ) {
targetList.get().forEach { targetName -> targetList.get().forEach { targetName ->
val platformManager = project.rootProject.findProperty("platformManager") as PlatformManager val platformManager = project.rootProject.project(":kotlin-native").findProperty("platformManager") as PlatformManager
val target = platformManager.targetByName(targetName) val target = platformManager.targetByName(targetName)
val sanitizers: List<SanitizerKind?> = target.supportedSanitizers() + listOf(null) val sanitizers: List<SanitizerKind?> = target.supportedSanitizers() + listOf(null)
sanitizers.forEach { sanitizer -> sanitizers.forEach { sanitizer ->
@@ -57,15 +57,15 @@ open class CompileToBitcodeExtension @Inject constructor(val project: Project) {
CompileToBitcode::class.java, CompileToBitcode::class.java,
srcDir, name, targetName, outputGroup srcDir, name, targetName, outputGroup
).configure { ).configure {
it.sanitizer = sanitizer this.sanitizer = sanitizer
it.group = BasePlugin.BUILD_GROUP group = BasePlugin.BUILD_GROUP
val sanitizerDescription = when (sanitizer) { val sanitizerDescription = when (sanitizer) {
null -> "" null -> ""
SanitizerKind.ADDRESS -> " with ASAN" SanitizerKind.ADDRESS -> " with ASAN"
SanitizerKind.THREAD -> " with TSAN" SanitizerKind.THREAD -> " with TSAN"
} }
it.description = "Compiles '$name' to bitcode for $targetName$sanitizerDescription" description = "Compiles '$name' to bitcode for $targetName$sanitizerDescription"
it.configurationBlock() configurationBlock()
} }
} }
} }
@@ -19,7 +19,7 @@ internal class KmComparator(private val configuration: ComparisonConfig) {
::compareClassFlags to "Different flags for ${kmClass1.name}", ::compareClassFlags to "Different flags for ${kmClass1.name}",
compare(KmClass::constructors, compareLists(::compare)) to "Constructors mismatch for ${kmClass1.name}", compare(KmClass::constructors, compareLists(::compare)) to "Constructors mismatch for ${kmClass1.name}",
compare(KmClass::properties, compareLists(::compare, KmProperty::mangle)) to "Properties mismatch for ${kmClass1.name}", compare(KmClass::properties, compareLists(::compare, KmProperty::mangle)) to "Properties mismatch for ${kmClass1.name}",
compare(KmClass::functions, compareLists(::compare, KmFunction::mangle)) to "Functions mismatch for ${kmClass1.name}", compare(KmClass::functions, compareLists(::compare, KmFunction::mangle)) to "Functions mismatch for ${kmClass1.name}"
)(kmClass1, kmClass2) )(kmClass1, kmClass2)
fun compare(typealias1: KmTypeAlias, typealias2: KmTypeAlias): MetadataCompareResult = serialComparator( fun compare(typealias1: KmTypeAlias, typealias2: KmTypeAlias): MetadataCompareResult = serialComparator(
@@ -26,7 +26,7 @@ private class JoinedFragments(
val classes: JoinResult<KmClass>, val classes: JoinResult<KmClass>,
val functions: JoinResult<KmFunction>, val functions: JoinResult<KmFunction>,
val properties: JoinResult<KmProperty>, val properties: JoinResult<KmProperty>,
val typeAliases: JoinResult<KmTypeAlias>, val typeAliases: JoinResult<KmTypeAlias>
) )
private fun processMissing(comparisonConfig: ComparisonConfig, joinResult: JoinResult<*>): MetadataCompareResult { private fun processMissing(comparisonConfig: ComparisonConfig, joinResult: JoinResult<*>): MetadataCompareResult {
@@ -55,7 +55,7 @@ private fun processMissing(
processMissing(comparisonConfig, joinedFragments.typeAliases) processMissing(comparisonConfig, joinedFragments.typeAliases)
.messageIfFail("Missing type aliases"), .messageIfFail("Missing type aliases"),
processMissing(comparisonConfig, joinedFragments.properties) processMissing(comparisonConfig, joinedFragments.properties)
.messageIfFail("Missing properties"), .messageIfFail("Missing properties")
).wrap() ).wrap()
private data class JoinResult<T>( private data class JoinResult<T>(
@@ -56,10 +56,10 @@ open class GitDownloadTask @Inject constructor(
execConfiguration: ExecSpec.() -> Unit = {} execConfiguration: ExecSpec.() -> Unit = {}
): ExecResult = ): ExecResult =
project.exec { project.exec {
it.executable = "git" executable = "git"
it.args(*args) args(*args)
it.isIgnoreExitValue = ignoreExitValue isIgnoreExitValue = ignoreExitValue
it.execConfiguration() execConfiguration()
} }
private fun tryCloneBranch(): Boolean { private fun tryCloneBranch(): Boolean {
@@ -93,7 +93,7 @@ open class GitDownloadTask @Inject constructor(
} }
project.delete { project.delete {
it.delete(outputDirectory) delete(outputDirectory)
} }
if (!tryCloneBranch()) { if (!tryCloneBranch()) {
@@ -18,7 +18,7 @@ import org.jetbrains.kotlin.konan.target.*
open class CompileNativeTest @Inject constructor( open class CompileNativeTest @Inject constructor(
@InputFile val inputFile: File, @InputFile val inputFile: File,
@Input val target: KonanTarget, @Input val target: KonanTarget
) : DefaultTask() { ) : DefaultTask() {
@OutputFile @OutputFile
var outputFile = project.buildDir.resolve("bin/test/${target.name}/${inputFile.nameWithoutExtension}.o") var outputFile = project.buildDir.resolve("bin/test/${target.name}/${inputFile.nameWithoutExtension}.o")
@@ -42,13 +42,13 @@ open class CompileNativeTest @Inject constructor(
val args = clangArgs + sanitizerFlags + listOf(inputFile.absolutePath, "-o", outputFile.absolutePath) val args = clangArgs + sanitizerFlags + listOf(inputFile.absolutePath, "-o", outputFile.absolutePath)
if (target.family.isAppleFamily) { if (target.family.isAppleFamily) {
plugin.execToolchainClang(target) { plugin.execToolchainClang(target) {
it.executable = "clang++" executable = "clang++"
it.args = args this.args = args
} }
} else { } else {
plugin.execBareClang { plugin.execBareClang {
it.executable = "clang++" executable = "clang++"
it.args = args this.args = args
} }
} }
} }
@@ -82,13 +82,13 @@ open class LlvmLinkNativeTest @Inject constructor(
// except the one containing the entry point to a single *.bc without internalization. The second // except the one containing the entry point to a single *.bc without internalization. The second
// run internalizes this big module and links it with a module containing the entry point. // run internalizes this big module and links it with a module containing the entry point.
project.exec { project.exec {
it.executable = "$llvmDir/bin/llvm-link" executable = "$llvmDir/bin/llvm-link"
it.args = listOf("-o", tmpOutput.absolutePath) + inputFiles.map { it.absolutePath } args = listOf("-o", tmpOutput.absolutePath) + inputFiles.map { it.absolutePath }
} }
project.exec { project.exec {
it.executable = "$llvmDir/bin/llvm-link" executable = "$llvmDir/bin/llvm-link"
it.args = listOf( args = listOf(
"-o", outputFile.absolutePath, "-o", outputFile.absolutePath,
mainFile.absolutePath, mainFile.absolutePath,
tmpOutput.absolutePath, tmpOutput.absolutePath,
@@ -104,7 +104,7 @@ open class LinkNativeTest @Inject constructor(
@Internal val target: String, @Internal val target: String,
@Internal val linkerArgs: List<String>, @Internal val linkerArgs: List<String>,
private val platformManager: PlatformManager, private val platformManager: PlatformManager,
private val mimallocEnabled: Boolean, private val mimallocEnabled: Boolean
) : DefaultTask () { ) : DefaultTask () {
companion object { companion object {
fun create( fun create(
@@ -115,7 +115,7 @@ open class LinkNativeTest @Inject constructor(
target: String, target: String,
outputFile: File, outputFile: File,
linkerArgs: List<String>, linkerArgs: List<String>,
mimallocEnabled: Boolean, mimallocEnabled: Boolean
): LinkNativeTest = project.tasks.create( ): LinkNativeTest = project.tasks.create(
taskName, taskName,
LinkNativeTest::class.java, LinkNativeTest::class.java,
@@ -165,7 +165,7 @@ open class LinkNativeTest @Inject constructor(
outputDsymBundle = "", outputDsymBundle = "",
needsProfileLibrary = false, needsProfileLibrary = false,
mimallocEnabled = mimallocEnabled, mimallocEnabled = mimallocEnabled,
sanitizer = sanitizer, sanitizer = sanitizer
).map { it.argsWithExecutable } ).map { it.argsWithExecutable }
} }
@@ -173,7 +173,7 @@ open class LinkNativeTest @Inject constructor(
fun link() { fun link() {
for (command in commands) { for (command in commands) {
project.exec { project.exec {
it.commandLine(command) commandLine(command)
} }
} }
} }
@@ -184,9 +184,9 @@ private fun createTestTask(
testName: String, testName: String,
testedTaskNames: List<String>, testedTaskNames: List<String>,
sanitizer: SanitizerKind?, sanitizer: SanitizerKind?,
configureCompileToBitcode: CompileToBitcode.() -> Unit = {}, configureCompileToBitcode: CompileToBitcode.() -> Unit = {}
): Task { ): Task {
val platformManager = project.rootProject.findProperty("platformManager") as PlatformManager val platformManager = project.project(":kotlin-native").findProperty("platformManager") as PlatformManager
val googleTestExtension = project.extensions.getByName(RuntimeTestingPlugin.GOOGLE_TEST_EXTENSION_NAME) as GoogleTestExtension val googleTestExtension = project.extensions.getByName(RuntimeTestingPlugin.GOOGLE_TEST_EXTENSION_NAME) as GoogleTestExtension
val testedTasks = testedTaskNames.map { val testedTasks = testedTaskNames.map {
project.tasks.getByName(it) as CompileToBitcode project.tasks.getByName(it) as CompileToBitcode
@@ -243,7 +243,7 @@ private fun createTestTask(
"${testName}Compile", "${testName}Compile",
CompileNativeTest::class.java, CompileNativeTest::class.java,
llvmLinkTask.outputFile, llvmLinkTask.outputFile,
konanTarget, konanTarget
).apply { ).apply {
this.sanitizer = sanitizer this.sanitizer = sanitizer
dependsOn(llvmLinkTask) dependsOn(llvmLinkTask)
@@ -259,7 +259,7 @@ private fun createTestTask(
listOf(compileTask.outputFile), listOf(compileTask.outputFile),
target, target,
testName, testName,
mimallocEnabled, mimallocEnabled
).apply { ).apply {
this.sanitizer = sanitizer this.sanitizer = sanitizer
dependsOn(compileTask) dependsOn(compileTask)
@@ -302,9 +302,9 @@ fun createTestTasks(
targetName: String, targetName: String,
testTaskName: String, testTaskName: String,
testedTaskNames: List<String>, testedTaskNames: List<String>,
configureCompileToBitcode: CompileToBitcode.() -> Unit = {}, configureCompileToBitcode: CompileToBitcode.() -> Unit = {}
): List<Task> { ): List<Task> {
val platformManager = project.rootProject.findProperty("platformManager") as PlatformManager val platformManager = project.rootProject.project(":kotlin-native").findProperty("platformManager") as PlatformManager
val target = platformManager.targetByName(targetName) val target = platformManager.targetByName(targetName)
val sanitizers: List<SanitizerKind?> = target.supportedSanitizers() + listOf(null) val sanitizers: List<SanitizerKind?> = target.supportedSanitizers() + listOf(null)
return sanitizers.map { sanitizer -> return sanitizers.map { sanitizer ->
@@ -38,10 +38,10 @@ open class RuntimeTestingPlugin : Plugin<Project> {
provider { extension.fetchDirectory } provider { extension.fetchDirectory }
) )
task.configure { task.configure {
it.refresh.set(provider { extension.refresh }) refresh.set(provider { extension.refresh })
it.onlyIf { extension.localSourceRoot == null } onlyIf { extension.localSourceRoot == null }
it.description = "Retrieves GoogleTest from the given repository" description = "Retrieves GoogleTest from the given repository"
it.group = "Google Test" group = "Google Test"
} }
return task return task
} }
@@ -0,0 +1,95 @@
/*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.report.json
open class JsonSerializable
data class JsonObject(val content: Map<String, JsonElement>) : JsonElement(), Map<String, JsonElement> by content {
fun getOrNull(key: String): JsonElement? = null
fun getObject(key: String): JsonObject = JsonObject(emptyMap<String, JsonElement>())
fun getArray(key: String): JsonArray = JsonArray(emptyList())
fun getPrimitive(key: String): JsonPrimitive = JsonNull
}
data class JsonLiteral internal constructor(
private val body: Any,
private val isString: Boolean
) : JsonPrimitive() {
override val content = body.toString()
override val contentOrNull: String = content
constructor(number: Number) : this(number, false)
constructor(boolean: Boolean) : this(boolean, false)
constructor(string: String) : this(string, true)
fun unquoted() = ""
}
sealed class JsonPrimitive():JsonElement(){
abstract val content: String
abstract val contentOrNull: String?
val int: Int get() = 0
}
object JsonNull : JsonPrimitive() {
override val content: String = "null"
override val contentOrNull: String? = null
}
open class JsonElement:JsonSerializable() {
open val jsonObject: JsonObject
get() = error("JsonObject")
open val jsonArray: JsonArray
get() = error("JsonArray")
}
open class JsonTreeParser:JsonSerializable() {
companion object{
fun parse(benchDesc:String) = JsonElement()
}
}
open class JsonArray(val content: List<JsonElement>):JsonElement(), List<JsonElement> by content {
fun getObject(index: Int): JsonObject = JsonObject(emptyMap<String, JsonElement>())
}
open class BenchmarksReport(val env: Environment, benchmarksList: List<BenchmarkResult>, val compiler: Compiler) : JsonSerializable() {
constructor() : this(Environment(Environment.Machine("Pentium Pro", "Haiku OS"), Environment.JDKInstance("KaffeJVM", "Kaffe")),
emptyList<BenchmarkResult>(),
Compiler(Compiler.Backend(Compiler.BackendType.NATIVE, "1.0", emptyList()),"1.0"))
companion object {
fun create(data: JsonElement): BenchmarksReport = BenchmarksReport()
}
fun toJson() = "{}"
operator fun plus(other: BenchmarksReport): BenchmarksReport = this
}
open class BenchmarkResult(val name: String, val status: Status,
val score: Double, val metric: Metric, val runtimeInUs: Double,
val repeat: Int, val warmup: Int) : JsonSerializable() {
enum class Status(val value: String) {
PASSED("PASSED"),
FAILED("FAILED")
}
enum class Metric(val suffix: String, val value: String) {
EXECUTION_TIME("", "EXECUTION_TIME"),
CODE_SIZE(".codeSize", "CODE_SIZE"),
COMPILE_TIME(".compileTime", "COMPILE_TIME"),
BUNDLE_SIZE(".bundleSize", "BUNDLE_SIZE")
}
}
data class Environment(val machine: Machine, val jdk: JDKInstance) : JsonSerializable() {
data class Machine(val cpu: String, val os: String) : JsonSerializable()
data class JDKInstance(val version: String, val vendor: String) : JsonSerializable()
}
data class Compiler(val backend: Backend, val kotlinVersion: String) : JsonSerializable() {
enum class BackendType(val type: String) {
JVM("jvm"),
NATIVE("native")
}
data class Backend(val type: BackendType, val version: String, val flags: List<String>) : JsonSerializable()
companion object{
fun backendTypeFromString(ignored0:String? = null , ignored1:String? = null) = Compiler.BackendType.NATIVE
}
}
fun parseBenchmarksArray(data: JsonElement): List<BenchmarkResult> = emptyList<BenchmarkResult>()
@@ -0,0 +1,41 @@
/*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.report.json
// Entity can be created from json description.
interface ConvertedFromJson {
// Methods for conversion to expected type with checks of possibility of such conversions.
fun elementToDouble(element: JsonElement, name: String): Double =
if (element is JsonPrimitive)
0.0
else
error("Field '$name' in '$element' is expected to be a double number. Please, check origin files.")
fun elementToInt(element: JsonElement, name: String): Int =
if (element is JsonPrimitive)
0
else
error("Field '$name' in '$element' is expected to be an integer number. Please, check origin files.")
fun elementToString(element: JsonElement, name:String): String =
if (element is JsonLiteral)
""
else
error("Field '$name' in '$element' is expected to be a string. Please, check origin files.")
fun elementToStringOrNull(element: JsonElement, name:String): String? =
when (element) {
else -> error("Field '$name' in '$element' is expected to be a string. Please, check origin files.")
}
}
fun JsonObject.getRequiredField(fieldName: String): JsonElement {
error("Field '$fieldName' doesn't exist in '$this'. Please, check origin files.")
}
fun JsonObject.getOptionalField(fieldName: String): JsonElement? {
return getOrNull(fieldName)
}
+68 -74
View File
@@ -33,7 +33,6 @@ buildscript {
apply from: "gradle/kotlinGradlePlugin.gradle" apply from: "gradle/kotlinGradlePlugin.gradle"
repositories { repositories {
maven { url kotlinCompilerRepo }
maven { url "https://kotlin.bintray.com/kotlinx" } maven { url "https://kotlin.bintray.com/kotlinx" }
maven { url "https://cache-redirector.jetbrains.com/maven-central" } maven { url "https://cache-redirector.jetbrains.com/maven-central" }
mavenCentral() mavenCentral()
@@ -43,9 +42,7 @@ buildscript {
} }
dependencies { dependencies {
classpath "org.jetbrains.kotlin:kotlin-native-utils:$kotlinVersion" //classpath project(":kotlin-native-utils")
classpath "org.jetbrains.kotlin:kotlin-native-shared:$konanVersion"
classpath "org.jetbrains.kotlin:kotlin-native-build-tools:$konanVersion"
classpath 'com.github.jengelman.gradle.plugins:shadow:5.1.0' classpath 'com.github.jengelman.gradle.plugins:shadow:5.1.0'
} }
} }
@@ -53,10 +50,10 @@ import org.jetbrains.kotlin.konan.*
// Allows generating wrappers for the root build and all the samples during execution of the default 'wrapper' task. // Allows generating wrappers for the root build and all the samples during execution of the default 'wrapper' task.
// Run './gradlew wrapper --gradle-version <version>' to update all the wrappers. // Run './gradlew wrapper --gradle-version <version>' to update all the wrappers.
apply plugin: org.jetbrains.kotlin.GradleWrappers //apply plugin: org.jetbrains.kotlin.GradleWrappers
//
wrappers.projects = ['samples', 'samples/calculator', 'samples/androidNativeActivity', 'samples/cocoapods/kotlin-library'] //wrappers.projects = ['samples', 'samples/calculator', 'samples/androidNativeActivity', 'samples/cocoapods/kotlin-library']
wrapper.distributionType = Wrapper.DistributionType.ALL //wrapper.distributionType = Wrapper.DistributionType.ALL
// FIXME: Remove until IDEA-231214 is fixed. // FIXME: Remove until IDEA-231214 is fixed.
//defaultTasks 'clean', 'dist' //defaultTasks 'clean', 'dist'
@@ -85,14 +82,14 @@ ext {
KonanTarget.LINUX_MIPSEL32.INSTANCE KonanTarget.LINUX_MIPSEL32.INSTANCE
] ]
kotlinCompilerModule="org.jetbrains.kotlin:kotlin-compiler:${kotlinVersion}" kotlinCompilerModule= project(":kotlin-compiler")
kotlinStdLibModule="org.jetbrains.kotlin:kotlin-stdlib:${kotlinVersion}" kotlinStdLibModule= project(":kotlin-stdlib")
kotlinCommonStdlibModule="org.jetbrains.kotlin:kotlin-stdlib-common:${kotlinStdlibVersion}:sources" kotlinCommonStdlibModule= project(":kotlin-stdlib-common")
kotlinTestCommonModule="org.jetbrains.kotlin:kotlin-test-common:${kotlinStdlibVersion}:sources" kotlinTestCommonModule= project(":kotlin-test:kotlin-test-common")
kotlinTestAnnotationsCommonModule="org.jetbrains.kotlin:kotlin-test-annotations-common:${kotlinStdlibVersion}:sources" kotlinTestAnnotationsCommonModule= project(":kotlin-test:kotlin-test-annotations-common")
kotlinReflectModule="org.jetbrains.kotlin:kotlin-reflect:${kotlinVersion}" kotlinReflectModule= project(":kotlin-reflect")
kotlinScriptRuntimeModule="org.jetbrains.kotlin:kotlin-script-runtime:${kotlinVersion}" kotlinScriptRuntimeModule= project(":kotlin-script-runtime")
kotlinUtilKliMetadatabModule="org.jetbrains.kotlin:kotlin-util-klib-metadata:${kotlinVersion}" kotlinUtilKliMetadatabModule= project(":kotlin-util-klib-metadata")
konanVersionFull = CompilerVersionGeneratedKt.getCurrentCompilerVersion() konanVersionFull = CompilerVersionGeneratedKt.getCurrentCompilerVersion()
gradlePluginVersion = konanVersionFull gradlePluginVersion = konanVersionFull
@@ -108,8 +105,8 @@ allprojects {
maven { url "https://dl.bintray.com/kotlin/kotlin-dev" } maven { url "https://dl.bintray.com/kotlin/kotlin-dev" }
} }
} }
if (path != ":dependencies") { if (path != ":kotlin-native:dependencies") {
evaluationDependsOn(":dependencies") evaluationDependsOn(":kotlin-native:dependencies")
} }
repositories { repositories {
@@ -118,10 +115,7 @@ allprojects {
} }
mavenCentral() mavenCentral()
maven { maven {
url kotlinStdlibRepo url project.bootstrapKotlinRepo
}
maven {
url kotlinCompilerRepo
} }
maven { maven {
url "https://dl.bintray.com/kotlin/kotlin-dev" url "https://dl.bintray.com/kotlin/kotlin-dev"
@@ -151,7 +145,7 @@ void setupHostAndTarget() {
void setupClang(Project project) { void setupClang(Project project) {
project.convention.plugins.platformManager = project.rootProject.ext.platformManager project.convention.plugins.platformManager = project.project(":kotlin-native").ext.platformManager
project.convention.plugins.execClang = new org.jetbrains.kotlin.ExecClang(project) project.convention.plugins.execClang = new org.jetbrains.kotlin.ExecClang(project)
project.plugins.withType(NativeComponentPlugin) { project.plugins.withType(NativeComponentPlugin) {
@@ -223,28 +217,28 @@ dependencies {
[kotlinCommonStdlibModule, kotlinTestCommonModule, kotlinTestAnnotationsCommonModule].each { [kotlinCommonStdlibModule, kotlinTestCommonModule, kotlinTestAnnotationsCommonModule].each {
kotlinCommonSources(it) { transitive = false } kotlinCommonSources(it) { transitive = false }
} }
distPack project(':Interop:Runtime') distPack project(':kotlin-native:Interop:Runtime')
distPack project(':Interop:Indexer') distPack project(':kotlin-native:Interop:Indexer')
distPack project(':Interop:StubGenerator') distPack project(':kotlin-native:Interop:StubGenerator')
distPack project(':backend.native') //distPack project(':kotlin-native:backend.native')
distPack project(':utilities:cli-runner') distPack project(':kotlin-native:utilities:cli-runner')
distPack project(':utilities:basic-utils') distPack project(':kotlin-native:utilities:basic-utils')
distPack project(':klib') distPack project(':kotlin-native:klib')
distPack project(path: ':endorsedLibraries:kotlinx.cli', configuration: "jvmRuntimeElements") distPack project(path: ':kotlin-native:endorsedLibraries:kotlinx.cli', configuration: "jvmRuntimeElements")
distPack "org.jetbrains.kotlin:kotlin-native-shared:$konanVersion" //distPack "org.jetbrains.kotlin:kotlin-native-shared:$konanVersion"
} }
task sharedJar { //task sharedJar {
dependsOn gradle.includedBuild('shared').task(':jar') // dependsOn gradle.includedBuild('shared').task(':jar')
} //}
task gradlePluginJar { //task gradlePluginJar {
dependsOn gradle.includedBuild('kotlin-native-gradle-plugin').task(':shadowJar') // dependsOn gradle.includedBuild('kotlin-native-gradle-plugin').task(':shadowJar')
} //}
task gradlePluginCheck { //task gradlePluginCheck {
dependsOn gradle.includedBuild('kotlin-native-gradle-plugin').task(':check') // dependsOn gradle.includedBuild('kotlin-native-gradle-plugin').task(':check')
} //}
task dist_compiler(dependsOn: "distCompiler") task dist_compiler(dependsOn: "distCompiler")
task dist_runtime(dependsOn: "distRuntime") task dist_runtime(dependsOn: "distRuntime")
@@ -256,7 +250,7 @@ task build {
task distCommonSources(type: CopyCommonSources) { task distCommonSources(type: CopyCommonSources) {
outputDir "$distDir/sources" outputDir "$distDir/sources"
sourcePaths configurations.kotlinCommonSources.files sourcePaths project(":kotlin-stdlib-common").file("src")
zipSources true zipSources true
} }
@@ -267,16 +261,16 @@ task distNativeSources(type: Zip) {
includeEmptyDirs = false includeEmptyDirs = false
include('**/*.kt') include('**/*.kt')
from(project(':runtime').file('src/main/kotlin')) from(project(':kotlin-native:runtime').file('src/main/kotlin'))
from(project(':Interop:Runtime').file('src/main/kotlin')) from(project(':kotlin-native:Interop:Runtime').file('src/main/kotlin'))
from(project(':Interop:Runtime').file('src/native/kotlin')) from(project(':kotlin-native:Interop:Runtime').file('src/native/kotlin'))
from(project(':Interop:JsRuntime').file('src/main/kotlin')) { from(project(':kotlin-native:Interop:JsRuntime').file('src/main/kotlin')) {
into('kotlinx/wasm/jsinterop') into('kotlinx/wasm/jsinterop')
} }
} }
task distEndorsedSources { task distEndorsedSources {
dependsOn(':endorsedLibraries:endorsedLibsSources') dependsOn(':kotlin-native:endorsedLibraries:endorsedLibsSources')
} }
task distSources { task distSources {
@@ -366,35 +360,35 @@ task distCompiler(type: Copy) {
destinationDir distDir destinationDir distDir
from(project(':backend.native').file("build/nativelibs/$hostName")) { from(project(':kotlin-native:backend.native').file("build/nativelibs/$hostName")) {
into('konan/nativelib') into('konan/nativelib')
} }
from(project(':backend.native').file('build/external_jars/trove4j.jar')) { from(project(':kotlin-native:backend.native').file('build/external_jars/trove4j.jar')) {
into('konan/lib') into('konan/lib')
} }
from(project(':Interop').file('Indexer/build/nativelibs')) { from(project(':kotlin-native:Interop').file('Indexer/build/nativelibs')) {
into('konan/nativelib') into('konan/nativelib')
} }
from(project(':Interop').file('Runtime/build/nativelibs')) { from(project(':kotlin-native:Interop').file('Runtime/build/nativelibs')) {
into('konan/nativelib') into('konan/nativelib')
} }
from(project(':llvmCoverageMappingC').file('build/libs/coverageMapping/shared')) { from(project(':kotlin-native:llvmCoverageMappingC').file('build/libs/coverageMapping/shared')) {
into('konan/nativelib') into('konan/nativelib')
} }
from(project(':llvmDebugInfoC').file('build/libs/debugInfo/shared')) { from(project(':kotlin-native:llvmDebugInfoC').file('build/libs/debugInfo/shared')) {
into('konan/nativelib') into('konan/nativelib')
} }
from(project(':llvmDebugInfoC').file('src/scripts/konan_lldb.py')) { from(project(':kotlin-native:llvmDebugInfoC').file('src/scripts/konan_lldb.py')) {
into('tools') into('tools')
} }
from(project(':utilities').file('env_blacklist')) { from(project(':kotlin-native:utilities').file('env_blacklist')) {
into('tools') into('tools')
} }
@@ -428,7 +422,7 @@ task distDef(type: Copy) {
destinationDir distDir destinationDir distDir
platformManager.targetValues.each { target -> platformManager.targetValues.each { target ->
from(project("platformLibs").file("src/platform/${target.family.name().toLowerCase()}")) { from(project(":kotlin-native:platformLibs").file("src/platform/${target.family.name().toLowerCase()}")) {
into("konan/platformDef/${target.visibleName}") into("konan/platformDef/${target.visibleName}")
include '**/*.def' include '**/*.def'
if (target in targetsWithoutZlib) { if (target in targetsWithoutZlib) {
@@ -489,12 +483,12 @@ task crossDistEndorsedCache {
targetList.each { target -> targetList.each { target ->
task("${target}CrossDistRuntime", type: Copy) { task("${target}CrossDistRuntime", type: Copy) {
dependsOn ":runtime:${target}Runtime" dependsOn ":kotlin-native:runtime:${target}Runtime"
dependsOn ":backend.native:${target}Stdlib" dependsOn ":kotlin-native:backend.native:${target}Stdlib"
destinationDir distDir destinationDir distDir
from(project(':runtime').file("build/${target}Stdlib")) { from(project(':kotlin-native:runtime').file("build/${target}Stdlib")) {
include('**') include('**')
into(stdlib) into(stdlib)
eachFile { eachFile {
@@ -507,38 +501,38 @@ targetList.each { target ->
} }
} }
} }
from(project(':runtime').file("build/bitcode/main/$target")) { from(project(':kotlin-native:runtime').file("build/bitcode/main/$target")) {
include("runtime.bc") include("runtime.bc")
into("$stdlibDefaultComponent/targets/$target/native") into("$stdlibDefaultComponent/targets/$target/native")
} }
from(project(':runtime').file("build/bitcode/main/$target")) { from(project(':kotlin-native:runtime').file("build/bitcode/main/$target")) {
include("*.bc") include("*.bc")
exclude("runtime.bc") exclude("runtime.bc")
into("konan/targets/$target/native") into("konan/targets/$target/native")
} }
if (target == 'wasm32') { if (target == 'wasm32') {
into("$stdlibDefaultComponent/targets/wasm32/included") { into("$stdlibDefaultComponent/targets/wasm32/included") {
from(project(':runtime').file('src/main/js')) from(project(':kotlin-native:runtime').file('src/main/js'))
from(project(':runtime').file('src/launcher/js')) from(project(':kotlin-native:runtime').file('src/launcher/js'))
from(project(':Interop:JsRuntime').file('src/main/js')) from(project(':kotlin-native:Interop:JsRuntime').file('src/main/js'))
} }
} }
} }
task("${target}PlatformLibs") { task("${target}PlatformLibs") {
dependsOn ":platformLibs:${target}Install" dependsOn ":kotlin-native:platformLibs:${target}Install"
if (target in cacheableTargetNames) { if (target in cacheableTargetNames) {
dependsOn(":platformLibs:${target}Cache") dependsOn(":kotlin-native:platformLibs:${target}Cache")
} }
} }
if (target in cacheableTargetNames) { if (target in cacheableTargetNames) {
task "${target}StdlibCache" { task "${target}StdlibCache" {
dependsOn ":platformLibs:${target}StdlibCache" dependsOn ":kotlin-native:platformLibs:${target}StdlibCache"
} }
task "${target}EndorsedCache" { task "${target}EndorsedCache" {
dependsOn ":endorsedLibraries:${target}Cache" dependsOn ":kotlin-native:endorsedLibraries:${target}Cache"
} }
} }
@@ -550,10 +544,10 @@ targetList.each { target ->
} }
task("${target}CrossDistEndorsedLibraries", type: Copy) { task("${target}CrossDistEndorsedLibraries", type: Copy) {
dependsOn ":endorsedLibraries:${target}EndorsedLibraries" dependsOn ":kotlin-native:endorsedLibraries:${target}EndorsedLibraries"
destinationDir distDir destinationDir distDir
from(project(':endorsedLibraries').file("build")) { from(project(':kotlin-native:endorsedLibraries').file("build")) {
include('**') include('**')
into("$endorsedLibsBase") into("$endorsedLibsBase")
} }
@@ -561,8 +555,8 @@ targetList.each { target ->
} }
task distPlatformLibs { task distPlatformLibs {
dependsOn ':platformLibs:hostInstall' dependsOn ':kotlin-native:platformLibs:hostInstall'
dependsOn ':platformLibs:hostCache' dependsOn ':kotlin-native:platformLibs:hostCache'
} }
task dist { task dist {
@@ -777,8 +771,8 @@ task pusher(type: KotlinBuildPusher){
targetList.each { target -> targetList.each { target ->
CompilationDatabaseKt.mergeCompilationDatabases(project, "${target}CompilationDatabase".toString(), [ CompilationDatabaseKt.mergeCompilationDatabases(project, "${target}CompilationDatabase".toString(), [
":common:${target}CompilationDatabase".toString(), ":kotlin-native::common:${target}CompilationDatabase".toString(),
":runtime:${target}CompilationDatabase".toString() ":kotlin-native:runtime:${target}CompilationDatabase".toString()
]).configure { ]).configure {
outputFile = file("$buildDir/${target}/compile_commands.json") outputFile = file("$buildDir/${target}/compile_commands.json")
} }
+5 -5
View File
@@ -14,7 +14,7 @@ import org.jetbrains.kotlin.konan.util.DependencyProcessor
import static org.jetbrains.kotlin.konan.util.VisibleNamedKt.getVisibleName import static org.jetbrains.kotlin.konan.util.VisibleNamedKt.getVisibleName
buildscript { buildscript {
apply from: "$rootDir/gradle/kotlinGradlePlugin.gradle" apply from: "$rootDir/kotlin-native/gradle/kotlinGradlePlugin.gradle"
repositories { repositories {
maven { maven {
@@ -33,7 +33,7 @@ class NativeDep extends DefaultTask {
KonanPropertiesLoader konanPropertiesLoader = null KonanPropertiesLoader konanPropertiesLoader = null
final File getBaseOutDir() { final File getBaseOutDir() {
final File res = project.rootProject.ext.dependenciesDir final File res = rootProject.project(":kotlin-native").ext.dependenciesDir
res.mkdirs() res.mkdirs()
return res return res
} }
@@ -75,7 +75,7 @@ enum DependencyKind {
String toString() { return name } String toString() { return name }
} }
def platformManager = rootProject.ext.platformManager def platformManager = rootProject.project(":kotlin-native").ext.platformManager
platformManager.enabled.each { target -> platformManager.enabled.each { target ->
@@ -87,7 +87,7 @@ platformManager.enabled.each { target ->
// Also resolves all dependencies: // Also resolves all dependencies:
final DependencyProcessor dependencyProcessor = new DependencyProcessor( final DependencyProcessor dependencyProcessor = new DependencyProcessor(
project.rootProject.ext.dependenciesDir, rootProject.project(":kotlin-native").ext.dependenciesDir,
loader.properties, loader.properties,
loader.dependencies, loader.dependencies,
NativeDep.baseUrl, NativeDep.baseUrl,
@@ -99,7 +99,7 @@ platformManager.enabled.each { target ->
def dir = kind.getDirectory(loader) def dir = kind.getDirectory(loader)
if (dir != null) { if (dir != null) {
String path = dependencyProcessor.resolve(dir).canonicalPath String path = dependencyProcessor.resolve(dir).canonicalPath
rootProject.ext.set(kind.getPropertyName(target), path) rootProject.project(":kotlin-native").ext.set(kind.getPropertyName(target), path)
} }
} }
} }
@@ -7,10 +7,6 @@ buildscript {
maven { url 'https://cache-redirector.jetbrains.com/jcenter' } maven { url 'https://cache-redirector.jetbrains.com/jcenter' }
jcenter() jcenter()
} }
dependencies {
classpath "org.jetbrains.kotlin:kotlin-native-gradle-plugin:$gradlePluginVersion"
}
} }
ext { ext {
@@ -8,13 +8,10 @@ buildscript {
} }
jcenter() jcenter()
maven { maven {
url kotlinCompilerRepo url project.bootstrapKotlinRepo
} }
} }
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
}
} }
apply plugin: 'kotlin-multiplatform' apply plugin: 'kotlin-multiplatform'
@@ -24,40 +21,34 @@ repositories {
url 'https://cache-redirector.jetbrains.com/jcenter' url 'https://cache-redirector.jetbrains.com/jcenter'
} }
jcenter() jcenter()
maven {
url kotlinCompilerRepo
}
maven {
url buildKotlinCompilerRepo
}
} }
kotlin { kotlin {
sourceSets { sourceSets {
commonMain { commonMain {
dependencies { dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-common:$kotlinVersion" implementation project(":kotlin-stdlib-common")
} }
kotlin.srcDir 'src/main/kotlin' kotlin.srcDir 'src/main/kotlin'
} }
commonTest { commonTest {
dependencies { dependencies {
implementation "org.jetbrains.kotlin:kotlin-test-common:$kotlinVersion" implementation project(":kotlin-test:kotlin-test-common")
implementation "org.jetbrains.kotlin:kotlin-test-annotations-common:$kotlinVersion" implementation project(":kotlin-test:kotlin-test-annotations-common")
} }
kotlin.srcDir 'src/tests' kotlin.srcDir 'src/tests'
} }
jvm().compilations.main.defaultSourceSet { jvm().compilations.main.defaultSourceSet {
dependencies { dependencies {
implementation kotlin('stdlib-jdk8') implementation project(":kotlin-stdlib-jdk8")
} }
kotlin.srcDir 'src/main/kotlin-jvm' kotlin.srcDir 'src/main/kotlin-jvm'
} }
// JVM-specific tests and their dependencies: // JVM-specific tests and their dependencies:
jvm().compilations.test.defaultSourceSet { jvm().compilations.test.defaultSourceSet {
dependencies { dependencies {
implementation kotlin('test-junit') implementation project(":kotlin-test:kotlin-test-junit")
} }
} }
@@ -80,7 +71,7 @@ targetList.each { target ->
if (target != "wasm32") defaultArgs += '-g' if (target != "wasm32") defaultArgs += '-g'
def konanArgs = [*defaultArgs, def konanArgs = [*defaultArgs,
'-target', target, '-target', target,
"-Xruntime=${project(':runtime').file('build/bitcode/main/' + target + '/runtime.bc')}", "-Xruntime=${project(':kotlin-native:runtime').file('build/bitcode/main/' + target + '/runtime.bc')}",
*project.globalBuildArgs] *project.globalBuildArgs]
task("${target}KotlinxCli", type: JavaExec) { task("${target}KotlinxCli", type: JavaExec) {
@@ -88,8 +79,8 @@ targetList.each { target ->
// See :endorsedLibraries.ext for full endorsedLibraries list. // See :endorsedLibraries.ext for full endorsedLibraries list.
def moduleName = endorsedLibraries[project].name def moduleName = endorsedLibraries[project].name
dependsOn ":distCompiler" dependsOn ":kotlin-native:distCompiler"
dependsOn ":${target}CrossDistRuntime" dependsOn ":kotlin-native:${target}CrossDistRuntime"
main = 'org.jetbrains.kotlin.cli.bc.K2NativeKt' main = 'org.jetbrains.kotlin.cli.bc.K2NativeKt'
// This task depends on distCompiler, so the compiler jar is already in the dist directory. // This task depends on distCompiler, so the compiler jar is already in the dist directory.
+1 -4
View File
@@ -43,7 +43,4 @@ shadowVersion=5.1.0
metadataVersion=0.0.1-dev-10 metadataVersion=0.0.1-dev-10
# Uncomment to compile Kotlin/Native backend modules with JVM IR backend. # Uncomment to compile Kotlin/Native backend modules with JVM IR backend.
# kotlin.build.useIR=true # kotlin.build.useIR=true
# Uncomment to enable composite build
kotlinProjectPath=..
+3 -20
View File
@@ -1,17 +1,6 @@
def properties = ['buildKotlinVersion', 'buildKotlinCompilerRepo', 'kotlinVersion', 'kotlinCompilerRepo']
for (prop in properties) {
if (!hasProperty(prop)) {
throw new GradleException("Please ensure the '$prop' property is defined before applying this script.")
}
}
project.buildscript.repositories { project.buildscript.repositories {
maven { maven {
url buildKotlinCompilerRepo url project.bootstrapKotlinRepo
}
maven {
url kotlinCompilerRepo
} }
maven { maven {
url 'https://cache-redirector.jetbrains.com/maven-central' url 'https://cache-redirector.jetbrains.com/maven-central'
@@ -20,18 +9,12 @@ project.buildscript.repositories {
} }
project.buildscript.dependencies { project.buildscript.dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion" classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${project.bootstrapKotlinVersion}"
} }
configurations { configurations {
kotlinCompilerClasspath kotlinCompilerClasspath
} }
project.repositories {
maven { url buildKotlinCompilerRepo }
maven {
url kotlinCompilerRepo
}
}
project.dependencies { project.dependencies {
kotlinCompilerClasspath("org.jetbrains.kotlin:kotlin-compiler-embeddable:$buildKotlinVersion") kotlinCompilerClasspath(project(":kotlin-compiler-embeddable"))
} }
+5 -9
View File
@@ -3,10 +3,7 @@
* that can be found in the LICENSE file. * that can be found in the LICENSE file.
*/ */
buildscript { buildscript {
apply from: "$rootDir/gradle/kotlinGradlePlugin.gradle" apply from: "$rootDir/kotlin-native/gradle/kotlinGradlePlugin.gradle"
dependencies {
classpath "org.jetbrains.kotlin:kotlin-native-gradle-plugin:$gradlePluginVersion"
}
ext.useCustomDist = project.hasProperty("org.jetbrains.kotlin.native.home") || project.hasProperty("konan.home") ext.useCustomDist = project.hasProperty("org.jetbrains.kotlin.native.home") || project.hasProperty("konan.home")
if (!useCustomDist) { if (!useCustomDist) {
@@ -48,12 +45,11 @@ repositories {
} }
dependencies { dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion" implementation project(":kotlin-stdlib")
implementation project(path: ':backend.native', configuration: 'cli_bc') implementation project(path: ':kotlin-native:backend.native', configuration: 'cli_bc')
implementation project(":utilities:basic-utils") implementation project(":kotlin-native:utilities:basic-utils")
testImplementation "junit:junit:4.12" testImplementation "junit:junit:4.12"
testImplementation "org.jetbrains.kotlin:kotlin-test-junit:$buildKotlinVersion" testImplementation project(":kotlin-test:kotlin-test-junit")
testImplementation "org.jetbrains.kotlin:kotlin-test:$buildKotlinVersion"
} }
test { test {
+1 -2
View File
@@ -22,8 +22,7 @@ buildscript {
apply from: "$rootBuildDirectory/gradle/kotlinGradlePlugin.gradle" apply from: "$rootBuildDirectory/gradle/kotlinGradlePlugin.gradle"
dependencies { dependencies {
classpath "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion" classpath "org.jetbrains.kotlin:kotlin-stdlib:${project.bootstrapKotlinVersion}"
classpath "org.jetbrains.kotlin:kotlin-native-shared:$konanVersion"
} }
} }
import org.jetbrains.kotlin.konan.target.ClangArgs import org.jetbrains.kotlin.konan.target.ClangArgs
@@ -23,8 +23,7 @@ buildscript {
apply from: "$rootBuildDirectory/gradle/kotlinGradlePlugin.gradle" apply from: "$rootBuildDirectory/gradle/kotlinGradlePlugin.gradle"
dependencies { dependencies {
classpath "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion" classpath "org.jetbrains.kotlin:kotlin-stdlib:${project.bootstrapKotlinVersion}"
classpath "org.jetbrains.kotlin:kotlin-native-shared:$konanVersion"
} }
} }
import org.jetbrains.kotlin.konan.target.ClangArgs import org.jetbrains.kotlin.konan.target.ClangArgs
+1 -2
View File
@@ -23,8 +23,7 @@ buildscript {
apply from: "$rootBuildDirectory/gradle/kotlinGradlePlugin.gradle" apply from: "$rootBuildDirectory/gradle/kotlinGradlePlugin.gradle"
dependencies { dependencies {
classpath "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion" classpath "org.jetbrains.kotlin:kotlin-stdlib:${project.bootstrapKotlinVersion}"
classpath "org.jetbrains.kotlin:kotlin-native-shared:$konanVersion"
} }
} }
import org.jetbrains.kotlin.konan.target.ClangArgs import org.jetbrains.kotlin.konan.target.ClangArgs
+2 -10
View File
@@ -12,20 +12,12 @@ buildscript {
} }
mavenCentral() mavenCentral()
maven { maven {
url buildKotlinCompilerRepo url project.bootstrapKotlinRepo
}
maven {
url kotlinCompilerRepo
} }
maven { maven {
url "https://kotlin.bintray.com/kotlinx" url "https://kotlin.bintray.com/kotlinx"
} }
} }
dependencies {
classpath "org.jetbrains.kotlin:kotlin-native-gradle-plugin:$gradlePluginVersion"
classpath "org.jetbrains.kotlin:kotlin-native-build-tools:$konanVersion"
}
} }
// These properties are used by the 'konan' plugin, thus we set them before applying it. // These properties are used by the 'konan' plugin, thus we set them before applying it.
ext.konanHome = distDir.absolutePath ext.konanHome = distDir.absolutePath
@@ -54,7 +46,7 @@ private String defFileToLibName(String target, String name) {
// TODO: I think most for the non-DSL language below can either be incorporated into DSL // TODO: I think most for the non-DSL language below can either be incorporated into DSL
// or moved out of .gradle file. // or moved out of .gradle file.
project.rootProject.ext.platformManager.enabled.each { target -> rootProject.project("kotlin-native").ext.platformManager.enabled.each { target ->
def targetName = target.visibleName def targetName = target.visibleName
-60
View File
@@ -1,60 +0,0 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
include ':dependencies'
include ':Interop:Indexer'
include ':Interop:JsRuntime'
include ':Interop:StubGenerator'
include ':Interop:Runtime'
include ':llvmCoverageMappingC'
include ':llvmDebugInfoC'
include ':libclangext'
include ':klib'
include ':backend.native'
include ':runtime'
include ':common'
include ':backend.native:tests'
include ':backend.native:debugger-tests'
include ':utilities:basic-utils'
include ':utilities:cli-runner'
include ':dependencyPacker'
include ':platformLibs'
include ':endorsedLibraries'
include ':endorsedLibraries:kotlinx.cli'
if (hasProperty("kotlinProjectPath")) {
include ':runtime:generator'
includeBuild(kotlinProjectPath) {
dependencySubstitution {
substitute module("org.jetbrains.kotlin:kotlin-compiler:$kotlinVersion") with project(':include:kotlin-compiler')
substitute module("org.jetbrains.kotlin:kotlin-stdlib-common:$kotlinStdlibVersion") with project(':include:kotlin-stdlib-common-sources')
substitute module("org.jetbrains.kotlin:kotlin-stdlib-gen:$kotlinStdlibVersion") with project(':tools:kotlin-stdlib-gen')
substitute module("org.jetbrains.kotlin:kotlin-util-io:$kotlinVersion") with project(':kotlin-util-io')
substitute module("org.jetbrains.kotlin:kotlin-util-klib:$kotlinVersion") with project(':kotlin-util-klib')
substitute module("org.jetbrains.kotlin:kotlin-util-klib-metadata:$kotlinVersion") with project(':kotlin-util-klib-metadata')
substitute module("org.jetbrains.kotlin:kotlin-native-utils:$kotlinVersion") with project(':native:kotlin-native-utils')
substitute module("org.jetbrains.kotlin:kotlin-reflect:$kotlinVersion") with project(':kotlin-reflect')
substitute module("org.jetbrains.kotlinx:kotlinx-metadata-klib") with project(':kotlinx-metadata-klib')
}
}
}
includeBuild 'shared'
includeBuild 'build-tools'
includeBuild 'tools/kotlin-native-gradle-plugin'
@@ -285,7 +285,7 @@ class MacOSBasedLinker(targetProperties: AppleConfigurables)
else -> error(target) else -> error(target)
}, },
"@loader_path/Frameworks".takeIf { dynamic }, "@loader_path/Frameworks".takeIf { dynamic },
compilerRtDir.takeIf { sanitizer != null }, compilerRtDir.takeIf { sanitizer != null }
).flatMap { listOf("-rpath", it) } ).flatMap { listOf("-rpath", it) }
fun dsymUtilCommand(executable: ExecutableFile, outputDsymBundle: String) = fun dsymUtilCommand(executable: ExecutableFile, outputDsymBundle: String) =
@@ -36,7 +36,7 @@ open class KonanArtifactContainer(val project: ProjectInternal)
var targets: Iterable<String> = emptyList() var targets: Iterable<String> = emptyList()
override fun create(name: String?): T = override fun create(name: String): T =
instantiator.newInstance(configClass.java, name, project, targets) instantiator.newInstance(configClass.java, name, project, targets)
} }
@@ -117,20 +117,20 @@ abstract class KonanBuildingConfig<T : KonanBuildingTask>(
private fun createTask(target: KonanTarget): TaskProvider<T> = private fun createTask(target: KonanTarget): TaskProvider<T> =
project.tasks.register(generateTaskName(target), type) { project.tasks.register(generateTaskName(target), type) {
val outputDescription = determineOutputPlacement(target) val outputDescription = determineOutputPlacement(target)
it.init(this, outputDescription.destinationDir, outputDescription.artifactName, target) init(this@KonanBuildingConfig, outputDescription.destinationDir, outputDescription.artifactName, target)
it.group = BasePlugin.BUILD_GROUP group = BasePlugin.BUILD_GROUP
it.description = generateTaskDescription(it) description = generateTaskDescription(this)
} ?: throw Exception("Cannot create task for target: ${target.visibleName}") } ?: throw Exception("Cannot create task for target: ${target.visibleName}")
private fun createAggregateTask(): TaskProvider<Task> = private fun createAggregateTask(): TaskProvider<Task> =
project.tasks.register(generateAggregateTaskName()) { task -> project.tasks.register(generateAggregateTaskName()) {
task.group = BasePlugin.BUILD_GROUP group = BasePlugin.BUILD_GROUP
task.description = generateAggregateTaskDescription(task) description = generateAggregateTaskDescription(this)
targetToTask.filter { targetToTask.filter {
project.targetIsRequested(it.key) project.targetIsRequested(it.key)
}.forEach { }.forEach {
task.dependsOn(it.value) dependsOn(it.value)
} }
}.also { }.also {
project.compileAllTask.dependsOn(it) project.compileAllTask.dependsOn(it)
@@ -141,9 +141,9 @@ abstract class KonanBuildingConfig<T : KonanBuildingTask>(
return this[canonicalTarget]?.let { canonicalBuild -> return this[canonicalTarget]?.let { canonicalBuild ->
project.tasks.register(generateTargetAliasTaskName(targetName)) { project.tasks.register(generateTargetAliasTaskName(targetName)) {
it.group = BasePlugin.BUILD_GROUP group = BasePlugin.BUILD_GROUP
it.description = generateTargetAliasTaskDescription(it, targetName) description = generateTargetAliasTaskDescription(this, targetName)
it.dependsOn(canonicalBuild) dependsOn(canonicalBuild)
} }
} }
} }
@@ -160,43 +160,43 @@ abstract class KonanBuildingConfig<T : KonanBuildingTask>(
// Common building DSL. // Common building DSL.
override fun artifactName(name: String) = tasks().forEach { it.configure { t -> t.artifactName(name) } } override fun artifactName(name: String) = tasks().forEach { it.configure { artifactName(name) } }
fun baseDir(dir: Any) = fun baseDir(dir: Any) =
tasks().forEach { tasks().forEach {
it.configure { t -> it.configure {
t.destinationDir( destinationDir(
project.file(dir).targetSubdir(t.konanTarget) project.file(dir).targetSubdir(konanTarget)
) )
} }
} }
override fun libraries(closure: Closure<Unit>) = override fun libraries(closure: Closure<Unit>) =
tasks().forEach { it.configure { t -> t.libraries(closure) } } tasks().forEach { it.configure { libraries(closure) } }
override fun libraries(action: Action<KonanLibrariesSpec>) = override fun libraries(action: Action<KonanLibrariesSpec>) =
tasks().forEach { it.configure { t -> t.libraries(action) } } tasks().forEach { it.configure { libraries(action) } }
override fun libraries(configure: KonanLibrariesSpec.() -> Unit) = override fun libraries(configure: KonanLibrariesSpec.() -> Unit) =
tasks().forEach { it.configure { t -> t.libraries(configure) } } tasks().forEach { it.configure { libraries(configure) } }
override fun noDefaultLibs(flag: Boolean) = override fun noDefaultLibs(flag: Boolean) =
tasks().forEach { it.configure { t -> t.noDefaultLibs(flag) } } tasks().forEach { it.configure { noDefaultLibs(flag) } }
override fun noEndorsedLibs(flag: Boolean) = override fun noEndorsedLibs(flag: Boolean) =
tasks().forEach { it.configure { t -> t.noEndorsedLibs(flag) } } tasks().forEach { it.configure { noEndorsedLibs(flag) } }
override fun dumpParameters(flag: Boolean) = override fun dumpParameters(flag: Boolean) =
tasks().forEach { it.configure { t -> t.dumpParameters(flag) } } tasks().forEach { it.configure { dumpParameters(flag) } }
override fun extraOpts(vararg values: Any) = override fun extraOpts(vararg values: Any) =
tasks().forEach { it.configure { t -> t.extraOpts(*values) } } tasks().forEach { it.configure { extraOpts(*values) } }
override fun extraOpts(values: List<Any>) = override fun extraOpts(values: List<Any>) =
tasks().forEach { it.configure { t -> t.extraOpts(values) } } tasks().forEach { it.configure { extraOpts(values) } }
fun dependsOn(vararg dependencies: Any?) = fun dependsOn(vararg dependencies: Any?) =
tasks().forEach { it.configure { t -> t.dependsOn(*dependencies) } } tasks().forEach { it.configure { dependsOn(*dependencies) } }
fun target(targetString: String, configureAction: T.() -> Unit) { fun target(targetString: String, configureAction: T.() -> Unit) {
val target = project.hostManager.targetByName(targetString) val target = project.hostManager.targetByName(targetString)
@@ -43,33 +43,33 @@ abstract class KonanCompileConfig<T: KonanCompileTask>(name: String,
override fun generateTargetAliasTaskDescription(task: Task, targetName: String) = override fun generateTargetAliasTaskDescription(task: Task, targetName: String) =
"Build the Kotlin/Native $typeForDescription '${task.name}' for target '$targetName'" "Build the Kotlin/Native $typeForDescription '${task.name}' for target '$targetName'"
override fun srcDir(dir: Any) = tasks().forEach { it.configure { t -> t.srcDir(dir) } } override fun srcDir(dir: Any) = tasks().forEach { it.configure { srcDir(dir) } }
override fun srcFiles(vararg files: Any) = tasks().forEach { it.configure { t -> t.srcFiles(*files) } } override fun srcFiles(vararg files: Any) = tasks().forEach { it.configure { srcFiles(*files) } }
override fun srcFiles(files: Collection<Any>) = tasks().forEach { it.configure { t -> t.srcFiles(files) } } override fun srcFiles(files: Collection<Any>) = tasks().forEach { it.configure { srcFiles(files) } }
override fun nativeLibrary(lib: Any) = tasks().forEach { it.configure { t -> t.nativeLibrary(lib) } } override fun nativeLibrary(lib: Any) = tasks().forEach { it.configure { nativeLibrary(lib) } }
override fun nativeLibraries(vararg libs: Any) = tasks().forEach { it.configure { t -> t.nativeLibraries(*libs) } } override fun nativeLibraries(vararg libs: Any) = tasks().forEach { it.configure { nativeLibraries(*libs) } }
override fun nativeLibraries(libs: FileCollection) = tasks().forEach { it.configure { t -> t.nativeLibraries(libs) } } override fun nativeLibraries(libs: FileCollection) = tasks().forEach { it.configure { nativeLibraries(libs) } }
@Deprecated("Use commonSourceSets instead", ReplaceWith("commonSourceSets(sourceSetName)")) @Deprecated("Use commonSourceSets instead", ReplaceWith("commonSourceSets(sourceSetName)"))
override fun commonSourceSet(sourceSetName: String) = tasks().forEach { it.configure { t -> t.commonSourceSets(sourceSetName) } } override fun commonSourceSet(sourceSetName: String) = tasks().forEach { it.configure { commonSourceSets(sourceSetName) } }
override fun commonSourceSets(vararg sourceSetNames: String) = tasks().forEach { it.configure { t -> t.commonSourceSets(*sourceSetNames) } } override fun commonSourceSets(vararg sourceSetNames: String) = tasks().forEach { it.configure { commonSourceSets(*sourceSetNames) } }
override fun enableMultiplatform(flag: Boolean) = tasks().forEach { it.configure { t -> t.enableMultiplatform(flag) } } override fun enableMultiplatform(flag: Boolean) = tasks().forEach { it.configure { enableMultiplatform(flag) } }
override fun linkerOpts(values: List<String>) = tasks().forEach { it.configure { t -> t.linkerOpts(values) } } override fun linkerOpts(values: List<String>) = tasks().forEach { it.configure { linkerOpts(values) } }
override fun linkerOpts(vararg values: String) = tasks().forEach { it.configure { t -> t.linkerOpts(*values) } } override fun linkerOpts(vararg values: String) = tasks().forEach { it.configure { linkerOpts(*values) } }
override fun enableDebug(flag: Boolean) = tasks().forEach { it.configure { t -> t.enableDebug(flag) } } override fun enableDebug(flag: Boolean) = tasks().forEach { it.configure { enableDebug(flag) } }
override fun noStdLib(flag: Boolean) = tasks().forEach { it.configure { t -> t.noStdLib(flag) } } override fun noStdLib(flag: Boolean) = tasks().forEach { it.configure { noStdLib(flag) } }
override fun noMain(flag: Boolean) = tasks().forEach { it.configure { t -> t.noMain(flag) } } override fun noMain(flag: Boolean) = tasks().forEach { it.configure { noMain(flag) } }
override fun enableOptimizations(flag: Boolean) = tasks().forEach { it.configure { t -> t.enableOptimizations(flag) } } override fun enableOptimizations(flag: Boolean) = tasks().forEach { it.configure { enableOptimizations(flag) } }
override fun enableAssertions(flag: Boolean) = tasks().forEach { it.configure { t -> t.enableAssertions(flag) } } override fun enableAssertions(flag: Boolean) = tasks().forEach { it.configure { enableAssertions(flag) } }
override fun entryPoint(entryPoint: String) = tasks().forEach { it.configure { t -> t.entryPoint(entryPoint) } } override fun entryPoint(entryPoint: String) = tasks().forEach { it.configure { entryPoint(entryPoint) } }
override fun measureTime(flag: Boolean) = tasks().forEach { it.configure { t -> t.measureTime(flag) } } override fun measureTime(flag: Boolean) = tasks().forEach { it.configure { measureTime(flag) } }
override fun dependencies(closure: Closure<Unit>) = tasks().forEach { it.configure { t -> t.dependencies(closure) } } override fun dependencies(closure: Closure<Unit>) = tasks().forEach { it.configure { dependencies(closure) } }
} }
open class KonanProgram(name: String, open class KonanProgram(name: String,
@@ -50,36 +50,36 @@ open class KonanInteropLibrary(name: String,
inner class IncludeDirectoriesSpecImpl: IncludeDirectoriesSpec { inner class IncludeDirectoriesSpecImpl: IncludeDirectoriesSpec {
override fun allHeaders(vararg includeDirs: Any) = allHeaders(includeDirs.toList()) override fun allHeaders(vararg includeDirs: Any) = allHeaders(includeDirs.toList())
override fun allHeaders(includeDirs: Collection<Any>) = tasks().forEach { override fun allHeaders(includeDirs: Collection<Any>) = tasks().forEach {
it.configure { t -> t.includeDirs.allHeaders(includeDirs) } it.configure { this@configure.includeDirs.allHeaders(includeDirs) }
} }
override fun headerFilterOnly(vararg includeDirs: Any) = headerFilterOnly(includeDirs.toList()) override fun headerFilterOnly(vararg includeDirs: Any) = headerFilterOnly(includeDirs.toList())
override fun headerFilterOnly(includeDirs: Collection<Any>) = tasks().forEach { override fun headerFilterOnly(includeDirs: Collection<Any>) = tasks().forEach {
it.configure { t -> t.includeDirs.headerFilterOnly(includeDirs) } it.configure { this@configure.includeDirs.headerFilterOnly(includeDirs) }
} }
} }
val includeDirs = IncludeDirectoriesSpecImpl() val includeDirs = IncludeDirectoriesSpecImpl()
override fun defFile(file: Any) = tasks().forEach { it.configure { t -> t.defFile(file) } } override fun defFile(file: Any) = tasks().forEach { it.configure { defFile(file) } }
override fun packageName(value: String) = tasks().forEach { it.configure { t -> t.packageName(value) } } override fun packageName(value: String) = tasks().forEach { it.configure { packageName(value) } }
override fun compilerOpts(vararg values: String) = tasks().forEach { it.configure { t -> t.compilerOpts(*values) } } override fun compilerOpts(vararg values: String) = tasks().forEach { it.configure { compilerOpts(*values) } }
override fun headers(vararg files: Any) = tasks().forEach { it.configure { t -> t.headers(*files) } } override fun headers(vararg files: Any) = tasks().forEach { it.configure { headers(*files) } }
override fun headers(files: FileCollection) = tasks().forEach { it.configure { t -> t.headers(files) } } override fun headers(files: FileCollection) = tasks().forEach { it.configure { headers(files) } }
override fun includeDirs(vararg values: Any) = tasks().forEach { it.configure { t -> t.includeDirs(*values) } } override fun includeDirs(vararg values: Any) = tasks().forEach { it.configure { includeDirs(*values) } }
override fun includeDirs(closure: Closure<Unit>) = includeDirs(ConfigureUtil.configureUsing(closure)) override fun includeDirs(closure: Closure<Unit>) = includeDirs(ConfigureUtil.configureUsing(closure))
override fun includeDirs(action: Action<IncludeDirectoriesSpec>) = includeDirs { action.execute(this) } override fun includeDirs(action: Action<IncludeDirectoriesSpec>) = includeDirs { action.execute(this) }
override fun includeDirs(configure: IncludeDirectoriesSpec.() -> Unit) = includeDirs.configure() override fun includeDirs(configure: IncludeDirectoriesSpec.() -> Unit) = includeDirs.configure()
override fun linkerOpts(values: List<String>) = tasks().forEach { it.configure { t -> t.linkerOpts(values) } } override fun linkerOpts(values: List<String>) = tasks().forEach { it.configure { linkerOpts(values) } }
override fun linkerOpts(vararg values: String) = linkerOpts(values.toList()) override fun linkerOpts(vararg values: String) = linkerOpts(values.toList())
override fun link(vararg files: Any) = tasks().forEach { it.configure { t -> t.link(*files) } } override fun link(vararg files: Any) = tasks().forEach { it.configure { link(*files) } }
override fun link(files: FileCollection) = tasks().forEach { it.configure { t -> t.link(files) } } override fun link(files: FileCollection) = tasks().forEach { it.configure { link(files) } }
override fun dependencies(closure: Closure<Unit>) = tasks().forEach { it.configure { t -> t.dependencies(closure) }} override fun dependencies(closure: Closure<Unit>) = tasks().forEach { it.configure { dependencies(closure) }}
} }
@@ -327,7 +327,7 @@ class KonanPlugin @Inject constructor(private val registry: ToolingModelBuilderR
} }
override fun apply(project: ProjectInternal?) { override fun apply(project: ProjectInternal) {
if (project == null) { if (project == null) {
return return
} }
@@ -370,16 +370,16 @@ class KonanPlugin @Inject constructor(private val registry: ToolingModelBuilderR
val isCrossCompile = (task.target != HostManager.host.visibleName) val isCrossCompile = (task.target != HostManager.host.visibleName)
if (!isCrossCompile && !project.hasProperty("konanNoRun")) if (!isCrossCompile && !project.hasProperty("konanNoRun"))
task.runTask = project.tasks.register("run${task.artifactName.capitalize()}", Exec::class.java) { task.runTask = project.tasks.register("run${task.artifactName.capitalize()}", Exec::class.java) {
it.group= "run" group= "run"
it.dependsOn(task) dependsOn(task)
val artifactPathClosure = object : Closure<String>(this) { val artifactPathClosure = object : Closure<String>(this) {
override fun call() = task.artifactPath override fun call() = task.artifactPath
} }
// Use GString to evaluate a path to the artifact lazily thus allow changing it at configuration phase. // Use GString to evaluate a path to the artifact lazily thus allow changing it at configuration phase.
val lazyArtifactPath = GStringImpl(arrayOf(artifactPathClosure), arrayOf("")) val lazyArtifactPath = GStringImpl(arrayOf(artifactPathClosure), arrayOf(""))
it.executable(lazyArtifactPath) executable(lazyArtifactPath)
// Add values passed in the runArgs project property as arguments. // Add values passed in the runArgs project property as arguments.
it.argumentProviders.add(task.RunArgumentProvider()) argumentProviders.add(task.RunArgumentProvider())
} }
} }
} }
@@ -390,7 +390,7 @@ class KonanPlugin @Inject constructor(private val registry: ToolingModelBuilderR
.filterIsInstance(KonanProgram::class.java) .filterIsInstance(KonanProgram::class.java)
.forEach { program -> .forEach { program ->
program.tasks().forEach { compile -> program.tasks().forEach { compile ->
compile.configure { it.runTask?.let { runTask.dependsOn(it) } } compile.configure { runTask?.let { runTask.dependsOn(it) } }
} }
} }
} }
@@ -403,7 +403,7 @@ class KonanPlugin @Inject constructor(private val registry: ToolingModelBuilderR
val konanSoftwareComponent = buildingConfig.mainVariant val konanSoftwareComponent = buildingConfig.mainVariant
project.extensions.configure(PublishingExtension::class.java) { project.extensions.configure(PublishingExtension::class.java) {
val builtArtifact = buildingConfig.name val builtArtifact = buildingConfig.name
val mavenPublication = it.publications.maybeCreate(builtArtifact, MavenPublication::class.java) val mavenPublication = publications.maybeCreate(builtArtifact, MavenPublication::class.java)
mavenPublication.apply { mavenPublication.apply {
artifactId = builtArtifact artifactId = builtArtifact
groupId = project.group.toString() groupId = project.group.toString()
@@ -416,22 +416,22 @@ class KonanPlugin @Inject constructor(private val registry: ToolingModelBuilderR
} }
project.extensions.configure(PublishingExtension::class.java) { project.extensions.configure(PublishingExtension::class.java) {
val publishing = it
for (v in konanSoftwareComponent.variants) { for (v in konanSoftwareComponent.variants) {
publishing.publications.create(v.name, MavenPublication::class.java) { mavenPublication -> this@configure.publications.create(v.name, MavenPublication::class.java) {
val coordinates = (v as NativeVariantIdentity).coordinates val coordinates = (v as NativeVariantIdentity).coordinates
project.logger.info("variant with coordinates($coordinates) and module: ${coordinates.module}") project.logger.info("variant with coordinates($coordinates) and module: ${coordinates.module}")
mavenPublication.artifactId = coordinates.module.name artifactId = coordinates.module.name
mavenPublication.groupId = coordinates.group groupId = coordinates.group
mavenPublication.version = coordinates.version version = coordinates.version
mavenPublication.from(v) from(v)
(mavenPublication as MavenPublicationInternal).publishWithOriginalFileName() (this as MavenPublicationInternal).publishWithOriginalFileName()
buildingConfig.pomActions.forEach { buildingConfig.pomActions.forEach {
mavenPublication.pom(it) pom(it)
} }
} }
} }
} }
true
} }
} }
} }
@@ -91,20 +91,20 @@ internal abstract class KonanCliRunner(
"Please change it to the compiler root directory and rerun the build.") "Please change it to the compiler root directory and rerun the build.")
} }
project.javaexec { spec -> project.javaexec {
spec.main = mainClass main = this@KonanCliRunner.mainClass
spec.classpath = classpath classpath = classpath
spec.jvmArgs(jvmArgs) jvmArgs(jvmArgs)
spec.systemProperties( systemProperties(
System.getProperties().asSequence() System.getProperties().asSequence()
.map { (k, v) -> k.toString() to v.toString() } .map { (k, v) -> k.toString() to v.toString() }
.filter { (k, _) -> k !in blacklistProperties } .filter { (k, _) -> k !in blacklistProperties }
.escapeQuotesForWindows() .escapeQuotesForWindows()
.toMap() .toMap()
) )
spec.args(listOf(toolName) + transformArgs(args)) args(listOf(toolName) + transformArgs(args))
blacklistEnvironment.forEach { spec.environment.remove(it) } blacklistEnvironment.forEach { environment.remove(it) }
spec.environment(environment) environment(environment)
} }
} }
} }
@@ -97,11 +97,11 @@ abstract class KonanArtifactTask: KonanTargetableTask(), KonanArtifactSpec {
platformConfiguration = project.configurations.create("artifact${artifactName}_${target.name}") platformConfiguration = project.configurations.create("artifact${artifactName}_${target.name}")
platformConfiguration.extendsFrom(configuration) platformConfiguration.extendsFrom(configuration)
platformConfiguration.attributes{ platformConfiguration.attributes{
it.attribute(Usage.USAGE_ATTRIBUTE, project.objects.named(Usage::class.java, Usage.NATIVE_LINK)) attribute(Usage.USAGE_ATTRIBUTE, project.objects.named(Usage::class.java, Usage.NATIVE_LINK))
it.attribute(CppBinary.LINKAGE_ATTRIBUTE, Linkage.STATIC) attribute(CppBinary.LINKAGE_ATTRIBUTE, Linkage.STATIC)
it.attribute(CppBinary.OPTIMIZED_ATTRIBUTE, false) attribute(CppBinary.OPTIMIZED_ATTRIBUTE, false)
it.attribute(CppBinary.DEBUGGABLE_ATTRIBUTE, false) attribute(CppBinary.DEBUGGABLE_ATTRIBUTE, false)
it.attribute(Attribute.of("org.gradle.native.kotlin.platform", String::class.java), target.name) attribute(Attribute.of("org.gradle.native.kotlin.platform", String::class.java), target.name)
} }
val artifactNameWithoutSuffix = artifact.name.removeSuffix("$artifactSuffix") val artifactNameWithoutSuffix = artifact.name.removeSuffix("$artifactSuffix")
@@ -190,8 +190,8 @@ open class KonanInteropTask @Inject constructor(@Internal val workerExecutor: Wo
val workQueue = workerExecutor.noIsolation() val workQueue = workerExecutor.noIsolation()
interchangeBox[this.path] = toolRunner interchangeBox[this.path] = toolRunner
workQueue.submit(RunTool::class.java) { workQueue.submit(RunTool::class.java) {
it.taskName = this.path taskName = path
it.args = args this.args = args
} }
} else { } else {
toolRunner.run(args) toolRunner.run(args)
@@ -6,7 +6,7 @@
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
buildscript { buildscript {
apply(from = "$rootDir/gradle/kotlinGradlePlugin.gradle") apply(from = "$rootDir/kotlin-native/gradle/kotlinGradlePlugin.gradle")
} }
plugins { plugins {
@@ -19,11 +19,7 @@ tasks.named<KotlinCompile>("compileKotlin") {
} }
} }
// Convert to normal strings since originally these properties contain GStrings.
val kotlinCompilerModule = rootProject.ext["kotlinCompilerModule"].toString()
val kotlinStdLibModule = rootProject.ext["kotlinStdLibModule"].toString()
dependencies { dependencies {
api(kotlinStdLibModule) api(project(":kotlin-stdlib"))
implementation(kotlinCompilerModule) implementation(project(":kotlin-compiler"))
} }
@@ -3,17 +3,11 @@
* that can be found in the LICENSE file. * that can be found in the LICENSE file.
*/ */
buildscript { buildscript {
apply from: "$rootDir/gradle/kotlinGradlePlugin.gradle" apply from: "$rootDir/kotlin-native/gradle/kotlinGradlePlugin.gradle"
} }
apply plugin: 'kotlin' apply plugin: 'kotlin'
repositories {
maven {
url buildKotlinCompilerRepo
}
}
compileKotlin { compileKotlin {
kotlinOptions { kotlinOptions {
freeCompilerArgs = ['-Xskip-metadata-version-check'] freeCompilerArgs = ['-Xskip-metadata-version-check']
@@ -22,9 +16,10 @@ compileKotlin {
dependencies { dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion" implementation project(":kotlin-stdlib")
implementation project(':backend.native') implementation project(":kotlin-stdlib-common")
implementation project(':Interop:StubGenerator') implementation project(':kotlin-native:backend.native')
implementation project(':klib') implementation project(':kotlin-native:Interop:StubGenerator')
implementation project(":utilities:basic-utils") implementation project(':kotlin-native:klib')
implementation project(":kotlin-native:utilities:basic-utils")
} }
+18
View File
@@ -581,3 +581,21 @@ project(':kotlin-serialization-unshaded').projectDir = file("$rootDir/libraries/
// Uncomment to use locally built protobuf-relocated // Uncomment to use locally built protobuf-relocated
// includeBuild("dependencies/protobuf") // includeBuild("dependencies/protobuf")
include ':kotlin-native:dependencies'
include ':kotlin-native:endorsedLibraries:kotlinx.cli'
include ':kotlin-native:endorsedLibraries'
include ':kotlin-native:Interop:StubGenerator'
include ':kotlin-native:backend.native'
include ':kotlin-native:Interop:Runtime'
include ':kotlin-native:Interop:Indexer'
include ':kotlin-native:Interop:JsRuntime'
include ':kotlin-native:utilities:basic-utils'
include ':kotlin-native:utilities:cli-runner'
include ':kotlin-native:klib'
include ':kotlin-native:common'
include ':kotlin-native:runtime'
include ':kotlin-native:llvmCoverageMappingC'
include ':kotlin-native:llvmDebugInfoC'
include ':kotlin-native:utilities'
include ':kotlin-native:platformLibs'
include ':kotlin-native:libclangext'