Merge commits from both masters to 1.4.30-dev-3009 compiler
Kotlin/Native base commit: b4d5f092a138b9aed2f459e44774c5c0ef18cca7
Kotlin base commit: 926dc085da
This commit is contained in:
Generated
+1
-1
@@ -101,4 +101,4 @@
|
||||
<option name="ALIGN_MULTILINE_PARAMETERS_IN_CALLS" value="true" />
|
||||
</codeStyleSettings>
|
||||
</code_scheme>
|
||||
</component>
|
||||
</component>
|
||||
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
<component name="ProjectDictionaryState">
|
||||
<dictionary name="svyatoslav.kuzmich">
|
||||
<words>
|
||||
<w>anyfunc</w>
|
||||
<w>copysign</w>
|
||||
<w>eqref</w>
|
||||
<w>exnref</w>
|
||||
<w>externref</w>
|
||||
<w>funcref</w>
|
||||
<w>jetbrains</w>
|
||||
<w>kotlinx</w>
|
||||
<w>ktor</w>
|
||||
<w>optref</w>
|
||||
<w>popcnt</w>
|
||||
<w>rotl</w>
|
||||
<w>rotr</w>
|
||||
<w>simd</w>
|
||||
<w>sqrt</w>
|
||||
<w>testsuite</w>
|
||||
<w>uninstantiable</w>
|
||||
<w>unlinkable</w>
|
||||
<w>vtable</w>
|
||||
<w>wabt</w>
|
||||
<w>xopt</w>
|
||||
</words>
|
||||
</dictionary>
|
||||
</component>
|
||||
+1
-1
@@ -453,4 +453,4 @@
|
||||
<option name="ignoreNonEmtpyLoops" value="false" />
|
||||
</inspection_tool>
|
||||
</profile>
|
||||
</component>
|
||||
</component>
|
||||
|
||||
@@ -40,9 +40,7 @@ dependencies {
|
||||
compile(project(":compiler:cli"))
|
||||
compile(intellijCoreDep()) { includeJars("intellij-core") }
|
||||
compile(jpsStandalone()) { includeJars("jps-model") }
|
||||
Platform[192].orHigher {
|
||||
compile(intellijPluginDep("java"))
|
||||
}
|
||||
compile(intellijPluginDep("java"))
|
||||
compile(intellijDep()) { includeIntellijCoreJarDependencies(project) }
|
||||
compile("org.jetbrains.kotlinx:kotlinx.benchmark.runtime-jvm:$benchmarks_version")
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+5
-4
@@ -3,9 +3,10 @@
|
||||
* 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.findUsages
|
||||
package org.jetbrains.kotlin.build
|
||||
|
||||
import com.intellij.util.Processor
|
||||
import java.io.Serializable
|
||||
|
||||
// FIX ME WHEN BUNCH 193 REMOVED
|
||||
typealias ProcessorInCompat<T> = Processor<T>
|
||||
enum class ExecutionStrategy : Serializable {
|
||||
DAEMON, IN_PROCESS, OUT_OF_PROCESS
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
/*
|
||||
* 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.build.report
|
||||
|
||||
import org.jetbrains.kotlin.build.report.metrics.BuildMetricsReporter
|
||||
import org.jetbrains.kotlin.build.report.metrics.RemoteBuildMetricsReporter
|
||||
|
||||
open class BuildReporter(
|
||||
protected open val icReporter: ICReporter,
|
||||
protected open val buildMetricsReporter: BuildMetricsReporter
|
||||
) : ICReporter by icReporter, BuildMetricsReporter by buildMetricsReporter
|
||||
|
||||
class RemoteBuildReporter(
|
||||
override val icReporter: RemoteICReporter,
|
||||
override val buildMetricsReporter: RemoteBuildMetricsReporter
|
||||
) : BuildReporter(icReporter, buildMetricsReporter), RemoteReporter {
|
||||
override fun flush() {
|
||||
icReporter.flush()
|
||||
buildMetricsReporter.flush()
|
||||
}
|
||||
}
|
||||
+3
-1
@@ -3,7 +3,7 @@
|
||||
* 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.incremental
|
||||
package org.jetbrains.kotlin.build.report
|
||||
|
||||
import org.jetbrains.kotlin.cli.common.ExitCode
|
||||
import java.io.File
|
||||
@@ -17,3 +17,5 @@ interface ICReporter {
|
||||
fun reportMarkDirtyMember(affectedFiles: Iterable<File>, scope: String, name: String)
|
||||
fun reportMarkDirty(affectedFiles: Iterable<File>, reason: String)
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -1,9 +1,9 @@
|
||||
/*
|
||||
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
|
||||
* 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.incremental
|
||||
package org.jetbrains.kotlin.build.report
|
||||
|
||||
import java.io.File
|
||||
|
||||
+3
-5
@@ -3,9 +3,7 @@
|
||||
* 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.idea.projectView
|
||||
package org.jetbrains.kotlin.build.report
|
||||
|
||||
import com.intellij.ide.util.treeView.AbstractTreeNode
|
||||
|
||||
// FIX ME WHEN BUNCH 193 REMOVED
|
||||
typealias AbstractTreeNodeAny = AbstractTreeNode<Any>
|
||||
interface RemoteICReporter : ICReporter,
|
||||
RemoteReporter
|
||||
+4
-6
@@ -3,11 +3,9 @@
|
||||
* 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.idea
|
||||
package org.jetbrains.kotlin.build.report
|
||||
|
||||
import com.intellij.openapi.project.Project
|
||||
interface RemoteReporter {
|
||||
fun flush()
|
||||
}
|
||||
|
||||
// FIX ME WHEN BUNCH 193 REMOVED
|
||||
fun runActivity(project: Project) {
|
||||
// nothing for 193
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
* 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.build.report.metrics
|
||||
|
||||
import java.io.Serializable
|
||||
|
||||
enum class BuildAttributeKind : Serializable {
|
||||
REBUILD_REASON;
|
||||
|
||||
companion object {
|
||||
const val serialVersionUID = 0L
|
||||
}
|
||||
}
|
||||
|
||||
enum class BuildAttribute(val kind: BuildAttributeKind) : Serializable {
|
||||
NO_BUILD_HISTORY(BuildAttributeKind.REBUILD_REASON),
|
||||
CACHE_CORRUPTION(BuildAttributeKind.REBUILD_REASON),
|
||||
UNKNOWN_CHANGES_IN_GRADLE_INPUTS(BuildAttributeKind.REBUILD_REASON),
|
||||
JAVA_CHANGE_UNTRACKED_FILE_IS_REMOVED(BuildAttributeKind.REBUILD_REASON),
|
||||
JAVA_CHANGE_UNEXPECTED_PSI(BuildAttributeKind.REBUILD_REASON),
|
||||
JAVA_CHANGE_UNKNOWN_QUALIFIER(BuildAttributeKind.REBUILD_REASON),
|
||||
DEP_CHANGE_REMOVED_ENTRY(BuildAttributeKind.REBUILD_REASON),
|
||||
DEP_CHANGE_HISTORY_IS_NOT_FOUND(BuildAttributeKind.REBUILD_REASON),
|
||||
DEP_CHANGE_HISTORY_CANNOT_BE_READ(BuildAttributeKind.REBUILD_REASON),
|
||||
DEP_CHANGE_HISTORY_NO_KNOWN_BUILDS(BuildAttributeKind.REBUILD_REASON),
|
||||
DEP_CHANGE_NON_INCREMENTAL_BUILD_IN_DEP(BuildAttributeKind.REBUILD_REASON),
|
||||
IN_PROCESS_EXECUTION(BuildAttributeKind.REBUILD_REASON),
|
||||
OUT_OF_PROCESS_EXECUTION(BuildAttributeKind.REBUILD_REASON),
|
||||
IC_IS_NOT_ENABLED(BuildAttributeKind.REBUILD_REASON);
|
||||
|
||||
companion object {
|
||||
const val serialVersionUID = 0L
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
* 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.build.report.metrics
|
||||
|
||||
import java.io.Serializable
|
||||
import java.util.*
|
||||
|
||||
class BuildAttributes : Serializable {
|
||||
private val myAttributes =
|
||||
EnumMap<BuildAttribute, Int>(
|
||||
BuildAttribute::class.java
|
||||
)
|
||||
|
||||
fun add(attr: BuildAttribute, count: Int = 1) {
|
||||
myAttributes[attr] = myAttributes.getOrDefault(attr, 0) + count
|
||||
}
|
||||
|
||||
fun addAll(other: BuildAttributes) {
|
||||
other.myAttributes.forEach { (attr, n) -> add(attr, n) }
|
||||
}
|
||||
|
||||
fun asMap(): Map<BuildAttribute, Int> = myAttributes
|
||||
|
||||
companion object {
|
||||
const val serialVersionUID = 0L
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/*
|
||||
* 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.build.report.metrics
|
||||
|
||||
import java.io.Serializable
|
||||
|
||||
data class BuildMetrics(
|
||||
val buildTimes: BuildTimes = BuildTimes(),
|
||||
val buildAttributes: BuildAttributes = BuildAttributes()
|
||||
) : Serializable {
|
||||
fun addAll(other: BuildMetrics) {
|
||||
buildTimes.addAll(other.buildTimes)
|
||||
buildAttributes.addAll(other.buildAttributes)
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val serialVersionUID = 0L
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* 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.build.report.metrics
|
||||
|
||||
interface BuildMetricsReporter {
|
||||
fun startMeasure(metric: BuildTime, startNs: Long)
|
||||
fun endMeasure(metric: BuildTime, endNs: Long)
|
||||
|
||||
fun addAttribute(attribute: BuildAttribute)
|
||||
|
||||
fun getMetrics(): BuildMetrics
|
||||
fun addMetrics(metrics: BuildMetrics?)
|
||||
}
|
||||
|
||||
inline fun <T> BuildMetricsReporter.measure(metric: BuildTime, fn: () -> T): T {
|
||||
val start = System.nanoTime()
|
||||
startMeasure(metric, start)
|
||||
|
||||
try {
|
||||
return fn()
|
||||
} finally {
|
||||
val end = System.nanoTime()
|
||||
endMeasure(metric, end)
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
* 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.build.report.metrics
|
||||
|
||||
import java.util.*
|
||||
|
||||
class BuildMetricsReporterImpl : BuildMetricsReporter {
|
||||
private val myBuildTimeStartNs: EnumMap<BuildTime, Long> =
|
||||
EnumMap(
|
||||
BuildTime::class.java
|
||||
)
|
||||
private val myBuildTimes = BuildTimes()
|
||||
private val myBuildAttributes = BuildAttributes()
|
||||
|
||||
override fun startMeasure(metric: BuildTime, startNs: Long) {
|
||||
if (metric in myBuildTimeStartNs) {
|
||||
error("$metric was restarted before it finished")
|
||||
}
|
||||
myBuildTimeStartNs[metric] = startNs
|
||||
}
|
||||
|
||||
override fun endMeasure(metric: BuildTime, endNs: Long) {
|
||||
val startNs = myBuildTimeStartNs.remove(metric) ?: error("$metric finished before it started")
|
||||
val durationNs = endNs - startNs
|
||||
myBuildTimes.add(metric, durationNs)
|
||||
}
|
||||
|
||||
override fun addAttribute(attribute: BuildAttribute) {
|
||||
myBuildAttributes.add(attribute)
|
||||
}
|
||||
|
||||
override fun getMetrics(): BuildMetrics =
|
||||
BuildMetrics(
|
||||
buildTimes = myBuildTimes,
|
||||
buildAttributes = myBuildAttributes
|
||||
)
|
||||
|
||||
override fun addMetrics(metrics: BuildMetrics?) {
|
||||
if (metrics == null) return
|
||||
|
||||
myBuildAttributes.addAll(metrics.buildAttributes)
|
||||
myBuildTimes.addAll(metrics.buildTimes)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
* 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.build.report.metrics
|
||||
|
||||
import java.io.Serializable
|
||||
|
||||
@Suppress("Reformat")
|
||||
enum class BuildTime(val parent: BuildTime? = null) : Serializable {
|
||||
GRADLE_TASK,
|
||||
CLEAR_OUTPUT(GRADLE_TASK),
|
||||
BACKUP_OUTPUT(GRADLE_TASK),
|
||||
RESTORE_OUTPUT_FROM_BACKUP(GRADLE_TASK),
|
||||
CONNECT_TO_DAEMON(GRADLE_TASK),
|
||||
CLEAR_JAR_CACHE(GRADLE_TASK),
|
||||
RUN_COMPILER(GRADLE_TASK),
|
||||
NON_INCREMENTAL_COMPILATION_IN_PROCESS(RUN_COMPILER),
|
||||
NON_INCREMENTAL_COMPILATION_OUT_OF_PROCESS(RUN_COMPILER),
|
||||
NON_INCREMENTAL_COMPILATION_DAEMON(RUN_COMPILER),
|
||||
INCREMENTAL_COMPILATION(RUN_COMPILER),
|
||||
IC_CALCULATE_INITIAL_DIRTY_SET(INCREMENTAL_COMPILATION),
|
||||
IC_ANALYZE_CHANGES_IN_DEPENDENCIES(IC_CALCULATE_INITIAL_DIRTY_SET),
|
||||
IC_FIND_HISTORY_FILES(IC_ANALYZE_CHANGES_IN_DEPENDENCIES),
|
||||
IC_ANALYZE_HISTORY_FILES(IC_ANALYZE_CHANGES_IN_DEPENDENCIES),
|
||||
IC_ANALYZE_CHANGES_IN_JAVA_SOURCES(IC_CALCULATE_INITIAL_DIRTY_SET),
|
||||
IC_ANALYZE_CHANGES_IN_ANDROID_LAYOUTS(IC_CALCULATE_INITIAL_DIRTY_SET),
|
||||
IC_DETECT_REMOVED_CLASSES(IC_CALCULATE_INITIAL_DIRTY_SET),
|
||||
CLEAR_OUTPUT_ON_REBUILD(INCREMENTAL_COMPILATION),
|
||||
IC_UPDATE_CACHES(INCREMENTAL_COMPILATION),
|
||||
INCREMENTAL_ITERATION(INCREMENTAL_COMPILATION),
|
||||
NON_INCREMENTAL_ITERATION(INCREMENTAL_COMPILATION),
|
||||
IC_WRITE_HISTORY_FILE(INCREMENTAL_COMPILATION);
|
||||
|
||||
companion object {
|
||||
const val serialVersionUID = 0L
|
||||
|
||||
val children by lazy {
|
||||
values().filter { it.parent != null }.groupBy { it.parent }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
* 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.build.report.metrics
|
||||
|
||||
import java.io.Serializable
|
||||
import java.util.*
|
||||
|
||||
class BuildTimes : Serializable {
|
||||
private val myBuildTimes = EnumMap<BuildTime, Long>(BuildTime::class.java)
|
||||
|
||||
fun addAll(other: BuildTimes) {
|
||||
for ((bt, timeNs) in other.myBuildTimes) {
|
||||
add(bt, timeNs)
|
||||
}
|
||||
}
|
||||
|
||||
fun add(buildTime: BuildTime, timeNs: Long) {
|
||||
myBuildTimes[buildTime] = myBuildTimes.getOrDefault(buildTime, 0) + timeNs
|
||||
}
|
||||
|
||||
fun asMap(): Map<BuildTime, Long> = myBuildTimes
|
||||
|
||||
companion object {
|
||||
const val serialVersionUID = 0L
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
* 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.build.report.metrics
|
||||
|
||||
object DoNothingBuildMetricsReporter : BuildMetricsReporter {
|
||||
override fun startMeasure(metric: BuildTime, startNs: Long) {
|
||||
}
|
||||
|
||||
override fun endMeasure(metric: BuildTime, endNs: Long) {
|
||||
}
|
||||
|
||||
override fun addAttribute(attribute: BuildAttribute) {
|
||||
}
|
||||
|
||||
override fun getMetrics(): BuildMetrics =
|
||||
BuildMetrics(
|
||||
BuildTimes(),
|
||||
BuildAttributes()
|
||||
)
|
||||
|
||||
override fun addMetrics(metrics: BuildMetrics?) {}
|
||||
}
|
||||
+4
-4
@@ -3,9 +3,9 @@
|
||||
* 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.idea.projectView
|
||||
package org.jetbrains.kotlin.build.report.metrics
|
||||
|
||||
import com.intellij.ide.util.treeView.AbstractTreeNode
|
||||
import org.jetbrains.kotlin.build.report.RemoteReporter
|
||||
|
||||
// FIX ME WHEN BUNCH 193 REMOVED
|
||||
typealias AbstractTreeNodeAny = AbstractTreeNode<*>
|
||||
interface RemoteBuildMetricsReporter : BuildMetricsReporter,
|
||||
RemoteReporter
|
||||
@@ -20,6 +20,7 @@ import org.jetbrains.kotlin.build.GeneratedFile
|
||||
import org.jetbrains.kotlin.build.GeneratedJvmClass
|
||||
import org.jetbrains.kotlin.build.JvmSourceRoot
|
||||
import org.jetbrains.kotlin.build.isModuleMappingFile
|
||||
import org.jetbrains.kotlin.build.report.ICReporter
|
||||
import org.jetbrains.kotlin.config.Services
|
||||
import org.jetbrains.kotlin.incremental.components.LookupTracker
|
||||
import org.jetbrains.kotlin.load.kotlin.incremental.components.IncrementalCache
|
||||
@@ -31,6 +32,7 @@ import org.jetbrains.kotlin.progress.CompilationCanceledStatus
|
||||
import org.jetbrains.kotlin.resolve.sam.SAM_LOOKUP_NAME
|
||||
import org.jetbrains.kotlin.utils.addToStdlib.flattenTo
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
import java.util.*
|
||||
import kotlin.collections.HashSet
|
||||
import kotlin.collections.LinkedHashSet
|
||||
@@ -66,7 +68,7 @@ fun makeModuleFile(
|
||||
friendDirs
|
||||
)
|
||||
|
||||
val scriptFile = File.createTempFile("kjps", sanitizeJavaIdentifier(name) + ".script.xml")
|
||||
val scriptFile = Files.createTempFile("kjps", sanitizeJavaIdentifier(name) + ".script.xml").toFile()
|
||||
scriptFile.writeText(builder.asText().toString())
|
||||
return scriptFile
|
||||
}
|
||||
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
* 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.incremental.storage
|
||||
|
||||
import java.io.File
|
||||
|
||||
open class IncrementalFileToPathConverter(val rootProjectDir: File?) : FileToPathConverter {
|
||||
//project root dir
|
||||
private val projectDirPath = rootProjectDir?.normalize()?.absolutePath
|
||||
|
||||
override fun toPath(file: File): String {
|
||||
val path = file.normalize().absolutePath
|
||||
return when {
|
||||
projectDirPath == null || !path.startsWith(projectDirPath) -> path
|
||||
else -> PROJECT_DIR_PLACEHOLDER + path.substring(projectDirPath.length)
|
||||
}
|
||||
}
|
||||
|
||||
override fun toFile(path: String): File =
|
||||
when {
|
||||
rootProjectDir != null && path.startsWith(PROJECT_DIR_PLACEHOLDER) -> rootProjectDir.resolve(path.substring(PATH_PREFIX.length))
|
||||
else -> File(path)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
private const val PROJECT_DIR_PLACEHOLDER = "${'$'}PROJECT_DIR$"
|
||||
//use only for prefix length because it OS dependent
|
||||
private const val PATH_PREFIX = "$PROJECT_DIR_PLACEHOLDER/"
|
||||
|
||||
}
|
||||
}
|
||||
-106
@@ -1,106 +0,0 @@
|
||||
/*
|
||||
* Copyright 2010-2015 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.
|
||||
*/
|
||||
|
||||
package org.jetbrains.kotlin.incremental.storage
|
||||
|
||||
import com.intellij.util.io.DataExternalizer
|
||||
import com.intellij.util.io.KeyDescriptor
|
||||
import com.intellij.util.io.JpsPersistentHashMap
|
||||
import java.io.File
|
||||
|
||||
|
||||
class NonCachingLazyStorage<K, V>(
|
||||
private val storageFile: File,
|
||||
private val keyDescriptor: KeyDescriptor<K>,
|
||||
private val valueExternalizer: DataExternalizer<V>
|
||||
) : LazyStorage<K, V> {
|
||||
@Volatile
|
||||
private var storage: JpsPersistentHashMap<K, V>? = null
|
||||
|
||||
@Synchronized
|
||||
private fun getStorageIfExists(): JpsPersistentHashMap<K, V>? {
|
||||
if (storage != null) return storage
|
||||
|
||||
if (storageFile.exists()) {
|
||||
storage = createMap()
|
||||
return storage
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
private fun getStorageOrCreateNew(): JpsPersistentHashMap<K, V> {
|
||||
if (storage == null) {
|
||||
storage = createMap()
|
||||
}
|
||||
|
||||
return storage!!
|
||||
}
|
||||
|
||||
override val keys: Collection<K>
|
||||
get() = getStorageIfExists()?.allKeysWithExistingMapping ?: listOf()
|
||||
|
||||
override operator fun contains(key: K): Boolean =
|
||||
getStorageIfExists()?.containsMapping(key) ?: false
|
||||
|
||||
override operator fun get(key: K): V? =
|
||||
getStorageIfExists()?.get(key)
|
||||
|
||||
override operator fun set(key: K, value: V) {
|
||||
getStorageOrCreateNew().put(key, value)
|
||||
}
|
||||
|
||||
override fun remove(key: K) {
|
||||
getStorageIfExists()?.remove(key)
|
||||
}
|
||||
|
||||
override fun append(key: K, value: V) {
|
||||
getStorageOrCreateNew().appendDataWithoutCache(key, value)
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
override fun clean() {
|
||||
try {
|
||||
storage?.close()
|
||||
} catch (ignored: Throwable) {
|
||||
}
|
||||
|
||||
JpsPersistentHashMap.deleteFilesStartingWith(storageFile)
|
||||
storage = null
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
override fun flush(memoryCachesOnly: Boolean) {
|
||||
val existingStorage = storage ?: return
|
||||
|
||||
if (memoryCachesOnly) {
|
||||
if (existingStorage.isDirty) {
|
||||
existingStorage.dropMemoryCaches()
|
||||
}
|
||||
} else {
|
||||
existingStorage.force()
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
override fun close() {
|
||||
storage?.close()
|
||||
}
|
||||
|
||||
private fun createMap(): JpsPersistentHashMap<K, V> =
|
||||
JpsPersistentHashMap(storageFile, keyDescriptor, valueExternalizer)
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
* 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.incremental.storage
|
||||
|
||||
import org.jetbrains.kotlin.TestWithWorkingDir
|
||||
import org.junit.Test
|
||||
import java.io.File
|
||||
|
||||
internal class IncrementalFileToPathConverterTest : TestWithWorkingDir() {
|
||||
val separator: String = File.separator
|
||||
|
||||
@Test
|
||||
fun testPathTransform() {
|
||||
val relativeFilePath = "testFile.txt"
|
||||
val transformedPath = testPathTransformation(workingDir.resolve("testDir"), relativeFilePath)
|
||||
|
||||
assertEquals("${'$'}PROJECT_DIR${'$'}$separator$relativeFilePath", transformedPath)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testComplicatedProjectRootPath() {
|
||||
val relativeFilePath = "testFile.txt"
|
||||
val transformedPath = testPathTransformation(workingDir.resolve("first$separator..${separator}testDir"), relativeFilePath)
|
||||
|
||||
assertEquals("${'$'}PROJECT_DIR${'$'}$separator$relativeFilePath", transformedPath)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testInccorectProjectRootPath() {
|
||||
val relativeFilePath = "testFile.txt"
|
||||
val transformedPath = testPathTransformation(workingDir.resolve("testDir$separator"), relativeFilePath)
|
||||
|
||||
assertEquals("${'$'}PROJECT_DIR${'$'}$separator$relativeFilePath", transformedPath)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testFileOutOfProject() {
|
||||
val relativeFilePath = "..${separator}testFile.txt"
|
||||
val transformedPath = testPathTransformation(workingDir.resolve("testDir"), relativeFilePath)
|
||||
|
||||
assertEquals("${workingDir.absolutePath}${separator}testFile.txt", transformedPath)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testFileWithExtraSlash() {
|
||||
val relativeFilePath = "testFile.txt$separator"
|
||||
val transformedPath = testPathTransformation(workingDir.resolve("testDir"), relativeFilePath)
|
||||
|
||||
assertEquals("${'$'}PROJECT_DIR${'$'}${separator}testFile.txt", transformedPath)
|
||||
}
|
||||
|
||||
private fun testPathTransformation(projectRoot: File, relativeFilePath: String): String {
|
||||
val pathConverter = IncrementalFileToPathConverter(projectRoot)
|
||||
val testFile = projectRoot.resolve(relativeFilePath)
|
||||
val transformedPath = pathConverter.toPath(testFile)
|
||||
assertEquals(testFile.normalize().absolutePath, pathConverter.toFile(transformedPath).normalize().absolutePath)
|
||||
return transformedPath
|
||||
}
|
||||
}
|
||||
+20
-15
@@ -27,8 +27,9 @@ buildscript {
|
||||
dependencies {
|
||||
bootstrapCompilerClasspath(kotlin("compiler-embeddable", bootstrapKotlinVersion))
|
||||
|
||||
classpath("org.jetbrains.kotlin:kotlin-build-gradle-plugin:0.0.20")
|
||||
classpath("org.jetbrains.kotlin:kotlin-build-gradle-plugin:0.0.21")
|
||||
classpath(kotlin("gradle-plugin", bootstrapKotlinVersion))
|
||||
classpath(kotlin("serialization", bootstrapKotlinVersion))
|
||||
classpath("org.jetbrains.dokka:dokka-gradle-plugin:0.9.17")
|
||||
classpath("org.jfrog.buildinfo:build-info-extractor-gradle:4.17.2")
|
||||
}
|
||||
@@ -167,9 +168,8 @@ extra["versions.junit"] = "4.12"
|
||||
extra["versions.javaslang"] = "2.0.6"
|
||||
extra["versions.ant"] = "1.8.2"
|
||||
extra["versions.android"] = "2.3.1"
|
||||
val coroutinesVersion = if (Platform[192].orHigher()) "1.3.7" else "1.1.1"
|
||||
extra["versions.kotlinx-coroutines-core"] = coroutinesVersion
|
||||
extra["versions.kotlinx-coroutines-jdk8"] = coroutinesVersion
|
||||
extra["versions.kotlinx-coroutines-core"] = "1.3.8"
|
||||
extra["versions.kotlinx-coroutines-jdk8"] = "1.3.8"
|
||||
extra["versions.json"] = "20160807"
|
||||
extra["versions.native-platform"] = "0.14"
|
||||
extra["versions.ant-launcher"] = "1.8.0"
|
||||
@@ -188,13 +188,13 @@ extra["versions.kotlinx-collections-immutable-jvm"] = immutablesVersion
|
||||
extra["versions.ktor-network"] = "1.0.1"
|
||||
|
||||
if (!project.hasProperty("versions.kotlin-native")) {
|
||||
extra["versions.kotlin-native"] = "1.4.30-dev-16766"
|
||||
extra["versions.kotlin-native"] = "1.4.30-dev-17200"
|
||||
}
|
||||
|
||||
val intellijUltimateEnabled by extra(project.kotlinBuildProperties.intellijUltimateEnabled)
|
||||
val effectSystemEnabled by extra(project.getBooleanProperty("kotlin.compiler.effectSystemEnabled") ?: false)
|
||||
val newInferenceEnabled by extra(project.getBooleanProperty("kotlin.compiler.newInferenceEnabled") ?: false)
|
||||
val useJvmIrBackend by extra(project.getBooleanProperty("kotlin.build.useIR") ?: false)
|
||||
val useJvmIrBackend by extra(project.kotlinBuildProperties.useIR)
|
||||
|
||||
val intellijSeparateSdks = project.getBooleanProperty("intellijSeparateSdks") ?: false
|
||||
|
||||
@@ -292,7 +292,8 @@ extra["compilerModules"] = arrayOf(
|
||||
":compiler:fir:jvm",
|
||||
":compiler:fir:checkers",
|
||||
":compiler:fir:entrypoint",
|
||||
":compiler:fir:analysis-tests"
|
||||
":compiler:fir:analysis-tests",
|
||||
":wasm:wasm.ir"
|
||||
)
|
||||
|
||||
extra["compilerModulesForJps"] = listOf(
|
||||
@@ -650,8 +651,11 @@ tasks {
|
||||
}
|
||||
|
||||
register("wasmCompilerTest") {
|
||||
// TODO: fix once
|
||||
// dependsOn(":js:js.tests:wasmTest")
|
||||
dependsOn(":js:js.tests:wasmTest")
|
||||
// Windows WABT release requires Visual C++ Redistributable
|
||||
if (!kotlinBuildProperties.isTeamcityBuild || !org.gradle.internal.os.OperatingSystem.current().isWindows) {
|
||||
dependsOn(":wasm:wasm.ir:test")
|
||||
}
|
||||
}
|
||||
|
||||
register("nativeCompilerTest") {
|
||||
@@ -781,9 +785,10 @@ tasks {
|
||||
}
|
||||
|
||||
register("idea-plugin-performance-tests") {
|
||||
dependsOn("dist")
|
||||
dependsOn(
|
||||
":idea:performanceTests:performanceTest"
|
||||
"dist",
|
||||
":idea:performanceTests:performanceTest",
|
||||
":idea:performanceTests:aggregateResults"
|
||||
)
|
||||
}
|
||||
|
||||
@@ -865,8 +870,8 @@ tasks {
|
||||
":compiler:test",
|
||||
":js:js.tests:test"
|
||||
)
|
||||
if (Ide.IJ193.orHigher())
|
||||
dependsOn(":kotlin-gradle-plugin-integration-tests:test")
|
||||
|
||||
dependsOn(":kotlin-gradle-plugin-integration-tests:test")
|
||||
if (Ide.AS40.orHigher())
|
||||
dependsOn(":kotlin-ultimate:ide:android-studio-native:test")
|
||||
|
||||
@@ -900,7 +905,6 @@ tasks {
|
||||
":prepare:ide-plugin-dependencies:incremental-compilation-impl-tests-for-ide:publish",
|
||||
":prepare:ide-plugin-dependencies:kotlin-build-common-tests-for-ide:publish",
|
||||
":prepare:ide-plugin-dependencies:kotlin-compiler-for-ide:publish",
|
||||
":prepare:ide-plugin-dependencies:kotlin-dist-for-ide:publish",
|
||||
":prepare:ide-plugin-dependencies:kotlin-gradle-statistics-for-ide:publish",
|
||||
":prepare:ide-plugin-dependencies:kotlinx-serialization-compiler-plugin-for-ide:publish",
|
||||
":prepare:ide-plugin-dependencies:noarg-compiler-plugin-for-ide:publish",
|
||||
@@ -921,7 +925,8 @@ tasks {
|
||||
":kotlin-reflect:publish",
|
||||
":kotlin-main-kts:publish",
|
||||
":kotlin-stdlib-js:publish",
|
||||
":kotlin-test:kotlin-test-js:publish"
|
||||
":kotlin-test:kotlin-test-js:publish",
|
||||
":kotlin-coroutines-experimental-compat:publish"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
|
||||
|
||||
extra["versions.native-platform"] = "0.14"
|
||||
|
||||
buildscript {
|
||||
@@ -22,7 +24,7 @@ buildscript {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
classpath("org.jetbrains.kotlin:kotlin-build-gradle-plugin:0.0.20")
|
||||
classpath("org.jetbrains.kotlin:kotlin-build-gradle-plugin:0.0.21")
|
||||
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${project.bootstrapKotlinVersion}")
|
||||
classpath("org.jetbrains.kotlin:kotlin-sam-with-receiver:${project.bootstrapKotlinVersion}")
|
||||
}
|
||||
@@ -97,7 +99,7 @@ repositories {
|
||||
dependencies {
|
||||
implementation(kotlin("stdlib", embeddedKotlinVersion))
|
||||
implementation("org.jetbrains.kotlin:kotlin-gradle-plugin:${project.bootstrapKotlinVersion}")
|
||||
implementation("org.jetbrains.kotlin:kotlin-build-gradle-plugin:0.0.20")
|
||||
implementation("org.jetbrains.kotlin:kotlin-build-gradle-plugin:0.0.21")
|
||||
implementation("com.gradle.publish:plugin-publish-plugin:0.12.0")
|
||||
|
||||
implementation("net.rubygrapefruit:native-platform:${property("versions.native-platform")}")
|
||||
@@ -126,6 +128,11 @@ java {
|
||||
targetCompatibility = JavaVersion.VERSION_1_8
|
||||
}
|
||||
|
||||
tasks.withType<KotlinCompile>().configureEach {
|
||||
kotlinOptions.freeCompilerArgs +=
|
||||
listOf("-Xopt-in=kotlin.RequiresOptIn", "-Xskip-runtime-version-check")
|
||||
}
|
||||
|
||||
tasks["build"].dependsOn(":prepare-deps:build")
|
||||
|
||||
allprojects {
|
||||
|
||||
@@ -20,7 +20,7 @@ buildscript {
|
||||
}
|
||||
}
|
||||
dependencies {
|
||||
classpath("org.jetbrains.kotlin:kotlin-build-gradle-plugin:0.0.20")
|
||||
classpath("org.jetbrains.kotlin:kotlin-build-gradle-plugin:0.0.21")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,10 +5,13 @@ import org.gradle.api.Project
|
||||
import org.gradle.api.file.DuplicatesStrategy
|
||||
import org.gradle.api.tasks.TaskProvider
|
||||
import org.gradle.jvm.tasks.Jar
|
||||
import org.gradle.kotlin.dsl.*
|
||||
import org.gradle.kotlin.dsl.named
|
||||
import org.gradle.kotlin.dsl.project
|
||||
import org.gradle.kotlin.dsl.provideDelegate
|
||||
import org.gradle.kotlin.dsl.register
|
||||
import java.io.File
|
||||
|
||||
val kotlinEmbeddableRootPackage = "org.jetbrains.kotlin"
|
||||
const val kotlinEmbeddableRootPackage = "org.jetbrains.kotlin"
|
||||
|
||||
val packagesToRelocate =
|
||||
listOf(
|
||||
@@ -31,21 +34,23 @@ val packagesToRelocate =
|
||||
// But due to the shadow plugin bug (https://github.com/johnrengelman/shadow/issues/262) it is not possible to use
|
||||
// packagesToRelocate list to for the include list. Therefore the exclude list has to be created.
|
||||
val packagesToExcludeFromDummy =
|
||||
listOf("org/jetbrains/kotlin/**",
|
||||
"org/intellij/lang/annotations/**",
|
||||
"org/jetbrains/jps/**",
|
||||
"META-INF/**",
|
||||
"com/sun/jna/**",
|
||||
"com/thoughtworks/xstream/**",
|
||||
"javaslang/**",
|
||||
"*.proto",
|
||||
"messages/**",
|
||||
"net/sf/cglib/**",
|
||||
"one/util/streamex/**",
|
||||
"org/iq80/snappy/**",
|
||||
"org/jline/**",
|
||||
"org/xmlpull/**",
|
||||
"*.txt")
|
||||
listOf(
|
||||
"org/jetbrains/kotlin/**",
|
||||
"org/intellij/lang/annotations/**",
|
||||
"org/jetbrains/jps/**",
|
||||
"META-INF/**",
|
||||
"com/sun/jna/**",
|
||||
"com/thoughtworks/xstream/**",
|
||||
"javaslang/**",
|
||||
"*.proto",
|
||||
"messages/**",
|
||||
"net/sf/cglib/**",
|
||||
"one/util/streamex/**",
|
||||
"org/iq80/snappy/**",
|
||||
"org/jline/**",
|
||||
"org/xmlpull/**",
|
||||
"*.txt"
|
||||
)
|
||||
|
||||
private fun ShadowJar.configureEmbeddableCompilerRelocation(withJavaxInject: Boolean = true) {
|
||||
relocate("com.google.protobuf", "org.jetbrains.kotlin.protobuf")
|
||||
@@ -67,8 +72,8 @@ private fun Project.compilerShadowJar(taskName: String, body: ShadowJar.() -> Un
|
||||
dependencies.add(compilerJar.name, dependencies.project(":kotlin-compiler", configuration = "runtimeJar"))
|
||||
|
||||
return tasks.register<ShadowJar>(taskName) {
|
||||
destinationDir = File(buildDir, "libs")
|
||||
setDuplicatesStrategy(DuplicatesStrategy.EXCLUDE)
|
||||
destinationDirectory.set(project.file(File(buildDir, "libs")))
|
||||
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
|
||||
from(compilerJar)
|
||||
body()
|
||||
}
|
||||
@@ -107,8 +112,8 @@ fun Project.embeddableCompilerDummyForDependenciesRewriting(
|
||||
)
|
||||
|
||||
return tasks.register<ShadowJar>(taskName) {
|
||||
destinationDir = File(buildDir, "libs")
|
||||
setDuplicatesStrategy(DuplicatesStrategy.EXCLUDE)
|
||||
destinationDirectory.set(project.file(File(buildDir, "libs")))
|
||||
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
|
||||
from(compilerDummyJar)
|
||||
configureEmbeddableCompilerRelocation(withJavaxInject = false)
|
||||
body()
|
||||
@@ -119,7 +124,7 @@ fun Project.rewriteDepsToShadedJar(
|
||||
originalJarTask: TaskProvider<out Jar>, shadowJarTask: TaskProvider<out Jar>, body: Jar.() -> Unit = {}
|
||||
): TaskProvider<out Jar> {
|
||||
originalJarTask.configure {
|
||||
classifier = "original"
|
||||
archiveClassifier.set("original")
|
||||
}
|
||||
|
||||
val compilerDummyJarFile by lazy { configurations.getAt("compilerDummyJar").singleFile }
|
||||
@@ -132,7 +137,7 @@ fun Project.rewriteDepsToShadedJar(
|
||||
// which leads to the content of that JAR being excluded as well:
|
||||
exclude { it.file == compilerDummyJarFile }
|
||||
|
||||
classifier = ""
|
||||
archiveClassifier.set("original")
|
||||
body()
|
||||
}
|
||||
return shadowJarTask
|
||||
|
||||
@@ -132,12 +132,10 @@ object IntellijRootUtils {
|
||||
}
|
||||
}
|
||||
|
||||
fun ModuleDependency.includeIntellijCoreJarDependencies(project: Project) =
|
||||
includeJars(*(project.rootProject.extra["IntellijCoreDependencies"] as List<String>).toTypedArray(), rootProject = project.rootProject)
|
||||
|
||||
fun ModuleDependency.includeIntellijCoreJarDependencies(project: Project, jarsFilterPredicate: (String) -> Boolean) =
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
fun ModuleDependency.includeIntellijCoreJarDependencies(project: Project, jarsFilterPredicate: (String) -> Boolean = { true }): Unit =
|
||||
includeJars(
|
||||
*(project.rootProject.extra["IntellijCoreDependencies"] as List<String>).filter { jarsFilterPredicate(it) }.toTypedArray(),
|
||||
*(project.rootProject.extra["IntellijCoreDependencies"] as List<String>).filter(jarsFilterPredicate).toTypedArray(),
|
||||
rootProject = project.rootProject
|
||||
)
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ import java.util.*
|
||||
|
||||
internal const val PLUGIN_MARKER_SUFFIX = ".gradle.plugin"
|
||||
|
||||
@UseExperimental(ExperimentalStdlibApi::class)
|
||||
@OptIn(ExperimentalStdlibApi::class)
|
||||
fun Project.publishPluginMarkers(withEmptyJars: Boolean = true) {
|
||||
val pluginDevelopment = extensions.getByType<PluginBundleExtension>()
|
||||
val publishingExtension = extensions.getByType<PublishingExtension>()
|
||||
|
||||
@@ -8,7 +8,6 @@ package plugins
|
||||
import org.gradle.api.Plugin
|
||||
import org.gradle.api.Project
|
||||
import org.gradle.api.attributes.Usage
|
||||
import org.gradle.api.component.AdhocComponentWithVariants
|
||||
import org.gradle.api.component.SoftwareComponentFactory
|
||||
import org.gradle.api.plugins.JavaBasePlugin
|
||||
import org.gradle.api.publish.PublishingExtension
|
||||
@@ -23,7 +22,6 @@ import org.gradle.plugins.signing.SigningPlugin
|
||||
import java.util.*
|
||||
import javax.inject.Inject
|
||||
|
||||
|
||||
class KotlinBuildPublishingPlugin @Inject constructor(
|
||||
private val componentFactory: SoftwareComponentFactory
|
||||
) : Plugin<Project> {
|
||||
@@ -47,7 +45,7 @@ class KotlinBuildPublishingPlugin @Inject constructor(
|
||||
}
|
||||
}
|
||||
|
||||
val kotlinLibraryComponent = componentFactory.adhoc(ADHOC_COMPONENT_NAME) as AdhocComponentWithVariants
|
||||
val kotlinLibraryComponent = componentFactory.adhoc(ADHOC_COMPONENT_NAME)
|
||||
components.add(kotlinLibraryComponent)
|
||||
kotlinLibraryComponent.addVariantsFromConfiguration(publishedCompile) { mapToMavenScope("compile") }
|
||||
kotlinLibraryComponent.addVariantsFromConfiguration(publishedRuntime) { mapToMavenScope("runtime") }
|
||||
@@ -139,7 +137,7 @@ class KotlinBuildPublishingPlugin @Inject constructor(
|
||||
const val COMPILE_CONFIGURATION = "publishedCompile"
|
||||
const val RUNTIME_CONFIGURATION = "publishedRuntime"
|
||||
|
||||
@UseExperimental(ExperimentalStdlibApi::class)
|
||||
@OptIn(ExperimentalStdlibApi::class)
|
||||
fun humanReadableName(project: Project) =
|
||||
project.name.split("-").joinToString(separator = " ") { it.capitalize(Locale.ROOT) }
|
||||
}
|
||||
@@ -163,4 +161,4 @@ fun TaskProvider<PublishToMavenRepository>.configureRepository() = configure {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
@file:Suppress("DEPRECATION")
|
||||
package plugins
|
||||
|
||||
import org.codehaus.groovy.runtime.InvokerHelper
|
||||
@@ -16,10 +17,8 @@ import org.gradle.plugins.signing.Sign
|
||||
import org.gradle.plugins.signing.SigningExtension
|
||||
import kotlin.properties.Delegates
|
||||
|
||||
|
||||
/**
|
||||
* Configures a Kotlin module for publication.
|
||||
*
|
||||
*/
|
||||
open class PublishedKotlinModule : Plugin<Project> {
|
||||
|
||||
|
||||
@@ -154,7 +154,7 @@ fun Project.projectTest(
|
||||
|
||||
var subProjectTempRoot: Path? = null
|
||||
doFirst {
|
||||
val teamcity = rootProject.findProperty("teamcity") as? Map<Any?, *>
|
||||
val teamcity = rootProject.findProperty("teamcity") as? Map<*, *>
|
||||
val systemTempRoot =
|
||||
// TC by default doesn't switch `teamcity.build.tempDir` to 'java.io.tmpdir' so it could cause to wasted disk space
|
||||
// Should be fixed soon on Teamcity side
|
||||
@@ -180,7 +180,7 @@ fun Project.projectTest(
|
||||
if (parallel) {
|
||||
maxParallelForks =
|
||||
project.findProperty("kotlin.test.maxParallelForks")?.toString()?.toInt()
|
||||
?: Math.max(Runtime.getRuntime().availableProcessors() / if (kotlinBuildProperties.isTeamcityBuild) 2 else 4, 1)
|
||||
?: (Runtime.getRuntime().availableProcessors() / if (kotlinBuildProperties.isTeamcityBuild) 2 else 4).coerceAtLeast(1)
|
||||
}
|
||||
body()
|
||||
}
|
||||
|
||||
@@ -34,9 +34,7 @@ dependencies {
|
||||
Platform[201].orLower {
|
||||
testCompile(intellijDep()) { includeJars("groovy-all", rootProject = rootProject) }
|
||||
}
|
||||
Platform[192].orHigher {
|
||||
testCompile(intellijPluginDep("java")) { includeJars("jps-builders") }
|
||||
}
|
||||
testCompile(intellijPluginDep("java")) { includeJars("jps-builders") }
|
||||
testCompile(jpsStandalone()) { includeJars("jps-model") }
|
||||
testCompile(jpsBuildTest())
|
||||
}
|
||||
|
||||
+9
-5
@@ -27,6 +27,9 @@ import org.junit.Assert
|
||||
import java.io.File
|
||||
import java.io.FileWriter
|
||||
import java.io.IOException
|
||||
import kotlin.io.path.ExperimentalPathApi
|
||||
import kotlin.io.path.Path
|
||||
import kotlin.io.path.createTempDirectory
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
data class ConfigurationKey(val kind: ConfigurationKind, val jdkKind: TestJdkKind, val configuration: String)
|
||||
@@ -345,14 +348,15 @@ class CodegenTestsOnAndroidGenerator private constructor(private val pathManager
|
||||
FileWriter(file).use { fw -> fw.write("sdk.dir=$sdkRoot") }
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalPathApi::class)
|
||||
@JvmStatic
|
||||
fun main(args: Array<String>) {
|
||||
val tmpFolder = createTempDir()
|
||||
println("Created temporary folder for android tests: " + tmpFolder.absolutePath)
|
||||
val rootFolder = File("")
|
||||
val pathManager = PathManager(rootFolder.absolutePath, tmpFolder.absolutePath)
|
||||
val tmpFolder = createTempDirectory().toAbsolutePath().toString()
|
||||
println("Created temporary folder for android tests: $tmpFolder")
|
||||
val rootFolder = Path("").toAbsolutePath().toString()
|
||||
val pathManager = PathManager(rootFolder, tmpFolder)
|
||||
generate(pathManager, true)
|
||||
println("Android test project is generated into " + tmpFolder.absolutePath + " folder")
|
||||
println("Android test project is generated into $tmpFolder folder")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
/*
|
||||
* 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.backend.common
|
||||
|
||||
class BackendException(message: String, cause: Throwable?) : IllegalStateException(message, cause)
|
||||
@@ -232,12 +232,13 @@ object CodegenUtil {
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun reportBackendException(exception: Throwable, phase: String, fileUrl: String?): Nothing {
|
||||
fun reportBackendException(exception: Throwable, phase: String, location: String?, additionalMessage: String? = null): Nothing {
|
||||
// CompilationException (the only KotlinExceptionWithAttachments possible here) is already supposed
|
||||
// to have all information about the context.
|
||||
if (exception is KotlinExceptionWithAttachments) throw exception
|
||||
throw IllegalStateException(
|
||||
getExceptionMessage("Backend", "Exception during $phase", exception, fileUrl),
|
||||
throw BackendException(
|
||||
getExceptionMessage("Backend", "Exception during $phase", exception, location) +
|
||||
additionalMessage?.let { "\n" + it }.orEmpty(),
|
||||
exception
|
||||
)
|
||||
}
|
||||
|
||||
@@ -254,14 +254,14 @@ public class ClassFileFactory implements OutputFileCollection {
|
||||
public PackageCodegen forPackage(@NotNull FqName fqName, @NotNull Collection<KtFile> files) {
|
||||
assert !isDone : "Already done!";
|
||||
registerSourceFiles(files);
|
||||
return state.getCodegenFactory().createPackageCodegen(state, files, fqName);
|
||||
return new PackageCodegenImpl(state, files, fqName);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public MultifileClassCodegen forMultifileClass(@NotNull FqName facadeFqName, @NotNull Collection<KtFile> files) {
|
||||
assert !isDone : "Already done!";
|
||||
registerSourceFiles(files);
|
||||
return state.getCodegenFactory().createMultifileClassCodegen(state, files, facadeFqName);
|
||||
return new MultifileClassCodegenImpl(state, files, facadeFqName);
|
||||
}
|
||||
|
||||
private void registerSourceFiles(Collection<KtFile> files) {
|
||||
|
||||
@@ -26,10 +26,6 @@ import org.jetbrains.kotlin.psi.KtFile
|
||||
interface CodegenFactory {
|
||||
fun generateModule(state: GenerationState, files: Collection<KtFile>)
|
||||
|
||||
fun createPackageCodegen(state: GenerationState, files: Collection<KtFile>, fqName: FqName): PackageCodegen
|
||||
|
||||
fun createMultifileClassCodegen(state: GenerationState, files: Collection<KtFile>, fqName: FqName): MultifileClassCodegen
|
||||
|
||||
companion object {
|
||||
fun doCheckCancelled(state: GenerationState) {
|
||||
if (state.classBuilderMode.generateBodies) {
|
||||
@@ -49,8 +45,7 @@ object DefaultCodegenFactory : CodegenFactory {
|
||||
|
||||
if (fileClassInfo.withJvmMultifileClass) {
|
||||
filesInMultifileClasses.putValue(fileClassInfo.facadeClassFqName, file)
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
filesInPackages.putValue(file.packageFqName, file)
|
||||
}
|
||||
}
|
||||
@@ -68,23 +63,17 @@ object DefaultCodegenFactory : CodegenFactory {
|
||||
}
|
||||
}
|
||||
|
||||
override fun createPackageCodegen(state: GenerationState, files: Collection<KtFile>, fqName: FqName) =
|
||||
PackageCodegenImpl(state, files, fqName)
|
||||
|
||||
override fun createMultifileClassCodegen(state: GenerationState, files: Collection<KtFile>, fqName: FqName) =
|
||||
MultifileClassCodegenImpl(state, files, fqName)
|
||||
|
||||
private fun generateMultifileClass(state: GenerationState, multifileClassFqName: FqName, files: Collection<KtFile>) {
|
||||
state.factory.forMultifileClass(multifileClassFqName, files).generate()
|
||||
}
|
||||
|
||||
fun generatePackage(
|
||||
state: GenerationState,
|
||||
packageFqName: FqName,
|
||||
jetFiles: Collection<KtFile>
|
||||
state: GenerationState,
|
||||
packageFqName: FqName,
|
||||
ktFiles: Collection<KtFile>
|
||||
) {
|
||||
// We do not really generate package class, but use old package fqName to identify package in module-info.
|
||||
//FqName packageClassFqName = PackageClassUtils.getPackageClassFqName(packageFqName);
|
||||
state.factory.forPackage(packageFqName, jetFiles).generate()
|
||||
state.factory.forPackage(packageFqName, ktFiles).generate()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ import org.jetbrains.kotlin.descriptors.*;
|
||||
import org.jetbrains.kotlin.psi.*;
|
||||
import org.jetbrains.kotlin.resolve.BindingContext;
|
||||
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils;
|
||||
import org.jetbrains.kotlin.resolve.InlineClassesUtilsKt;
|
||||
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall;
|
||||
import org.jetbrains.kotlin.resolve.jvm.InlineClassManglingRulesKt;
|
||||
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin;
|
||||
@@ -192,6 +193,7 @@ public class ConstructorCodegen {
|
||||
markLineNumberForConstructor(constructorDescriptor, primaryConstructor, codegen);
|
||||
|
||||
if (OwnerKind.ERASED_INLINE_CLASS == kind) {
|
||||
memberCodegen.generateInitializers(() -> codegen);
|
||||
Type t = typeMapper.mapType(constructorDescriptor.getContainingDeclaration());
|
||||
iv.load(0, t);
|
||||
iv.areturn(t);
|
||||
@@ -226,7 +228,7 @@ public class ConstructorCodegen {
|
||||
}
|
||||
|
||||
//object initialization was moved to initializeObjects()
|
||||
if (!isObject(descriptor)) {
|
||||
if (!isObject(descriptor) && !InlineClassesUtilsKt.isInlineClass(descriptor)) {
|
||||
memberCodegen.generateInitializers(() -> codegen);
|
||||
}
|
||||
iv.visitInsn(RETURN);
|
||||
|
||||
+6
-2
@@ -17,6 +17,7 @@
|
||||
package org.jetbrains.kotlin.codegen
|
||||
|
||||
import org.jetbrains.kotlin.codegen.JvmCodegenUtil.getDispatchReceiverParameterForConstructorCall
|
||||
import org.jetbrains.kotlin.codegen.JvmCodegenUtil.isJvmInterface
|
||||
import org.jetbrains.kotlin.codegen.binding.CodegenBinding
|
||||
import org.jetbrains.kotlin.codegen.state.GenerationState
|
||||
import org.jetbrains.kotlin.config.LanguageFeature
|
||||
@@ -32,6 +33,7 @@ import org.jetbrains.kotlin.resolve.jvm.AsmTypes
|
||||
import org.jetbrains.kotlin.resolve.jvm.annotations.findJvmOverloadsAnnotation
|
||||
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin
|
||||
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOriginKind
|
||||
import org.jetbrains.kotlin.resolve.jvm.shouldHideConstructorDueToInlineClassTypeValueParameters
|
||||
import org.jetbrains.org.objectweb.asm.Label
|
||||
import org.jetbrains.org.objectweb.asm.Opcodes
|
||||
import org.jetbrains.org.objectweb.asm.Type
|
||||
@@ -134,8 +136,9 @@ class DefaultParameterValueSubstitutor(val state: GenerationState) {
|
||||
remainingParameters.map { DescriptorToSourceUtils.descriptorToDeclaration(it) as? KtParameter }
|
||||
|
||||
val generateAsFinal =
|
||||
functionDescriptor.modality == Modality.FINAL ||
|
||||
state.languageVersionSettings.supportsFeature(LanguageFeature.GenerateJvmOverloadsAsFinal)
|
||||
(functionDescriptor.modality == Modality.FINAL ||
|
||||
state.languageVersionSettings.supportsFeature(LanguageFeature.GenerateJvmOverloadsAsFinal)) &&
|
||||
!isJvmInterface(functionDescriptor.containingDeclaration)
|
||||
val flags =
|
||||
baseMethodFlags or
|
||||
(if (isStatic) Opcodes.ACC_STATIC else 0) or
|
||||
@@ -265,6 +268,7 @@ class DefaultParameterValueSubstitutor(val state: GenerationState) {
|
||||
|
||||
if (classOrObject.isLocal) return false
|
||||
if (classDescriptor.isInline) return false
|
||||
if (shouldHideConstructorDueToInlineClassTypeValueParameters(constructorDescriptor)) return false
|
||||
|
||||
if (CodegenBinding.canHaveOuter(state.bindingContext, classDescriptor)) return false
|
||||
|
||||
|
||||
@@ -188,8 +188,7 @@ public class DescriptorAsmUtil {
|
||||
|
||||
if (functionDescriptor.getModality() == Modality.FINAL && !(functionDescriptor instanceof ConstructorDescriptor)) {
|
||||
DeclarationDescriptor containingDeclaration = functionDescriptor.getContainingDeclaration();
|
||||
if (!(containingDeclaration instanceof ClassDescriptor) ||
|
||||
((ClassDescriptor) containingDeclaration).getKind() != ClassKind.INTERFACE) {
|
||||
if (!isJvmInterface(containingDeclaration)) {
|
||||
flags |= ACC_FINAL;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,8 +44,10 @@ import org.jetbrains.kotlin.codegen.when.SwitchCodegen;
|
||||
import org.jetbrains.kotlin.codegen.when.SwitchCodegenProvider;
|
||||
import org.jetbrains.kotlin.config.ApiVersion;
|
||||
import org.jetbrains.kotlin.config.JVMAssertionsMode;
|
||||
import org.jetbrains.kotlin.config.JVMConfigurationKeys;
|
||||
import org.jetbrains.kotlin.config.LanguageFeature;
|
||||
import org.jetbrains.kotlin.descriptors.*;
|
||||
import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor;
|
||||
import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor;
|
||||
import org.jetbrains.kotlin.descriptors.impl.SyntheticFieldDescriptor;
|
||||
import org.jetbrains.kotlin.descriptors.impl.TypeAliasConstructorDescriptor;
|
||||
@@ -1705,26 +1707,38 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
|
||||
Type returnType;
|
||||
KotlinType returnKotlinType;
|
||||
if (isNonLocalReturn) {
|
||||
// This is inline lambda. Find inline-site and check, whether it is suspend functions returning unboxed inline class
|
||||
CodegenContext<?> inlineSiteContext = this.context.getFirstCrossInlineOrNonInlineContext();
|
||||
KotlinType originalInlineClass = null;
|
||||
boolean invokeSuspendOfLambda = false;
|
||||
FunctionDescriptor inlineSiteDescriptor = null;
|
||||
if (inlineSiteContext instanceof MethodContext) {
|
||||
inlineSiteDescriptor = ((MethodContext) inlineSiteContext).getFunctionDescriptor();
|
||||
originalInlineClass = CoroutineCodegenUtilKt
|
||||
.originalReturnTypeOfSuspendFunctionReturningUnboxedInlineClass(inlineSiteDescriptor, typeMapper);
|
||||
invokeSuspendOfLambda = CoroutineCodegenUtilKt.isInvokeSuspendOfLambda(inlineSiteDescriptor);
|
||||
}
|
||||
if (originalInlineClass != null) {
|
||||
returnType = typeMapper.mapType(originalInlineClass);
|
||||
returnKotlinType = originalInlineClass;
|
||||
} else if (!invokeSuspendOfLambda) {
|
||||
returnType = nonLocalReturn.returnType.getType();
|
||||
returnKotlinType = nonLocalReturn.returnType.getKotlinType();
|
||||
} else {
|
||||
FunctionDescriptor returnTarget =
|
||||
nonLocalReturn.descriptor instanceof FunctionDescriptor
|
||||
? (FunctionDescriptor) nonLocalReturn.descriptor
|
||||
: null;
|
||||
if (returnTarget == null || !returnTarget.isSuspend()) {
|
||||
JvmKotlinType jvmKotlinType = nonLocalReturn.getJvmKotlinType(typeMapper);
|
||||
returnType = jvmKotlinType.getType();
|
||||
returnKotlinType = jvmKotlinType.getKotlinType();
|
||||
} else if (returnTarget instanceof AnonymousFunctionDescriptor) {
|
||||
// Suspend lambdas always return Any?
|
||||
returnType = OBJECT_TYPE;
|
||||
returnKotlinType = inlineSiteDescriptor.getReturnType();
|
||||
returnKotlinType = state.getModule().getBuiltIns().getNullableAnyType();
|
||||
} else {
|
||||
// This is inline lambda, but return target is ordinary, yet suspend, function.
|
||||
// Find inline-site and check, whether it is suspend functions returning unboxed inline class
|
||||
CodegenContext<?> inlineSiteContext = this.context.getFirstCrossInlineOrNonInlineContext();
|
||||
KotlinType originalInlineClass = null;
|
||||
if (inlineSiteContext instanceof MethodContext) {
|
||||
FunctionDescriptor view = CoroutineCodegenUtilKt.getOrCreateJvmSuspendFunctionView(returnTarget, state);
|
||||
originalInlineClass =
|
||||
CoroutineCodegenUtilKt.originalReturnTypeOfSuspendFunctionReturningUnboxedInlineClass(view, typeMapper);
|
||||
}
|
||||
if (originalInlineClass != null) {
|
||||
// As an optimization, suspend functions, returning inline classes with reference underlying
|
||||
// type return unboxed inline class. Save the type so the coercer will not box it.
|
||||
returnType = typeMapper.mapType(originalInlineClass);
|
||||
returnKotlinType = originalInlineClass;
|
||||
} else {
|
||||
JvmKotlinType jvmKotlinType = nonLocalReturn.getJvmKotlinType(typeMapper);
|
||||
returnType = jvmKotlinType.getType();
|
||||
returnKotlinType = jvmKotlinType.getKotlinType();
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
@@ -1788,13 +1802,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
|
||||
FunctionDescriptor containingFunction =
|
||||
BindingContextUtils.getContainingFunctionSkipFunctionLiterals(descriptor, true).getFirst();
|
||||
//FIRST_FUN_LABEL to prevent clashing with existing labels
|
||||
return new NonLocalReturnInfo(
|
||||
new JvmKotlinType(
|
||||
typeMapper.mapReturnType(containingFunction),
|
||||
containingFunction.getReturnType()
|
||||
),
|
||||
FIRST_FUN_LABEL
|
||||
);
|
||||
return new NonLocalReturnInfo(containingFunction, FIRST_FUN_LABEL);
|
||||
} else {
|
||||
//local
|
||||
return null;
|
||||
@@ -1807,10 +1815,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
|
||||
assert element != null : "Expression should be not null " + expression.getText();
|
||||
assert elementDescriptor != null : "Descriptor should be not null: " + element.getText();
|
||||
CallableDescriptor function = (CallableDescriptor) elementDescriptor;
|
||||
return new NonLocalReturnInfo(
|
||||
new JvmKotlinType(typeMapper.mapReturnType(function), function.getReturnType()),
|
||||
expression.getLabelName()
|
||||
);
|
||||
return new NonLocalReturnInfo(function, expression.getLabelName());
|
||||
}
|
||||
}
|
||||
return null;
|
||||
@@ -2680,7 +2685,21 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
|
||||
fd = ArgumentGeneratorKt.getFunctionWithDefaultArguments(fd);
|
||||
}
|
||||
|
||||
return typeMapper.mapToCallableMethod(fd, superCall, null, resolvedCall);
|
||||
CallableMethod method = typeMapper.mapToCallableMethod(fd, superCall, null, resolvedCall);
|
||||
|
||||
if (method.getAsmMethod().getName().contains("-") &&
|
||||
!state.getConfiguration().getBoolean(JVMConfigurationKeys.USE_OLD_INLINE_CLASSES_MANGLING_SCHEME)
|
||||
) {
|
||||
Boolean classFileContainsMethod =
|
||||
InlineClassesCodegenUtilKt.classFileContainsMethod(fd, state, method.getAsmMethod());
|
||||
if (classFileContainsMethod != null && !classFileContainsMethod) {
|
||||
typeMapper.setUseOldManglingRulesForFunctionAcceptingInlineClass(true);
|
||||
method = typeMapper.mapToCallableMethod(fd, superCall, null, resolvedCall);
|
||||
typeMapper.setUseOldManglingRulesForFunctionAcceptingInlineClass(false);
|
||||
}
|
||||
}
|
||||
|
||||
return method;
|
||||
}
|
||||
|
||||
public void invokeMethodWithArguments(
|
||||
@@ -2896,6 +2915,17 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
|
||||
|
||||
sourceCompiler.initializeInlineFunctionContext(functionDescriptor);
|
||||
JvmMethodSignature signature = typeMapper.mapSignatureWithGeneric(functionDescriptor, sourceCompiler.getContextKind());
|
||||
if (signature.getAsmMethod().getName().contains("-") &&
|
||||
!state.getConfiguration().getBoolean(JVMConfigurationKeys.USE_OLD_INLINE_CLASSES_MANGLING_SCHEME)
|
||||
) {
|
||||
Boolean classFileContainsMethod =
|
||||
InlineClassesCodegenUtilKt.classFileContainsMethod(functionDescriptor, state, signature.getAsmMethod());
|
||||
if (classFileContainsMethod != null && !classFileContainsMethod) {
|
||||
typeMapper.setUseOldManglingRulesForFunctionAcceptingInlineClass(true);
|
||||
signature = typeMapper.mapSignatureWithGeneric(functionDescriptor, sourceCompiler.getContextKind());
|
||||
typeMapper.setUseOldManglingRulesForFunctionAcceptingInlineClass(false);
|
||||
}
|
||||
}
|
||||
Type methodOwner = typeMapper.mapImplementationOwner(functionDescriptor);
|
||||
if (isDefaultCompilation) {
|
||||
return new InlineCodegenForDefaultBody(functionDescriptor, this, state, methodOwner, signature, sourceCompiler);
|
||||
@@ -5427,14 +5457,18 @@ The "returned" value of try expression with no finally is either the last expres
|
||||
|
||||
private static class NonLocalReturnInfo {
|
||||
|
||||
private final JvmKotlinType returnType;
|
||||
private final CallableDescriptor descriptor;
|
||||
|
||||
private final String labelName;
|
||||
|
||||
private NonLocalReturnInfo(@NotNull JvmKotlinType type, @NotNull String name) {
|
||||
returnType = type;
|
||||
private NonLocalReturnInfo(@NotNull CallableDescriptor descriptor, @NotNull String name) {
|
||||
this.descriptor = descriptor;
|
||||
labelName = name;
|
||||
}
|
||||
|
||||
private JvmKotlinType getJvmKotlinType(@NotNull KotlinTypeMapper typeMapper) {
|
||||
return new JvmKotlinType(typeMapper.mapReturnType(descriptor), descriptor.getReturnType());
|
||||
}
|
||||
}
|
||||
|
||||
@NotNull
|
||||
|
||||
@@ -85,7 +85,6 @@ import static org.jetbrains.kotlin.types.expressions.ExpressionTypingUtils.*;
|
||||
import static org.jetbrains.org.objectweb.asm.Opcodes.*;
|
||||
|
||||
public class FunctionCodegen {
|
||||
private static final String JAVA_LANG_DEPRECATED = Type.getType(Deprecated.class).getDescriptor();
|
||||
|
||||
public final GenerationState state;
|
||||
private final KotlinTypeMapper typeMapper;
|
||||
@@ -225,7 +224,7 @@ public class FunctionCodegen {
|
||||
InlineClassDescriptorResolver.isSpecializedEqualsMethod(functionDescriptor);
|
||||
generateMethodAnnotationsIfRequired(
|
||||
functionDescriptor, asmMethod, jvmSignature, mv,
|
||||
isCompatibilityStubInDefaultImpls ? Collections.singletonList(JAVA_LANG_DEPRECATED) : Collections.emptyList(),
|
||||
isCompatibilityStubInDefaultImpls ? Collections.singletonList(CodegenUtilKt.JAVA_LANG_DEPRECATED) : Collections.emptyList(),
|
||||
skipNullabilityAnnotations
|
||||
);
|
||||
GenerateJava8ParameterNamesKt.generateParameterNames(functionDescriptor, mv, jvmSignature, state, (flags & ACC_SYNTHETIC) != 0);
|
||||
|
||||
@@ -903,19 +903,26 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
|
||||
}
|
||||
|
||||
private void generateCompanionObjectBackingFieldCopies() {
|
||||
if (companionObjectPropertiesToCopy == null) return;
|
||||
if (companionObjectPropertiesToCopy == null || companionObjectPropertiesToCopy.isEmpty()) return;
|
||||
|
||||
boolean isPrivateCompanion =
|
||||
DescriptorVisibilities.isPrivate(
|
||||
((ClassDescriptor) companionObjectPropertiesToCopy.get(0).descriptor.getContainingDeclaration()).getVisibility());
|
||||
|
||||
int modifiers = ACC_STATIC | ACC_FINAL | ACC_PUBLIC | (isPrivateCompanion ? ACC_DEPRECATED : 0);
|
||||
List<String> additionalVisibleAnnotations =
|
||||
isPrivateCompanion ? Collections.singletonList(CodegenUtilKt.JAVA_LANG_DEPRECATED) : Collections.emptyList();
|
||||
for (PropertyAndDefaultValue info : companionObjectPropertiesToCopy) {
|
||||
PropertyDescriptor property = info.descriptor;
|
||||
|
||||
Type type = typeMapper.mapType(property);
|
||||
int modifiers = ACC_STATIC | ACC_FINAL | ACC_PUBLIC;
|
||||
|
||||
FieldVisitor fv = v.newField(JvmDeclarationOriginKt.Synthetic(DescriptorToSourceUtils.descriptorToDeclaration(property), property),
|
||||
modifiers, context.getFieldName(property, false),
|
||||
type.getDescriptor(), typeMapper.mapFieldSignature(property.getType(), property),
|
||||
info.defaultValue);
|
||||
|
||||
AnnotationCodegen.forField(fv, this, state).genAnnotations(property, type, null);
|
||||
AnnotationCodegen.forField(fv, this, state).genAnnotations(property, type, null, null, additionalVisibleAnnotations);
|
||||
|
||||
//This field are always static and final so if it has constant initializer don't do anything in clinit,
|
||||
//field would be initialized via default value in v.newField(...) - see JVM SPEC Ch.4
|
||||
|
||||
@@ -75,7 +75,7 @@ public class PackageCodegenImpl implements PackageCodegen {
|
||||
}
|
||||
catch (Throwable e) {
|
||||
VirtualFile vFile = file.getVirtualFile();
|
||||
CodegenUtil.reportBackendException(e, "file facade code generation", vFile == null ? null : vFile.getUrl());
|
||||
CodegenUtil.reportBackendException(e, "file facade code generation", vFile == null ? null : vFile.getUrl(), null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,9 +42,11 @@ import org.jetbrains.org.objectweb.asm.Type;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
import static org.jetbrains.kotlin.codegen.DescriptorAsmUtil.writeAnnotationData;
|
||||
import static org.jetbrains.kotlin.load.java.JvmAnnotationNames.METADATA_PACKAGE_NAME_FIELD_NAME;
|
||||
import static org.jetbrains.kotlin.resolve.jvm.annotations.JvmAnnotationUtilKt.JVM_SYNTHETIC_ANNOTATION_FQ_NAME;
|
||||
import static org.jetbrains.org.objectweb.asm.Opcodes.*;
|
||||
|
||||
public class PackagePartCodegen extends MemberCodegen<KtFile> {
|
||||
@@ -63,8 +65,20 @@ public class PackagePartCodegen extends MemberCodegen<KtFile> {
|
||||
|
||||
@Override
|
||||
protected void generateDeclaration() {
|
||||
boolean isSynthetic = false;
|
||||
List<AnnotationDescriptor> fileAnnotationDescriptors = new ArrayList<>();
|
||||
for (KtAnnotationEntry annotationEntry : element.getAnnotationEntries()) {
|
||||
AnnotationDescriptor annotationDescriptor = state.getBindingContext().get(BindingContext.ANNOTATION, annotationEntry);
|
||||
if (annotationDescriptor != null) {
|
||||
fileAnnotationDescriptors.add(annotationDescriptor);
|
||||
if (Objects.equals(annotationDescriptor.getFqName(), JVM_SYNTHETIC_ANNOTATION_FQ_NAME)) {
|
||||
isSynthetic = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
v.defineClass(element, state.getClassFileVersion(),
|
||||
ACC_PUBLIC | ACC_FINAL | ACC_SUPER,
|
||||
ACC_PUBLIC | ACC_FINAL | ACC_SUPER | (isSynthetic ? ACC_SYNTHETIC : 0),
|
||||
packagePartType.getInternalName(),
|
||||
null,
|
||||
"java/lang/Object",
|
||||
@@ -74,17 +88,6 @@ public class PackagePartCodegen extends MemberCodegen<KtFile> {
|
||||
|
||||
generatePropertyMetadataArrayFieldIfNeeded(packagePartType);
|
||||
|
||||
generateAnnotationsForPartClass();
|
||||
}
|
||||
|
||||
private void generateAnnotationsForPartClass() {
|
||||
List<AnnotationDescriptor> fileAnnotationDescriptors = new ArrayList<>();
|
||||
for (KtAnnotationEntry annotationEntry : element.getAnnotationEntries()) {
|
||||
AnnotationDescriptor annotationDescriptor = state.getBindingContext().get(BindingContext.ANNOTATION, annotationEntry);
|
||||
if (annotationDescriptor != null) {
|
||||
fileAnnotationDescriptors.add(annotationDescriptor);
|
||||
}
|
||||
}
|
||||
Annotated annotatedFile = new AnnotatedImpl(Annotations.Companion.create(fileAnnotationDescriptors));
|
||||
AnnotationCodegen.forClass(v.getVisitor(), this, state).genAnnotations(annotatedFile, null, null);
|
||||
}
|
||||
|
||||
@@ -42,6 +42,7 @@ import org.jetbrains.org.objectweb.asm.Type;
|
||||
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter;
|
||||
import org.jetbrains.org.objectweb.asm.commons.Method;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static org.jetbrains.kotlin.codegen.DescriptorAsmUtil.getDeprecatedAccessFlag;
|
||||
@@ -408,6 +409,7 @@ public class PropertyCodegen {
|
||||
ClassBuilder builder = v;
|
||||
|
||||
FieldOwnerContext backingFieldContext = context;
|
||||
List<String> additionalVisibleAnnotations = Collections.emptyList();
|
||||
if (DescriptorAsmUtil.isInstancePropertyWithStaticBackingField(propertyDescriptor) ) {
|
||||
modifiers |= ACC_STATIC;
|
||||
|
||||
@@ -415,6 +417,10 @@ public class PropertyCodegen {
|
||||
ImplementationBodyCodegen codegen = (ImplementationBodyCodegen) memberCodegen.getParentCodegen();
|
||||
builder = codegen.v;
|
||||
backingFieldContext = codegen.context;
|
||||
if (DescriptorVisibilities.isPrivate(((ClassDescriptor) propertyDescriptor.getContainingDeclaration()).getVisibility())) {
|
||||
modifiers |= ACC_DEPRECATED;
|
||||
additionalVisibleAnnotations = Collections.singletonList(CodegenUtilKt.JAVA_LANG_DEPRECATED);
|
||||
}
|
||||
}
|
||||
}
|
||||
modifiers |= getVisibilityForBackingField(propertyDescriptor, isDelegate);
|
||||
@@ -442,7 +448,7 @@ public class PropertyCodegen {
|
||||
(modifiers & ACC_SYNTHETIC) != 0 ||
|
||||
propertyDescriptor.isLateInit();
|
||||
AnnotationCodegen.forField(fv, memberCodegen, state, skipNullabilityAnnotations)
|
||||
.genAnnotations(annotatedField, type, propertyDescriptor.getType());
|
||||
.genAnnotations(annotatedField, type, propertyDescriptor.getType(), null, additionalVisibleAnnotations);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -672,8 +672,8 @@ public abstract class StackValue {
|
||||
box(fromType, toType, v);
|
||||
}
|
||||
}
|
||||
else if (fromType.getSort() == Type.OBJECT) {
|
||||
//toType is primitive here
|
||||
else if (fromType.getSort() == Type.OBJECT || fromType.getSort() == Type.ARRAY) {
|
||||
// here toType is primitive and fromType is reference (object or array)
|
||||
Type unboxedType = unboxPrimitiveTypeOrNull(fromType);
|
||||
if (unboxedType != null) {
|
||||
unbox(fromType, unboxedType, v);
|
||||
|
||||
@@ -8,6 +8,7 @@ package org.jetbrains.kotlin.codegen
|
||||
import com.intellij.psi.PsiElement
|
||||
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
|
||||
import org.jetbrains.kotlin.builtins.UnsignedTypes
|
||||
import org.jetbrains.kotlin.codegen.JvmCodegenUtil.isJvmInterface
|
||||
import org.jetbrains.kotlin.codegen.binding.CodegenBinding
|
||||
import org.jetbrains.kotlin.codegen.context.CodegenContext
|
||||
import org.jetbrains.kotlin.codegen.context.FieldOwnerContext
|
||||
@@ -24,8 +25,8 @@ import org.jetbrains.kotlin.config.isReleaseCoroutines
|
||||
import org.jetbrains.kotlin.descriptors.*
|
||||
import org.jetbrains.kotlin.descriptors.deserialization.PLATFORM_DEPENDENT_ANNOTATION_FQ_NAME
|
||||
import org.jetbrains.kotlin.descriptors.impl.ValueParameterDescriptorImpl
|
||||
import org.jetbrains.kotlin.load.java.SpecialGenericSignatures.SpecialSignatureInfo
|
||||
import org.jetbrains.kotlin.load.java.DescriptorsJvmAbiUtil
|
||||
import org.jetbrains.kotlin.load.java.SpecialGenericSignatures.SpecialSignatureInfo
|
||||
import org.jetbrains.kotlin.load.java.descriptors.JavaCallableMemberDescriptor
|
||||
import org.jetbrains.kotlin.name.ClassId
|
||||
import org.jetbrains.kotlin.name.FqName
|
||||
@@ -60,8 +61,12 @@ import org.jetbrains.org.objectweb.asm.Type
|
||||
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter
|
||||
import org.jetbrains.org.objectweb.asm.commons.Method
|
||||
import org.jetbrains.org.objectweb.asm.tree.LabelNode
|
||||
import java.lang.Deprecated
|
||||
import java.util.*
|
||||
|
||||
@JvmField
|
||||
internal val JAVA_LANG_DEPRECATED = Type.getType(Deprecated::class.java).descriptor
|
||||
|
||||
fun generateIsCheck(
|
||||
v: InstructionAdapter,
|
||||
kotlinType: KotlinType,
|
||||
@@ -240,7 +245,7 @@ fun CallableDescriptor.isJvmStaticInObjectOrClassOrInterface(): Boolean =
|
||||
DescriptorUtils.isNonCompanionObject(it) ||
|
||||
// This is necessary because for generation of @JvmStatic methods from companion of class A
|
||||
// we create a synthesized descriptor containing in class A
|
||||
DescriptorUtils.isClassOrEnumClass(it) || DescriptorUtils.isInterface(it)
|
||||
DescriptorUtils.isClassOrEnumClass(it) || isJvmInterface(it)
|
||||
}
|
||||
|
||||
fun CallableDescriptor.isJvmStaticInCompanionObject(): Boolean =
|
||||
|
||||
@@ -84,15 +84,20 @@ class SourceMapper(val sourceInfo: SourceInfo?) {
|
||||
val resultMappings: List<FileMapping>
|
||||
get() = fileMappings.values.toList()
|
||||
|
||||
companion object {
|
||||
const val FAKE_FILE_NAME = "fake.kt"
|
||||
const val FAKE_PATH = "kotlin/jvm/internal/FakeKt"
|
||||
}
|
||||
|
||||
init {
|
||||
sourceInfo?.let { sourceInfo ->
|
||||
// If 'sourceFileName' is null, this class doesn't have debug information
|
||||
// (e.g., multi-file class facade with multiple parts).
|
||||
sourceInfo.sourceFileName?.let { sourceFileName ->
|
||||
// Explicitly map the file to itself -- we'll probably need a lot of lines from it, so this will produce fewer ranges.
|
||||
getOrRegisterNewSource(sourceFileName, sourceInfo.pathOrCleanFQN)
|
||||
.mapNewInterval(1, 1, sourceInfo.linesInFile)
|
||||
}
|
||||
// If 'sourceFileName' is null we are dealing with a synthesized class
|
||||
// (e.g., multi-file class facade with multiple parts). Such classes
|
||||
// only have synthetic debug information and we use a fake file name.
|
||||
val sourceFileName = sourceInfo.sourceFileName ?: FAKE_FILE_NAME
|
||||
// Explicitly map the file to itself -- we'll probably need a lot of lines from it, so this will produce fewer ranges.
|
||||
getOrRegisterNewSource(sourceFileName, sourceInfo.pathOrCleanFQN)
|
||||
.mapNewInterval(1, 1, sourceInfo.linesInFile)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,7 +115,7 @@ class SourceMapper(val sourceInfo: SourceInfo?) {
|
||||
}
|
||||
|
||||
fun mapSyntheticLineNumber(id: Int): Int {
|
||||
return mapLineNumber(SourcePosition(id, "fake.kt", "kotlin/jvm/internal/FakeKt"), null)
|
||||
return mapLineNumber(SourcePosition(id, FAKE_FILE_NAME, FAKE_PATH), null)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,15 +5,28 @@
|
||||
|
||||
package org.jetbrains.kotlin.codegen
|
||||
|
||||
import org.jetbrains.kotlin.codegen.state.GenerationState
|
||||
import org.jetbrains.kotlin.descriptors.CallableDescriptor
|
||||
import org.jetbrains.kotlin.descriptors.ClassDescriptor
|
||||
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
|
||||
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
|
||||
import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor
|
||||
import org.jetbrains.kotlin.load.kotlin.JvmPackagePartSource
|
||||
import org.jetbrains.kotlin.load.kotlin.VirtualFileFinder
|
||||
import org.jetbrains.kotlin.name.ClassId
|
||||
import org.jetbrains.kotlin.resolve.descriptorUtil.classId
|
||||
import org.jetbrains.kotlin.resolve.isInlineClassType
|
||||
import org.jetbrains.kotlin.resolve.underlyingRepresentation
|
||||
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedClassDescriptor
|
||||
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedSimpleFunctionDescriptor
|
||||
import org.jetbrains.kotlin.types.KotlinType
|
||||
import org.jetbrains.kotlin.types.typeUtil.isAnyOrNullableAny
|
||||
import org.jetbrains.kotlin.types.typeUtil.isTypeParameter
|
||||
import org.jetbrains.org.objectweb.asm.ClassReader
|
||||
import org.jetbrains.org.objectweb.asm.ClassVisitor
|
||||
import org.jetbrains.org.objectweb.asm.MethodVisitor
|
||||
import org.jetbrains.org.objectweb.asm.Opcodes
|
||||
import org.jetbrains.org.objectweb.asm.commons.Method
|
||||
|
||||
fun KotlinType.isInlineClassWithUnderlyingTypeAnyOrAnyN(): Boolean {
|
||||
if (!isInlineClassType()) return false
|
||||
@@ -26,4 +39,39 @@ fun CallableDescriptor.isGenericParameter(): Boolean {
|
||||
if (containingDeclaration is AnonymousFunctionDescriptor) return true
|
||||
val index = containingDeclaration.valueParameters.indexOf(this)
|
||||
return containingDeclaration.overriddenDescriptors.any { it.original.valueParameters[index].type.isTypeParameter() }
|
||||
}
|
||||
|
||||
fun classFileContainsMethod(descriptor: FunctionDescriptor, state: GenerationState, method: Method): Boolean? {
|
||||
if (descriptor !is DeserializedSimpleFunctionDescriptor) return null
|
||||
|
||||
val classId: ClassId = when {
|
||||
descriptor.containingDeclaration is DeserializedClassDescriptor -> {
|
||||
(descriptor.containingDeclaration as DeserializedClassDescriptor).classId ?: return null
|
||||
}
|
||||
descriptor.containerSource is JvmPackagePartSource -> {
|
||||
(descriptor.containerSource as JvmPackagePartSource).classId
|
||||
}
|
||||
else -> {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
val bytes = VirtualFileFinder.getInstance(state.project, state.module).findVirtualFileWithHeader(classId)
|
||||
?.contentsToByteArray() ?: return null
|
||||
var found = false
|
||||
ClassReader(bytes).accept(object : ClassVisitor(Opcodes.API_VERSION) {
|
||||
override fun visitMethod(
|
||||
access: Int,
|
||||
name: String?,
|
||||
descriptor: String?,
|
||||
signature: String?,
|
||||
exceptions: Array<out String>?
|
||||
): MethodVisitor? {
|
||||
if (name == method.name && descriptor == method.descriptor) {
|
||||
found = true
|
||||
}
|
||||
return super.visitMethod(access, name, descriptor, signature, exceptions)
|
||||
}
|
||||
}, ClassReader.SKIP_FRAMES)
|
||||
return found
|
||||
}
|
||||
+16
@@ -12,6 +12,7 @@ import org.jetbrains.kotlin.codegen.createFreeFakeLocalPropertyDescriptor
|
||||
import org.jetbrains.kotlin.codegen.serialization.JvmSerializationBindings.*
|
||||
import org.jetbrains.kotlin.codegen.state.GenerationState
|
||||
import org.jetbrains.kotlin.codegen.state.KotlinTypeMapperBase
|
||||
import org.jetbrains.kotlin.config.JVMConfigurationKeys
|
||||
import org.jetbrains.kotlin.config.JvmDefaultMode
|
||||
import org.jetbrains.kotlin.config.LanguageFeature
|
||||
import org.jetbrains.kotlin.descriptors.*
|
||||
@@ -60,6 +61,7 @@ class JvmSerializerExtension @JvmOverloads constructor(
|
||||
override val metadataVersion = state.metadataVersion
|
||||
private val jvmDefaultMode = state.jvmDefaultMode
|
||||
private val approximator = state.typeApproximator
|
||||
private val useOldManglingScheme = state.useOldManglingSchemeForFunctionsWithInlineClassesInSignatures
|
||||
|
||||
override fun shouldUseTypeTable(): Boolean = useTypeTable
|
||||
override fun shouldSerializeFunction(descriptor: FunctionDescriptor): Boolean {
|
||||
@@ -215,6 +217,13 @@ class JvmSerializerExtension @JvmOverloads constructor(
|
||||
) {
|
||||
versionRequirementTable?.writeFunctionNameManglingForReturnTypeRequirement(proto::addVersionRequirement)
|
||||
}
|
||||
|
||||
if ((requiresFunctionNameManglingForReturnType(descriptor) ||
|
||||
requiresFunctionNameManglingForParameterTypes(descriptor)) &&
|
||||
!DescriptorUtils.hasJvmNameAnnotation(descriptor) && !useOldManglingScheme
|
||||
) {
|
||||
versionRequirementTable?.writeNewFunctionNameManglingRequirement(proto::addVersionRequirement)
|
||||
}
|
||||
}
|
||||
|
||||
private fun MutableVersionRequirementTable.writeInlineParameterNullCheckRequirement(add: (Int) -> Unit) {
|
||||
@@ -231,6 +240,10 @@ class JvmSerializerExtension @JvmOverloads constructor(
|
||||
}
|
||||
}
|
||||
|
||||
private fun MutableVersionRequirementTable.writeNewFunctionNameManglingRequirement(add: (Int) -> Unit) {
|
||||
add(writeVersionRequirement(1, 4, 30, ProtoBuf.VersionRequirement.VersionKind.COMPILER_VERSION, this))
|
||||
}
|
||||
|
||||
private fun FunctionDescriptor.needsInlineParameterNullCheckRequirement(): Boolean =
|
||||
isInline && !isSuspend && !isParamAssertionsDisabled &&
|
||||
!DescriptorVisibilities.isPrivate(visibility) &&
|
||||
@@ -278,6 +291,9 @@ class JvmSerializerExtension @JvmOverloads constructor(
|
||||
}
|
||||
|
||||
if (!DescriptorUtils.hasJvmNameAnnotation(descriptor) && requiresFunctionNameManglingForReturnType(descriptor)) {
|
||||
if (!useOldManglingScheme) {
|
||||
versionRequirementTable?.writeNewFunctionNameManglingRequirement(proto::addVersionRequirement)
|
||||
}
|
||||
versionRequirementTable?.writeFunctionNameManglingForReturnTypeRequirement(proto::addVersionRequirement)
|
||||
}
|
||||
}
|
||||
|
||||
+2
-1
@@ -17,7 +17,8 @@ class KotlinToJvmSignatureMapperImpl : KotlinToJvmSignatureMapper {
|
||||
private val typeMapper = KotlinTypeMapper(
|
||||
BindingContext.EMPTY, ClassBuilderMode.LIGHT_CLASSES,
|
||||
JvmProtoBufUtil.DEFAULT_MODULE_NAME,
|
||||
KotlinTypeMapper.LANGUAGE_VERSION_SETTINGS_DEFAULT// TODO use proper LanguageVersionSettings
|
||||
KotlinTypeMapper.LANGUAGE_VERSION_SETTINGS_DEFAULT,// TODO use proper LanguageVersionSettings
|
||||
useOldInlineClassesManglingScheme = false
|
||||
)
|
||||
|
||||
override fun mapToJvmMethodSignature(function: FunctionDescriptor) = typeMapper.mapAsmMethod(function)
|
||||
|
||||
+3
-1
@@ -50,12 +50,14 @@ class BuilderFactoryForDuplicateSignatureDiagnostics(
|
||||
private val diagnostics: DiagnosticSink,
|
||||
moduleName: String,
|
||||
languageVersionSettings: LanguageVersionSettings,
|
||||
useOldInlineClassesManglingScheme: Boolean,
|
||||
shouldGenerate: (JvmDeclarationOrigin) -> Boolean,
|
||||
) : SignatureCollectingClassBuilderFactory(builderFactory, shouldGenerate) {
|
||||
|
||||
private val mapAsmMethod: (FunctionDescriptor) -> Method = KotlinTypeMapper(
|
||||
// Avoid errors when some classes are not loaded for some reason
|
||||
bindingContext, ClassBuilderMode.LIGHT_CLASSES, moduleName, languageVersionSettings, isIrBackend = false
|
||||
bindingContext, ClassBuilderMode.LIGHT_CLASSES, moduleName, languageVersionSettings, isIrBackend = false,
|
||||
useOldInlineClassesManglingScheme = useOldInlineClassesManglingScheme
|
||||
)::mapAsmMethod
|
||||
|
||||
private val reportDiagnosticsTasks = ArrayList<() -> Unit>()
|
||||
|
||||
@@ -39,6 +39,7 @@ import org.jetbrains.kotlin.resolve.*
|
||||
import org.jetbrains.kotlin.resolve.deprecation.CoroutineCompatibilitySupport
|
||||
import org.jetbrains.kotlin.resolve.deprecation.DeprecationResolver
|
||||
import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics
|
||||
import org.jetbrains.kotlin.resolve.diagnostics.PrecomputedSuppressCache
|
||||
import org.jetbrains.kotlin.resolve.jvm.JvmClassName
|
||||
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin
|
||||
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOriginKind.*
|
||||
@@ -178,7 +179,11 @@ class GenerationState private constructor(
|
||||
}
|
||||
|
||||
val extraJvmDiagnosticsTrace: BindingTrace =
|
||||
DelegatingBindingTrace(originalFrontendBindingContext, "For extra diagnostics in ${this::class.java}", false)
|
||||
DelegatingBindingTrace(
|
||||
originalFrontendBindingContext, "For extra diagnostics in ${this::class.java}", false,
|
||||
customSuppressCache = if (isIrBackend) PrecomputedSuppressCache(originalFrontendBindingContext, files) else null,
|
||||
)
|
||||
|
||||
private val interceptedBuilderFactory: ClassBuilderFactory
|
||||
private var used = false
|
||||
|
||||
@@ -190,6 +195,10 @@ class GenerationState private constructor(
|
||||
|
||||
val languageVersionSettings = configuration.languageVersionSettings
|
||||
|
||||
val useOldManglingSchemeForFunctionsWithInlineClassesInSignatures =
|
||||
configuration.getBoolean(JVMConfigurationKeys.USE_OLD_INLINE_CLASSES_MANGLING_SCHEME) ||
|
||||
languageVersionSettings.languageVersion.run { major == 1 && minor < 4 }
|
||||
|
||||
val target = configuration.get(JVMConfigurationKeys.JVM_TARGET) ?: JvmTarget.DEFAULT
|
||||
val runtimeStringConcat =
|
||||
if (target.bytecodeVersion >= JvmTarget.JVM_9.bytecodeVersion)
|
||||
@@ -209,6 +218,7 @@ class GenerationState private constructor(
|
||||
classBuilderMode,
|
||||
this.moduleName,
|
||||
languageVersionSettings,
|
||||
useOldManglingSchemeForFunctionsWithInlineClassesInSignatures,
|
||||
IncompatibleClassTrackerImpl(extraJvmDiagnosticsTrace),
|
||||
target,
|
||||
isIrBackend
|
||||
@@ -242,6 +252,7 @@ class GenerationState private constructor(
|
||||
var earlierScriptsForReplInterpreter: List<ScriptDescriptor>? = null
|
||||
// and the rest is an output from the codegen
|
||||
var resultFieldName: String? = null
|
||||
var resultTypeString: String? = null
|
||||
var resultType: KotlinType? = null
|
||||
}
|
||||
|
||||
@@ -312,6 +323,7 @@ class GenerationState private constructor(
|
||||
else
|
||||
BuilderFactoryForDuplicateSignatureDiagnostics(
|
||||
it, bindingContext, diagnostics, this.moduleName, languageVersionSettings,
|
||||
useOldManglingSchemeForFunctionsWithInlineClassesInSignatures,
|
||||
shouldGenerate = { origin -> !shouldOnlyCollectSignatures(origin) },
|
||||
).apply { duplicateSignatureFactory = this }
|
||||
},
|
||||
|
||||
@@ -83,6 +83,7 @@ class KotlinTypeMapper @JvmOverloads constructor(
|
||||
val classBuilderMode: ClassBuilderMode,
|
||||
private val moduleName: String,
|
||||
val languageVersionSettings: LanguageVersionSettings,
|
||||
private val useOldInlineClassesManglingScheme: Boolean,
|
||||
private val incompatibleClassTracker: IncompatibleClassTracker = IncompatibleClassTracker.DoNothing,
|
||||
val jvmTarget: JvmTarget = JvmTarget.DEFAULT,
|
||||
private val isIrBackend: Boolean = false,
|
||||
@@ -91,6 +92,11 @@ class KotlinTypeMapper @JvmOverloads constructor(
|
||||
) : KotlinTypeMapperBase() {
|
||||
private val isReleaseCoroutines = languageVersionSettings.supportsFeature(LanguageFeature.ReleaseCoroutines)
|
||||
val jvmDefaultMode = languageVersionSettings.getFlag(JvmAnalysisFlags.jvmDefaultMode)
|
||||
var useOldManglingRulesForFunctionAcceptingInlineClass: Boolean = useOldInlineClassesManglingScheme
|
||||
set(value) {
|
||||
require(!useOldInlineClassesManglingScheme)
|
||||
field = value
|
||||
}
|
||||
|
||||
private val typeMappingConfiguration = object : TypeMappingConfiguration<Type> {
|
||||
override fun commonSupertype(types: Collection<KotlinType>): KotlinType {
|
||||
@@ -636,7 +642,11 @@ class KotlinTypeMapper @JvmOverloads constructor(
|
||||
// so that we don't have to repeat the same logic in reflection
|
||||
// in case of properties without getter methods.
|
||||
if (kind !== OwnerKind.PROPERTY_REFERENCE_SIGNATURE || descriptor.isPropertyWithGetterSignaturePresent()) {
|
||||
val suffix = getManglingSuffixBasedOnKotlinSignature(descriptor, shouldMangleByReturnType)
|
||||
val suffix = getManglingSuffixBasedOnKotlinSignature(
|
||||
descriptor,
|
||||
shouldMangleByReturnType,
|
||||
useOldManglingRulesForFunctionAcceptingInlineClass
|
||||
)
|
||||
if (suffix != null) {
|
||||
newName += suffix
|
||||
} else if (kind === OwnerKind.ERASED_INLINE_CLASS) {
|
||||
|
||||
+84
-30
@@ -7,8 +7,11 @@ package org.jetbrains.kotlin.codegen.state
|
||||
|
||||
import org.jetbrains.kotlin.codegen.coroutines.unwrapInitialDescriptorForSuspendFunction
|
||||
import org.jetbrains.kotlin.descriptors.*
|
||||
import org.jetbrains.kotlin.name.FqNameUnsafe
|
||||
import org.jetbrains.kotlin.name.Name
|
||||
import org.jetbrains.kotlin.resolve.DescriptorUtils
|
||||
import org.jetbrains.kotlin.resolve.InlineClassDescriptorResolver
|
||||
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
|
||||
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
|
||||
import org.jetbrains.kotlin.resolve.jvm.requiresFunctionNameManglingForParameterTypes
|
||||
import org.jetbrains.kotlin.resolve.jvm.requiresFunctionNameManglingForReturnType
|
||||
@@ -17,9 +20,68 @@ import org.jetbrains.kotlin.types.typeUtil.representativeUpperBound
|
||||
import java.security.MessageDigest
|
||||
import java.util.*
|
||||
|
||||
const val NOT_INLINE_CLASS_PARAMETER_PLACEHOLDER = "_"
|
||||
|
||||
class InfoForMangling(
|
||||
val fqName: FqNameUnsafe,
|
||||
val isInline: Boolean,
|
||||
val isNullable: Boolean
|
||||
)
|
||||
|
||||
fun collectFunctionSignatureForManglingSuffix(
|
||||
useOldManglingRules: Boolean,
|
||||
requiresFunctionNameManglingForParameterTypes: Boolean,
|
||||
fqNamesForMangling: List<InfoForMangling?>,
|
||||
returnTypeInfo: InfoForMangling?,
|
||||
): String? {
|
||||
fun getSignatureElementForMangling(info: InfoForMangling?): String = buildString {
|
||||
if (info == null) return ""
|
||||
if (useOldManglingRules || info.isInline) {
|
||||
append('L')
|
||||
append(info.fqName)
|
||||
if (info.isNullable) append('?')
|
||||
append(';')
|
||||
} else {
|
||||
append(NOT_INLINE_CLASS_PARAMETER_PLACEHOLDER)
|
||||
}
|
||||
}
|
||||
|
||||
fun collectSignatureForMangling(): String =
|
||||
fqNamesForMangling.joinToString(separator = if (useOldManglingRules) ", " else "") {
|
||||
getSignatureElementForMangling(it)
|
||||
}
|
||||
|
||||
if (useOldManglingRules) {
|
||||
if (requiresFunctionNameManglingForParameterTypes) {
|
||||
return collectSignatureForMangling()
|
||||
}
|
||||
|
||||
// If a class member function returns inline class value, mangle its name.
|
||||
// NB here function can be a suspend function JVM view with return type replaced with 'Any',
|
||||
// should unwrap it and take original return type instead.
|
||||
if (returnTypeInfo != null) {
|
||||
return ":" + getSignatureElementForMangling(returnTypeInfo)
|
||||
}
|
||||
} else {
|
||||
// If a function accepts inline class parameters, mangle its name.
|
||||
if (requiresFunctionNameManglingForParameterTypes || returnTypeInfo != null) {
|
||||
// If a class member function returns inline class value, mangle its name.
|
||||
// NB here function can be a suspend function JVM view with return type replaced with 'Any',
|
||||
// should unwrap it and take original return type instead.
|
||||
val signature = collectSignatureForMangling() +
|
||||
if (returnTypeInfo != null)
|
||||
":" + getSignatureElementForMangling(returnTypeInfo)
|
||||
else ""
|
||||
return signature
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
fun getManglingSuffixBasedOnKotlinSignature(
|
||||
descriptor: CallableMemberDescriptor,
|
||||
shouldMangleByReturnType: Boolean
|
||||
shouldMangleByReturnType: Boolean,
|
||||
useOldManglingRules: Boolean
|
||||
): String? {
|
||||
if (descriptor !is FunctionDescriptor) return null
|
||||
if (descriptor is ConstructorDescriptor) return null
|
||||
@@ -29,41 +91,33 @@ fun getManglingSuffixBasedOnKotlinSignature(
|
||||
// Some stdlib functions ('Result.success', 'Result.failure') are annotated with '@JvmName' as a workaround for forward compatibility.
|
||||
if (DescriptorUtils.hasJvmNameAnnotation(descriptor)) return null
|
||||
|
||||
// If a function accepts inline class parameters, mangle its name.
|
||||
if (requiresFunctionNameManglingForParameterTypes(descriptor)) {
|
||||
return "-" + md5base64(collectSignatureForMangling(descriptor))
|
||||
}
|
||||
val unwrappedDescriptor = descriptor.unwrapInitialDescriptorForSuspendFunction()
|
||||
|
||||
// If a class member function returns inline class value, mangle its name.
|
||||
// NB here function can be a suspend function JVM view with return type replaced with 'Any',
|
||||
// should unwrap it and take original return type instead.
|
||||
if (shouldMangleByReturnType) {
|
||||
val unwrappedDescriptor = descriptor.unwrapInitialDescriptorForSuspendFunction()
|
||||
if (requiresFunctionNameManglingForReturnType(unwrappedDescriptor)) {
|
||||
return "-" + md5base64(":" + getSignatureElementForMangling(unwrappedDescriptor.returnType!!))
|
||||
}
|
||||
}
|
||||
return null
|
||||
val resultNew = collectFunctionSignatureForManglingSuffix(
|
||||
useOldManglingRules = useOldManglingRules,
|
||||
requiresFunctionNameManglingForParameterTypes = requiresFunctionNameManglingForParameterTypes(descriptor),
|
||||
fqNamesForMangling =
|
||||
(listOfNotNull(descriptor.extensionReceiverParameter?.type) + descriptor.valueParameters.map { it.type })
|
||||
.map { getInfoForMangling(it) },
|
||||
returnTypeInfo =
|
||||
if (shouldMangleByReturnType && requiresFunctionNameManglingForReturnType(unwrappedDescriptor))
|
||||
getInfoForMangling(unwrappedDescriptor.returnType!!)
|
||||
else null
|
||||
)
|
||||
|
||||
return resultNew?.let { "-" + md5base64(it) }
|
||||
}
|
||||
|
||||
private fun collectSignatureForMangling(descriptor: CallableMemberDescriptor): String {
|
||||
val types = listOfNotNull(descriptor.extensionReceiverParameter?.type) + descriptor.valueParameters.map { it.type }
|
||||
return types.joinToString { getSignatureElementForMangling(it) }
|
||||
}
|
||||
|
||||
private fun getSignatureElementForMangling(type: KotlinType): String = buildString {
|
||||
val descriptor = type.constructor.declarationDescriptor ?: return ""
|
||||
when (descriptor) {
|
||||
is ClassDescriptor -> {
|
||||
append('L')
|
||||
append(descriptor.fqNameUnsafe)
|
||||
if (type.isMarkedNullable) append('?')
|
||||
append(';')
|
||||
}
|
||||
private fun getInfoForMangling(type: KotlinType): InfoForMangling? {
|
||||
val descriptor = type.constructor.declarationDescriptor ?: return null
|
||||
return when (descriptor) {
|
||||
is ClassDescriptor -> InfoForMangling(descriptor.fqNameUnsafe, descriptor.isInline, type.isMarkedNullable)
|
||||
|
||||
is TypeParameterDescriptor -> {
|
||||
append(getSignatureElementForMangling(descriptor.representativeUpperBound))
|
||||
getInfoForMangling(descriptor.representativeUpperBound)
|
||||
}
|
||||
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -57,14 +57,9 @@ dependencies {
|
||||
testCompileOnly(project(it))
|
||||
}
|
||||
testCompileOnly(intellijCoreDep()) { includeJars("intellij-core") }
|
||||
Platform[193].orLower {
|
||||
testCompileOnly(intellijDep()) { includeJars("openapi", rootProject = rootProject) }
|
||||
}
|
||||
testCompileOnly(intellijDep()) { includeJars("idea", "idea_rt", "util", "asm-all", rootProject = rootProject) }
|
||||
|
||||
Platform[192].orHigher {
|
||||
testRuntimeOnly(intellijPluginDep("java"))
|
||||
}
|
||||
testRuntimeOnly(intellijPluginDep("java"))
|
||||
|
||||
testRuntime(project(":kotlin-reflect"))
|
||||
testRuntime(androidDxJar())
|
||||
|
||||
@@ -71,5 +71,7 @@
|
||||
interface="org.jetbrains.kotlin.fir.extensions.FirExtensionRegistrar"/>
|
||||
<extensionPoint qualifiedName="org.jetbrains.kotlin.DescriptorSerializerPlugin"
|
||||
interface="org.jetbrains.kotlin.serialization.DescriptorSerializerPlugin"/>
|
||||
<extensionPoint qualifiedName="org.jetbrains.kotlin.defaultErrorMessages"
|
||||
interface="org.jetbrains.kotlin.diagnostics.rendering.DefaultErrorMessages.Extension"/>
|
||||
</extensionPoints>
|
||||
</idea-plugin>
|
||||
|
||||
-6
@@ -352,12 +352,6 @@ abstract class CommonCompilerArguments : CommonToolArguments() {
|
||||
)
|
||||
var explicitApi: String by FreezableVar(ExplicitApiMode.DISABLED.state)
|
||||
|
||||
@Argument(
|
||||
value = "-Xdeserialize-fake-overrides",
|
||||
description = "Fallback to deserializing fake overrides"
|
||||
)
|
||||
var deserializeFakeOverrides: Boolean by FreezableVar(false)
|
||||
|
||||
@Argument(
|
||||
value = "-Xinference-compatibility",
|
||||
description = "Enable compatibility changes for generic type inference algorithm"
|
||||
|
||||
+6
-3
@@ -172,12 +172,15 @@ class K2JSCompilerArguments : CommonCompilerArguments() {
|
||||
@Argument(value = "-Xenable-js-scripting", description = "Enable experimental support of .kts files using K/JS (with -Xir only)")
|
||||
var enableJsScripting: Boolean by FreezableVar(false)
|
||||
|
||||
@Argument(value = "-Xdisable-fake-override-validator", description = "Disable IR fake override validator")
|
||||
var disableFakeOverrideValidator: Boolean by FreezableVar(false)
|
||||
@Argument(value = "-Xfake-override-validator", description = "Enable IR fake override validator")
|
||||
var fakeOverrideValidator: Boolean by FreezableVar(false)
|
||||
|
||||
@Argument(value = "-Xerror-tolerance-policy", description = "Set up error tolerance policy (NONE, SEMANTIC, SYNTAX, ALL)")
|
||||
var errorTolerancePolicy: String? by NullableStringFreezableVar(null)
|
||||
|
||||
@Argument(value = "-Xwasm", description = "Use experimental WebAssembly compiler backend")
|
||||
var wasm: Boolean by FreezableVar(false)
|
||||
|
||||
override fun checkIrSupport(languageVersionSettings: LanguageVersionSettings, collector: MessageCollector) {
|
||||
if (!isIrBackendEnabled()) return
|
||||
|
||||
@@ -196,4 +199,4 @@ fun K2JSCompilerArguments.isPreIrBackendDisabled(): Boolean =
|
||||
irOnly || irProduceJs || irProduceKlibFile
|
||||
|
||||
fun K2JSCompilerArguments.isIrBackendEnabled(): Boolean =
|
||||
irProduceKlibDir || irProduceJs || irProduceKlibFile
|
||||
irProduceKlibDir || irProduceJs || irProduceKlibFile || wasm
|
||||
+12
@@ -377,6 +377,12 @@ class K2JVMCompilerArguments : CommonCompilerArguments() {
|
||||
)
|
||||
var noKotlinNothingValueException: Boolean by FreezableVar(false)
|
||||
|
||||
@Argument(
|
||||
value = "-Xno-reset-jar-timestamps",
|
||||
description = "Do not reset jar entry timestamps to a fixed date"
|
||||
)
|
||||
var noResetJarTimestamps: Boolean by FreezableVar(false)
|
||||
|
||||
@Argument(
|
||||
value = "-Xno-unified-null-checks",
|
||||
description = "Use pre-1.4 exception types in null checks instead of java.lang.NPE. See KT-22275 for more details"
|
||||
@@ -406,6 +412,12 @@ class K2JVMCompilerArguments : CommonCompilerArguments() {
|
||||
)
|
||||
var useOldSpilledVarTypeAnalysis: Boolean by FreezableVar(false)
|
||||
|
||||
@Argument(
|
||||
value = "-Xuse-14-inline-classes-mangling-scheme",
|
||||
description = "Use 1.4 inline classes mangling scheme instead of 1.4.30 one"
|
||||
)
|
||||
var useOldInlineClassesManglingScheme: Boolean by FreezableVar(false)
|
||||
|
||||
override fun configureAnalysisFlags(collector: MessageCollector): MutableMap<AnalysisFlag<*>, Any> {
|
||||
val result = super.configureAnalysisFlags(collector)
|
||||
result[JvmAnalysisFlags.strictMetadataVersionSemantics] = strictMetadataVersionSemantics
|
||||
|
||||
@@ -12,6 +12,7 @@ dependencies {
|
||||
compile(project(":compiler:ir.backend.common"))
|
||||
compile(project(":compiler:ir.serialization.js"))
|
||||
compile(project(":compiler:backend.js"))
|
||||
compile(project(":compiler:backend.wasm"))
|
||||
compile(project(":js:js.translator"))
|
||||
compile(project(":js:js.serializer"))
|
||||
compile(project(":js:js.dce"))
|
||||
|
||||
@@ -8,7 +8,10 @@ package org.jetbrains.kotlin.cli.js
|
||||
import com.intellij.openapi.Disposable
|
||||
import com.intellij.openapi.util.io.FileUtil
|
||||
import com.intellij.openapi.util.text.StringUtil
|
||||
import org.jetbrains.kotlin.backend.common.phaser.PhaseConfig
|
||||
import org.jetbrains.kotlin.backend.common.serialization.metadata.KlibMetadataVersion
|
||||
import org.jetbrains.kotlin.backend.wasm.compileWasm
|
||||
import org.jetbrains.kotlin.backend.wasm.wasmPhases
|
||||
import org.jetbrains.kotlin.cli.common.*
|
||||
import org.jetbrains.kotlin.cli.common.ExitCode.COMPILATION_ERROR
|
||||
import org.jetbrains.kotlin.cli.common.ExitCode.OK
|
||||
@@ -34,6 +37,7 @@ import org.jetbrains.kotlin.ir.backend.js.*
|
||||
import org.jetbrains.kotlin.ir.declarations.persistent.PersistentIrFactory
|
||||
import org.jetbrains.kotlin.js.config.*
|
||||
import org.jetbrains.kotlin.metadata.deserialization.BinaryVersion
|
||||
import org.jetbrains.kotlin.name.FqName
|
||||
import org.jetbrains.kotlin.psi.KtFile
|
||||
import org.jetbrains.kotlin.serialization.js.ModuleKind
|
||||
import org.jetbrains.kotlin.util.Logger
|
||||
@@ -216,6 +220,33 @@ class K2JsIrCompiler : CLICompiler<K2JSCompilerArguments>() {
|
||||
MainModule.SourceFiles(sourcesFiles)
|
||||
}
|
||||
|
||||
if (arguments.wasm) {
|
||||
val res = compileWasm(
|
||||
projectJs,
|
||||
mainModule,
|
||||
AnalyzerWithCompilerReport(config.configuration),
|
||||
config.configuration,
|
||||
PhaseConfig(wasmPhases),
|
||||
allDependencies = resolvedLibraries,
|
||||
friendDependencies = friendDependencies,
|
||||
exportedDeclarations = setOf(FqName("main"))
|
||||
)
|
||||
val outputWasmFile = outputFile.withReplacedExtensionOrNull(outputFile.extension, "wasm")!!
|
||||
outputWasmFile.writeBytes(res.wasm)
|
||||
val outputWatFile = outputFile.withReplacedExtensionOrNull(outputFile.extension, "wat")!!
|
||||
outputWatFile.writeText(res.wat)
|
||||
|
||||
val runner = """
|
||||
const wasmBinary = read(String.raw`${outputWasmFile.absoluteFile}`, 'binary');
|
||||
const wasmModule = new WebAssembly.Module(wasmBinary);
|
||||
const wasmInstance = new WebAssembly.Instance(wasmModule, { runtime, js_code });
|
||||
wasmInstance.exports.main();
|
||||
""".trimIndent()
|
||||
|
||||
outputFile.writeText(res.js + "\n" + runner)
|
||||
return OK
|
||||
}
|
||||
|
||||
val compiledModule = try {
|
||||
compile(
|
||||
projectJs,
|
||||
@@ -333,7 +364,7 @@ class K2JsIrCompiler : CLICompiler<K2JSCompilerArguments>() {
|
||||
}
|
||||
|
||||
configuration.put(JSConfigurationKeys.PRINT_REACHABILITY_INFO, arguments.irDcePrintReachabilityInfo)
|
||||
configuration.put(JSConfigurationKeys.DISABLE_FAKE_OVERRIDE_VALIDATOR, arguments.disableFakeOverrideValidator)
|
||||
configuration.put(JSConfigurationKeys.FAKE_OVERRIDE_VALIDATOR, arguments.fakeOverrideValidator)
|
||||
}
|
||||
|
||||
override fun executableScriptFileName(): String {
|
||||
|
||||
@@ -27,7 +27,6 @@ fun <A : CommonCompilerArguments> CompilerConfiguration.setupCommonArguments(
|
||||
put(CommonConfigurationKeys.EXPECT_ACTUAL_LINKER, arguments.expectActualLinker)
|
||||
putIfNotNull(CLIConfigurationKeys.INTELLIJ_PLUGIN_ROOT, arguments.intellijPluginRoot)
|
||||
put(CommonConfigurationKeys.REPORT_OUTPUT_FILES, arguments.reportOutputFiles)
|
||||
put(CommonConfigurationKeys.DESERIALIZE_FAKE_OVERRIDES, arguments.deserializeFakeOverrides)
|
||||
|
||||
val metadataVersionString = arguments.metadataVersion
|
||||
if (metadataVersionString != null) {
|
||||
|
||||
+1
@@ -87,6 +87,7 @@ class CliLightClassGenerationSupport(
|
||||
ClassBuilderMode.LIGHT_CLASSES,
|
||||
moduleName,
|
||||
languageVersionSettings,
|
||||
useOldInlineClassesManglingScheme = false,
|
||||
jvmTarget = JvmTarget.JVM_1_8,
|
||||
typePreprocessor = KotlinType::cleanFromAnonymousTypes,
|
||||
namePreprocessor = ::tryGetPredefinedName
|
||||
|
||||
@@ -31,11 +31,15 @@ import org.jetbrains.kotlin.utils.ExceptionUtilsKt;
|
||||
import org.jetbrains.kotlin.utils.PathUtil;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.*;
|
||||
import java.util.jar.*;
|
||||
|
||||
import static org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.ERROR;
|
||||
|
||||
public class CompileEnvironmentUtil {
|
||||
|
||||
public static long DOS_EPOCH = new GregorianCalendar(1980, Calendar.JANUARY, 1, 0, 0, 0).getTimeInMillis();
|
||||
|
||||
@NotNull
|
||||
public static ModuleChunk loadModuleChunk(File buildFile, MessageCollector messageCollector) {
|
||||
if (!buildFile.exists()) {
|
||||
@@ -51,7 +55,11 @@ public class CompileEnvironmentUtil {
|
||||
|
||||
// TODO: includeRuntime should be not a flag but a path to runtime
|
||||
private static void doWriteToJar(
|
||||
OutputFileCollection outputFiles, OutputStream fos, @Nullable FqName mainClass, boolean includeRuntime
|
||||
OutputFileCollection outputFiles,
|
||||
OutputStream fos,
|
||||
@Nullable FqName mainClass,
|
||||
boolean includeRuntime,
|
||||
boolean resetJarTimestamps
|
||||
) {
|
||||
try {
|
||||
Manifest manifest = new Manifest();
|
||||
@@ -61,13 +69,25 @@ public class CompileEnvironmentUtil {
|
||||
if (mainClass != null) {
|
||||
mainAttributes.putValue("Main-Class", mainClass.asString());
|
||||
}
|
||||
JarOutputStream stream = new JarOutputStream(fos, manifest);
|
||||
|
||||
JarOutputStream stream = new JarOutputStream(fos);
|
||||
JarEntry manifestEntry = new JarEntry(JarFile.MANIFEST_NAME);
|
||||
if (resetJarTimestamps) {
|
||||
manifestEntry.setTime(DOS_EPOCH);
|
||||
}
|
||||
stream.putNextEntry(manifestEntry);
|
||||
manifest.write(new BufferedOutputStream(stream));
|
||||
|
||||
for (OutputFile outputFile : outputFiles.asList()) {
|
||||
stream.putNextEntry(new JarEntry(outputFile.getRelativePath()));
|
||||
JarEntry entry = new JarEntry(outputFile.getRelativePath());
|
||||
if (resetJarTimestamps) {
|
||||
entry.setTime(DOS_EPOCH);
|
||||
}
|
||||
stream.putNextEntry(entry);
|
||||
stream.write(outputFile.asByteArray());
|
||||
}
|
||||
if (includeRuntime) {
|
||||
writeRuntimeToJar(stream);
|
||||
writeRuntimeToJar(stream, resetJarTimestamps);
|
||||
}
|
||||
stream.finish();
|
||||
}
|
||||
@@ -76,11 +96,13 @@ public class CompileEnvironmentUtil {
|
||||
}
|
||||
}
|
||||
|
||||
public static void writeToJar(File jarPath, boolean jarRuntime, FqName mainClass, OutputFileCollection outputFiles) {
|
||||
public static void writeToJar(
|
||||
File jarPath, boolean jarRuntime, boolean resetJarTimestamps, FqName mainClass, OutputFileCollection outputFiles
|
||||
) {
|
||||
FileOutputStream outputStream = null;
|
||||
try {
|
||||
outputStream = new FileOutputStream(jarPath);
|
||||
doWriteToJar(outputFiles, outputStream, mainClass, jarRuntime);
|
||||
doWriteToJar(outputFiles, outputStream, mainClass, jarRuntime, resetJarTimestamps);
|
||||
outputStream.close();
|
||||
}
|
||||
catch (FileNotFoundException e) {
|
||||
@@ -94,21 +116,24 @@ public class CompileEnvironmentUtil {
|
||||
}
|
||||
}
|
||||
|
||||
private static void writeRuntimeToJar(JarOutputStream stream) throws IOException {
|
||||
private static void writeRuntimeToJar(JarOutputStream stream, boolean resetJarTimestamps) throws IOException {
|
||||
File stdlibPath = PathUtil.getKotlinPathsForCompiler().getStdlibPath();
|
||||
if (!stdlibPath.exists()) {
|
||||
throw new CompileEnvironmentException("Couldn't find kotlin-stdlib at " + stdlibPath);
|
||||
}
|
||||
copyJarImpl(stream, stdlibPath);
|
||||
copyJarImpl(stream, stdlibPath, resetJarTimestamps);
|
||||
}
|
||||
|
||||
private static void copyJarImpl(JarOutputStream stream, File jarPath) throws IOException {
|
||||
private static void copyJarImpl(JarOutputStream stream, File jarPath, boolean resetJarTimestamps) throws IOException {
|
||||
try (JarInputStream jis = new JarInputStream(new FileInputStream(jarPath))) {
|
||||
while (true) {
|
||||
JarEntry e = jis.getNextJarEntry();
|
||||
if (e == null) {
|
||||
break;
|
||||
}
|
||||
if (resetJarTimestamps) {
|
||||
e.setTime(DOS_EPOCH);
|
||||
}
|
||||
if (FileUtilRt.extensionEquals(e.getName(), "class")) {
|
||||
stream.putNextEntry(e);
|
||||
FileUtil.copy(jis, stream);
|
||||
|
||||
-150
@@ -1,150 +0,0 @@
|
||||
/*
|
||||
* Copyright 2010-2019 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.cli.jvm.compiler;
|
||||
|
||||
import com.intellij.codeInsight.ContainerProvider;
|
||||
import com.intellij.codeInsight.JavaContainerProvider;
|
||||
import com.intellij.codeInsight.folding.JavaCodeFoldingSettings;
|
||||
import com.intellij.codeInsight.folding.impl.JavaCodeFoldingSettingsBase;
|
||||
import com.intellij.codeInsight.folding.impl.JavaFoldingBuilderBase;
|
||||
import com.intellij.codeInsight.runner.JavaMainMethodProvider;
|
||||
import com.intellij.core.CoreApplicationEnvironment;
|
||||
import com.intellij.core.CoreJavaDirectoryService;
|
||||
import com.intellij.core.CorePsiPackageImplementationHelper;
|
||||
import com.intellij.ide.highlighter.ArchiveFileType;
|
||||
import com.intellij.ide.highlighter.JavaClassFileType;
|
||||
import com.intellij.ide.highlighter.JavaFileType;
|
||||
import com.intellij.lang.LanguageASTFactory;
|
||||
import com.intellij.lang.MetaLanguage;
|
||||
import com.intellij.lang.folding.LanguageFolding;
|
||||
import com.intellij.lang.java.JavaLanguage;
|
||||
import com.intellij.lang.java.JavaParserDefinition;
|
||||
import com.intellij.navigation.ItemPresentationProviders;
|
||||
import com.intellij.openapi.Disposable;
|
||||
import com.intellij.openapi.extensions.Extensions;
|
||||
import com.intellij.openapi.extensions.ExtensionsArea;
|
||||
import com.intellij.openapi.fileTypes.FileTypeExtensionPoint;
|
||||
import com.intellij.openapi.fileTypes.PlainTextFileType;
|
||||
import com.intellij.openapi.fileTypes.PlainTextLanguage;
|
||||
import com.intellij.openapi.fileTypes.PlainTextParserDefinition;
|
||||
import com.intellij.openapi.projectRoots.JavaVersionService;
|
||||
import com.intellij.openapi.vfs.VirtualFileSystem;
|
||||
import com.intellij.psi.*;
|
||||
import com.intellij.psi.augment.PsiAugmentProvider;
|
||||
import com.intellij.psi.augment.TypeAnnotationModifier;
|
||||
import com.intellij.psi.compiled.ClassFileDecompilers;
|
||||
import com.intellij.psi.impl.LanguageConstantExpressionEvaluator;
|
||||
import com.intellij.psi.impl.PsiExpressionEvaluator;
|
||||
import com.intellij.psi.impl.PsiSubstitutorFactoryImpl;
|
||||
import com.intellij.psi.impl.compiled.ClassFileStubBuilder;
|
||||
import com.intellij.psi.impl.file.PsiPackageImplementationHelper;
|
||||
import com.intellij.psi.impl.search.MethodSuperSearcher;
|
||||
import com.intellij.psi.impl.source.tree.JavaASTFactory;
|
||||
import com.intellij.psi.impl.source.tree.PlainTextASTFactory;
|
||||
import com.intellij.psi.meta.MetaDataContributor;
|
||||
import com.intellij.psi.presentation.java.*;
|
||||
import com.intellij.psi.search.searches.SuperMethodsSearch;
|
||||
import com.intellij.psi.stubs.BinaryFileStubBuilders;
|
||||
import com.intellij.util.QueryExecutor;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.jetbrains.kotlin.cli.jvm.modules.CoreJrtFileSystem;
|
||||
|
||||
/**
|
||||
* adapted from com.intellij.core.JavaCoreApplicationEnvironment
|
||||
* TODO: initiate removal original from com.intellij.core since it seems that there are no usages left
|
||||
*/
|
||||
public class KotlinCoreApplicationEnvironment extends CoreApplicationEnvironment {
|
||||
|
||||
public static KotlinCoreApplicationEnvironment create(@NotNull Disposable parentDisposable, boolean unitTestMode) {
|
||||
return new KotlinCoreApplicationEnvironment(parentDisposable, unitTestMode);
|
||||
}
|
||||
|
||||
private KotlinCoreApplicationEnvironment(@NotNull Disposable parentDisposable, boolean unitTestMode) {
|
||||
super(parentDisposable, unitTestMode);
|
||||
|
||||
registerExtensionPoints();
|
||||
|
||||
registerExtensions();
|
||||
}
|
||||
|
||||
private void registerExtensionPoints() {
|
||||
ExtensionsArea area = Extensions.getRootArea();
|
||||
|
||||
CoreApplicationEnvironment.registerExtensionPoint(area, BinaryFileStubBuilders.EP_NAME, FileTypeExtensionPoint.class);
|
||||
CoreApplicationEnvironment.registerExtensionPoint(area, FileContextProvider.EP_NAME, FileContextProvider.class);
|
||||
|
||||
CoreApplicationEnvironment.registerExtensionPoint(area, MetaDataContributor.EP_NAME, MetaDataContributor.class);
|
||||
CoreApplicationEnvironment.registerExtensionPoint(area, PsiAugmentProvider.EP_NAME, PsiAugmentProvider.class);
|
||||
CoreApplicationEnvironment.registerExtensionPoint(area, JavaMainMethodProvider.EP_NAME, JavaMainMethodProvider.class);
|
||||
|
||||
CoreApplicationEnvironment.registerExtensionPoint(area, ContainerProvider.EP_NAME, ContainerProvider.class);
|
||||
CoreApplicationEnvironment.registerExtensionPoint(area, ClassFileDecompilers.EP_NAME, ClassFileDecompilers.Decompiler.class);
|
||||
|
||||
CoreApplicationEnvironment.registerExtensionPoint(area, TypeAnnotationModifier.EP_NAME, TypeAnnotationModifier.class);
|
||||
CoreApplicationEnvironment.registerExtensionPoint(area, MetaLanguage.EP_NAME, MetaLanguage.class);
|
||||
|
||||
IdeaExtensionPoints.INSTANCE.registerVersionSpecificAppExtensionPoints(area);
|
||||
}
|
||||
|
||||
private void registerExtensions() {
|
||||
registerFileType(JavaClassFileType.INSTANCE, "class");
|
||||
registerFileType(JavaFileType.INSTANCE, "java");
|
||||
registerFileType(ArchiveFileType.INSTANCE, "jar;zip");
|
||||
registerFileType(PlainTextFileType.INSTANCE, "txt;sh;bat;cmd;policy;log;cgi;MF;jad;jam;htaccess");
|
||||
|
||||
addExplicitExtension(LanguageASTFactory.INSTANCE, PlainTextLanguage.INSTANCE, new PlainTextASTFactory());
|
||||
registerParserDefinition(new PlainTextParserDefinition());
|
||||
|
||||
addExplicitExtension(FileTypeFileViewProviders.INSTANCE, JavaClassFileType.INSTANCE, new ClassFileViewProviderFactory());
|
||||
addExplicitExtension(BinaryFileStubBuilders.INSTANCE, JavaClassFileType.INSTANCE, new ClassFileStubBuilder());
|
||||
|
||||
addExplicitExtension(LanguageASTFactory.INSTANCE, JavaLanguage.INSTANCE, new JavaASTFactory());
|
||||
registerParserDefinition(new JavaParserDefinition());
|
||||
addExplicitExtension(LanguageConstantExpressionEvaluator.INSTANCE, JavaLanguage.INSTANCE, new PsiExpressionEvaluator());
|
||||
|
||||
addExtension(ContainerProvider.EP_NAME, new JavaContainerProvider());
|
||||
|
||||
myApplication.registerService(PsiPackageImplementationHelper.class, new CorePsiPackageImplementationHelper());
|
||||
myApplication.registerService(PsiSubstitutorFactory.class, new PsiSubstitutorFactoryImpl());
|
||||
|
||||
myApplication.registerService(JavaDirectoryService.class, createJavaDirectoryService());
|
||||
myApplication.registerService(JavaVersionService.class, new JavaVersionService());
|
||||
|
||||
addExplicitExtension(ItemPresentationProviders.INSTANCE, PsiPackage.class, new PackagePresentationProvider());
|
||||
addExplicitExtension(ItemPresentationProviders.INSTANCE, PsiClass.class, new ClassPresentationProvider());
|
||||
addExplicitExtension(ItemPresentationProviders.INSTANCE, PsiMethod.class, new MethodPresentationProvider());
|
||||
addExplicitExtension(ItemPresentationProviders.INSTANCE, PsiField.class, new FieldPresentationProvider());
|
||||
addExplicitExtension(ItemPresentationProviders.INSTANCE, PsiLocalVariable.class, new VariablePresentationProvider());
|
||||
addExplicitExtension(ItemPresentationProviders.INSTANCE, PsiParameter.class, new VariablePresentationProvider());
|
||||
|
||||
registerApplicationService(JavaCodeFoldingSettings.class, new JavaCodeFoldingSettingsBase());
|
||||
addExplicitExtension(LanguageFolding.INSTANCE, JavaLanguage.INSTANCE, new JavaFoldingBuilderBase() {
|
||||
@Override
|
||||
protected boolean shouldShowExplicitLambdaType(@NotNull PsiAnonymousClass anonymousClass, @NotNull PsiNewExpression expression) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean isBelowRightMargin(@NotNull PsiFile file, int lineLength) {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
registerApplicationExtensionPoint(SuperMethodsSearch.EP_NAME, QueryExecutor.class);
|
||||
addExtension(SuperMethodsSearch.EP_NAME, new MethodSuperSearcher());
|
||||
}
|
||||
|
||||
// overridden in upsource
|
||||
protected CoreJavaDirectoryService createJavaDirectoryService() {
|
||||
return new CoreJavaDirectoryService();
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
protected VirtualFileSystem createJrtFileSystem() {
|
||||
return new CoreJrtFileSystem();
|
||||
}
|
||||
}
|
||||
@@ -102,6 +102,7 @@ import org.jetbrains.kotlin.resolve.lazy.declarations.DeclarationProviderFactory
|
||||
import org.jetbrains.kotlin.serialization.DescriptorSerializerPlugin
|
||||
import org.jetbrains.kotlin.utils.PathUtil
|
||||
import java.io.File
|
||||
import java.nio.file.FileSystems
|
||||
import java.util.zip.ZipFile
|
||||
|
||||
class KotlinCoreEnvironment private constructor(
|
||||
@@ -536,7 +537,11 @@ class KotlinCoreEnvironment private constructor(
|
||||
"(cp:\n ${(Thread.currentThread().contextClassLoader as? UrlClassLoader)?.urls?.joinToString("\n ") { it.file }})"
|
||||
)
|
||||
|
||||
registerExtensionPointAndExtensionsEx(pluginRoot, configFilePath, Extensions.getRootArea())
|
||||
CoreApplicationEnvironment.registerExtensionPointAndExtensions(
|
||||
FileSystems.getDefault().getPath(pluginRoot.path),
|
||||
configFilePath,
|
||||
Extensions.getRootArea()
|
||||
)
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
|
||||
+6
-1
@@ -106,6 +106,7 @@ import org.jetbrains.kotlin.resolve.lazy.declarations.DeclarationProviderFactory
|
||||
import org.jetbrains.kotlin.serialization.DescriptorSerializerPlugin
|
||||
import org.jetbrains.kotlin.utils.PathUtil
|
||||
import java.io.File
|
||||
import java.nio.file.FileSystems
|
||||
import java.util.zip.ZipFile
|
||||
|
||||
class KotlinCoreEnvironment private constructor(
|
||||
@@ -534,7 +535,11 @@ class KotlinCoreEnvironment private constructor(
|
||||
"(cp:\n ${(Thread.currentThread().contextClassLoader as? UrlClassLoader)?.urls?.joinToString("\n ") { it.file }})"
|
||||
)
|
||||
|
||||
registerExtensionPointAndExtensionsEx(pluginRoot, configFilePath, Extensions.getRootArea())
|
||||
CoreApplicationEnvironment.registerExtensionPointAndExtensions(
|
||||
FileSystems.getDefault().getPath(pluginRoot.path),
|
||||
configFilePath,
|
||||
Extensions.getRootArea()
|
||||
)
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
|
||||
+16
-46
@@ -25,7 +25,6 @@ import com.intellij.psi.search.DelegatingGlobalSearchScope
|
||||
import com.intellij.psi.search.GlobalSearchScope
|
||||
import com.intellij.psi.search.ProjectScope
|
||||
import org.jetbrains.kotlin.analyzer.AnalysisResult
|
||||
import org.jetbrains.kotlin.analyzer.ModuleInfo
|
||||
import org.jetbrains.kotlin.asJava.FilteredJvmDiagnostics
|
||||
import org.jetbrains.kotlin.asJava.finder.JavaElementFinder
|
||||
import org.jetbrains.kotlin.backend.common.output.OutputFileCollection
|
||||
@@ -37,7 +36,8 @@ import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys
|
||||
import org.jetbrains.kotlin.cli.common.checkKotlinPackageUsage
|
||||
import org.jetbrains.kotlin.cli.common.config.addKotlinSourceRoot
|
||||
import org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport
|
||||
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.*
|
||||
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.OUTPUT
|
||||
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.WARNING
|
||||
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
|
||||
import org.jetbrains.kotlin.cli.common.messages.OutputMessageUtil
|
||||
import org.jetbrains.kotlin.cli.common.output.writeAll
|
||||
@@ -54,13 +54,13 @@ import org.jetbrains.kotlin.container.get
|
||||
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
|
||||
import org.jetbrains.kotlin.diagnostics.*
|
||||
import org.jetbrains.kotlin.fir.FirPsiSourceElement
|
||||
import org.jetbrains.kotlin.fir.FirSession
|
||||
import org.jetbrains.kotlin.fir.analysis.FirAnalyzerFacade
|
||||
import org.jetbrains.kotlin.fir.analysis.diagnostics.*
|
||||
import org.jetbrains.kotlin.fir.backend.jvm.FirJvmBackendClassResolver
|
||||
import org.jetbrains.kotlin.fir.backend.jvm.FirMetadataSerializer
|
||||
import org.jetbrains.kotlin.fir.checkers.registerExtendedCommonCheckers
|
||||
import org.jetbrains.kotlin.fir.java.FirProjectSessionProvider
|
||||
import org.jetbrains.kotlin.fir.session.FirJvmModuleInfo
|
||||
import org.jetbrains.kotlin.fir.session.FirSessionFactory
|
||||
import org.jetbrains.kotlin.ir.backend.jvm.jvmResolveLibraries
|
||||
import org.jetbrains.kotlin.javac.JavacWrapper
|
||||
@@ -68,16 +68,11 @@ import org.jetbrains.kotlin.load.kotlin.ModuleVisibilityManager
|
||||
import org.jetbrains.kotlin.modules.Module
|
||||
import org.jetbrains.kotlin.modules.TargetId
|
||||
import org.jetbrains.kotlin.name.FqName
|
||||
import org.jetbrains.kotlin.name.Name
|
||||
import org.jetbrains.kotlin.platform.TargetPlatform
|
||||
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
|
||||
import org.jetbrains.kotlin.progress.ProgressIndicatorAndCompilationCanceledStatus
|
||||
import org.jetbrains.kotlin.psi.KtFile
|
||||
import org.jetbrains.kotlin.resolve.CompilerEnvironment
|
||||
import org.jetbrains.kotlin.resolve.PlatformDependentAnalyzerServices
|
||||
import org.jetbrains.kotlin.resolve.diagnostics.SimpleDiagnostics
|
||||
import org.jetbrains.kotlin.resolve.jvm.KotlinJavaPsiFacade
|
||||
import org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatformAnalyzerServices
|
||||
import org.jetbrains.kotlin.resolve.lazy.declarations.FileBasedDeclarationProviderFactory
|
||||
import org.jetbrains.kotlin.utils.newLinkedHashMapWithExpectedSize
|
||||
import java.io.File
|
||||
@@ -93,7 +88,8 @@ object KotlinToJVMBytecodeCompiler {
|
||||
val messageCollector = configuration.get(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY, MessageCollector.NONE)
|
||||
if (jarPath != null) {
|
||||
val includeRuntime = configuration.get(JVMConfigurationKeys.INCLUDE_RUNTIME, false)
|
||||
CompileEnvironmentUtil.writeToJar(jarPath, includeRuntime, mainClassFqName, outputFiles)
|
||||
val resetJarTimestamps = !configuration.get(JVMConfigurationKeys.NO_RESET_JAR_TIMESTAMPS, false)
|
||||
CompileEnvironmentUtil.writeToJar(jarPath, includeRuntime, resetJarTimestamps, mainClassFqName, outputFiles)
|
||||
if (reportOutputFiles) {
|
||||
val message = OutputMessageUtil.formatOutputMessage(outputFiles.asList().flatMap { it.sourceFiles }.distinct(), jarPath)
|
||||
messageCollector.report(OUTPUT, message)
|
||||
@@ -325,43 +321,26 @@ object KotlinToJVMBytecodeCompiler {
|
||||
|
||||
val scope = GlobalSearchScope.filesScope(project, ktFiles.map { it.virtualFile })
|
||||
.uniteWith(TopDownAnalyzerFacadeForJVM.AllJavaSourcesInProjectScope(project))
|
||||
val provider = FirProjectSessionProvider(project)
|
||||
val provider = FirProjectSessionProvider()
|
||||
|
||||
class FirJvmModuleInfo(override val name: Name) : ModuleInfo {
|
||||
constructor(moduleName: String) : this(Name.identifier(moduleName))
|
||||
val librariesModuleInfo = FirJvmModuleInfo.createForLibraries()
|
||||
val librariesScope = ProjectScope.getLibrariesScope(project)
|
||||
FirSessionFactory.createLibrarySession(
|
||||
librariesModuleInfo, provider, librariesScope,
|
||||
project, environment.createPackagePartProvider(librariesScope)
|
||||
)
|
||||
|
||||
val dependencies: MutableList<ModuleInfo> = mutableListOf()
|
||||
|
||||
override val platform: TargetPlatform
|
||||
get() = JvmPlatforms.unspecifiedJvmPlatform
|
||||
|
||||
override val analyzerServices: PlatformDependentAnalyzerServices
|
||||
get() = JvmPlatformAnalyzerServices
|
||||
|
||||
override fun dependencies(): List<ModuleInfo> {
|
||||
return dependencies
|
||||
}
|
||||
}
|
||||
|
||||
val moduleInfo = FirJvmModuleInfo(module.getModuleName())
|
||||
val session: FirSession = FirSessionFactory.createJavaModuleBasedSession(moduleInfo, provider, scope) {
|
||||
val moduleInfo = FirJvmModuleInfo(module.getModuleName(), listOf(librariesModuleInfo))
|
||||
val session = FirSessionFactory.createJavaModuleBasedSession(moduleInfo, provider, scope, project) {
|
||||
if (extendedAnalysisMode) {
|
||||
registerExtendedCommonCheckers()
|
||||
}
|
||||
}.also {
|
||||
val dependenciesInfo = FirJvmModuleInfo(Name.special("<dependencies>"))
|
||||
moduleInfo.dependencies.add(dependenciesInfo)
|
||||
val librariesScope = ProjectScope.getLibrariesScope(project)
|
||||
FirSessionFactory.createLibrarySession(
|
||||
dependenciesInfo, provider, librariesScope,
|
||||
project, environment.createPackagePartProvider(librariesScope)
|
||||
)
|
||||
}
|
||||
|
||||
val firAnalyzerFacade = FirAnalyzerFacade(session, moduleConfiguration.languageVersionSettings, ktFiles)
|
||||
|
||||
firAnalyzerFacade.runResolution()
|
||||
val firDiagnostics = firAnalyzerFacade.runCheckers()
|
||||
val firDiagnostics = firAnalyzerFacade.runCheckers().values.flatten()
|
||||
AnalyzerWithCompilerReport.reportDiagnostics(
|
||||
SimpleDiagnostics(
|
||||
firDiagnostics.map { it.toRegularDiagnostic() }
|
||||
@@ -616,17 +595,8 @@ object KotlinToJVMBytecodeCompiler {
|
||||
sourceFiles: List<KtFile>,
|
||||
module: Module?
|
||||
): GenerationState {
|
||||
// The IR backend does not handle .kts files yet.
|
||||
var isIR = (configuration.getBoolean(JVMConfigurationKeys.IR) ||
|
||||
val isIR = (configuration.getBoolean(JVMConfigurationKeys.IR) ||
|
||||
configuration.getBoolean(CommonConfigurationKeys.USE_FIR))
|
||||
val anyKts = sourceFiles.any { it.isScript() }
|
||||
if (isIR && anyKts) {
|
||||
environment.messageCollector.report(
|
||||
STRONG_WARNING,
|
||||
"IR backend does not support .kts scripts, switching to old JVM backend"
|
||||
)
|
||||
isIR = false
|
||||
}
|
||||
val generationState = GenerationState.Builder(
|
||||
environment.project,
|
||||
ClassBuilderFactories.BINARIES,
|
||||
|
||||
-61
@@ -1,61 +0,0 @@
|
||||
/*
|
||||
* Copyright 2010-2016 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.
|
||||
*/
|
||||
|
||||
package org.jetbrains.kotlin.cli.jvm.compiler
|
||||
|
||||
import com.intellij.codeInsight.ExternalAnnotationsManager
|
||||
import com.intellij.openapi.vfs.VirtualFile
|
||||
import com.intellij.psi.*
|
||||
|
||||
class MockExternalAnnotationsManager : ExternalAnnotationsManager() {
|
||||
override fun chooseAnnotationsPlace(element: PsiElement): AnnotationPlace = AnnotationPlace.NOWHERE
|
||||
|
||||
override fun isExternalAnnotationWritable(listOwner: PsiModifierListOwner, annotationFQN: String): Boolean = false
|
||||
override fun isExternalAnnotation(annotation: PsiAnnotation): Boolean = false
|
||||
|
||||
override fun findExternalAnnotationsFiles(listOwner: PsiModifierListOwner): List<PsiFile>? = null
|
||||
override fun findExternalAnnotation(listOwner: PsiModifierListOwner, annotationFQN: String): PsiAnnotation? = null
|
||||
override fun findExternalAnnotations(listOwner: PsiModifierListOwner): Array<out PsiAnnotation>? = null
|
||||
|
||||
override fun annotateExternally(
|
||||
listOwner: PsiModifierListOwner,
|
||||
annotationFQName: String,
|
||||
fromFile: PsiFile,
|
||||
value: Array<out PsiNameValuePair>?
|
||||
) {
|
||||
throw UnsupportedOperationException("not implemented")
|
||||
}
|
||||
|
||||
override fun deannotate(listOwner: PsiModifierListOwner, annotationFQN: String): Boolean {
|
||||
throw UnsupportedOperationException("not implemented")
|
||||
}
|
||||
|
||||
override fun editExternalAnnotation(
|
||||
listOwner: PsiModifierListOwner,
|
||||
annotationFQN: String,
|
||||
value: Array<out PsiNameValuePair>?
|
||||
): Boolean {
|
||||
throw UnsupportedOperationException("not implemented")
|
||||
}
|
||||
|
||||
override fun hasAnnotationRootsForFile(file: VirtualFile): Boolean = false
|
||||
|
||||
override fun findDefaultConstructorExternalAnnotations(aClass: PsiClass, annotationFQN: String): List<PsiAnnotation> = emptyList()
|
||||
|
||||
override fun findDefaultConstructorExternalAnnotations(aClass: PsiClass): List<PsiAnnotation> = emptyList()
|
||||
|
||||
override fun findExternalAnnotations(listOwner: PsiModifierListOwner, annotationFQN: String): List<PsiAnnotation> = emptyList()
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
/*
|
||||
* Copyright 2010-2018 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.cli.jvm.compiler
|
||||
|
||||
fun setupIdeaStandaloneExecution() {
|
||||
}
|
||||
-18
@@ -1,18 +0,0 @@
|
||||
/*
|
||||
* 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.cli.jvm.compiler
|
||||
|
||||
import com.intellij.core.CoreApplicationEnvironment
|
||||
import com.intellij.openapi.extensions.ExtensionsArea
|
||||
import java.io.File
|
||||
import java.nio.file.FileSystems
|
||||
|
||||
// FIX ME WHEN BUNCH 193 REMOVED
|
||||
fun registerExtensionPointAndExtensionsEx(pluginFile: File, fileName: String, area: ExtensionsArea) {
|
||||
val pluginRoot = FileSystems.getDefault().getPath(pluginFile.path)
|
||||
@Suppress("MissingRecentApi")
|
||||
CoreApplicationEnvironment.registerExtensionPointAndExtensions(pluginRoot, fileName, area)
|
||||
}
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
/*
|
||||
* 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.cli.jvm.compiler
|
||||
|
||||
import com.intellij.core.CoreApplicationEnvironment
|
||||
import com.intellij.openapi.extensions.ExtensionsArea
|
||||
import java.io.File
|
||||
|
||||
// FIX ME WHEN BUNCH 193 REMOVED
|
||||
fun registerExtensionPointAndExtensionsEx(pluginFile: File, fileName: String, area: ExtensionsArea) {
|
||||
@Suppress("MissingRecentApi")
|
||||
CoreApplicationEnvironment.registerExtensionPointAndExtensions(pluginFile, fileName, area)
|
||||
}
|
||||
@@ -185,6 +185,7 @@ fun CompilerConfiguration.configureAdvancedJvmOptions(arguments: K2JVMCompilerAr
|
||||
put(JVMConfigurationKeys.EMIT_JVM_TYPE_ANNOTATIONS, arguments.emitJvmTypeAnnotations)
|
||||
put(JVMConfigurationKeys.NO_OPTIMIZED_CALLABLE_REFERENCES, arguments.noOptimizedCallableReferences)
|
||||
put(JVMConfigurationKeys.NO_KOTLIN_NOTHING_VALUE_EXCEPTION, arguments.noKotlinNothingValueException)
|
||||
put(JVMConfigurationKeys.NO_RESET_JAR_TIMESTAMPS, arguments.noResetJarTimestamps)
|
||||
put(JVMConfigurationKeys.NO_UNIFIED_NULL_CHECKS, arguments.noUnifiedNullChecks)
|
||||
|
||||
if (!JVMConstructorCallNormalizationMode.isSupportedValue(arguments.constructorCallNormalizationMode)) {
|
||||
@@ -230,6 +231,7 @@ fun CompilerConfiguration.configureAdvancedJvmOptions(arguments: K2JVMCompilerAr
|
||||
put(CLIConfigurationKeys.ALLOW_KOTLIN_PACKAGE, arguments.allowKotlinPackage)
|
||||
put(JVMConfigurationKeys.USE_SINGLE_MODULE, arguments.singleModule)
|
||||
put(JVMConfigurationKeys.USE_OLD_SPILLED_VAR_TYPE_ANALYSIS, arguments.useOldSpilledVarTypeAnalysis)
|
||||
put(JVMConfigurationKeys.USE_OLD_INLINE_CLASSES_MANGLING_SCHEME, arguments.useOldInlineClassesManglingScheme)
|
||||
|
||||
arguments.declarationsOutputPath?.let { put(JVMConfigurationKeys.DECLARATIONS_JSON_PATH, it) }
|
||||
}
|
||||
|
||||
@@ -129,9 +129,15 @@ public class JVMConfigurationKeys {
|
||||
public static final CompilerConfigurationKey<Boolean> NO_KOTLIN_NOTHING_VALUE_EXCEPTION =
|
||||
CompilerConfigurationKey.create("Do not use KotlinNothingValueException available since 1.4");
|
||||
|
||||
public static final CompilerConfigurationKey<Boolean> NO_RESET_JAR_TIMESTAMPS =
|
||||
CompilerConfigurationKey.create("Do not reset timestamps in jar entries");
|
||||
|
||||
public static final CompilerConfigurationKey<Boolean> NO_UNIFIED_NULL_CHECKS =
|
||||
CompilerConfigurationKey.create("Use pre-1.4 exception types in null checks instead of java.lang.NPE");
|
||||
|
||||
public static final CompilerConfigurationKey<Boolean> USE_OLD_SPILLED_VAR_TYPE_ANALYSIS =
|
||||
CompilerConfigurationKey.create("Use old, SourceInterpreter-based analysis for fields, used for spilled variables in coroutines");
|
||||
|
||||
public static final CompilerConfigurationKey<Boolean> USE_OLD_INLINE_CLASSES_MANGLING_SCHEME =
|
||||
CompilerConfigurationKey.create("Use old, 1.4 version of inline classes mangling scheme");
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ object JvmAnalysisFlags {
|
||||
val strictMetadataVersionSemantics by AnalysisFlag.Delegates.Boolean
|
||||
|
||||
@JvmStatic
|
||||
val javaTypeEnhancementState by AnalysisFlag.Delegates.JavaTypeEnhancementStateWarnByDefault
|
||||
val javaTypeEnhancementState by Delegates.JavaTypeEnhancementStateWarnByDefault
|
||||
|
||||
@JvmStatic
|
||||
val jvmDefaultMode by Delegates.JvmDefaultModeDisabledByDefault
|
||||
@@ -34,7 +34,7 @@ object JvmAnalysisFlags {
|
||||
val disableUltraLightClasses by AnalysisFlag.Delegates.Boolean
|
||||
|
||||
private object Delegates {
|
||||
object Jsr305StateWarnByDefault {
|
||||
object JavaTypeEnhancementStateWarnByDefault {
|
||||
operator fun provideDelegate(instance: Any?, property: KProperty<*>): AnalysisFlag.Delegate<JavaTypeEnhancementState> =
|
||||
AnalysisFlag.Delegate(property.name, JavaTypeEnhancementState.DEFAULT)
|
||||
}
|
||||
|
||||
@@ -48,9 +48,6 @@ object CommonConfigurationKeys {
|
||||
@JvmField
|
||||
val EXPECT_ACTUAL_LINKER = CompilerConfigurationKey.create<Boolean>("Experimental expext/actual linker")
|
||||
|
||||
@JvmField
|
||||
val DESERIALIZE_FAKE_OVERRIDES = CompilerConfigurationKey.create<Boolean>("Deserialize fake overrides")
|
||||
|
||||
@JvmField
|
||||
val USE_FIR_EXTENDED_CHECKERS = CompilerConfigurationKey.create<Boolean>("fir extended checkers")
|
||||
}
|
||||
|
||||
+2
-1
@@ -25,6 +25,7 @@ import java.io.File
|
||||
import java.io.Serializable
|
||||
import java.net.SocketException
|
||||
import java.nio.channels.ClosedChannelException
|
||||
import java.nio.file.Files
|
||||
import java.rmi.ConnectException
|
||||
import java.rmi.ConnectIOException
|
||||
import java.rmi.UnmarshalException
|
||||
@@ -422,7 +423,7 @@ class KotlinCompilerClient : KotlinCompilerDaemonClient {
|
||||
report: (DaemonReportCategory, String) -> Unit
|
||||
): Deferred<Pair<CompileServiceAsync?, DaemonJVMOptions>> = GlobalScope.async {
|
||||
registryDir.mkdirs()
|
||||
val timestampMarker = createTempFile("kotlin-daemon-client-tsmarker", directory = registryDir)
|
||||
val timestampMarker = Files.createTempFile(registryDir.toPath(), "kotlin-daemon-client-tsmarker", null).toFile()
|
||||
val aliveWithMetadata = try {
|
||||
walkDaemonsAsync(registryDir, compilerId, timestampMarker, report = report)
|
||||
} finally {
|
||||
|
||||
+2
-1
@@ -26,6 +26,7 @@ import java.io.File
|
||||
import java.io.OutputStream
|
||||
import java.io.PrintStream
|
||||
import java.net.SocketException
|
||||
import java.nio.file.Files
|
||||
import java.rmi.ConnectException
|
||||
import java.rmi.ConnectIOException
|
||||
import java.rmi.UnmarshalException
|
||||
@@ -347,7 +348,7 @@ object KotlinCompilerClient {
|
||||
|
||||
private fun tryFindSuitableDaemonOrNewOpts(registryDir: File, compilerId: CompilerId, daemonJVMOptions: DaemonJVMOptions, report: (DaemonReportCategory, String) -> Unit): Pair<CompileService?, DaemonJVMOptions> {
|
||||
registryDir.mkdirs()
|
||||
val timestampMarker = createTempFile("kotlin-daemon-client-tsmarker", directory = registryDir)
|
||||
val timestampMarker = Files.createTempFile(registryDir.toPath(), "kotlin-daemon-client-tsmarker", null).toFile()
|
||||
val aliveWithMetadata = try {
|
||||
walkDaemons(registryDir, compilerId, timestampMarker, report = report).toList()
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
package org.jetbrains.kotlin.daemon.common
|
||||
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
import java.rmi.registry.LocateRegistry
|
||||
|
||||
|
||||
@@ -106,7 +107,12 @@ private inline fun tryConnectToDaemon(port: Int, report: (DaemonReportCategory,
|
||||
private const val validFlagFileKeywordChars = "abcdefghijklmnopqrstuvwxyz0123456789-_"
|
||||
|
||||
fun makeAutodeletingFlagFile(keyword: String = "compiler-client", baseDir: File? = null): File {
|
||||
val flagFile = File.createTempFile("kotlin-${keyword.filter { validFlagFileKeywordChars.contains(it.toLowerCase()) }}-", "-is-running", baseDir?.takeIf { it.isDirectory && it.exists() })
|
||||
val prefix = "kotlin-${keyword.filter { validFlagFileKeywordChars.contains(it.toLowerCase()) }}-"
|
||||
val flagFile = if (baseDir?.isDirectory == true)
|
||||
Files.createTempFile(baseDir.toPath(), prefix, "-is-running").toFile()
|
||||
else
|
||||
Files.createTempFile(prefix, "-is-running").toFile()
|
||||
|
||||
flagFile.deleteOnExit()
|
||||
return flagFile
|
||||
}
|
||||
|
||||
+1
@@ -29,6 +29,7 @@ enum class CompilationResultCategory(val code: Int) {
|
||||
IC_COMPILE_ITERATION(0),
|
||||
BUILD_REPORT_LINES(1),
|
||||
VERBOSE_BUILD_REPORT_LINES(2),
|
||||
BUILD_METRICS(3)
|
||||
}
|
||||
|
||||
interface CompilationResultsAsync {
|
||||
|
||||
+12
-10
@@ -323,17 +323,19 @@ fun configureDaemonJVMOptions(opts: DaemonJVMOptions,
|
||||
|
||||
private val jvmAssertArgsRegex = "(es?a|ds?a|(enable|disable)(system)?assertions)(${'$'}|:)".toRegex()
|
||||
|
||||
fun configureDaemonJVMOptions(vararg additionalParams: String,
|
||||
inheritMemoryLimits: Boolean,
|
||||
inheritOtherJvmOptions: Boolean,
|
||||
inheritAdditionalProperties: Boolean
|
||||
fun configureDaemonJVMOptions(
|
||||
vararg additionalParams: String,
|
||||
inheritMemoryLimits: Boolean,
|
||||
inheritOtherJvmOptions: Boolean,
|
||||
inheritAdditionalProperties: Boolean
|
||||
): DaemonJVMOptions =
|
||||
configureDaemonJVMOptions(DaemonJVMOptions(),
|
||||
additionalParams = additionalParams,
|
||||
inheritMemoryLimits = inheritMemoryLimits,
|
||||
inheritOtherJvmOptions = inheritOtherJvmOptions,
|
||||
inheritAdditionalProperties = inheritAdditionalProperties)
|
||||
|
||||
configureDaemonJVMOptions(
|
||||
DaemonJVMOptions(),
|
||||
*additionalParams,
|
||||
inheritMemoryLimits = inheritMemoryLimits,
|
||||
inheritOtherJvmOptions = inheritOtherJvmOptions,
|
||||
inheritAdditionalProperties = inheritAdditionalProperties,
|
||||
)
|
||||
|
||||
fun configureDaemonOptions(opts: DaemonOptions): DaemonOptions {
|
||||
System.getProperty(COMPILE_DAEMON_OPTIONS_PROPERTY)?.let {
|
||||
|
||||
@@ -35,7 +35,10 @@ import java.io.ByteArrayOutputStream
|
||||
import java.io.File
|
||||
import java.io.PrintStream
|
||||
import java.net.URLClassLoader
|
||||
import java.nio.file.Path
|
||||
import kotlin.io.path.*
|
||||
|
||||
@OptIn(ExperimentalPathApi::class)
|
||||
class CompilerApiTest : KotlinIntegrationTestBase() {
|
||||
|
||||
private val compilerLibDir = getCompilerLib()
|
||||
@@ -119,7 +122,7 @@ class CompilerApiTest : KotlinIntegrationTestBase() {
|
||||
verbose = true,
|
||||
reportPerf = true)
|
||||
|
||||
val logFile = createTempFile("kotlin-daemon-test.", ".log")
|
||||
val logFile: Path = createTempFile("kotlin-daemon-test.", ".log")
|
||||
|
||||
val daemonJVMOptions = configureDaemonJVMOptions("D$COMPILE_DAEMON_LOG_PATH_PROPERTY=\"${logFile.loggerCompatiblePath}\"",
|
||||
inheritMemoryLimits = false, inheritOtherJvmOptions = false, inheritAdditionalProperties = false)
|
||||
@@ -137,7 +140,8 @@ class CompilerApiTest : KotlinIntegrationTestBase() {
|
||||
}
|
||||
finally {
|
||||
KotlinCompilerClient.shutdownCompileService(compilerId, daemonOptions)
|
||||
logFile.delete()
|
||||
runCatching { logFile.deleteIfExists() }
|
||||
.onFailure { e -> println("Failed to delete log file: $e") }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -158,7 +162,7 @@ class CompilerApiTest : KotlinIntegrationTestBase() {
|
||||
verbose = true,
|
||||
reportPerf = true)
|
||||
|
||||
val logFile = createTempFile("kotlin-daemon-test.", ".log")
|
||||
val logFile: Path = createTempFile("kotlin-daemon-test.", ".log")
|
||||
|
||||
val daemonJVMOptions = configureDaemonJVMOptions("D$COMPILE_DAEMON_LOG_PATH_PROPERTY=\"${logFile.loggerCompatiblePath}\"",
|
||||
inheritMemoryLimits = false, inheritOtherJvmOptions = false, inheritAdditionalProperties = false)
|
||||
@@ -174,7 +178,8 @@ class CompilerApiTest : KotlinIntegrationTestBase() {
|
||||
}
|
||||
finally {
|
||||
KotlinCompilerClient.shutdownCompileService(compilerId, daemonOptions)
|
||||
logFile.delete()
|
||||
runCatching { logFile.deleteIfExists() }
|
||||
.onFailure { e -> println("Failed to delete log file: $e") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,10 +36,13 @@ import java.lang.management.ManagementFactory
|
||||
import java.net.URL
|
||||
import java.net.URLClassLoader
|
||||
import java.nio.charset.Charset
|
||||
import java.nio.file.Path
|
||||
import java.rmi.server.UnicastRemoteObject
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import kotlin.concurrent.thread
|
||||
import kotlin.io.path.ExperimentalPathApi
|
||||
import kotlin.io.path.invariantSeparatorsPath
|
||||
import kotlin.script.dependencies.Environment
|
||||
import kotlin.script.dependencies.ScriptContents
|
||||
import kotlin.script.experimental.dependencies.DependenciesResolver
|
||||
@@ -997,9 +1000,12 @@ internal inline fun withLogFile(prefix: String, suffix: String = ".log", printLo
|
||||
// if file path is given in windows form (using backslash as a separator); the reason is unknown
|
||||
// this function makes a path with forward slashed, that works on windows too
|
||||
internal val File.loggerCompatiblePath: String
|
||||
get() =
|
||||
if (OSKind.current == OSKind.Windows) absolutePath.replace('\\', '/')
|
||||
else absolutePath
|
||||
get() = invariantSeparatorsPath
|
||||
|
||||
@OptIn(ExperimentalPathApi::class)
|
||||
internal val Path.loggerCompatiblePath: String
|
||||
get() = invariantSeparatorsPath
|
||||
|
||||
|
||||
open class TestKotlinScriptDummyDependenciesResolver : DependenciesResolver {
|
||||
|
||||
|
||||
+6
-3
@@ -28,13 +28,16 @@ import org.junit.Assert
|
||||
import org.junit.runner.RunWith
|
||||
import java.io.File
|
||||
import java.net.URLClassLoader
|
||||
import java.nio.file.Path
|
||||
import java.util.logging.LogManager
|
||||
import java.util.logging.Logger
|
||||
import kotlin.io.path.*
|
||||
|
||||
private val logFiles = arrayListOf<String>()
|
||||
|
||||
// TODO: remove ignore annotation from tests.
|
||||
|
||||
@OptIn(ExperimentalPathApi::class)
|
||||
@RunWith(IgnoreAll::class)
|
||||
class CompilerApiTest : KotlinIntegrationTestBase() {
|
||||
|
||||
@@ -43,7 +46,7 @@ class CompilerApiTest : KotlinIntegrationTestBase() {
|
||||
|
||||
private val compilerLibDir = getCompilerLib()
|
||||
|
||||
private fun createNewLogFile(): File {
|
||||
private fun createNewLogFile(): Path {
|
||||
println("creating logFile")
|
||||
val newLogFile = createTempFile("kotlin-daemon-experimental-test.", ".log")
|
||||
println("logFile created (${newLogFile.loggerCompatiblePath})")
|
||||
@@ -51,7 +54,7 @@ class CompilerApiTest : KotlinIntegrationTestBase() {
|
||||
return newLogFile
|
||||
}
|
||||
|
||||
private val currentLogFile: File by lazy {
|
||||
private val currentLogFile: Path by lazy {
|
||||
val newLogFile = createNewLogFile()
|
||||
val cfg: String =
|
||||
"handlers = java.util.logging.FileHandler\n" +
|
||||
@@ -67,7 +70,7 @@ class CompilerApiTest : KotlinIntegrationTestBase() {
|
||||
newLogFile
|
||||
}
|
||||
|
||||
private val externalLogFile: File by lazy { createNewLogFile() }
|
||||
private val externalLogFile: Path by lazy { createNewLogFile() }
|
||||
|
||||
private val log by lazy {
|
||||
currentLogFile
|
||||
|
||||
+14
-18
@@ -3,6 +3,8 @@
|
||||
* that can be found in the license/LICENSE.txt file.
|
||||
*/
|
||||
|
||||
@file:OptIn(ExperimentalPathApi::class)
|
||||
|
||||
package org.jetbrains.kotlin.daemon.experimental.integration
|
||||
|
||||
import junit.framework.TestCase
|
||||
@@ -38,6 +40,7 @@ import java.net.URL
|
||||
import java.net.URLClassLoader
|
||||
import java.nio.channels.ClosedChannelException
|
||||
import java.nio.charset.Charset
|
||||
import java.nio.file.Path
|
||||
import java.rmi.ConnectException
|
||||
import java.rmi.ConnectIOException
|
||||
import java.rmi.UnmarshalException
|
||||
@@ -46,6 +49,7 @@ import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.logging.LogManager
|
||||
import kotlin.concurrent.thread
|
||||
import kotlin.io.path.*
|
||||
import kotlin.script.dependencies.Environment
|
||||
import kotlin.script.dependencies.ScriptContents
|
||||
import kotlin.script.experimental.dependencies.DependenciesResolver
|
||||
@@ -64,7 +68,7 @@ class CompilerDaemonTest : KotlinIntegrationTestBase() {
|
||||
|
||||
val kotlinCompilerClientInstance = KotlinCompilerDaemonClient.instantiate(DaemonProtocolVariant.SOCKETS)
|
||||
|
||||
private fun createNewLogFile(): File {
|
||||
private fun createNewLogFile(): Path {
|
||||
println("creating logFile")
|
||||
val newLogFile = createTempFile("kotlin-daemon-experimental-test.", ".log")
|
||||
println("logFile created (${newLogFile.loggerCompatiblePath})")
|
||||
@@ -595,8 +599,8 @@ class CompilerDaemonTest : KotlinIntegrationTestBase() {
|
||||
shutdownDelayMilliseconds = 1,
|
||||
runFilesPath = File(tmpdir, getTestName(true)).absolutePath
|
||||
)
|
||||
val clientFlag = createTempFile(getTestName(true), "-client.alive")
|
||||
val sessionFlag = createTempFile(getTestName(true), "-session.alive")
|
||||
val clientFlag = createTempFile(getTestName(true), "-client.alive").toFile()
|
||||
val sessionFlag = createTempFile(getTestName(true), "-session.alive").toFile()
|
||||
try {
|
||||
withLogFile("kotlin-daemon-test") { logFile ->
|
||||
val daemonJVMOptions = makeTestDaemonJvmOptions(logFile)
|
||||
@@ -635,8 +639,8 @@ class CompilerDaemonTest : KotlinIntegrationTestBase() {
|
||||
shutdownDelayMilliseconds = 1,
|
||||
runFilesPath = File(tmpdir, getTestName(true)).absolutePath
|
||||
)
|
||||
val clientFlag = createTempFile(getTestName(true), "-client.alive")
|
||||
val sessionFlag = createTempFile(getTestName(true), "-session.alive")
|
||||
val clientFlag = createTempFile(getTestName(true), "-client.alive").toFile()
|
||||
val sessionFlag = createTempFile(getTestName(true), "-session.alive").toFile()
|
||||
try {
|
||||
withLogFile("kotlin-daemon-test") { logFile ->
|
||||
val daemonJVMOptions = makeTestDaemonJvmOptions(logFile)
|
||||
@@ -678,8 +682,8 @@ class CompilerDaemonTest : KotlinIntegrationTestBase() {
|
||||
shutdownDelayMilliseconds = 3000,
|
||||
runFilesPath = File(tmpdir, getTestName(true)).absolutePath
|
||||
)
|
||||
val clientFlag = createTempFile(getTestName(true), "-client.alive")
|
||||
val clientFlag2 = createTempFile(getTestName(true), "-client.alive")
|
||||
val clientFlag = createTempFile(getTestName(true), "-client.alive").toFile()
|
||||
val clientFlag2 = createTempFile(getTestName(true), "-client.alive").toFile()
|
||||
try {
|
||||
withLogFile("kotlin-daemon-test") { logFile ->
|
||||
val daemonJVMOptions = makeTestDaemonJvmOptions(logFile)
|
||||
@@ -769,8 +773,7 @@ class CompilerDaemonTest : KotlinIntegrationTestBase() {
|
||||
assertEquals("Compilation failed:\n$resOutput", 0, resCode)
|
||||
println("OK")
|
||||
} finally {
|
||||
if (clientAliveFile.exists())
|
||||
clientAliveFile.delete()
|
||||
clientAliveFile.deleteIfExists()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1427,7 +1430,7 @@ fun restoreSystemProperty(propertyName: String, backupValue: String?) {
|
||||
}
|
||||
|
||||
internal inline fun withFlagFile(prefix: String, suffix: String? = null, body: (File) -> Unit) {
|
||||
val file = createTempFile(prefix, suffix)
|
||||
val file = createTempFile(prefix, suffix).toFile()
|
||||
try {
|
||||
body(file)
|
||||
} finally {
|
||||
@@ -1436,7 +1439,7 @@ internal inline fun withFlagFile(prefix: String, suffix: String? = null, body: (
|
||||
}
|
||||
|
||||
internal inline fun withLogFile(prefix: String, suffix: String = ".log", printLogOnException: Boolean = true, body: (File) -> Unit) {
|
||||
val logFile = createTempFile(prefix, suffix)
|
||||
val logFile = createTempFile(prefix, suffix).toFile()
|
||||
println("LOG FILE : ${logFile.path}")
|
||||
try {
|
||||
body(logFile)
|
||||
@@ -1449,13 +1452,6 @@ internal inline fun withLogFile(prefix: String, suffix: String = ".log", printLo
|
||||
}
|
||||
}
|
||||
|
||||
// java.util.Logger used in the daemon silently forgets to log into a file specified in the config on Windows,
|
||||
// if file path is given in windows form (using backslash as a separator); the reason is unknown
|
||||
// this function makes a path with forward slashed, that works on windows too
|
||||
internal val File.loggerCompatiblePath: String
|
||||
get() =
|
||||
if (OSKind.current == OSKind.Windows) absolutePath.replace('\\', '/')
|
||||
else absolutePath
|
||||
|
||||
open class TestKotlinScriptDummyDependenciesResolver : DependenciesResolver {
|
||||
|
||||
|
||||
+2
@@ -24,6 +24,7 @@ import java.io.ObjectInputStream
|
||||
import java.io.ObjectOutputStream
|
||||
import java.net.InetSocketAddress
|
||||
import java.util.logging.Logger
|
||||
import kotlin.io.path.*
|
||||
|
||||
@OptIn(KtorExperimentalAPI::class)
|
||||
class TestServer(val serverPort: Int = 6999) {
|
||||
@@ -44,6 +45,7 @@ val testServer = TestServer()
|
||||
|
||||
@RunWith(IgnoreAll::class)
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
@OptIn(ExperimentalPathApi::class)
|
||||
class ClientSerializationTest : KotlinIntegrationTestBase() {
|
||||
|
||||
val file = createTempFile()
|
||||
|
||||
+6
-3
@@ -31,11 +31,14 @@ import java.io.ByteArrayOutputStream
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.io.PrintStream
|
||||
import java.nio.file.Path
|
||||
import java.util.*
|
||||
import java.util.logging.LogManager
|
||||
import java.util.logging.Logger
|
||||
import kotlin.concurrent.schedule
|
||||
import kotlin.io.path.*
|
||||
|
||||
@OptIn(ExperimentalPathApi::class)
|
||||
@RunWith(IgnoreAll::class)
|
||||
class ConnectionsTest : KotlinIntegrationTestBase() {
|
||||
|
||||
@@ -247,15 +250,15 @@ class ConnectionsTest : KotlinIntegrationTestBase() {
|
||||
extraAction
|
||||
)
|
||||
|
||||
private val clientFiles = arrayListOf<File>()
|
||||
private val clientFiles = mutableListOf<Path>()
|
||||
private fun generateClient(): String {
|
||||
val file = createTempFile(getTestName(true), ".alive")
|
||||
clientFiles.add(file)
|
||||
return file.absolutePath
|
||||
return file.toAbsolutePath().toString()
|
||||
}
|
||||
|
||||
private fun deleteClients() {
|
||||
clientFiles.forEach { it.delete() }
|
||||
clientFiles.forEach { it.deleteIfExists() }
|
||||
}
|
||||
|
||||
private fun endTest() {
|
||||
|
||||
@@ -21,6 +21,9 @@ import com.intellij.openapi.util.Disposer
|
||||
import com.intellij.openapi.vfs.impl.ZipHandler
|
||||
import com.intellij.openapi.vfs.impl.jar.CoreJarFileSystem
|
||||
import org.jetbrains.kotlin.build.DEFAULT_KOTLIN_SOURCE_FILES_EXTENSIONS
|
||||
import org.jetbrains.kotlin.build.report.BuildReporter
|
||||
import org.jetbrains.kotlin.build.report.RemoteBuildReporter
|
||||
import org.jetbrains.kotlin.build.report.RemoteReporter
|
||||
import org.jetbrains.kotlin.cli.common.CLICompiler
|
||||
import org.jetbrains.kotlin.cli.common.ExitCode
|
||||
import org.jetbrains.kotlin.cli.common.KOTLIN_COMPILER_ENVIRONMENT_KEEPALIVE_PROPERTY
|
||||
@@ -286,7 +289,7 @@ abstract class CompileServiceImplBase(
|
||||
createMessageCollector: (ServicesFacadeT, CompilationOptions) -> MessageCollector,
|
||||
createReporter: (ServicesFacadeT, CompilationOptions) -> DaemonMessageReporter,
|
||||
createServices: (JpsServicesFacadeT, EventManager, Profiler) -> Services,
|
||||
getICReporter: (ServicesFacadeT, CompilationResultsT?, IncrementalCompilationOptions) -> RemoteICReporter
|
||||
getICReporter: (ServicesFacadeT, CompilationResultsT?, IncrementalCompilationOptions) -> RemoteBuildReporter
|
||||
) = kotlin.run {
|
||||
val messageCollector = createMessageCollector(servicesFacade, compilationOptions)
|
||||
val daemonReporter = createReporter(servicesFacade, compilationOptions)
|
||||
@@ -514,7 +517,7 @@ abstract class CompileServiceImplBase(
|
||||
args: K2JSCompilerArguments,
|
||||
incrementalCompilationOptions: IncrementalCompilationOptions,
|
||||
compilerMessageCollector: MessageCollector,
|
||||
reporter: RemoteICReporter
|
||||
reporter: RemoteBuildReporter
|
||||
): ExitCode {
|
||||
val allKotlinFiles = arrayListOf<File>()
|
||||
val freeArgsWithoutKotlinFiles = arrayListOf<String>()
|
||||
@@ -554,7 +557,7 @@ abstract class CompileServiceImplBase(
|
||||
k2jvmArgs: K2JVMCompilerArguments,
|
||||
incrementalCompilationOptions: IncrementalCompilationOptions,
|
||||
compilerMessageCollector: MessageCollector,
|
||||
reporter: RemoteICReporter
|
||||
reporter: RemoteBuildReporter
|
||||
): ExitCode {
|
||||
val allKotlinExtensions = (DEFAULT_KOTLIN_SOURCE_FILES_EXTENSIONS +
|
||||
(incrementalCompilationOptions.kotlinScriptExtensions ?: emptyArray())).distinct()
|
||||
@@ -589,6 +592,8 @@ abstract class CompileServiceImplBase(
|
||||
}
|
||||
}
|
||||
|
||||
val projectRoot = incrementalCompilationOptions.modulesInfo.projectRoot
|
||||
|
||||
val compiler = IncrementalJvmCompilerRunner(
|
||||
workingDir,
|
||||
reporter,
|
||||
@@ -599,7 +604,7 @@ abstract class CompileServiceImplBase(
|
||||
kotlinSourceFilesExtensions = allKotlinExtensions
|
||||
)
|
||||
return try {
|
||||
compiler.compile(allKotlinFiles, k2jvmArgs, compilerMessageCollector, changedFiles)
|
||||
compiler.compile(allKotlinFiles, k2jvmArgs, compilerMessageCollector, changedFiles, projectRoot)
|
||||
} finally {
|
||||
reporter.flush()
|
||||
}
|
||||
@@ -782,7 +787,7 @@ class CompileServiceImpl(
|
||||
createMessageCollector = ::CompileServicesFacadeMessageCollector,
|
||||
createReporter = ::DaemonMessageReporter,
|
||||
createServices = this::createCompileServices,
|
||||
getICReporter = { a, b, c -> getICReporter(a, b!!, c)}
|
||||
getICReporter = { a, b, c -> getBuildReporter(a, b!!, c)}
|
||||
)
|
||||
|
||||
override fun leaseReplSession(
|
||||
|
||||
@@ -8,10 +8,12 @@ package org.jetbrains.kotlin.daemon.report
|
||||
import org.jetbrains.kotlin.cli.common.ExitCode
|
||||
import org.jetbrains.kotlin.daemon.common.CompilationResultCategory
|
||||
import org.jetbrains.kotlin.daemon.common.CompilationResults
|
||||
import org.jetbrains.kotlin.incremental.ICReporterBase
|
||||
import org.jetbrains.kotlin.build.report.ICReporterBase
|
||||
import org.jetbrains.kotlin.build.report.RemoteICReporter
|
||||
import java.io.File
|
||||
import java.util.HashMap
|
||||
import java.util.*
|
||||
|
||||
// todo: sync BuildReportICReporterAsync
|
||||
internal class BuildReportICReporter(
|
||||
private val compilationResults: CompilationResults,
|
||||
rootDir: File,
|
||||
|
||||
+2
-1
@@ -9,7 +9,8 @@ import org.jetbrains.kotlin.cli.common.ExitCode
|
||||
import org.jetbrains.kotlin.daemon.common.CompilationResultCategory
|
||||
import org.jetbrains.kotlin.daemon.common.CompilationResults
|
||||
import org.jetbrains.kotlin.daemon.common.CompileIterationResult
|
||||
import org.jetbrains.kotlin.incremental.ICReporterBase
|
||||
import org.jetbrains.kotlin.build.report.ICReporterBase
|
||||
import org.jetbrains.kotlin.build.report.RemoteICReporter
|
||||
import java.io.File
|
||||
|
||||
internal class CompileIterationICReporter(
|
||||
|
||||
@@ -5,11 +5,11 @@
|
||||
|
||||
package org.jetbrains.kotlin.daemon.report
|
||||
|
||||
import org.jetbrains.kotlin.build.report.RemoteICReporter
|
||||
import org.jetbrains.kotlin.cli.common.ExitCode
|
||||
import java.io.File
|
||||
|
||||
internal class CompositeICReporter(private val reporters: Iterable<RemoteICReporter>) :
|
||||
RemoteICReporter {
|
||||
internal class CompositeICReporter(private val reporters: Iterable<RemoteICReporter>) : RemoteICReporter {
|
||||
override fun report(message: () -> String) {
|
||||
reporters.forEach { it.report(message) }
|
||||
}
|
||||
|
||||
@@ -7,7 +7,8 @@ package org.jetbrains.kotlin.daemon.report
|
||||
|
||||
import org.jetbrains.kotlin.cli.common.ExitCode
|
||||
import org.jetbrains.kotlin.daemon.common.*
|
||||
import org.jetbrains.kotlin.incremental.ICReporterBase
|
||||
import org.jetbrains.kotlin.build.report.ICReporterBase
|
||||
import org.jetbrains.kotlin.build.report.RemoteICReporter
|
||||
import java.io.File
|
||||
|
||||
internal class DebugMessagesICReporter(
|
||||
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* 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.daemon.report
|
||||
|
||||
import org.jetbrains.kotlin.build.report.metrics.BuildMetricsReporter
|
||||
import org.jetbrains.kotlin.build.report.metrics.RemoteBuildMetricsReporter
|
||||
import org.jetbrains.kotlin.daemon.common.CompilationResultCategory
|
||||
import org.jetbrains.kotlin.daemon.common.CompilationResults
|
||||
|
||||
class RemoteBuildMetricsReporterAdapter(
|
||||
private val delegate: BuildMetricsReporter,
|
||||
private val shouldReport: Boolean,
|
||||
private val compilationResults: CompilationResults
|
||||
) :
|
||||
BuildMetricsReporter by delegate,
|
||||
RemoteBuildMetricsReporter {
|
||||
|
||||
override fun flush() {
|
||||
if (shouldReport) {
|
||||
val metrics = delegate.getMetrics()
|
||||
compilationResults.add(CompilationResultCategory.BUILD_METRICS.code, metrics)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
/*
|
||||
* Copyright 2010-2019 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.daemon.report
|
||||
|
||||
import org.jetbrains.kotlin.incremental.ICReporter
|
||||
|
||||
interface RemoteICReporter : ICReporter {
|
||||
fun flush()
|
||||
}
|
||||
+43
-61
@@ -5,25 +5,29 @@
|
||||
|
||||
package org.jetbrains.kotlin.daemon.report.experimental
|
||||
|
||||
import kotlinx.coroutines.*
|
||||
import kotlinx.coroutines.GlobalScope
|
||||
import kotlinx.coroutines.async
|
||||
import org.jetbrains.kotlin.build.report.ICReporterBase
|
||||
import org.jetbrains.kotlin.build.report.RemoteBuildReporter
|
||||
import org.jetbrains.kotlin.build.report.RemoteICReporter
|
||||
import org.jetbrains.kotlin.build.report.metrics.BuildMetricsReporter
|
||||
import org.jetbrains.kotlin.build.report.metrics.DoNothingBuildMetricsReporter
|
||||
import org.jetbrains.kotlin.build.report.metrics.RemoteBuildMetricsReporter
|
||||
import org.jetbrains.kotlin.cli.common.ExitCode
|
||||
import org.jetbrains.kotlin.daemon.common.*
|
||||
import org.jetbrains.kotlin.daemon.report.RemoteICReporter
|
||||
import org.jetbrains.kotlin.incremental.ICReporter
|
||||
import org.jetbrains.kotlin.incremental.ICReporterBase
|
||||
import org.jetbrains.kotlin.daemon.report.CompositeICReporter
|
||||
import java.io.File
|
||||
import java.io.Serializable
|
||||
|
||||
internal class DebugMessagesICReporterAsync(
|
||||
private val servicesFacade: CompilerServicesFacadeBaseAsync,
|
||||
rootDir: File,
|
||||
private val isVerbose: Boolean
|
||||
private val servicesFacade: CompilerServicesFacadeBaseAsync,
|
||||
rootDir: File,
|
||||
private val isVerbose: Boolean
|
||||
) : ICReporterBase(rootDir), RemoteICReporter {
|
||||
override fun report(message: () -> String) {
|
||||
GlobalScope.async {
|
||||
servicesFacade.report(
|
||||
ReportCategory.IC_MESSAGE,
|
||||
ReportSeverity.DEBUG, message()
|
||||
ReportCategory.IC_MESSAGE,
|
||||
ReportSeverity.DEBUG, message()
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -42,13 +46,13 @@ internal class DebugMessagesICReporterAsync(
|
||||
}
|
||||
|
||||
internal class CompileIterationICReporterAsync(
|
||||
private val compilationResults: CompilationResultsAsync?
|
||||
private val compilationResults: CompilationResultsAsync?
|
||||
) : ICReporterBase(), RemoteICReporter {
|
||||
override fun reportCompileIteration(incremental: Boolean, sourceFiles: Collection<File>, exitCode: ExitCode) {
|
||||
GlobalScope.async {
|
||||
compilationResults?.add(
|
||||
CompilationResultCategory.IC_COMPILE_ITERATION.code,
|
||||
CompileIterationResult(sourceFiles, exitCode.toString())
|
||||
CompilationResultCategory.IC_COMPILE_ITERATION.code,
|
||||
CompileIterationResult(sourceFiles, exitCode.toString())
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -64,9 +68,9 @@ internal class CompileIterationICReporterAsync(
|
||||
}
|
||||
|
||||
internal class BuildReportICReporterAsync(
|
||||
private val compilationResults: CompilationResultsAsync?,
|
||||
rootDir: File,
|
||||
private val isVerbose: Boolean = false
|
||||
private val compilationResults: CompilationResultsAsync?,
|
||||
rootDir: File,
|
||||
private val isVerbose: Boolean = false
|
||||
) : ICReporterBase(rootDir), RemoteICReporter {
|
||||
private val icLogLines = arrayListOf<String>()
|
||||
private val recompilationReason = HashMap<File, String>()
|
||||
@@ -103,42 +107,11 @@ internal class BuildReportICReporterAsync(
|
||||
}
|
||||
}
|
||||
|
||||
internal class CompositeICReporterAsync(private val reporters: Iterable<RemoteICReporter>) :
|
||||
RemoteICReporter {
|
||||
override fun report(message: () -> String) {
|
||||
reporters.forEach { it.report(message) }
|
||||
}
|
||||
|
||||
override fun reportVerbose(message: () -> String) {
|
||||
reporters.forEach { it.reportVerbose(message) }
|
||||
}
|
||||
|
||||
override fun reportCompileIteration(incremental: Boolean, sourceFiles: Collection<File>, exitCode: ExitCode) {
|
||||
reporters.forEach { it.reportCompileIteration(incremental, sourceFiles, exitCode) }
|
||||
}
|
||||
|
||||
override fun reportMarkDirtyClass(affectedFiles: Iterable<File>, classFqName: String) {
|
||||
reporters.forEach { it.reportMarkDirtyClass(affectedFiles, classFqName) }
|
||||
}
|
||||
|
||||
override fun reportMarkDirtyMember(affectedFiles: Iterable<File>, scope: String, name: String) {
|
||||
reporters.forEach { it.reportMarkDirtyMember(affectedFiles, scope, name) }
|
||||
}
|
||||
|
||||
override fun reportMarkDirty(affectedFiles: Iterable<File>, reason: String) {
|
||||
reporters.forEach { it.reportMarkDirty(affectedFiles, reason) }
|
||||
}
|
||||
|
||||
override fun flush() {
|
||||
reporters.forEach { it.flush() }
|
||||
}
|
||||
}
|
||||
|
||||
fun getICReporterAsync(
|
||||
servicesFacade: CompilerServicesFacadeBaseAsync,
|
||||
compilationResults: CompilationResultsAsync?,
|
||||
compilationOptions: IncrementalCompilationOptions
|
||||
): RemoteICReporter {
|
||||
servicesFacade: CompilerServicesFacadeBaseAsync,
|
||||
compilationResults: CompilationResultsAsync?,
|
||||
compilationOptions: IncrementalCompilationOptions
|
||||
): RemoteBuildReporter {
|
||||
val root = compilationOptions.modulesInfo.projectRoot
|
||||
val reporters = ArrayList<RemoteICReporter>()
|
||||
|
||||
@@ -148,23 +121,32 @@ fun getICReporterAsync(
|
||||
}
|
||||
|
||||
val requestedResults = compilationOptions
|
||||
.requestedCompilationResults
|
||||
.mapNotNullTo(HashSet()) { resultCode ->
|
||||
CompilationResultCategory.values().getOrNull(resultCode)
|
||||
}
|
||||
requestedResults.mapTo(reporters) { requestedResult ->
|
||||
.requestedCompilationResults
|
||||
.mapNotNullTo(HashSet()) { resultCode ->
|
||||
CompilationResultCategory.values().getOrNull(resultCode)
|
||||
}
|
||||
for (requestedResult in requestedResults) {
|
||||
when (requestedResult) {
|
||||
CompilationResultCategory.IC_COMPILE_ITERATION -> {
|
||||
CompileIterationICReporterAsync(compilationResults)
|
||||
reporters.add(CompileIterationICReporterAsync(compilationResults))
|
||||
}
|
||||
CompilationResultCategory.BUILD_REPORT_LINES -> {
|
||||
BuildReportICReporterAsync(compilationResults, root)
|
||||
reporters.add(BuildReportICReporterAsync(compilationResults, root))
|
||||
}
|
||||
CompilationResultCategory.VERBOSE_BUILD_REPORT_LINES -> {
|
||||
BuildReportICReporterAsync(compilationResults, root, isVerbose = true)
|
||||
reporters.add(BuildReportICReporterAsync(compilationResults, root, isVerbose = true))
|
||||
}
|
||||
CompilationResultCategory.BUILD_METRICS -> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return CompositeICReporterAsync(reporters)
|
||||
}
|
||||
val icReporter = CompositeICReporter(reporters)
|
||||
val metricsReporter = DoNothingRemoteBuildMetricsReporter
|
||||
return RemoteBuildReporter(icReporter, metricsReporter)
|
||||
}
|
||||
|
||||
object DoNothingRemoteBuildMetricsReporter : BuildMetricsReporter by DoNothingBuildMetricsReporter, RemoteBuildMetricsReporter {
|
||||
override fun flush() {
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,15 +16,18 @@
|
||||
|
||||
package org.jetbrains.kotlin.daemon.report
|
||||
|
||||
import org.jetbrains.kotlin.build.report.RemoteBuildReporter
|
||||
import org.jetbrains.kotlin.build.report.RemoteICReporter
|
||||
import org.jetbrains.kotlin.build.report.metrics.BuildMetricsReporterImpl
|
||||
import org.jetbrains.kotlin.build.report.metrics.DoNothingBuildMetricsReporter
|
||||
import org.jetbrains.kotlin.daemon.common.*
|
||||
import java.io.File
|
||||
import java.util.*
|
||||
|
||||
fun getICReporter(
|
||||
fun getBuildReporter(
|
||||
servicesFacade: CompilerServicesFacadeBase,
|
||||
compilationResults: CompilationResults,
|
||||
compilationOptions: IncrementalCompilationOptions
|
||||
): RemoteICReporter {
|
||||
): RemoteBuildReporter {
|
||||
val root = compilationOptions.modulesInfo.projectRoot
|
||||
val reporters = ArrayList<RemoteICReporter>()
|
||||
|
||||
@@ -38,21 +41,25 @@ fun getICReporter(
|
||||
.mapNotNullTo(HashSet()) { resultCode ->
|
||||
CompilationResultCategory.values().getOrNull(resultCode)
|
||||
}
|
||||
requestedResults.mapTo(reporters) { requestedResult ->
|
||||
for (requestedResult in requestedResults) {
|
||||
when (requestedResult) {
|
||||
CompilationResultCategory.IC_COMPILE_ITERATION -> {
|
||||
CompileIterationICReporter(compilationResults)
|
||||
reporters.add(CompileIterationICReporter(compilationResults))
|
||||
}
|
||||
CompilationResultCategory.BUILD_REPORT_LINES -> {
|
||||
BuildReportICReporter(compilationResults, root)
|
||||
reporters.add(BuildReportICReporter(compilationResults, root))
|
||||
}
|
||||
CompilationResultCategory.VERBOSE_BUILD_REPORT_LINES -> {
|
||||
BuildReportICReporter(compilationResults, root, isVerbose = true)
|
||||
reporters.add(BuildReportICReporter(compilationResults, root, isVerbose = true))
|
||||
}
|
||||
CompilationResultCategory.BUILD_METRICS -> {
|
||||
}
|
||||
}
|
||||
}
|
||||
val areBuildMetricsNeeded = CompilationResultCategory.BUILD_METRICS in requestedResults
|
||||
val metricsReporter =
|
||||
(if (areBuildMetricsNeeded) BuildMetricsReporterImpl() else DoNothingBuildMetricsReporter)
|
||||
.let { RemoteBuildMetricsReporterAdapter(it, areBuildMetricsNeeded, compilationResults) }
|
||||
|
||||
return CompositeICReporter(reporters)
|
||||
return RemoteBuildReporter(CompositeICReporter(reporters), metricsReporter)
|
||||
}
|
||||
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user