Compare commits

..

6 Commits

Author SHA1 Message Date
Abduqodiri Qurbonzoda
feec8dfd77 Fix deprecations ReplaceWith 2020-04-13 02:50:56 +03:00
Abduqodiri Qurbonzoda
3e65148699 Revert "appendln" -> "appendLine" replacements in descriptors 2020-04-13 02:32:27 +03:00
Abduqodiri Qurbonzoda
a4cb3bcc04 Move new appendLine methods to the top 2020-04-10 14:25:46 +03:00
Abduqodiri Qurbonzoda
05806b8e18 Revert "appendln" -> "appendLine" replacements in tools 2020-04-10 14:09:19 +03:00
Abduqodiri Qurbonzoda
a54e659121 "linefeed" -> "line feed", "local platform" -> "system line separator" 2020-04-10 14:07:15 +03:00
Abduqodiri Qurbonzoda
2efa283014 Introduce StringBuilder.appendLine in stdlib-common #KT-37839 2020-04-07 08:21:54 +03:00
22274 changed files with 220349 additions and 769137 deletions

12
.bunch
View File

@@ -1,7 +1,7 @@
201
202
203_202
193
as40_193
as41
as42_202
201
192
191_192
as35_191_192
as36_192
as40

2
.gitattributes vendored
View File

@@ -2,7 +2,5 @@
*Generated.java linguist-generated=true
* text=auto
* eol=lf
*.png binary
*.jar binary
compiler/cli/bin/* eol=lf
compiler/cli/bin/*.bat eol=crlf

7
.gitignore vendored
View File

@@ -50,15 +50,10 @@ build/
.idea/artifacts/kotlin_main_kts_jar.xml
.idea/artifacts/kotlin_compiler_client_embeddable_jar.xml
.idea/artifacts/kotlin_reflect_jar.xml
.idea/artifacts/kotlin_stdlib_js_ir_*
.idea/artifacts/kotlin_test_js_ir_*
.idea/artifacts/kotlin_stdlib_wasm_*
.idea/jarRepositories.xml
kotlin-ultimate/
node_modules/
.rpt2_cache/
libraries/tools/kotlin-test-js-runner/lib/
libraries/tools/kotlin-source-map-loader/lib/
local.properties
buildSrcTmp/
distTmp/
outTmp/

View File

@@ -1,8 +0,0 @@
<component name="ArtifactManager">
<artifact build-on-make="true" name="dist_root">
<output-path>$PROJECT_DIR$/dist</output-path>
<root id="root">
<element id="artifact" artifact-name="dist" />
</root>
</artifact>
</component>

View File

@@ -11,7 +11,6 @@
<w>protobuf</w>
<w>redirector</w>
<w>remapper</w>
<w>sonatype</w>
<w>unpresent</w>
</words>
</dictionary>

View File

@@ -1,19 +1,12 @@
<component name="ProjectDictionaryState">
<dictionary name="dmitriy.dolovov">
<words>
<w>cinterop</w>
<w>commonizable</w>
<w>commonization</w>
<w>commonize</w>
<w>commonized</w>
<w>commonizer</w>
<w>commonizers</w>
<w>commonizes</w>
<w>commonizing</w>
<w>jetbrains</w>
<w>konan</w>
<w>kotlinx</w>
<w>macos</w>
</words>
</dictionary>
</component>

View File

@@ -10,10 +10,7 @@
<w>kapt</w>
<w>kotlinc</w>
<w>mutators</w>
<w>parcelable</w>
<w>parceler</w>
<w>parcelers</w>
<w>parcelize</w>
<w>repl</w>
<w>testdata</w>
<w>uast</w>

BIN
.idea/icon.png generated

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 KiB

After

Width:  |  Height:  |  Size: 1.4 KiB

12
.idea/misc.xml generated
View File

@@ -24,7 +24,7 @@
<option name="myDefaultNotNull" value="org.jetbrains.annotations.NotNull" />
<option name="myNullables">
<value>
<list size="14">
<list size="11">
<item index="0" class="java.lang.String" itemvalue="org.jetbrains.annotations.Nullable" />
<item index="1" class="java.lang.String" itemvalue="javax.annotation.Nullable" />
<item index="2" class="java.lang.String" itemvalue="javax.annotation.CheckForNull" />
@@ -36,15 +36,12 @@
<item index="8" class="java.lang.String" itemvalue="org.checkerframework.checker.nullness.compatqual.NullableType" />
<item index="9" class="java.lang.String" itemvalue="androidx.annotation.RecentlyNullable" />
<item index="10" class="java.lang.String" itemvalue="com.android.annotations.Nullable" />
<item index="11" class="java.lang.String" itemvalue="org.eclipse.jdt.annotation.Nullable" />
<item index="12" class="java.lang.String" itemvalue="io.reactivex.annotations.Nullable" />
<item index="13" class="java.lang.String" itemvalue="io.reactivex.rxjava3.annotations.Nullable" />
</list>
</value>
</option>
<option name="myNotNulls">
<value>
<list size="14">
<list size="11">
<item index="0" class="java.lang.String" itemvalue="org.jetbrains.annotations.NotNull" />
<item index="1" class="java.lang.String" itemvalue="javax.annotation.Nonnull" />
<item index="2" class="java.lang.String" itemvalue="javax.validation.constraints.NotNull" />
@@ -56,9 +53,6 @@
<item index="8" class="java.lang.String" itemvalue="org.checkerframework.checker.nullness.compatqual.NonNullType" />
<item index="9" class="java.lang.String" itemvalue="androidx.annotation.RecentlyNonNull" />
<item index="10" class="java.lang.String" itemvalue="com.android.annotations.NonNull" />
<item index="11" class="java.lang.String" itemvalue="org.eclipse.jdt.annotation.NonNull" />
<item index="12" class="java.lang.String" itemvalue="io.reactivex.annotations.NonNull" />
<item index="13" class="java.lang.String" itemvalue="io.reactivex.rxjava3.annotations.NonNull" />
</list>
</value>
</option>
@@ -66,7 +60,7 @@
<component name="ProjectResources">
<default-html-doctype>http://www.w3.org/1999/xhtml</default-html-doctype>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="false" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
<component name="PsiViewerSettings">

View File

@@ -1,20 +0,0 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Test: KMM" type="GradleRunConfiguration" factoryName="Gradle">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="kmmTest" />
</list>
</option>
<option name="vmOptions" value="" />
</ExternalSystemSettings>
<method v="2" />
</configuration>
</component>

View File

@@ -1,22 +0,0 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Test: stdlib-js public kotlin api test, overwrite results" type="GradleRunConfiguration" factoryName="Gradle">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="--tests &quot;org.jetbrains.kotlin.js.test.ApiTest&quot; -Poverwrite.output=true --parallel" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value=":js:js.tests:cleanTest" />
<option value=":js:js.tests:test" />
</list>
</option>
<option name="vmOptions" value="" />
</ExternalSystemSettings>
<GradleScriptDebugEnabled>false</GradleScriptDebugEnabled>
<method v="2" />
</configuration>
</component>

View File

@@ -1,3 +1,3 @@
<component name="DependencyValidationManager">
<scope name="Apply copyright" pattern="!file[*]:*//testData//*&amp;&amp;!file[*]:testData//*&amp;&amp;!file[*]:*.gradle.kts&amp;&amp;!file[*]:*.gradle&amp;&amp;!file[group:kotlin-ultimate]:*/&amp;&amp;!file[kotlin.libraries]:stdlib/api//*" />
<scope name="Apply copyright" pattern="!file[*]:*//testData//*&amp;&amp;!file[*]:testData//*&amp;&amp;!file[*]:*.gradle.kts&amp;&amp;!file[*]:*.gradle" />
</component>

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,5 @@
[![official project](https://jb.gg/badges/official.svg)](https://confluence.jetbrains.com/display/ALL/JetBrains+on+GitHub)
[![TeamCity (simple build status)](https://img.shields.io/teamcity/http/teamcity.jetbrains.com/s/Kotlin_KotlinPublic_Compiler.svg)](https://teamcity.jetbrains.com/buildConfiguration/Kotlin_KotlinPublic_Compiler?branch=%3Cdefault%3E&buildTypeTab=overview&mode=builds)
[![TeamCity (simple build status)](https://img.shields.io/teamcity/http/teamcity.jetbrains.com/s/Kotlin_dev_Compiler.svg)](https://teamcity.jetbrains.com/viewType.html?buildTypeId=Kotlin_dev_Compiler&branch_Kotlin_dev=%3Cdefault%3E&tab=buildTypeStatusDiv)
[![Maven Central](https://img.shields.io/maven-central/v/org.jetbrains.kotlin/kotlin-maven-plugin.svg)](https://search.maven.org/#search%7Cga%7C1%7Cg%3A%22org.jetbrains.kotlin%22)
[![GitHub license](https://img.shields.io/badge/license-Apache%20License%202.0-blue.svg?style=flat)](https://www.apache.org/licenses/LICENSE-2.0)
@@ -18,16 +18,6 @@ Welcome to [Kotlin](https://kotlinlang.org/)! Some handy links:
* [Public Slack channel](https://slack.kotlinlang.org/)
* [TeamCity CI build](https://teamcity.jetbrains.com/project.html?tab=projectOverview&projectId=Kotlin)
## Kotlin Multiplatform capabilities
Support for multiplatform programming is one of Kotlins key benefits. It reduces time spent writing and maintaining the same code for [different platforms](https://kotlinlang.org/docs/reference/mpp-supported-platforms.html) while retaining the flexibility and benefits of native programming.
* [Kotlin Multiplatform Mobile](https://kotlinlang.org/lp/mobile/) for sharing code between Android and iOS
* [Getting Started with Kotlin Multiplatform Mobile Guide](https://kotlinlang.org/docs/mobile/create-first-app.html)
* [Kotlin Multiplatform Benefits](https://kotlinlang.org/docs/reference/multiplatform.html)
* [Share code on all platforms](https://kotlinlang.org/docs/reference/mpp-share-on-platforms.html#share-code-on-all-platforms)
* [Share code on similar platforms](https://kotlinlang.org/docs/reference/mpp-share-on-platforms.html#share-code-on-similar-platforms)
## Editing Kotlin
* [Kotlin IntelliJ IDEA Plugin](https://kotlinlang.org/docs/tutorials/getting-started.html)
@@ -47,16 +37,11 @@ In order to build Kotlin distribution you need to have:
JDK_18="path to JDK 1.8"
JDK_9="path to JDK 9"
For local development, if you're not working on bytecode generation or the standard library, it's OK to have only JDK 1.8 and JDK 9 installed, and to point `JDK_16` and `JDK_17` environment variables to your JDK 1.8 installation.
For local development, if you're not working on bytecode generation or the standard library, it's OK to have only JDK 1.8 and JDK 9 installed, and to point JDK_16 and JDK_17 environment variables to your JDK 1.8 installation.
You also can use [Gradle properties](https://docs.gradle.org/current/userguide/build_environment.html#sec:gradle_configuration_properties) to setup `JDK_*` variables.
You also can use [Gradle properties](https://docs.gradle.org/current/userguide/build_environment.html#sec:gradle_configuration_properties) to setup JDK_* variables.
Note: The JDK 6 for MacOS is not available on Oracle's site. You can install it by
```bash
$ brew tap caskroom/versions
$ brew cask install java6
```
> Note: The JDK 6 for MacOS is not available on Oracle's site. You can [download it here](https://support.apple.com/kb/DL1572).
On Windows you might need to add long paths setting to the repo:
@@ -96,8 +81,6 @@ command line parameters on the first run:
- `compilerTest` - build and run all compiler tests
- `ideaPluginTest` - build and run all IDEA plugin tests
To reproduce TeamCity build use `-Pteamcity=true` flag. Local builds don't run proguard and have jar compression disabled by default.
**OPTIONAL:** Some artifacts, mainly Maven plugin ones, are built separately with Maven.
Refer to [libraries/ReadMe.md](libraries/ReadMe.md) for details.
@@ -123,22 +106,22 @@ bunch switch 191
Working with the Kotlin project requires at least IntelliJ IDEA 2019.1. You can download IntelliJ IDEA 2019.1 [here](https://www.jetbrains.com/idea/download).
After cloning the project, to import the project in IntelliJ choose the project directory in the Open project dialog. Then, after project opened, select
`File` -> `New` -> `Module from Existing Sources...` in the menu, and select `build.gradle.kts` file in the project's root folder.
After cloning the project, to import the project in Intellij choose the project directory in the Open project dialog. Then, after project opened, Select
`File` -> `New...` -> `Module from Existing Sources` in the menu, and select `build.gradle.kts` file in the project's root folder.
In the import dialog, select `use default gradle wrapper`.
To be able to run tests from IntelliJ easily, check `Delegate IDE build/run actions to Gradle` and choose `Gradle Test Runner` in the Gradle runner settings after importing the project.
At this time, you can use the latest released `1.3.x` version of the Kotlin plugin for working with the code. To make sure you have the latest version installed, use `Tools` -> `Kotlin` -> `Configure Kotlin Plugin Updates`.
At this time, you can use the latest released 1.3.x version of the Kotlin plugin for working with the code. To make sure you have the latest version installed, use Tools | Kotlin | Configure Kotlin Plugin Updates and press "Check for updates now".
### Compiling and running
From this root project there are Run/Debug Configurations for running `IDEA` or the `Generate Compiler Tests` for example; so if you want to try out the latest and greatest IDEA plugin
From this root project there are Run/Debug Configurations for running IDEA or the Compiler Tests for example; so if you want to try out the latest and greatest IDEA plugin
* `VCS` -> `Git` -> `Pull`
* Run the `IDEA` run configuration in the project
* A child IntelliJ IDEA with the Kotlin plugin will then startup
* VCS -> Git -> Pull
* Run the "IDEA" run configuration in the project
* a child IntelliJ IDEA with the Kotlin plugin will then startup
### Including into composite build

View File

@@ -8,8 +8,10 @@ buildscript {
val cacheRedirectorEnabled = findProperty("cacheRedirectorEnabled")?.toString()?.toBoolean() == true
if (cacheRedirectorEnabled) {
maven("https://cache-redirector.jetbrains.com/dl.bintray.com/kotlin/kotlinx")
maven("https://cache-redirector.jetbrains.com/dl.bintray.com/kotlin/kotlin-dev")
} else {
maven("https://dl.bintray.com/kotlin/kotlinx")
maven("https://dl.bintray.com/kotlin/kotlin-dev")
}
}
dependencies {
@@ -28,15 +30,16 @@ repositories {
val cacheRedirectorEnabled = findProperty("cacheRedirectorEnabled")?.toString()?.toBoolean() == true
if (cacheRedirectorEnabled) {
maven("https://cache-redirector.jetbrains.com/dl.bintray.com/kotlin/kotlinx")
} else {
maven("https://cache-redirector.jetbrains.com/dl.bintray.com/kotlin/kotlin-dev")
} else {
maven("https://dl.bintray.com/kotlin/kotlinx")
maven("https://dl.bintray.com/kotlin/kotlin-dev")
}
}
dependencies {
compile(kotlinStdlib())
compile(project(":compiler:frontend"))
compile(projectTests(":compiler:tests-common"))
compile(project(":compiler:cli"))
compile(intellijCoreDep()) { includeJars("intellij-core") }
compile(jpsStandalone()) { includeJars("jps-model") }
@@ -70,7 +73,6 @@ benchmark {
param("size", 1000)
include("CommonCallsBenchmark")
include("ControlFlowAnalysisBenchmark")
//include("InferenceBaselineCallsBenchmark")
}
@@ -93,52 +95,3 @@ benchmark {
register("main")
}
}
tasks.named("classes") {
doLast {
tasks.named("mainBenchmarkJar", Zip::class.java) {
isZip64 = true
archiveName = "benchmarks.jar"
}
listOf("mainBenchmark", "mainFirBenchmark", "mainNiBenchmark").forEach {
tasks.named(it, JavaExec::class.java) {
systemProperty("idea.home.path", intellijRootDir().canonicalPath)
}
}
}
}
tasks.register<JavaExec>("runBenchmark") {
// jmhArgs example: -PjmhArgs='CommonCalls -p size=500 -p isIR=true -p useNI=true -f 1'
val jmhArgs = if (project.hasProperty("jmhArgs")) project.property("jmhArgs").toString() else ""
val resultFilePath = "$buildDir/benchmarks/jmh-result.json"
val ideaHome = intellijRootDir().canonicalPath
val benchmarkJarPath = "$buildDir/benchmarks/main/jars/benchmarks.jar"
args = mutableListOf("-Didea.home.path=$ideaHome", benchmarkJarPath, "-rf", "json", "-rff", resultFilePath) + jmhArgs.split("\\s".toRegex())
main = "-jar"
doLast {
if (project.kotlinBuildProperties.isTeamcityBuild) {
val jsonArray = com.google.gson.JsonParser.parseString(File(resultFilePath).readText()).asJsonArray
jsonArray.forEach {
val benchmark = it.asJsonObject
// remove unnecessary name parts from string like this "org.jetbrains.kotlin.benchmarks.CommonCallsBenchmark.benchmark"
val name = benchmark["benchmark"].asString.removeSuffix(".benchmark").let {
val indexOfLastDot = it.indexOfLast { it == '.' }
it.removeRange(0..indexOfLastDot)
}
val params = benchmark["params"].asJsonObject
val isIR = if (params.has("isIR")) params["isIR"].asString else "false"
val useNI = if (params.has("useNI")) params["useNI"].asString else "false"
val size = params["size"].asString
val score = "%.3f".format(benchmark["primaryMetric"].asJsonObject["score"].asString.toFloat())
val irPostfix = if (isIR.toBoolean()) " isIR=true" else ""
val niPostfix = if (useNI.toBoolean() && !isIR.toBoolean()) " isNI=true" else ""
println("""##teamcity[buildStatisticValue key='$name size=$size${irPostfix}$niPostfix' value='$score']""")
}
}
}
}

View File

@@ -5,6 +5,7 @@
package org.jetbrains.kotlin.benchmarks
import com.intellij.openapi.Disposable
import com.intellij.openapi.extensions.Extensions
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.CharsetToolkit
import com.intellij.psi.PsiElementFinder
@@ -12,6 +13,7 @@ import com.intellij.psi.PsiFileFactory
import com.intellij.psi.impl.PsiFileFactoryImpl
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.testFramework.LightVirtualFile
import org.jetbrains.kotlin.analyzer.ModuleInfo
import org.jetbrains.kotlin.asJava.finder.JavaElementFinder
import org.jetbrains.kotlin.builtins.jvm.JvmBuiltIns
import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys
@@ -24,15 +26,21 @@ import org.jetbrains.kotlin.context.withModule
import org.jetbrains.kotlin.context.withProject
import org.jetbrains.kotlin.descriptors.impl.ModuleDescriptorImpl
import org.jetbrains.kotlin.diagnostics.Severity
import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.builder.RawFirBuilder
import org.jetbrains.kotlin.fir.createSession
import org.jetbrains.kotlin.fir.java.FirJavaElementFinder
import org.jetbrains.kotlin.fir.java.FirJavaModuleBasedSession
import org.jetbrains.kotlin.fir.java.FirLibrarySession
import org.jetbrains.kotlin.fir.java.FirProjectSessionProvider
import org.jetbrains.kotlin.fir.resolve.firProvider
import org.jetbrains.kotlin.fir.resolve.providers.impl.FirProviderImpl
import org.jetbrains.kotlin.fir.resolve.transformers.FirTotalResolveProcessor
import org.jetbrains.kotlin.fir.resolve.impl.FirProviderImpl
import org.jetbrains.kotlin.fir.resolve.transformers.FirTotalResolveTransformer
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.PlatformDependentAnalyzerServices
import org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatformAnalyzerServices
import org.jetbrains.kotlin.storage.ExceptionTracker
import org.jetbrains.kotlin.storage.LockBasedStorageManager
import org.jetbrains.kotlin.storage.StorageManager
@@ -58,10 +66,10 @@ private val JDK_PATH = File("${System.getProperty("java.home")!!}/lib/rt.jar")
private val RUNTIME_JAR = File(System.getProperty("kotlin.runtime.path") ?: "dist/kotlinc/lib/kotlin-runtime.jar")
private val LANGUAGE_FEATURE_SETTINGS =
LanguageVersionSettingsImpl(
LanguageVersion.KOTLIN_1_3, ApiVersion.KOTLIN_1_3,
specificFeatures = mapOf(LanguageFeature.NewInference to LanguageFeature.State.ENABLED)
)
LanguageVersionSettingsImpl(
LanguageVersion.KOTLIN_1_3, ApiVersion.KOTLIN_1_3,
specificFeatures = mapOf(LanguageFeature.NewInference to LanguageFeature.State.ENABLED)
)
private fun newConfiguration(useNewInference: Boolean): CompilerConfiguration {
val configuration = CompilerConfiguration()
@@ -73,10 +81,10 @@ private fun newConfiguration(useNewInference: Boolean): CompilerConfiguration {
val newInferenceState = if (useNewInference) LanguageFeature.State.ENABLED else LanguageFeature.State.DISABLED
configuration.languageVersionSettings = LanguageVersionSettingsImpl(
LanguageVersion.KOTLIN_1_3, ApiVersion.KOTLIN_1_3,
specificFeatures = mapOf(
LanguageFeature.NewInference to newInferenceState
)
LanguageVersion.KOTLIN_1_3, ApiVersion.KOTLIN_1_3,
specificFeatures = mapOf(
LanguageFeature.NewInference to newInferenceState
)
)
return configuration
}
@@ -97,19 +105,21 @@ abstract class AbstractSimpleFileBenchmark {
fun setUp() {
if (isIR && !useNewInference) error("Invalid configuration")
env = KotlinCoreEnvironment.createForTests(
myDisposable,
newConfiguration(useNewInference),
EnvironmentConfigFiles.JVM_CONFIG_FILES
myDisposable,
newConfiguration(useNewInference),
EnvironmentConfigFiles.JVM_CONFIG_FILES
)
if (isIR) {
PsiElementFinder.EP.getPoint(env.project).unregisterExtension(JavaElementFinder::class.java)
Extensions.getArea(env.project)
.getExtensionPoint(PsiElementFinder.EP_NAME)
.unregisterExtension(JavaElementFinder::class.java)
}
file = createFile(
"test.kt",
buildText(),
env.project
"test.kt",
buildText(),
env.project
)
}
@@ -124,22 +134,22 @@ abstract class AbstractSimpleFileBenchmark {
private fun analyzeGreenFileFrontend(bh: Blackhole) {
val tracker = ExceptionTracker()
val storageManager: StorageManager =
LockBasedStorageManager.createWithExceptionHandling("benchmarks", tracker)
LockBasedStorageManager.createWithExceptionHandling("benchmarks", tracker)
val context = SimpleGlobalContext(storageManager, tracker)
val module =
ModuleDescriptorImpl(
Name.special("<benchmark>"), storageManager,
JvmBuiltIns(storageManager, JvmBuiltIns.Kind.FROM_DEPENDENCIES)
)
ModuleDescriptorImpl(
Name.special("<benchmark>"), storageManager,
JvmBuiltIns(storageManager, JvmBuiltIns.Kind.FROM_DEPENDENCIES)
)
val moduleContext = context.withProject(env.project).withModule(module)
val result = TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration(
moduleContext.project,
listOf(file),
NoScopeRecordCliBindingTrace(),
env.configuration,
{ scope -> JvmPackagePartProvider(LANGUAGE_FEATURE_SETTINGS, scope) }
moduleContext.project,
listOf(file),
NoScopeRecordCliBindingTrace(),
env.configuration,
{ scope -> JvmPackagePartProvider(LANGUAGE_FEATURE_SETTINGS, scope) }
)
assert(result.bindingContext.diagnostics.none { it.severity == Severity.ERROR })
@@ -149,21 +159,56 @@ abstract class AbstractSimpleFileBenchmark {
private fun analyzeGreenFileIr(bh: Blackhole) {
val scope = GlobalSearchScope.filesScope(env.project, listOf(file.virtualFile))
.uniteWith(TopDownAnalyzerFacadeForJVM.AllJavaSourcesInProjectScope(env.project))
.uniteWith(TopDownAnalyzerFacadeForJVM.AllJavaSourcesInProjectScope(env.project))
val session = createSession(env, scope)
val firProvider = session.firProvider as FirProviderImpl
val builder = RawFirBuilder(session, firProvider.kotlinScopeProvider, stubMode = false)
val totalTransformer = FirTotalResolveProcessor(session)
val totalTransformer = FirTotalResolveTransformer()
val firFile = builder.buildFirFile(file).also(firProvider::recordFile)
totalTransformer.process(listOf(firFile))
for (transformer in totalTransformer.transformers) {
transformer.transformFile(firFile, null)
}
bh.consume(firFile.hashCode())
env.project.extensionArea
.getExtensionPoint<PsiElementFinder>(PsiElementFinder.EP.name)
.unregisterExtension(FirJavaElementFinder::class.java)
}
protected abstract fun buildText(): String
}
fun createSession(
environment: KotlinCoreEnvironment,
sourceScope: GlobalSearchScope,
librariesScope: GlobalSearchScope = GlobalSearchScope.notScope(sourceScope)
): FirSession {
val moduleInfo = FirTestModuleInfo()
val project = environment.project
val provider = FirProjectSessionProvider(project)
return FirJavaModuleBasedSession(moduleInfo, provider, sourceScope).also {
createSessionForDependencies(provider, moduleInfo, librariesScope, environment)
}
}
private fun createSessionForDependencies(
provider: FirProjectSessionProvider,
moduleInfo: FirTestModuleInfo,
librariesScope: GlobalSearchScope,
environment: KotlinCoreEnvironment
) {
val dependenciesInfo = FirTestModuleInfo()
moduleInfo.dependencies.add(dependenciesInfo)
FirLibrarySession.create(
dependenciesInfo, provider, librariesScope, environment.project,
environment.createPackagePartProvider(librariesScope)
)
}
class FirTestModuleInfo(
override val name: Name = Name.identifier("TestModule"),
val dependencies: MutableList<ModuleInfo> = mutableListOf(),
override val platform: TargetPlatform = JvmPlatforms.unspecifiedJvmPlatform,
override val analyzerServices: PlatformDependentAnalyzerServices = JvmPlatformAnalyzerServices
) : ModuleInfo {
override fun dependencies(): List<ModuleInfo> = dependencies
}

View File

@@ -1,35 +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.benchmarks
import org.openjdk.jmh.annotations.*
import org.openjdk.jmh.infra.Blackhole
import java.util.concurrent.TimeUnit
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Benchmark)
open class ControlFlowAnalysisBenchmark : AbstractSimpleFileBenchmark() {
@Param("1000")
private var size: Int = 0
@Benchmark
fun benchmark(bh: Blackhole) {
analyzeGreenFile(bh)
}
override fun buildText() =
buildString {
appendLine("fun test() {")
for (i in 0 until size) {
appendLine("for (i$i in 0..10) { ")
}
for (i in 0 until size) {
appendLine("}")
}
appendLine("}")
}
}

View File

@@ -23,28 +23,28 @@ open class ManyImplicitReceiversBenchmark : AbstractSimpleFileBenchmark() {
override fun buildText(): String {
return buildString {
appendLine("inline fun <T, R> with(receiver: T, block: T.() -> R): R = block()")
appendln("inline fun <T, R> with(receiver: T, block: T.() -> R): R = block()")
for (i in 1..size) {
appendLine("interface A$i {")
appendLine(" fun foo$i()")
appendLine("}")
appendLine()
appendln("interface A$i {")
appendln(" fun foo$i()")
appendln("}")
appendln()
}
appendLine()
appendln()
append("fun test(")
append((1..size).joinToString(", ") { "a$it: A$it" })
appendLine(" {")
appendln(" {")
for (i in 1..size) {
appendLine("with(a$i) {")
appendln("with(a$i) {")
}
for (i in 1..size) {
appendLine("foo$i()")
appendln("foo$i()")
}
for (i in 1..size) {
appendLine("}")
appendln("}")
}
appendLine("}")
appendln("}")
}
}
}

View File

@@ -1,49 +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.benchmarks
import org.openjdk.jmh.annotations.*
import org.openjdk.jmh.infra.Blackhole
import java.util.concurrent.TimeUnit
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Benchmark)
open class PlusAssignOperatorDesugaringBenchmark : AbstractInferenceBenchmark() {
@Param("9", "10", "11", "12", "13", "14")
private var size: Int = 0
@Benchmark
fun benchmark(bh: Blackhole) {
analyzeGreenFile(bh)
}
override fun buildText(): String = buildString {
appendLine(
"""
class A {
operator fun <T : Number> plus(other: (Int) -> T): A = this
operator fun <T : CharSequence> plusAssign(other: (String) -> T) {}
}
""".trimIndent()
)
appendLine("fun test() {")
appendLine("var a = A()")
for (i in 1..size) {
appendLine("a += {")
}
for (i in 1..size) {
appendLine(
"""
it.inc()
1
}
""".trimIndent()
)
}
appendLine()
}
}

View File

@@ -7,7 +7,6 @@ plugins {
dependencies {
compileOnly(project(":core:util.runtime"))
compileOnly(project(":compiler:backend.common.jvm"))
compileOnly(project(":compiler:util"))
compileOnly(project(":compiler:cli-common"))
compileOnly(project(":compiler:frontend.java"))

View File

@@ -16,7 +16,7 @@
package org.jetbrains.kotlin.compilerRunner
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSourceLocation
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.cli.common.messages.OutputMessageUtil
@@ -25,7 +25,7 @@ class MessageCollectorToOutputItemsCollectorAdapter(
private val delegate: MessageCollector,
private val outputCollector: OutputItemsCollector
) : MessageCollector by delegate {
override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageSourceLocation?) {
override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageLocation?) {
// TODO: consider adding some other way of passing input -> output mapping from compiler, e.g. dedicated service
OutputMessageUtil.parseOutputMessage(message)?.let {
outputCollector.add(it.sourceFiles, it.outputFile)

View File

@@ -75,7 +75,7 @@ open class IncrementalJsCache(
override fun markDirty(removedAndCompiledSources: Collection<File>) {
removedAndCompiledSources.forEach { sourceFile ->
// The common prefix of all FQN parents has to be the file package
sourceToClassesMap[sourceFile].map { it.parentOrNull()?.asString() ?: "" }.minByOrNull { it.length }?.let {
sourceToClassesMap[sourceFile].map { it.parentOrNull()?.asString() ?: "" }.minBy { it.length }?.let {
packageMetadata.remove(it)
}
}

View File

@@ -33,7 +33,6 @@ import org.jetbrains.kotlin.metadata.jvm.deserialization.JvmProtoBufUtil
import org.jetbrains.kotlin.metadata.jvm.deserialization.ModuleMapping
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.resolve.jvm.AsmTypes
import org.jetbrains.kotlin.resolve.jvm.JvmClassName
import org.jetbrains.org.objectweb.asm.*
import java.io.File
@@ -168,8 +167,6 @@ open class IncrementalJvmCache(
constantsMap.process(kotlinClass, changesCollector)
inlineFunctionsMap.process(kotlinClass, changesCollector)
}
KotlinClassHeader.Kind.UNKNOWN, KotlinClassHeader.Kind.SYNTHETIC_CLASS -> {
}
}
}
@@ -479,21 +476,8 @@ open class IncrementalJvmCache(
if (inlineFunctions.isEmpty()) return emptyMap()
val result = HashMap<String, Long>()
var dummyVersion: Int = -1
ClassReader(bytes).accept(object : ClassVisitor(Opcodes.API_VERSION) {
override fun visit(
version: Int,
access: Int,
name: String?,
signature: String?,
superName: String?,
interfaces: Array<out String>?
) {
super.visit(version, access, name, signature, superName, interfaces)
dummyVersion = version
}
override fun visitMethod(
access: Int,
name: String,
@@ -501,8 +485,7 @@ open class IncrementalJvmCache(
signature: String?,
exceptions: Array<out String>?
): MethodVisitor? {
val dummyClassWriter = ClassWriter(0)
dummyClassWriter.visit(dummyVersion, 0, "dummy", null, AsmTypes.OBJECT_TYPE.internalName, null)
val dummyClassWriter = ClassWriter(Opcodes.API_VERSION)
return object : MethodVisitor(Opcodes.API_VERSION, dummyClassWriter.visitMethod(0, name, desc, null, exceptions)) {
override fun visitEnd() {
@@ -510,7 +493,6 @@ open class IncrementalJvmCache(
if (jvmName !in inlineFunctions) return
val dummyBytes = dummyClassWriter.toByteArray()!!
val hash = dummyBytes.md5()
result[jvmName] = hash
}

View File

@@ -17,7 +17,7 @@
package org.jetbrains.kotlin.incremental
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.load.java.JavaDescriptorVisibilities
import org.jetbrains.kotlin.load.java.JavaVisibilities
import org.jetbrains.kotlin.metadata.ProtoBuf
import org.jetbrains.kotlin.metadata.deserialization.BinaryVersion
import org.jetbrains.kotlin.metadata.java.JavaClassProtoBuf
@@ -41,7 +41,7 @@ class JavaClassesSerializerExtension : KotlinSerializerExtensionBase(BuiltInSeri
childSerializer: DescriptorSerializer
) {
super.serializeClass(descriptor, proto, versionRequirementTable, childSerializer)
if (descriptor.visibility == JavaDescriptorVisibilities.PACKAGE_VISIBILITY) {
if (descriptor.visibility == JavaVisibilities.PACKAGE_VISIBILITY) {
proto.setExtension(JavaClassProtoBuf.isPackagePrivateClass, true)
}
}
@@ -50,7 +50,7 @@ class JavaClassesSerializerExtension : KotlinSerializerExtensionBase(BuiltInSeri
proto: ProtoBuf.Constructor.Builder,
childSerializer: DescriptorSerializer) {
super.serializeConstructor(descriptor, proto, childSerializer)
if (descriptor.visibility == JavaDescriptorVisibilities.PACKAGE_VISIBILITY) {
if (descriptor.visibility == JavaVisibilities.PACKAGE_VISIBILITY) {
proto.setExtension(JavaClassProtoBuf.isPackagePrivateConstructor, true)
}
}
@@ -62,7 +62,7 @@ class JavaClassesSerializerExtension : KotlinSerializerExtensionBase(BuiltInSeri
childSerializer: DescriptorSerializer
) {
super.serializeFunction(descriptor, proto, versionRequirementTable, childSerializer)
if (descriptor.visibility == JavaDescriptorVisibilities.PACKAGE_VISIBILITY) {
if (descriptor.visibility == JavaVisibilities.PACKAGE_VISIBILITY) {
proto.setExtension(JavaClassProtoBuf.isPackagePrivateMethod, true)
}
@@ -78,7 +78,7 @@ class JavaClassesSerializerExtension : KotlinSerializerExtensionBase(BuiltInSeri
childSerializer: DescriptorSerializer
) {
super.serializeProperty(descriptor, proto, versionRequirementTable, childSerializer)
if (descriptor.visibility == JavaDescriptorVisibilities.PACKAGE_VISIBILITY) {
if (descriptor.visibility == JavaVisibilities.PACKAGE_VISIBILITY) {
proto.setExtension(JavaClassProtoBuf.isPackagePrivateField, true)
}

View File

@@ -1,6 +1,17 @@
/*
* 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.
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.incremental

View File

@@ -23,12 +23,12 @@ import org.jetbrains.kotlin.resolve.jvm.JvmClassName
import java.io.File
class LocalFileKotlinClass private constructor(
private val file: File,
private val fileContents: ByteArray,
className: ClassId,
classVersion: Int,
classHeader: KotlinClassHeader,
innerClasses: InnerClassesInfo
private val file: File,
private val fileContents: ByteArray,
className: ClassId,
classVersion: Int,
classHeader: KotlinClassHeader,
innerClasses: InnerClassesInfo
) : FileBasedKotlinClass(className, classVersion, classHeader, innerClasses) {
companion object {

View File

@@ -80,7 +80,7 @@ open class LookupStorage(
for (lookupSymbol in lookups.keySet().sorted()) {
val key = LookupSymbolKey(lookupSymbol.name, lookupSymbol.scope)
val paths = lookups[lookupSymbol]
val paths = lookups[lookupSymbol]!!
val fileIds = paths.mapTo(TreeSet()) { pathToId[it]!! }
fileIds.addAll(lookupMap[key] ?: emptySet())
lookupMap[key] = fileIds

View File

@@ -14,8 +14,6 @@
* limitations under the License.
*/
@file:Suppress("UNUSED_PARAMETER")
package org.jetbrains.kotlin.incremental
import org.jetbrains.kotlin.library.metadata.KlibMetadataProtoBuf
@@ -208,11 +206,6 @@ open class ProtoCompareGenerated(
if (!checkStringEquals(old.getExtension(JvmProtoBuf.anonymousObjectOriginName), new.getExtension(JvmProtoBuf.anonymousObjectOriginName))) return false
}
if (old.hasExtension(JvmProtoBuf.jvmClassFlags) != new.hasExtension(JvmProtoBuf.jvmClassFlags)) return false
if (old.hasExtension(JvmProtoBuf.jvmClassFlags)) {
if (old.getExtension(JvmProtoBuf.jvmClassFlags) != new.getExtension(JvmProtoBuf.jvmClassFlags)) return false
}
if (old.getExtensionCount(JsProtoBuf.classAnnotation) != new.getExtensionCount(JsProtoBuf.classAnnotation)) {
return false
}
@@ -271,7 +264,6 @@ open class ProtoCompareGenerated(
JVM_EXT_CLASS_MODULE_NAME,
JVM_EXT_CLASS_LOCAL_VARIABLE_LIST,
JVM_EXT_ANONYMOUS_OBJECT_ORIGIN_NAME,
JVM_EXT_JVM_CLASS_FLAGS,
JS_EXT_CLASS_ANNOTATION_LIST,
JS_EXT_CLASS_CONTAINING_FILE_ID,
JAVA_EXT_IS_PACKAGE_PRIVATE_CLASS,
@@ -340,11 +332,6 @@ open class ProtoCompareGenerated(
if (!checkStringEquals(old.getExtension(JvmProtoBuf.anonymousObjectOriginName), new.getExtension(JvmProtoBuf.anonymousObjectOriginName))) result.add(ProtoBufClassKind.JVM_EXT_ANONYMOUS_OBJECT_ORIGIN_NAME)
}
if (old.hasExtension(JvmProtoBuf.jvmClassFlags) != new.hasExtension(JvmProtoBuf.jvmClassFlags)) result.add(ProtoBufClassKind.JVM_EXT_JVM_CLASS_FLAGS)
if (old.hasExtension(JvmProtoBuf.jvmClassFlags)) {
if (old.getExtension(JvmProtoBuf.jvmClassFlags) != new.getExtension(JvmProtoBuf.jvmClassFlags)) result.add(ProtoBufClassKind.JVM_EXT_JVM_CLASS_FLAGS)
}
if (old.getExtensionCount(JsProtoBuf.classAnnotation) != new.getExtensionCount(JsProtoBuf.classAnnotation)) {
result.add(ProtoBufClassKind.JS_EXT_CLASS_ANNOTATION_LIST)
}
@@ -1748,10 +1735,6 @@ fun ProtoBuf.Class.hashCode(stringIndexes: (Int) -> Int, fqNameIndexes: (Int) ->
hashCode = 31 * hashCode + stringIndexes(getExtension(JvmProtoBuf.anonymousObjectOriginName))
}
if (hasExtension(JvmProtoBuf.jvmClassFlags)) {
hashCode = 31 * hashCode + getExtension(JvmProtoBuf.jvmClassFlags)
}
for(i in 0..getExtensionCount(JsProtoBuf.classAnnotation) - 1) {
hashCode = 31 * hashCode + getExtension(JsProtoBuf.classAnnotation, i).hashCode(stringIndexes, fqNameIndexes, typeById)
}

View File

@@ -33,37 +33,36 @@ import org.jetbrains.kotlin.utils.addToStdlib.flattenTo
import java.io.File
import java.util.*
import kotlin.collections.HashSet
import kotlin.collections.LinkedHashSet
const val DELETE_MODULE_FILE_PROPERTY = "kotlin.delete.module.file.after.build"
fun makeModuleFile(
name: String,
isTest: Boolean,
outputDir: File,
sourcesToCompile: Iterable<File>,
commonSources: Iterable<File>,
javaSourceRoots: Iterable<JvmSourceRoot>,
classpath: Iterable<File>,
friendDirs: Iterable<File>
name: String,
isTest: Boolean,
outputDir: File,
sourcesToCompile: Iterable<File>,
commonSources: Iterable<File>,
javaSourceRoots: Iterable<JvmSourceRoot>,
classpath: Iterable<File>,
friendDirs: Iterable<File>
): File {
val builder = KotlinModuleXmlBuilder()
builder.addModule(
name,
outputDir.absolutePath,
// important to transform file to absolute paths,
// otherwise compiler will use module file's parent as base path (a temporary file; see below)
// (see org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.getAbsolutePaths)
sourcesToCompile.map { it.absoluteFile },
javaSourceRoots,
classpath,
commonSources.map { it.absoluteFile },
null,
"java-production",
isTest,
// this excludes the output directories from the class path, to be removed for true incremental compilation
setOf(outputDir),
friendDirs
name,
outputDir.absolutePath,
// important to transform file to absolute paths,
// otherwise compiler will use module file's parent as base path (a temporary file; see below)
// (see org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.getAbsolutePaths)
sourcesToCompile.map { it.absoluteFile },
javaSourceRoots,
classpath,
commonSources.map { it.absoluteFile },
null,
"java-production",
isTest,
// this excludes the output directories from the class path, to be removed for true incremental compilation
setOf(outputDir),
friendDirs
)
val scriptFile = File.createTempFile("kjps", sanitizeJavaIdentifier(name) + ".script.xml")
@@ -84,9 +83,9 @@ private fun sanitizeJavaIdentifier(string: String) =
}
fun makeCompileServices(
incrementalCaches: Map<TargetId, IncrementalCache>,
lookupTracker: LookupTracker,
compilationCanceledStatus: CompilationCanceledStatus?
incrementalCaches: Map<TargetId, IncrementalCache>,
lookupTracker: LookupTracker,
compilationCanceledStatus: CompilationCanceledStatus?
): Services =
with(Services.Builder()) {
register(LookupTracker::class.java, lookupTracker)
@@ -106,14 +105,12 @@ fun updateIncrementalCache(
for (generatedFile in generatedFiles) {
when {
generatedFile is GeneratedJvmClass -> cache.saveFileToCache(generatedFile, changesCollector)
generatedFile.outputFile.isModuleMappingFile() -> cache.saveModuleMappingToCache(
generatedFile.sourceFiles,
generatedFile.outputFile
)
generatedFile.outputFile.isModuleMappingFile() -> cache.saveModuleMappingToCache(generatedFile.sourceFiles, generatedFile.outputFile)
}
}
javaChangesTracker?.javaClassesUpdates?.forEach { (source, serializedJavaClass) ->
javaChangesTracker?.javaClassesUpdates?.forEach {
(source, serializedJavaClass) ->
cache.saveJavaClassProto(source, serializedJavaClass, changesCollector)
}
@@ -121,9 +118,9 @@ fun updateIncrementalCache(
}
fun LookupStorage.update(
lookupTracker: LookupTracker,
filesToCompile: Iterable<File>,
removedFiles: Iterable<File>
lookupTracker: LookupTracker,
filesToCompile: Iterable<File>,
removedFiles: Iterable<File>
) {
if (lookupTracker !is LookupTrackerImpl) throw AssertionError("Lookup tracker is expected to be LookupTrackerImpl, got ${lookupTracker::class.java}")
@@ -133,8 +130,8 @@ fun LookupStorage.update(
}
data class DirtyData(
val dirtyLookupSymbols: Collection<LookupSymbol> = emptyList(),
val dirtyClassesFqNames: Collection<FqName> = emptyList()
val dirtyLookupSymbols: Collection<LookupSymbol> = emptyList(),
val dirtyClassesFqNames: Collection<FqName> = emptyList()
)
fun ChangesCollector.getDirtyData(
@@ -216,21 +213,19 @@ fun mapClassesFqNamesToFiles(
}
fun withSubtypes(
typeFqName: FqName,
caches: Iterable<IncrementalCacheCommon>
typeFqName: FqName,
caches: Iterable<IncrementalCacheCommon>
): Set<FqName> {
val types = LinkedHashSet(listOf(typeFqName))
val types = LinkedList(listOf(typeFqName))
val subtypes = hashSetOf<FqName>()
while (types.isNotEmpty()) {
val iterator = types.iterator()
val unprocessedType = iterator.next()
iterator.remove()
val unprocessedType = types.pollFirst()
caches.asSequence()
.flatMap { it.getSubtypesOf(unprocessedType) }
.filter { it !in subtypes }
.forEach { types.add(it) }
.flatMap { it.getSubtypesOf(unprocessedType) }
.filter { it !in subtypes }
.forEach { types.addLast(it) }
subtypes.add(unprocessedType)
}

View File

@@ -16,7 +16,7 @@
package org.jetbrains.kotlin.incremental
import org.jetbrains.kotlin.descriptors.DescriptorVisibilities
import org.jetbrains.kotlin.descriptors.Visibilities
import org.jetbrains.kotlin.incremental.ProtoCompareGenerated.ProtoBufClassKind
import org.jetbrains.kotlin.incremental.ProtoCompareGenerated.ProtoBufPackageKind
import org.jetbrains.kotlin.incremental.storage.ProtoMapValue
@@ -27,7 +27,6 @@ import org.jetbrains.kotlin.metadata.jvm.deserialization.JvmProtoBufUtil
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.protobuf.MessageLite
import org.jetbrains.kotlin.serialization.deserialization.ProtoEnumFlags
import org.jetbrains.kotlin.serialization.deserialization.descriptorVisibility
import java.util.*
data class Difference(
@@ -50,8 +49,8 @@ fun ProtoMapValue.toProtoData(packageFqName: FqName): ProtoData =
}
internal val MessageLite.isPrivate: Boolean
get() = DescriptorVisibilities.isPrivate(
ProtoEnumFlags.descriptorVisibility(
get() = Visibilities.isPrivate(
ProtoEnumFlags.visibility(
when (this) {
is ProtoBuf.Constructor -> Flags.VISIBILITY.get(flags)
is ProtoBuf.Function -> Flags.VISIBILITY.get(flags)
@@ -274,10 +273,6 @@ class DifferenceCalculatorForClass(
isClassAffected = true
areSubclassesAffected = true
}
ProtoBufClassKind.JVM_EXT_JVM_CLASS_FLAGS -> {
isClassAffected = true
areSubclassesAffected = true
}
}
}
@@ -347,4 +342,4 @@ val ProtoBuf.Class.typeTableOrNull: ProtoBuf.TypeTable?
get() = if (hasTypeTable()) typeTable else null
val ProtoBuf.Package.typeTableOrNull: ProtoBuf.TypeTable?
get() = if (hasTypeTable()) typeTable else null
get() = if (hasTypeTable()) typeTable else null

View File

@@ -0,0 +1,81 @@
/*
* 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.EnumeratorStringDescriptor
import com.intellij.util.io.KeyDescriptor
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.utils.Printer
import java.io.File
abstract class BasicMap<K : Comparable<K>, V>(
internal val storageFile: File,
keyDescriptor: KeyDescriptor<K>,
valueExternalizer: DataExternalizer<V>
) {
protected val storage = LazyStorage(storageFile, keyDescriptor, valueExternalizer)
fun clean() {
storage.clean()
}
fun flush(memoryCachesOnly: Boolean) {
storage.flush(memoryCachesOnly)
}
fun close() {
storage.close()
}
@TestOnly
fun dump(): String {
return with(StringBuilder()) {
with(Printer(this)) {
println(this@BasicMap::class.java.simpleName)
pushIndent()
for (key in storage.keys.sorted()) {
println("${dumpKey(key)} -> ${dumpValue(storage[key]!!)}")
}
popIndent()
}
this
}.toString()
}
@TestOnly
protected abstract fun dumpKey(key: K): String
@TestOnly
protected abstract fun dumpValue(value: V): String
}
abstract class BasicStringMap<V>(
storageFile: File,
keyDescriptor: KeyDescriptor<String>,
valueExternalizer: DataExternalizer<V>
) : BasicMap<String, V>(storageFile, keyDescriptor, valueExternalizer) {
constructor(
storageFile: File,
valueExternalizer: DataExternalizer<V>
) : this(storageFile, EnumeratorStringDescriptor.INSTANCE, valueExternalizer)
override fun dumpKey(key: String): String = key
}

View File

@@ -0,0 +1,55 @@
/*
* 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 org.jetbrains.kotlin.incremental.dumpCollection
import org.jetbrains.kotlin.name.FqName
import java.io.File
internal open class ClassOneToManyMap(
storageFile: File
) : BasicStringMap<Collection<String>>(storageFile, StringCollectionExternalizer) {
override fun dumpValue(value: Collection<String>): String = value.dumpCollection()
fun add(key: FqName, value: FqName) {
storage.append(key.asString(), value.asString())
}
operator fun get(key: FqName): Collection<FqName> =
storage[key.asString()]?.map(::FqName) ?: setOf()
operator fun set(key: FqName, values: Collection<FqName>) {
if (values.isEmpty()) {
remove(key)
return
}
storage[key.asString()] = values.map(FqName::asString)
}
fun remove(key: FqName) {
storage.remove(key.asString())
}
fun removeValues(key: FqName, removed: Set<FqName>) {
val notRemoved = this[key].filter { it !in removed }
this[key] = notRemoved
}
}
internal class SubtypesMap(storageFile: File) : ClassOneToManyMap(storageFile)
internal class SupertypesMap(storageFile: File) : ClassOneToManyMap(storageFile)

View File

@@ -0,0 +1,122 @@
/*
* 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.IOUtil
import com.intellij.util.io.KeyDescriptor
import com.intellij.util.io.PersistentHashMap
import java.io.DataOutput
import java.io.File
import java.io.IOException
/**
* It's lazy in a sense that PersistentHashMap is created only on write
*/
class LazyStorage<K, V>(
private val storageFile: File,
private val keyDescriptor: KeyDescriptor<K>,
private val valueExternalizer: DataExternalizer<V>
) {
@Volatile
private var storage: PersistentHashMap<K, V>? = null
@Synchronized
private fun getStorageIfExists(): PersistentHashMap<K, V>? {
if (storage != null) return storage
if (storageFile.exists()) {
storage = createMap()
return storage
}
return null
}
@Synchronized
private fun getStorageOrCreateNew(): PersistentHashMap<K, V> {
if (storage == null) {
storage = createMap()
}
return storage!!
}
val keys: Collection<K>
get() = getStorageIfExists()?.allKeysWithExistingMapping ?: listOf()
operator fun contains(key: K): Boolean =
getStorageIfExists()?.containsMapping(key) ?: false
operator fun get(key: K): V? =
getStorageIfExists()?.get(key)
operator fun set(key: K, value: V) {
getStorageOrCreateNew().put(key, value)
}
fun remove(key: K) {
getStorageIfExists()?.remove(key)
}
fun append(key: K, value: String) {
append(key) { out -> IOUtil.writeUTF(out, value) }
}
fun append(key: K, value: Int) {
append(key) { out -> out.writeInt(value) }
}
@Synchronized
fun clean() {
try {
storage?.close()
}
catch (ignored: Throwable) {
}
PersistentHashMap.deleteFilesStartingWith(storageFile)
storage = null
}
@Synchronized
fun flush(memoryCachesOnly: Boolean) {
val existingStorage = storage ?: return
if (memoryCachesOnly) {
if (existingStorage.isDirty) {
existingStorage.dropMemoryCaches()
}
}
else {
existingStorage.force()
}
}
@Synchronized
fun close() {
storage?.close()
}
private fun createMap(): PersistentHashMap<K, V> =
PersistentHashMap(storageFile, keyDescriptor, valueExternalizer)
private fun append(key: K, append: (DataOutput)->Unit) {
getStorageOrCreateNew().appendData(key, append)
}
}

View File

@@ -0,0 +1,42 @@
/*
* 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 java.io.File
internal class LookupMap(storage: File) : BasicMap<LookupSymbolKey, Collection<Int>>(storage, LookupSymbolKeyDescriptor, IntCollectionExternalizer) {
override fun dumpKey(key: LookupSymbolKey): String = key.toString()
override fun dumpValue(value: Collection<Int>): String = value.toString()
fun add(name: String, scope: String, fileId: Int) {
storage.append(LookupSymbolKey(name, scope), fileId)
}
operator fun get(key: LookupSymbolKey): Collection<Int>? = storage[key]
operator fun set(key: LookupSymbolKey, fileIds: Set<Int>) {
storage[key] = fileIds
}
fun remove(key: LookupSymbolKey) {
storage.remove(key)
}
val keys: Collection<LookupSymbolKey>
get() = storage.keys
}

View File

@@ -18,7 +18,7 @@ package org.jetbrains.kotlin.incremental.storage
import com.intellij.util.io.DataExternalizer
import com.intellij.util.io.KeyDescriptor
import com.intellij.util.io.PersistentHashMap
import com.intellij.util.io.JpsPersistentHashMap
import java.io.File
@@ -28,10 +28,10 @@ class NonCachingLazyStorage<K, V>(
private val valueExternalizer: DataExternalizer<V>
) : LazyStorage<K, V> {
@Volatile
private var storage: PersistentHashMap<K, V>? = null
private var storage: JpsPersistentHashMap<K, V>? = null
@Synchronized
private fun getStorageIfExists(): PersistentHashMap<K, V>? {
private fun getStorageIfExists(): JpsPersistentHashMap<K, V>? {
if (storage != null) return storage
if (storageFile.exists()) {
@@ -43,7 +43,7 @@ class NonCachingLazyStorage<K, V>(
}
@Synchronized
private fun getStorageOrCreateNew(): PersistentHashMap<K, V> {
private fun getStorageOrCreateNew(): JpsPersistentHashMap<K, V> {
if (storage == null) {
storage = createMap()
}
@@ -69,7 +69,7 @@ class NonCachingLazyStorage<K, V>(
}
override fun append(key: K, value: V) {
getStorageOrCreateNew().appendData(key) { dataOutput -> valueExternalizer.save(dataOutput, value) }
getStorageOrCreateNew().appendDataWithoutCache(key, value)
}
@Synchronized
@@ -79,7 +79,7 @@ class NonCachingLazyStorage<K, V>(
} catch (ignored: Throwable) {
}
PersistentHashMap.deleteFilesStartingWith(storageFile)
JpsPersistentHashMap.deleteFilesStartingWith(storageFile)
storage = null
}
@@ -101,6 +101,6 @@ class NonCachingLazyStorage<K, V>(
storage?.close()
}
private fun createMap(): PersistentHashMap<K, V> =
PersistentHashMap(storageFile, keyDescriptor, valueExternalizer)
private fun createMap(): JpsPersistentHashMap<K, V> =
JpsPersistentHashMap(storageFile, keyDescriptor, valueExternalizer)
}

View File

@@ -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)
}

View File

@@ -0,0 +1,106 @@
/*
* 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.PersistentHashMap
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: PersistentHashMap<K, V>? = null
@Synchronized
private fun getStorageIfExists(): PersistentHashMap<K, V>? {
if (storage != null) return storage
if (storageFile.exists()) {
storage = createMap()
return storage
}
return null
}
@Synchronized
private fun getStorageOrCreateNew(): PersistentHashMap<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().appendData(key) { dataOutput -> valueExternalizer.save(dataOutput, value) }
}
@Synchronized
override fun clean() {
try {
storage?.close()
} catch (ignored: Throwable) {
}
PersistentHashMap.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(): PersistentHashMap<K, V> =
PersistentHashMap(storageFile, keyDescriptor, valueExternalizer)
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.incremental.storage
import org.jetbrains.kotlin.incremental.dumpCollection
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.resolve.jvm.JvmClassName
import java.io.File
internal class SourceToJvmNameMap(
storageFile: File,
pathConverter: FileToPathConverter
) : AbstractSourceToOutputMap<JvmClassName>(JvmClassNameTransformer, storageFile, pathConverter)
internal class SourceToFqNameMap(
storageFile: File,
pathConverter: FileToPathConverter
) : AbstractSourceToOutputMap<FqName>(FqNameTransformer, storageFile, pathConverter)
internal abstract class AbstractSourceToOutputMap<Name>(
private val nameTransformer: NameTransformer<Name>,
storageFile: File,
private val pathConverter: FileToPathConverter
) : BasicStringMap<Collection<String>>(storageFile, PathStringDescriptor, StringCollectionExternalizer) {
fun clearOutputsForSource(sourceFile: File) {
remove(pathConverter.toPath(sourceFile))
}
fun add(sourceFile: File, className: Name) {
storage.append(pathConverter.toPath(sourceFile), nameTransformer.asString(className))
}
fun contains(sourceFile: File): Boolean =
pathConverter.toPath(sourceFile) in storage
operator fun get(sourceFile: File): Collection<Name> =
storage[pathConverter.toPath(sourceFile)].orEmpty().map(nameTransformer::asName)
fun getFqNames(sourceFile: File): Collection<FqName> =
storage[pathConverter.toPath(sourceFile)].orEmpty().map(nameTransformer::asFqName)
override fun dumpValue(value: Collection<String>) =
value.dumpCollection()
private fun remove(path: String) {
storage.remove(path)
}
}

View File

@@ -17258,7 +17258,6 @@ public final class DebugProtoBuf {
*hasAnnotations
*Visibility
*isSecondary
*hasNonStableParameterNames
* </pre>
*/
boolean hasFlags();
@@ -17269,7 +17268,6 @@ public final class DebugProtoBuf {
*hasAnnotations
*Visibility
*isSecondary
*hasNonStableParameterNames
* </pre>
*/
int getFlags();
@@ -17465,7 +17463,6 @@ public final class DebugProtoBuf {
*hasAnnotations
*Visibility
*isSecondary
*hasNonStableParameterNames
* </pre>
*/
public boolean hasFlags() {
@@ -17478,7 +17475,6 @@ public final class DebugProtoBuf {
*hasAnnotations
*Visibility
*isSecondary
*hasNonStableParameterNames
* </pre>
*/
public int getFlags() {
@@ -17898,7 +17894,6 @@ public final class DebugProtoBuf {
*hasAnnotations
*Visibility
*isSecondary
*hasNonStableParameterNames
* </pre>
*/
public boolean hasFlags() {
@@ -17911,7 +17906,6 @@ public final class DebugProtoBuf {
*hasAnnotations
*Visibility
*isSecondary
*hasNonStableParameterNames
* </pre>
*/
public int getFlags() {
@@ -17924,7 +17918,6 @@ public final class DebugProtoBuf {
*hasAnnotations
*Visibility
*isSecondary
*hasNonStableParameterNames
* </pre>
*/
public Builder setFlags(int value) {
@@ -17940,7 +17933,6 @@ public final class DebugProtoBuf {
*hasAnnotations
*Visibility
*isSecondary
*hasNonStableParameterNames
* </pre>
*/
public Builder clearFlags() {
@@ -18315,7 +18307,6 @@ public final class DebugProtoBuf {
*isExternal
*isSuspend
*isExpect
*hasNonStableParameterNames
* </pre>
*/
boolean hasFlags();
@@ -18334,7 +18325,6 @@ public final class DebugProtoBuf {
*isExternal
*isSuspend
*isExpect
*hasNonStableParameterNames
* </pre>
*/
int getFlags();
@@ -18733,7 +18723,6 @@ public final class DebugProtoBuf {
*isExternal
*isSuspend
*isExpect
*hasNonStableParameterNames
* </pre>
*/
public boolean hasFlags() {
@@ -18754,7 +18743,6 @@ public final class DebugProtoBuf {
*isExternal
*isSuspend
*isExpect
*hasNonStableParameterNames
* </pre>
*/
public int getFlags() {
@@ -19651,7 +19639,6 @@ public final class DebugProtoBuf {
*isExternal
*isSuspend
*isExpect
*hasNonStableParameterNames
* </pre>
*/
public boolean hasFlags() {
@@ -19672,7 +19659,6 @@ public final class DebugProtoBuf {
*isExternal
*isSuspend
*isExpect
*hasNonStableParameterNames
* </pre>
*/
public int getFlags() {
@@ -19693,7 +19679,6 @@ public final class DebugProtoBuf {
*isExternal
*isSuspend
*isExpect
*hasNonStableParameterNames
* </pre>
*/
public Builder setFlags(int value) {
@@ -19717,7 +19702,6 @@ public final class DebugProtoBuf {
*isExternal
*isSuspend
*isExpect
*hasNonStableParameterNames
* </pre>
*/
public Builder clearFlags() {

View File

@@ -208,65 +208,6 @@ public final class DebugJvmModuleProtoBuf {
*/
org.jetbrains.kotlin.metadata.DebugProtoBuf.AnnotationOrBuilder getAnnotationOrBuilder(
int index);
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Class optional_annotation_class = 16;</code>
*
* <pre>
* &#64;OptionalExpectation-annotated annotation classes in this module. This list is only used in the compiler frontend when compiling
* a second-tier multiplatform module against a multiplatform module which uses optional annotations, not actualized on the JVM.
* This is not needed in the IDE because optional annotations can only be used in common modules, where the IDE plugin resolves
* it to the corresponding class with the resolution capabilities of common modules.
* </pre>
*/
java.util.List<org.jetbrains.kotlin.metadata.DebugProtoBuf.Class>
getOptionalAnnotationClassList();
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Class optional_annotation_class = 16;</code>
*
* <pre>
* &#64;OptionalExpectation-annotated annotation classes in this module. This list is only used in the compiler frontend when compiling
* a second-tier multiplatform module against a multiplatform module which uses optional annotations, not actualized on the JVM.
* This is not needed in the IDE because optional annotations can only be used in common modules, where the IDE plugin resolves
* it to the corresponding class with the resolution capabilities of common modules.
* </pre>
*/
org.jetbrains.kotlin.metadata.DebugProtoBuf.Class getOptionalAnnotationClass(int index);
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Class optional_annotation_class = 16;</code>
*
* <pre>
* &#64;OptionalExpectation-annotated annotation classes in this module. This list is only used in the compiler frontend when compiling
* a second-tier multiplatform module against a multiplatform module which uses optional annotations, not actualized on the JVM.
* This is not needed in the IDE because optional annotations can only be used in common modules, where the IDE plugin resolves
* it to the corresponding class with the resolution capabilities of common modules.
* </pre>
*/
int getOptionalAnnotationClassCount();
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Class optional_annotation_class = 16;</code>
*
* <pre>
* &#64;OptionalExpectation-annotated annotation classes in this module. This list is only used in the compiler frontend when compiling
* a second-tier multiplatform module against a multiplatform module which uses optional annotations, not actualized on the JVM.
* This is not needed in the IDE because optional annotations can only be used in common modules, where the IDE plugin resolves
* it to the corresponding class with the resolution capabilities of common modules.
* </pre>
*/
java.util.List<? extends org.jetbrains.kotlin.metadata.DebugProtoBuf.ClassOrBuilder>
getOptionalAnnotationClassOrBuilderList();
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Class optional_annotation_class = 16;</code>
*
* <pre>
* &#64;OptionalExpectation-annotated annotation classes in this module. This list is only used in the compiler frontend when compiling
* a second-tier multiplatform module against a multiplatform module which uses optional annotations, not actualized on the JVM.
* This is not needed in the IDE because optional annotations can only be used in common modules, where the IDE plugin resolves
* it to the corresponding class with the resolution capabilities of common modules.
* </pre>
*/
org.jetbrains.kotlin.metadata.DebugProtoBuf.ClassOrBuilder getOptionalAnnotationClassOrBuilder(
int index);
}
/**
* Protobuf type {@code org.jetbrains.kotlin.metadata.jvm.Module}
@@ -379,14 +320,6 @@ public final class DebugJvmModuleProtoBuf {
annotation_.add(input.readMessage(org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.PARSER, extensionRegistry));
break;
}
case 130: {
if (!((mutable_bitField0_ & 0x00000040) == 0x00000040)) {
optionalAnnotationClass_ = new java.util.ArrayList<org.jetbrains.kotlin.metadata.DebugProtoBuf.Class>();
mutable_bitField0_ |= 0x00000040;
}
optionalAnnotationClass_.add(input.readMessage(org.jetbrains.kotlin.metadata.DebugProtoBuf.Class.PARSER, extensionRegistry));
break;
}
}
}
} catch (org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException e) {
@@ -407,9 +340,6 @@ public final class DebugJvmModuleProtoBuf {
if (((mutable_bitField0_ & 0x00000020) == 0x00000020)) {
annotation_ = java.util.Collections.unmodifiableList(annotation_);
}
if (((mutable_bitField0_ & 0x00000040) == 0x00000040)) {
optionalAnnotationClass_ = java.util.Collections.unmodifiableList(optionalAnnotationClass_);
}
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
@@ -698,76 +628,6 @@ public final class DebugJvmModuleProtoBuf {
return annotation_.get(index);
}
public static final int OPTIONAL_ANNOTATION_CLASS_FIELD_NUMBER = 16;
private java.util.List<org.jetbrains.kotlin.metadata.DebugProtoBuf.Class> optionalAnnotationClass_;
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Class optional_annotation_class = 16;</code>
*
* <pre>
* &#64;OptionalExpectation-annotated annotation classes in this module. This list is only used in the compiler frontend when compiling
* a second-tier multiplatform module against a multiplatform module which uses optional annotations, not actualized on the JVM.
* This is not needed in the IDE because optional annotations can only be used in common modules, where the IDE plugin resolves
* it to the corresponding class with the resolution capabilities of common modules.
* </pre>
*/
public java.util.List<org.jetbrains.kotlin.metadata.DebugProtoBuf.Class> getOptionalAnnotationClassList() {
return optionalAnnotationClass_;
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Class optional_annotation_class = 16;</code>
*
* <pre>
* &#64;OptionalExpectation-annotated annotation classes in this module. This list is only used in the compiler frontend when compiling
* a second-tier multiplatform module against a multiplatform module which uses optional annotations, not actualized on the JVM.
* This is not needed in the IDE because optional annotations can only be used in common modules, where the IDE plugin resolves
* it to the corresponding class with the resolution capabilities of common modules.
* </pre>
*/
public java.util.List<? extends org.jetbrains.kotlin.metadata.DebugProtoBuf.ClassOrBuilder>
getOptionalAnnotationClassOrBuilderList() {
return optionalAnnotationClass_;
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Class optional_annotation_class = 16;</code>
*
* <pre>
* &#64;OptionalExpectation-annotated annotation classes in this module. This list is only used in the compiler frontend when compiling
* a second-tier multiplatform module against a multiplatform module which uses optional annotations, not actualized on the JVM.
* This is not needed in the IDE because optional annotations can only be used in common modules, where the IDE plugin resolves
* it to the corresponding class with the resolution capabilities of common modules.
* </pre>
*/
public int getOptionalAnnotationClassCount() {
return optionalAnnotationClass_.size();
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Class optional_annotation_class = 16;</code>
*
* <pre>
* &#64;OptionalExpectation-annotated annotation classes in this module. This list is only used in the compiler frontend when compiling
* a second-tier multiplatform module against a multiplatform module which uses optional annotations, not actualized on the JVM.
* This is not needed in the IDE because optional annotations can only be used in common modules, where the IDE plugin resolves
* it to the corresponding class with the resolution capabilities of common modules.
* </pre>
*/
public org.jetbrains.kotlin.metadata.DebugProtoBuf.Class getOptionalAnnotationClass(int index) {
return optionalAnnotationClass_.get(index);
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Class optional_annotation_class = 16;</code>
*
* <pre>
* &#64;OptionalExpectation-annotated annotation classes in this module. This list is only used in the compiler frontend when compiling
* a second-tier multiplatform module against a multiplatform module which uses optional annotations, not actualized on the JVM.
* This is not needed in the IDE because optional annotations can only be used in common modules, where the IDE plugin resolves
* it to the corresponding class with the resolution capabilities of common modules.
* </pre>
*/
public org.jetbrains.kotlin.metadata.DebugProtoBuf.ClassOrBuilder getOptionalAnnotationClassOrBuilder(
int index) {
return optionalAnnotationClass_.get(index);
}
private void initFields() {
packageParts_ = java.util.Collections.emptyList();
metadataParts_ = java.util.Collections.emptyList();
@@ -775,7 +635,6 @@ public final class DebugJvmModuleProtoBuf {
stringTable_ = org.jetbrains.kotlin.metadata.DebugProtoBuf.StringTable.getDefaultInstance();
qualifiedNameTable_ = org.jetbrains.kotlin.metadata.DebugProtoBuf.QualifiedNameTable.getDefaultInstance();
annotation_ = java.util.Collections.emptyList();
optionalAnnotationClass_ = java.util.Collections.emptyList();
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
@@ -807,12 +666,6 @@ public final class DebugJvmModuleProtoBuf {
return false;
}
}
for (int i = 0; i < getOptionalAnnotationClassCount(); i++) {
if (!getOptionalAnnotationClass(i).isInitialized()) {
memoizedIsInitialized = 0;
return false;
}
}
memoizedIsInitialized = 1;
return true;
}
@@ -838,9 +691,6 @@ public final class DebugJvmModuleProtoBuf {
for (int i = 0; i < annotation_.size(); i++) {
output.writeMessage(6, annotation_.get(i));
}
for (int i = 0; i < optionalAnnotationClass_.size(); i++) {
output.writeMessage(16, optionalAnnotationClass_.get(i));
}
getUnknownFields().writeTo(output);
}
@@ -879,10 +729,6 @@ public final class DebugJvmModuleProtoBuf {
size += org.jetbrains.kotlin.protobuf.CodedOutputStream
.computeMessageSize(6, annotation_.get(i));
}
for (int i = 0; i < optionalAnnotationClass_.size(); i++) {
size += org.jetbrains.kotlin.protobuf.CodedOutputStream
.computeMessageSize(16, optionalAnnotationClass_.get(i));
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
@@ -997,7 +843,6 @@ public final class DebugJvmModuleProtoBuf {
getStringTableFieldBuilder();
getQualifiedNameTableFieldBuilder();
getAnnotationFieldBuilder();
getOptionalAnnotationClassFieldBuilder();
}
}
private static Builder create() {
@@ -1038,12 +883,6 @@ public final class DebugJvmModuleProtoBuf {
} else {
annotationBuilder_.clear();
}
if (optionalAnnotationClassBuilder_ == null) {
optionalAnnotationClass_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000040);
} else {
optionalAnnotationClassBuilder_.clear();
}
return this;
}
@@ -1120,15 +959,6 @@ public final class DebugJvmModuleProtoBuf {
} else {
result.annotation_ = annotationBuilder_.build();
}
if (optionalAnnotationClassBuilder_ == null) {
if (((bitField0_ & 0x00000040) == 0x00000040)) {
optionalAnnotationClass_ = java.util.Collections.unmodifiableList(optionalAnnotationClass_);
bitField0_ = (bitField0_ & ~0x00000040);
}
result.optionalAnnotationClass_ = optionalAnnotationClass_;
} else {
result.optionalAnnotationClass_ = optionalAnnotationClassBuilder_.build();
}
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
@@ -1239,32 +1069,6 @@ public final class DebugJvmModuleProtoBuf {
}
}
}
if (optionalAnnotationClassBuilder_ == null) {
if (!other.optionalAnnotationClass_.isEmpty()) {
if (optionalAnnotationClass_.isEmpty()) {
optionalAnnotationClass_ = other.optionalAnnotationClass_;
bitField0_ = (bitField0_ & ~0x00000040);
} else {
ensureOptionalAnnotationClassIsMutable();
optionalAnnotationClass_.addAll(other.optionalAnnotationClass_);
}
onChanged();
}
} else {
if (!other.optionalAnnotationClass_.isEmpty()) {
if (optionalAnnotationClassBuilder_.isEmpty()) {
optionalAnnotationClassBuilder_.dispose();
optionalAnnotationClassBuilder_ = null;
optionalAnnotationClass_ = other.optionalAnnotationClass_;
bitField0_ = (bitField0_ & ~0x00000040);
optionalAnnotationClassBuilder_ =
org.jetbrains.kotlin.protobuf.GeneratedMessage.alwaysUseFieldBuilders ?
getOptionalAnnotationClassFieldBuilder() : null;
} else {
optionalAnnotationClassBuilder_.addAllMessages(other.optionalAnnotationClass_);
}
}
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
@@ -1294,12 +1098,6 @@ public final class DebugJvmModuleProtoBuf {
return false;
}
}
for (int i = 0; i < getOptionalAnnotationClassCount(); i++) {
if (!getOptionalAnnotationClass(i).isInitialized()) {
return false;
}
}
return true;
}
@@ -2628,372 +2426,6 @@ public final class DebugJvmModuleProtoBuf {
return annotationBuilder_;
}
private java.util.List<org.jetbrains.kotlin.metadata.DebugProtoBuf.Class> optionalAnnotationClass_ =
java.util.Collections.emptyList();
private void ensureOptionalAnnotationClassIsMutable() {
if (!((bitField0_ & 0x00000040) == 0x00000040)) {
optionalAnnotationClass_ = new java.util.ArrayList<org.jetbrains.kotlin.metadata.DebugProtoBuf.Class>(optionalAnnotationClass_);
bitField0_ |= 0x00000040;
}
}
private org.jetbrains.kotlin.protobuf.RepeatedFieldBuilder<
org.jetbrains.kotlin.metadata.DebugProtoBuf.Class, org.jetbrains.kotlin.metadata.DebugProtoBuf.Class.Builder, org.jetbrains.kotlin.metadata.DebugProtoBuf.ClassOrBuilder> optionalAnnotationClassBuilder_;
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Class optional_annotation_class = 16;</code>
*
* <pre>
* &#64;OptionalExpectation-annotated annotation classes in this module. This list is only used in the compiler frontend when compiling
* a second-tier multiplatform module against a multiplatform module which uses optional annotations, not actualized on the JVM.
* This is not needed in the IDE because optional annotations can only be used in common modules, where the IDE plugin resolves
* it to the corresponding class with the resolution capabilities of common modules.
* </pre>
*/
public java.util.List<org.jetbrains.kotlin.metadata.DebugProtoBuf.Class> getOptionalAnnotationClassList() {
if (optionalAnnotationClassBuilder_ == null) {
return java.util.Collections.unmodifiableList(optionalAnnotationClass_);
} else {
return optionalAnnotationClassBuilder_.getMessageList();
}
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Class optional_annotation_class = 16;</code>
*
* <pre>
* &#64;OptionalExpectation-annotated annotation classes in this module. This list is only used in the compiler frontend when compiling
* a second-tier multiplatform module against a multiplatform module which uses optional annotations, not actualized on the JVM.
* This is not needed in the IDE because optional annotations can only be used in common modules, where the IDE plugin resolves
* it to the corresponding class with the resolution capabilities of common modules.
* </pre>
*/
public int getOptionalAnnotationClassCount() {
if (optionalAnnotationClassBuilder_ == null) {
return optionalAnnotationClass_.size();
} else {
return optionalAnnotationClassBuilder_.getCount();
}
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Class optional_annotation_class = 16;</code>
*
* <pre>
* &#64;OptionalExpectation-annotated annotation classes in this module. This list is only used in the compiler frontend when compiling
* a second-tier multiplatform module against a multiplatform module which uses optional annotations, not actualized on the JVM.
* This is not needed in the IDE because optional annotations can only be used in common modules, where the IDE plugin resolves
* it to the corresponding class with the resolution capabilities of common modules.
* </pre>
*/
public org.jetbrains.kotlin.metadata.DebugProtoBuf.Class getOptionalAnnotationClass(int index) {
if (optionalAnnotationClassBuilder_ == null) {
return optionalAnnotationClass_.get(index);
} else {
return optionalAnnotationClassBuilder_.getMessage(index);
}
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Class optional_annotation_class = 16;</code>
*
* <pre>
* &#64;OptionalExpectation-annotated annotation classes in this module. This list is only used in the compiler frontend when compiling
* a second-tier multiplatform module against a multiplatform module which uses optional annotations, not actualized on the JVM.
* This is not needed in the IDE because optional annotations can only be used in common modules, where the IDE plugin resolves
* it to the corresponding class with the resolution capabilities of common modules.
* </pre>
*/
public Builder setOptionalAnnotationClass(
int index, org.jetbrains.kotlin.metadata.DebugProtoBuf.Class value) {
if (optionalAnnotationClassBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureOptionalAnnotationClassIsMutable();
optionalAnnotationClass_.set(index, value);
onChanged();
} else {
optionalAnnotationClassBuilder_.setMessage(index, value);
}
return this;
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Class optional_annotation_class = 16;</code>
*
* <pre>
* &#64;OptionalExpectation-annotated annotation classes in this module. This list is only used in the compiler frontend when compiling
* a second-tier multiplatform module against a multiplatform module which uses optional annotations, not actualized on the JVM.
* This is not needed in the IDE because optional annotations can only be used in common modules, where the IDE plugin resolves
* it to the corresponding class with the resolution capabilities of common modules.
* </pre>
*/
public Builder setOptionalAnnotationClass(
int index, org.jetbrains.kotlin.metadata.DebugProtoBuf.Class.Builder builderForValue) {
if (optionalAnnotationClassBuilder_ == null) {
ensureOptionalAnnotationClassIsMutable();
optionalAnnotationClass_.set(index, builderForValue.build());
onChanged();
} else {
optionalAnnotationClassBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Class optional_annotation_class = 16;</code>
*
* <pre>
* &#64;OptionalExpectation-annotated annotation classes in this module. This list is only used in the compiler frontend when compiling
* a second-tier multiplatform module against a multiplatform module which uses optional annotations, not actualized on the JVM.
* This is not needed in the IDE because optional annotations can only be used in common modules, where the IDE plugin resolves
* it to the corresponding class with the resolution capabilities of common modules.
* </pre>
*/
public Builder addOptionalAnnotationClass(org.jetbrains.kotlin.metadata.DebugProtoBuf.Class value) {
if (optionalAnnotationClassBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureOptionalAnnotationClassIsMutable();
optionalAnnotationClass_.add(value);
onChanged();
} else {
optionalAnnotationClassBuilder_.addMessage(value);
}
return this;
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Class optional_annotation_class = 16;</code>
*
* <pre>
* &#64;OptionalExpectation-annotated annotation classes in this module. This list is only used in the compiler frontend when compiling
* a second-tier multiplatform module against a multiplatform module which uses optional annotations, not actualized on the JVM.
* This is not needed in the IDE because optional annotations can only be used in common modules, where the IDE plugin resolves
* it to the corresponding class with the resolution capabilities of common modules.
* </pre>
*/
public Builder addOptionalAnnotationClass(
int index, org.jetbrains.kotlin.metadata.DebugProtoBuf.Class value) {
if (optionalAnnotationClassBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureOptionalAnnotationClassIsMutable();
optionalAnnotationClass_.add(index, value);
onChanged();
} else {
optionalAnnotationClassBuilder_.addMessage(index, value);
}
return this;
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Class optional_annotation_class = 16;</code>
*
* <pre>
* &#64;OptionalExpectation-annotated annotation classes in this module. This list is only used in the compiler frontend when compiling
* a second-tier multiplatform module against a multiplatform module which uses optional annotations, not actualized on the JVM.
* This is not needed in the IDE because optional annotations can only be used in common modules, where the IDE plugin resolves
* it to the corresponding class with the resolution capabilities of common modules.
* </pre>
*/
public Builder addOptionalAnnotationClass(
org.jetbrains.kotlin.metadata.DebugProtoBuf.Class.Builder builderForValue) {
if (optionalAnnotationClassBuilder_ == null) {
ensureOptionalAnnotationClassIsMutable();
optionalAnnotationClass_.add(builderForValue.build());
onChanged();
} else {
optionalAnnotationClassBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Class optional_annotation_class = 16;</code>
*
* <pre>
* &#64;OptionalExpectation-annotated annotation classes in this module. This list is only used in the compiler frontend when compiling
* a second-tier multiplatform module against a multiplatform module which uses optional annotations, not actualized on the JVM.
* This is not needed in the IDE because optional annotations can only be used in common modules, where the IDE plugin resolves
* it to the corresponding class with the resolution capabilities of common modules.
* </pre>
*/
public Builder addOptionalAnnotationClass(
int index, org.jetbrains.kotlin.metadata.DebugProtoBuf.Class.Builder builderForValue) {
if (optionalAnnotationClassBuilder_ == null) {
ensureOptionalAnnotationClassIsMutable();
optionalAnnotationClass_.add(index, builderForValue.build());
onChanged();
} else {
optionalAnnotationClassBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Class optional_annotation_class = 16;</code>
*
* <pre>
* &#64;OptionalExpectation-annotated annotation classes in this module. This list is only used in the compiler frontend when compiling
* a second-tier multiplatform module against a multiplatform module which uses optional annotations, not actualized on the JVM.
* This is not needed in the IDE because optional annotations can only be used in common modules, where the IDE plugin resolves
* it to the corresponding class with the resolution capabilities of common modules.
* </pre>
*/
public Builder addAllOptionalAnnotationClass(
java.lang.Iterable<? extends org.jetbrains.kotlin.metadata.DebugProtoBuf.Class> values) {
if (optionalAnnotationClassBuilder_ == null) {
ensureOptionalAnnotationClassIsMutable();
org.jetbrains.kotlin.protobuf.AbstractMessageLite.Builder.addAll(
values, optionalAnnotationClass_);
onChanged();
} else {
optionalAnnotationClassBuilder_.addAllMessages(values);
}
return this;
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Class optional_annotation_class = 16;</code>
*
* <pre>
* &#64;OptionalExpectation-annotated annotation classes in this module. This list is only used in the compiler frontend when compiling
* a second-tier multiplatform module against a multiplatform module which uses optional annotations, not actualized on the JVM.
* This is not needed in the IDE because optional annotations can only be used in common modules, where the IDE plugin resolves
* it to the corresponding class with the resolution capabilities of common modules.
* </pre>
*/
public Builder clearOptionalAnnotationClass() {
if (optionalAnnotationClassBuilder_ == null) {
optionalAnnotationClass_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000040);
onChanged();
} else {
optionalAnnotationClassBuilder_.clear();
}
return this;
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Class optional_annotation_class = 16;</code>
*
* <pre>
* &#64;OptionalExpectation-annotated annotation classes in this module. This list is only used in the compiler frontend when compiling
* a second-tier multiplatform module against a multiplatform module which uses optional annotations, not actualized on the JVM.
* This is not needed in the IDE because optional annotations can only be used in common modules, where the IDE plugin resolves
* it to the corresponding class with the resolution capabilities of common modules.
* </pre>
*/
public Builder removeOptionalAnnotationClass(int index) {
if (optionalAnnotationClassBuilder_ == null) {
ensureOptionalAnnotationClassIsMutable();
optionalAnnotationClass_.remove(index);
onChanged();
} else {
optionalAnnotationClassBuilder_.remove(index);
}
return this;
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Class optional_annotation_class = 16;</code>
*
* <pre>
* &#64;OptionalExpectation-annotated annotation classes in this module. This list is only used in the compiler frontend when compiling
* a second-tier multiplatform module against a multiplatform module which uses optional annotations, not actualized on the JVM.
* This is not needed in the IDE because optional annotations can only be used in common modules, where the IDE plugin resolves
* it to the corresponding class with the resolution capabilities of common modules.
* </pre>
*/
public org.jetbrains.kotlin.metadata.DebugProtoBuf.Class.Builder getOptionalAnnotationClassBuilder(
int index) {
return getOptionalAnnotationClassFieldBuilder().getBuilder(index);
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Class optional_annotation_class = 16;</code>
*
* <pre>
* &#64;OptionalExpectation-annotated annotation classes in this module. This list is only used in the compiler frontend when compiling
* a second-tier multiplatform module against a multiplatform module which uses optional annotations, not actualized on the JVM.
* This is not needed in the IDE because optional annotations can only be used in common modules, where the IDE plugin resolves
* it to the corresponding class with the resolution capabilities of common modules.
* </pre>
*/
public org.jetbrains.kotlin.metadata.DebugProtoBuf.ClassOrBuilder getOptionalAnnotationClassOrBuilder(
int index) {
if (optionalAnnotationClassBuilder_ == null) {
return optionalAnnotationClass_.get(index); } else {
return optionalAnnotationClassBuilder_.getMessageOrBuilder(index);
}
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Class optional_annotation_class = 16;</code>
*
* <pre>
* &#64;OptionalExpectation-annotated annotation classes in this module. This list is only used in the compiler frontend when compiling
* a second-tier multiplatform module against a multiplatform module which uses optional annotations, not actualized on the JVM.
* This is not needed in the IDE because optional annotations can only be used in common modules, where the IDE plugin resolves
* it to the corresponding class with the resolution capabilities of common modules.
* </pre>
*/
public java.util.List<? extends org.jetbrains.kotlin.metadata.DebugProtoBuf.ClassOrBuilder>
getOptionalAnnotationClassOrBuilderList() {
if (optionalAnnotationClassBuilder_ != null) {
return optionalAnnotationClassBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(optionalAnnotationClass_);
}
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Class optional_annotation_class = 16;</code>
*
* <pre>
* &#64;OptionalExpectation-annotated annotation classes in this module. This list is only used in the compiler frontend when compiling
* a second-tier multiplatform module against a multiplatform module which uses optional annotations, not actualized on the JVM.
* This is not needed in the IDE because optional annotations can only be used in common modules, where the IDE plugin resolves
* it to the corresponding class with the resolution capabilities of common modules.
* </pre>
*/
public org.jetbrains.kotlin.metadata.DebugProtoBuf.Class.Builder addOptionalAnnotationClassBuilder() {
return getOptionalAnnotationClassFieldBuilder().addBuilder(
org.jetbrains.kotlin.metadata.DebugProtoBuf.Class.getDefaultInstance());
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Class optional_annotation_class = 16;</code>
*
* <pre>
* &#64;OptionalExpectation-annotated annotation classes in this module. This list is only used in the compiler frontend when compiling
* a second-tier multiplatform module against a multiplatform module which uses optional annotations, not actualized on the JVM.
* This is not needed in the IDE because optional annotations can only be used in common modules, where the IDE plugin resolves
* it to the corresponding class with the resolution capabilities of common modules.
* </pre>
*/
public org.jetbrains.kotlin.metadata.DebugProtoBuf.Class.Builder addOptionalAnnotationClassBuilder(
int index) {
return getOptionalAnnotationClassFieldBuilder().addBuilder(
index, org.jetbrains.kotlin.metadata.DebugProtoBuf.Class.getDefaultInstance());
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Class optional_annotation_class = 16;</code>
*
* <pre>
* &#64;OptionalExpectation-annotated annotation classes in this module. This list is only used in the compiler frontend when compiling
* a second-tier multiplatform module against a multiplatform module which uses optional annotations, not actualized on the JVM.
* This is not needed in the IDE because optional annotations can only be used in common modules, where the IDE plugin resolves
* it to the corresponding class with the resolution capabilities of common modules.
* </pre>
*/
public java.util.List<org.jetbrains.kotlin.metadata.DebugProtoBuf.Class.Builder>
getOptionalAnnotationClassBuilderList() {
return getOptionalAnnotationClassFieldBuilder().getBuilderList();
}
private org.jetbrains.kotlin.protobuf.RepeatedFieldBuilder<
org.jetbrains.kotlin.metadata.DebugProtoBuf.Class, org.jetbrains.kotlin.metadata.DebugProtoBuf.Class.Builder, org.jetbrains.kotlin.metadata.DebugProtoBuf.ClassOrBuilder>
getOptionalAnnotationClassFieldBuilder() {
if (optionalAnnotationClassBuilder_ == null) {
optionalAnnotationClassBuilder_ = new org.jetbrains.kotlin.protobuf.RepeatedFieldBuilder<
org.jetbrains.kotlin.metadata.DebugProtoBuf.Class, org.jetbrains.kotlin.metadata.DebugProtoBuf.Class.Builder, org.jetbrains.kotlin.metadata.DebugProtoBuf.ClassOrBuilder>(
optionalAnnotationClass_,
((bitField0_ & 0x00000040) == 0x00000040),
getParentForChildren(),
isClean());
optionalAnnotationClass_ = null;
}
return optionalAnnotationClassBuilder_;
}
// @@protoc_insertion_point(builder_scope:org.jetbrains.kotlin.metadata.jvm.Module)
}
@@ -5212,7 +4644,7 @@ public final class DebugJvmModuleProtoBuf {
"\n,core/metadata.jvm/src/jvm_module.debug" +
".proto\022!org.jetbrains.kotlin.metadata.jv" +
"m\032&core/metadata/src/metadata.debug.prot" +
"o\"\316\003\n\006Module\022F\n\rpackage_parts\030\001 \003(\0132/.or" +
"o\"\205\003\n\006Module\022F\n\rpackage_parts\030\001 \003(\0132/.or" +
"g.jetbrains.kotlin.metadata.jvm.PackageP" +
"arts\022G\n\016metadata_parts\030\002 \003(\0132/.org.jetbr" +
"ains.kotlin.metadata.jvm.PackageParts\022\030\n" +
@@ -5221,18 +4653,16 @@ public final class DebugJvmModuleProtoBuf {
"ringTable\022O\n\024qualified_name_table\030\005 \001(\0132",
"1.org.jetbrains.kotlin.metadata.Qualifie" +
"dNameTable\022=\n\nannotation\030\006 \003(\0132).org.jet" +
"brains.kotlin.metadata.Annotation\022G\n\031opt" +
"ional_annotation_class\030\020 \003(\0132$.org.jetbr" +
"ains.kotlin.metadata.Class\"\276\002\n\014PackagePa" +
"rts\022\027\n\017package_fq_name\030\001 \002(\t\022\030\n\020short_cl" +
"ass_name\030\002 \003(\t\022*\n\036multifile_facade_short" +
"_name_id\030\003 \003(\005B\002\020\001\022#\n\033multifile_facade_s" +
"hort_name\030\004 \003(\t\022.\n&class_with_jvm_packag" +
"e_name_short_name\030\005 \003(\t\022F\n:class_with_jv",
"m_package_name_multifile_facade_short_na" +
"me_id\030\007 \003(\005B\002\020\001\0222\n&class_with_jvm_packag" +
"e_name_package_id\030\006 \003(\005B\002\020\001B\030B\026DebugJvmM" +
"oduleProtoBuf"
"brains.kotlin.metadata.Annotation\"\276\002\n\014Pa" +
"ckageParts\022\027\n\017package_fq_name\030\001 \002(\t\022\030\n\020s" +
"hort_class_name\030\002 \003(\t\022*\n\036multifile_facad" +
"e_short_name_id\030\003 \003(\005B\002\020\001\022#\n\033multifile_f" +
"acade_short_name\030\004 \003(\t\022.\n&class_with_jvm" +
"_package_name_short_name\030\005 \003(\t\022F\n:class_" +
"with_jvm_package_name_multifile_facade_s" +
"hort_name_id\030\007 \003(\005B\002\020\001\0222\n&class_with_jvm",
"_package_name_package_id\030\006 \003(\005B\002\020\001B\030B\026De" +
"bugJvmModuleProtoBuf"
};
org.jetbrains.kotlin.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new org.jetbrains.kotlin.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() {
@@ -5252,7 +4682,7 @@ public final class DebugJvmModuleProtoBuf {
internal_static_org_jetbrains_kotlin_metadata_jvm_Module_fieldAccessorTable = new
org.jetbrains.kotlin.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_org_jetbrains_kotlin_metadata_jvm_Module_descriptor,
new java.lang.String[] { "PackageParts", "MetadataParts", "JvmPackageName", "StringTable", "QualifiedNameTable", "Annotation", "OptionalAnnotationClass", });
new java.lang.String[] { "PackageParts", "MetadataParts", "JvmPackageName", "StringTable", "QualifiedNameTable", "Annotation", });
internal_static_org_jetbrains_kotlin_metadata_jvm_PackageParts_descriptor =
getDescriptor().getMessageTypes().get(1);
internal_static_org_jetbrains_kotlin_metadata_jvm_PackageParts_fieldAccessorTable = new

View File

@@ -18,7 +18,6 @@ public final class DebugJvmProtoBuf {
registry.add(org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.classModuleName);
registry.add(org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.classLocalVariable);
registry.add(org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.anonymousObjectOriginName);
registry.add(org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.jvmClassFlags);
registry.add(org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.packageModuleName);
registry.add(org.jetbrains.kotlin.metadata.jvm.DebugJvmProtoBuf.packageLocalVariable);
}
@@ -4651,22 +4650,6 @@ public final class DebugJvmProtoBuf {
.newFileScopedGeneratedExtension(
java.lang.Integer.class,
null);
public static final int JVM_CLASS_FLAGS_FIELD_NUMBER = 104;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Class { ... }</code>
*
* <pre>
* first bit: isFunctionBodyInInterface: 0 if actual body generated in DefaultImpl, 1 - otherwise (in interface default method)
* second bit: is all-compatibility mode or not, 1 - yes, 0 - no
* </pre>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.Class,
java.lang.Integer> jvmClassFlags = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
java.lang.Integer.class,
null);
public static final int PACKAGE_MODULE_NAME_FIELD_NUMBER = 101;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Package { ... }</code>
@@ -4775,13 +4758,12 @@ public final class DebugJvmProtoBuf {
"\'.org.jetbrains.kotlin.metadata.Property",
":P\n\034anonymous_object_origin_name\022$.org.j" +
"etbrains.kotlin.metadata.Class\030g \001(\005B\004\230\265" +
"\030\001:@\n\017jvm_class_flags\022$.org.jetbrains.ko" +
"tlin.metadata.Class\030h \001(\005:\0010:I\n\023package_" +
"module_name\022&.org.jetbrains.kotlin.metad" +
"ata.Package\030e \001(\005B\004\230\265\030\001:o\n\026package_local" +
"_variable\022&.org.jetbrains.kotlin.metadat" +
"a.Package\030f \003(\0132\'.org.jetbrains.kotlin.m" +
"etadata.PropertyB\022B\020DebugJvmProtoBuf"
"\030\001:I\n\023package_module_name\022&.org.jetbrain" +
"s.kotlin.metadata.Package\030e \001(\005B\004\230\265\030\001:o\n" +
"\026package_local_variable\022&.org.jetbrains." +
"kotlin.metadata.Package\030f \003(\0132\'.org.jetb" +
"rains.kotlin.metadata.PropertyB\022B\020DebugJ" +
"vmProtoBuf"
};
org.jetbrains.kotlin.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new org.jetbrains.kotlin.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() {
@@ -4838,9 +4820,8 @@ public final class DebugJvmProtoBuf {
classModuleName.internalInit(descriptor.getExtensions().get(8));
classLocalVariable.internalInit(descriptor.getExtensions().get(9));
anonymousObjectOriginName.internalInit(descriptor.getExtensions().get(10));
jvmClassFlags.internalInit(descriptor.getExtensions().get(11));
packageModuleName.internalInit(descriptor.getExtensions().get(12));
packageLocalVariable.internalInit(descriptor.getExtensions().get(13));
packageModuleName.internalInit(descriptor.getExtensions().get(11));
packageLocalVariable.internalInit(descriptor.getExtensions().get(12));
org.jetbrains.kotlin.protobuf.ExtensionRegistry registry =
org.jetbrains.kotlin.protobuf.ExtensionRegistry.newInstance();
registry.add(org.jetbrains.kotlin.metadata.DebugExtOptionsProtoBuf.stringIdInTable);

View File

@@ -1,13 +1,13 @@
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import org.gradle.crypto.checksum.Checksum
import org.gradle.plugins.ide.idea.model.IdeaModel
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import proguard.gradle.ProGuardTask
buildscript {
val cacheRedirectorEnabled = findProperty("cacheRedirectorEnabled")?.toString()?.toBoolean() == true
kotlinBootstrapFrom(BootstrapOption.SpaceBootstrap(kotlinBuildProperties.kotlinBootstrapVersion!!, cacheRedirectorEnabled))
kotlinBootstrapFrom(BootstrapOption.BintrayBootstrap(kotlinBuildProperties.kotlinBootstrapVersion!!, cacheRedirectorEnabled))
repositories {
bootstrapKotlinRepo?.let(::maven)
@@ -27,10 +27,10 @@ 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.17")
classpath("com.gradle.publish:plugin-publish-plugin:0.9.7")
classpath(kotlin("gradle-plugin", bootstrapKotlinVersion))
classpath("org.jetbrains.dokka:dokka-gradle-plugin:0.9.17")
classpath("org.jfrog.buildinfo:build-info-extractor-gradle:4.17.2")
}
}
@@ -39,12 +39,9 @@ if (kotlinBuildProperties.buildScanServer != null) {
}
plugins {
base
idea
id("jps-compatible")
id("org.jetbrains.gradle.plugin.idea-ext")
id("org.gradle.crypto.checksum") version "1.2.0"
signing
}
pill {
@@ -57,6 +54,9 @@ pill {
}
val isTeamcityBuild = project.kotlinBuildProperties.isTeamcityBuild
val includeStdlibJsIr by extra(
findProperty("include.stdlib.js.ir")?.let { it.toString().toBoolean() } ?: isTeamcityBuild
)
val configuredJdks: List<JdkId> =
getConfiguredJdks().also {
@@ -67,11 +67,7 @@ val configuredJdks: List<JdkId> =
val defaultSnapshotVersion: String by extra
val buildNumber by extra(findProperty("build.number")?.toString() ?: defaultSnapshotVersion)
val kotlinVersion by extra(
findProperty("deployVersion")?.toString()?.let { deploySnapshotStr ->
if (deploySnapshotStr != "default.snapshot") deploySnapshotStr else defaultSnapshotVersion
} ?: buildNumber
)
val kotlinVersion by extra(findProperty("deployVersion")?.toString() ?: buildNumber)
val kotlinLanguageVersion by extra("1.4")
@@ -153,7 +149,6 @@ rootProject.apply {
from(rootProject.file("gradle/jps.gradle.kts"))
from(rootProject.file("gradle/checkArtifacts.gradle.kts"))
from(rootProject.file("gradle/checkCacheability.gradle.kts"))
from(rootProject.file("gradle/retryPublishing.gradle.kts"))
}
IdeVersionConfigurator.setCurrentIde(project)
@@ -167,34 +162,31 @@ 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"
val coroutinesVersion = if (Platform[192].orHigher()) "1.2.1" else "1.1.1"
extra["versions.kotlinx-coroutines-core"] = coroutinesVersion
extra["versions.kotlinx-coroutines-jdk8"] = coroutinesVersion
extra["versions.json"] = "20160807"
extra["versions.native-platform"] = "0.14"
extra["versions.ant-launcher"] = "1.8.0"
extra["versions.robolectric"] = "4.0"
extra["versions.robolectric"] = "3.1"
extra["versions.org.springframework"] = "4.2.0.RELEASE"
extra["versions.jflex"] = "1.7.0"
extra["versions.markdown"] = "0.1.25"
extra["versions.trove4j"] = "1.0.20181211"
extra["versions.completion-ranking-kotlin"] = "0.1.3"
extra["versions.r8"] = "2.0.88"
val immutablesVersion = "0.3.1"
extra["versions.kotlinx-collections-immutable"] = immutablesVersion
extra["versions.kotlinx-collections-immutable-jvm"] = immutablesVersion
extra["versions.completion-ranking-kotlin"] = "0.1.2"
extra["versions.r8"] = "1.5.70"
extra["versions.kotlinx-collections-immutable"] = "0.3.1"
// NOTE: please, also change KTOR_NAME in pathUtil.kt and all versions in corresponding jar names in daemon tests.
extra["versions.ktor-network"] = "1.0.1"
if (!project.hasProperty("versions.kotlin-native")) {
extra["versions.kotlin-native"] = "1.4.20-dev-16314"
extra["versions.kotlin-native"] = "1.4-M2-dev-15123"
}
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 intellijSeparateSdks = project.getBooleanProperty("intellijSeparateSdks") ?: false
@@ -202,10 +194,7 @@ extra["intellijSeparateSdks"] = intellijSeparateSdks
extra["IntellijCoreDependencies"] =
listOf(
when {
Platform[202].orHigher() -> "asm-all-8.0.1"
else -> "asm-all-7.0.1"
},
if (Platform[191].orHigher()) "asm-all-7.0.1" else "asm-all",
"guava",
"jdom",
"jna",
@@ -222,8 +211,6 @@ extra["compilerModules"] = arrayOf(
":compiler:config",
":compiler:config.jvm",
":compiler:container",
":compiler:resolution.common",
":compiler:resolution.common.jvm",
":compiler:resolution",
":compiler:serialization",
":compiler:psi",
@@ -232,8 +219,6 @@ extra["compilerModules"] = arrayOf(
":compiler:frontend.java",
":compiler:cli-common",
":compiler:ir.tree",
":compiler:ir.tree.impl",
":compiler:ir.tree.persistent",
":compiler:ir.psi2ir",
":compiler:ir.backend.common",
":compiler:backend.jvm",
@@ -242,7 +227,6 @@ extra["compilerModules"] = arrayOf(
":compiler:ir.serialization.common",
":compiler:ir.serialization.js",
":compiler:ir.serialization.jvm",
":compiler:ir.interpreter",
":kotlin-util-io",
":kotlin-util-klib",
":kotlin-util-klib-metadata",
@@ -268,22 +252,16 @@ extra["compilerModules"] = arrayOf(
":kotlin-build-common",
":core:metadata",
":core:metadata.jvm",
":core:deserialization.common",
":core:deserialization.common.jvm",
":core:compiler.common",
":core:compiler.common.jvm",
":compiler:backend.common.jvm",
":core:descriptors",
":core:descriptors.jvm",
":core:descriptors.runtime",
":core:deserialization",
":core:util.runtime",
":core:type-system",
":compiler:fir:cones",
":compiler:fir:resolve",
":compiler:fir:fir-serialization",
":compiler:fir:fir-deserialization",
":compiler:fir:tree",
":compiler:fir:raw-fir:raw-fir.common",
":compiler:fir:raw-fir:fir-common",
":compiler:fir:raw-fir:psi2fir",
":compiler:fir:raw-fir:light-tree2fir",
":compiler:fir:fir2ir",
@@ -291,37 +269,16 @@ extra["compilerModules"] = arrayOf(
":compiler:fir:java",
":compiler:fir:jvm",
":compiler:fir:checkers",
":compiler:fir:entrypoint",
":compiler:fir:analysis-tests"
)
extra["compilerModulesForJps"] = listOf(
":kotlin-build-common",
":kotlin-util-io",
":kotlin-util-klib",
":kotlin-util-klib-metadata",
":compiler:cli-common",
":kotlin-compiler-runner",
":daemon-common",
":daemon-common-new",
":core:compiler.common",
":core:compiler.common.jvm",
":core:descriptors",
":core:descriptors.jvm",
":idea:idea-jps-common",
":kotlin-preloader",
":compiler:util",
":compiler:config",
":compiler:config.jvm",
":js:js.config",
":core:util.runtime",
":compiler:compiler.version"
)
val coreLibProjects = listOfNotNull(
":kotlin-stdlib",
":kotlin-stdlib-common",
":kotlin-stdlib-js",
// Exclude JS IR from core libs because it depends on local compiler build, which
// in turn depends on local JVM stdlib. It slows down library testing.
":kotlin-stdlib-js-ir".takeIf { includeStdlibJsIr },
":kotlin-stdlib-jdk7",
":kotlin-stdlib-jdk8",
":kotlin-test:kotlin-test-annotations-common",
@@ -337,12 +294,15 @@ val coreLibProjects = listOfNotNull(
val gradlePluginProjects = listOf(
":kotlin-gradle-plugin",
":kotlin-gradle-plugin:plugin-marker",
":kotlin-gradle-plugin-api",
// ":kotlin-gradle-plugin-integration-tests", // TODO: build fails
":kotlin-allopen",
":kotlin-allopen:plugin-marker",
":kotlin-annotation-processing-gradle",
":kotlin-noarg",
":kotlin-sam-with-receiver",
":kotlin-parcelize-compiler"
":kotlin-noarg:plugin-marker",
":kotlin-sam-with-receiver"
)
apply {
@@ -366,28 +326,12 @@ fun Task.listConfigurationContents(configName: String) {
}
val defaultJvmTarget = "1.8"
val defaultJavaHome = jdkPath(if (Platform[203].orHigher()) "11" else defaultJvmTarget)
val ignoreTestFailures by extra(project.kotlinBuildProperties.ignoreTestFailures)
val defaultJavaHome = jdkPath(defaultJvmTarget)
val ignoreTestFailures by extra(project.findProperty("ignoreTestFailures")?.toString()?.toBoolean() ?: project.hasProperty("teamcity"))
allprojects {
configurations.maybeCreate("embedded").apply {
isCanBeConsumed = false
isCanBeResolved = true
attributes {
attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage.JAVA_RUNTIME))
attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, objects.named(LibraryElements.JAR))
}
}
configurations.maybeCreate("embeddedElements").apply {
extendsFrom(configurations["embedded"])
isCanBeConsumed = true
isCanBeResolved = false
attributes {
attribute(Usage.USAGE_ATTRIBUTE, objects.named("embedded-java-runtime"))
}
}
configurations.maybeCreate("embedded")
jvmTarget = defaultJvmTarget
javaHome = defaultJavaHome
@@ -411,7 +355,7 @@ allprojects {
maven("https://jetbrains.bintray.com/intellij-third-party-dependencies")
maven("https://dl.google.com/dl/android/maven2")
bootstrapKotlinRepo?.let(::maven)
internalBootstrapRepo?.let(::maven)
internalKotlinRepo?.let(::maven)
}
configureJvmProject(javaHome!!, jvmTarget!!)
@@ -419,6 +363,8 @@ allprojects {
val commonCompilerArgs = listOfNotNull(
"-Xopt-in=kotlin.RequiresOptIn",
"-Xread-deserialized-contracts",
"-Xjvm-default=compatibility",
"-Xno-optimized-callable-references",
"-progressive".takeIf { hasProperty("test.progressive.mode") }
)
@@ -430,20 +376,9 @@ allprojects {
}
}
val jvmCompilerArgs = listOf(
"-Xjvm-default=compatibility",
"-Xno-optimized-callable-references",
"-Xno-kotlin-nothing-value-exception",
"-Xnormalize-constructor-calls=enable"
)
tasks.withType<org.jetbrains.kotlin.gradle.dsl.KotlinJvmCompile> {
kotlinOptions {
freeCompilerArgs = commonCompilerArgs + jvmCompilerArgs
if (useJvmIrBackend) {
useIR = true
}
freeCompilerArgs = commonCompilerArgs + listOf("-Xnormalize-constructor-calls=enable")
}
}
@@ -473,7 +408,6 @@ allprojects {
ignore("META-INF/MANIFEST.MF")
ignore("META-INF/compiler.version")
ignore("META-INF/plugin.xml")
ignore("kotlin/KotlinVersionCurrentValue.class")
}
}
@@ -483,9 +417,6 @@ allprojects {
register("listRuntimeJar") { listConfigurationContents("runtimeJar") }
register("listDistJar") { listConfigurationContents("distJar") }
// Aggregate task for build related checks
register("checkBuild")
}
afterEvaluate {
@@ -522,24 +453,10 @@ allprojects {
?.exclude("org.jetbrains.kotlin", "kotlin-scripting-compiler-embeddable")
}
// Aggregate task for build related checks
tasks.register("checkBuild")
apply(from = "$rootDir/gradle/cacheRedirector.gradle.kts")
apply(from = "$rootDir/gradle/testRetry.gradle.kts")
}
}
gradle.buildFinished {
val taskGraph = gradle?.taskGraph
if (taskGraph != null) {
taskGraph.allTasks
.filterIsInstance<SourceTask>()
.filter { it.didWork }
.forEach {
it.source.visit {
if (file.isDirectory && file.listFiles()?.isEmpty() == true) {
logger.warn("Empty source directories may cause build cache misses: " + file.absolutePath)
}
}
}
}
}
@@ -547,12 +464,9 @@ gradle.taskGraph.whenReady {
fun Boolean.toOnOff(): String = if (this) "on" else "off"
val profile = if (isTeamcityBuild) "CI" else "Local"
val proguardMessage = "proguard is ${kotlinBuildProperties.proguard.toOnOff()}"
val jarCompressionMessage = "jar compression is ${kotlinBuildProperties.jarCompression.toOnOff()}"
val profileMessage = "$profile build profile is active ($proguardMessage, $jarCompressionMessage). " +
"Use -Pteamcity=<true|false> to reproduce CI/local build"
logger.warn("\n\n$profileMessage")
logger.warn("$profile build profile is active (proguard is ${kotlinBuildProperties.proguard.toOnOff()}" +
", jar compression is ${kotlinBuildProperties.jarCompression.toOnOff()})." +
" Use -Pteamcity=<true|false> to reproduce CI/local build")
allTasks.filterIsInstance<org.gradle.jvm.tasks.Jar>().forEach { task ->
task.entryCompression = if (kotlinBuildProperties.jarCompression)
@@ -566,10 +480,6 @@ val dist = tasks.register("dist") {
dependsOn(":kotlin-compiler:dist")
}
val syncMutedTests = tasks.register("syncMutedTests") {
dependsOn(":compiler:tests-mutes:run")
}
val copyCompilerToIdeaPlugin by task<Copy> {
dependsOn(dist)
into(ideaPluginDir)
@@ -582,7 +492,7 @@ val ideaPlugin by task<Task> {
}
tasks {
named("clean") {
register("clean") {
doLast {
delete("$buildDir/repo")
delete(distDir)
@@ -595,7 +505,7 @@ tasks {
}
}
listOf("clean", "assemble", "install").forEach { taskName ->
listOf("clean", "assemble", "install", "dist").forEach { taskName ->
register("coreLibs${taskName.capitalize()}") {
coreLibProjects.forEach { projectName -> dependsOn("$projectName:$taskName") }
}
@@ -604,8 +514,6 @@ tasks {
register("coreLibsTest") {
(coreLibProjects + listOf(
":kotlin-stdlib:samples",
":kotlin-stdlib-js-ir",
":kotlin-test:kotlin-test-js-ir".takeIf { !kotlinBuildProperties.isInJpsBuildIdeaSync },
":kotlin-test:kotlin-test-js:kotlin-test-js-it".takeIf { !kotlinBuildProperties.isInJpsBuildIdeaSync },
":kotlinx-metadata-jvm",
":tools:binary-compatibility-validator"
@@ -666,12 +574,11 @@ tasks {
register("firAllTest") {
dependsOn(
":dist",
":compiler:fir:raw-fir:psi2fir:test",
":compiler:fir:raw-fir:light-tree2fir:test",
":compiler:fir:analysis-tests:test",
":compiler:fir:fir2ir:test",
":plugins:fir:fir-plugin-prototype:test"
":idea:idea-fir:test"
)
}
@@ -682,7 +589,7 @@ tasks {
register("scriptingTest") {
dependsOn("dist")
dependsOn(":kotlin-script-util:test")
dependsOn(":kotlin-scripting-compiler-embeddable:test")
dependsOn(":kotlin-scripting-compiler:test")
dependsOn(":kotlin-scripting-common:test")
dependsOn(":kotlin-scripting-jvm:test")
dependsOn(":kotlin-scripting-jvm-host-test:test")
@@ -693,32 +600,21 @@ tasks {
// dependsOn(":kotlin-scripting-jvm-host-test:embeddableTest")
dependsOn(":kotlin-scripting-jsr223-test:embeddableTest")
dependsOn(":kotlin-main-kts-test:test")
dependsOn(":kotlin-scripting-ide-services-test:test")
dependsOn(":kotlin-scripting-ide-services-test:embeddableTest")
dependsOn(":kotlin-scripting-js-test:test")
}
register("compilerTest") {
dependsOn("jvmCompilerTest")
dependsOn("jsCompilerTest")
dependsOn("miscCompilerTest")
}
register("miscCompilerTest") {
dependsOn("wasmCompilerTest")
dependsOn("nativeCompilerTest")
dependsOn("firCompilerTest")
dependsOn(":kotlin-daemon-tests:test")
dependsOn("scriptingTest")
dependsOn(":kotlin-build-common:test")
dependsOn(":compiler:incremental-compilation-impl:test")
dependsOn(":compiler:incremental-compilation-impl:testJvmICWithJdk11")
dependsOn(":core:descriptors.runtime:test")
dependsOn("jvmCompilerIntegrationTest")
dependsOn(":plugins:parcelize:parcelize-compiler:test")
}
register("toolsTest") {
@@ -754,9 +650,16 @@ tasks {
dependsOn(":jps-plugin:test")
}
register("idea-plugin-main-tests") {
dependsOn("dist")
dependsOn(":idea:test")
}
register("idea-plugin-additional-tests") {
dependsOn("dist")
dependsOn(
":idea:idea-gradle:test",
":idea:idea-gradle-native:test",
":idea:idea-maven:test",
":j2k:test",
":nj2k:test",
@@ -764,7 +667,8 @@ tasks {
":idea:jvm-debugger:jvm-debugger-evaluation:test",
":idea:jvm-debugger:jvm-debugger-sequence:test",
":idea:jvm-debugger:eval4j:test",
":idea:scripting-support:test"
":idea:scripting-support:test",
":idea:idea-fir:test"
)
}
@@ -779,6 +683,17 @@ tasks {
}
}
register("idea-plugin-tests") {
dependsOn("dist")
dependsOn(
"idea-plugin-main-tests",
"idea-plugin-additional-tests"
)
if (Ide.IJ()) {
dependsOn("idea-new-project-wizard-tests")
}
}
register("idea-plugin-performance-tests") {
dependsOn("dist")
dependsOn(
@@ -786,38 +701,20 @@ tasks {
)
}
register("idea-fir-plugin-performance-tests") {
dependsOn("dist")
dependsOn(
":idea:idea-fir-performance-tests:ideaFirPerformanceTest"
)
}
register("android-ide-tests") {
dependsOn("dist")
dependsOn(
":plugins:android-extensions-ide:test",
":idea:idea-android:test",
":kotlin-annotation-processing:test"
)
}
register("plugins-tests") {
dependsOn("dist")
dependsOn(
":kotlin-annotation-processing:test",
":plugins:parcelize:parcelize-ide:test"
)
}
register("ideaPluginTest") {
dependsOn(
"mainIdeTests",
"gradleIdeTest",
"kaptIdeTest",
"miscIdeTests"
)
}
register("mainIdeTests") {
dependsOn(":idea:test")
}
register("miscIdeTests") {
dependsOn(
":kotlin-source-sections-compiler-plugin:test",
":kotlin-allopen-compiler-plugin:test",
":kotlin-noarg-compiler-plugin:test",
":kotlin-sam-with-receiver-compiler-plugin:test",
@@ -825,41 +722,21 @@ tasks {
":kotlin-annotation-processing-gradle:test",
":kotlinx-serialization-compiler-plugin:test",
":kotlinx-serialization-ide-plugin:test",
":idea:jvm-debugger:jvm-debugger-test:test",
"idea-plugin-additional-tests",
":idea:jvm-debugger:jvm-debugger-test:test"
)
}
register("ideaPluginTest") {
dependsOn(
"idea-plugin-tests",
"jps-tests",
"plugins-tests",
"android-ide-tests",
":generators:test"
)
if (Ide.IJ()) {
dependsOn("idea-new-project-wizard-tests")
}
}
register("kaptIdeTest") {
dependsOn(":kotlin-annotation-processing:test")
}
register("gradleIdeTest") {
dependsOn(
":idea:idea-gradle:test",
":idea:idea-gradle-native:test"
)
}
register("kmmTest", AggregateTest::class) {
dependsOn(
":idea:idea-gradle:test",
":idea:test",
":compiler:test",
":js:js.tests:test"
)
if (Ide.IJ193.orHigher())
dependsOn(":kotlin-gradle-plugin-integration-tests:test")
if (Ide.AS40.orHigher())
dependsOn(":kotlin-ultimate:ide:android-studio-native:test")
testPatternFile = file("tests/mpp/kmm-patterns.csv")
}
register("test") {
doLast {
@@ -867,52 +744,9 @@ tasks {
}
}
named("check") {
register("check") {
dependsOn("test")
}
named("checkBuild") {
if (kotlinBuildProperties.isTeamcityBuild) {
doFirst {
println("##teamcity[setParameter name='bootstrap.kotlin.version' value='$bootstrapKotlinVersion']")
}
}
}
register("publishIdeArtifacts") {
idePluginDependency {
dependsOn(
":prepare:ide-plugin-dependencies:android-extensions-compiler-plugin-for-ide:publish",
":prepare:ide-plugin-dependencies:allopen-compiler-plugin-for-ide:publish",
":prepare:ide-plugin-dependencies:allopen-compiler-plugin-tests-for-ide:publish",
":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",
":prepare:ide-plugin-dependencies:sam-with-receiver-compiler-plugin-for-ide:publish",
":prepare:ide-plugin-dependencies:compiler-components-for-jps:publish",
":prepare:ide-plugin-dependencies:parcelize-compiler-plugin-for-ide:publish",
":kotlin-script-runtime:publish",
":kotlin-script-util:publish",
":kotlin-scripting-common:publish",
":kotlin-scripting-jvm:publish",
":kotlin-scripting-compiler:publish",
":kotlin-scripting-compiler-impl:publish",
":kotlin-android-extensions-runtime:publish",
":kotlin-stdlib-common:publish",
":kotlin-stdlib:publish",
":kotlin-stdlib-jdk7:publish",
":kotlin-stdlib-jdk8:publish",
":kotlin-reflect:publish",
":kotlin-main-kts:publish",
":kotlin-stdlib-js:publish",
":kotlin-test:kotlin-test-js:publish"
)
}
}
}
fun CopySpec.setExecutablePermissions() {
@@ -922,15 +756,15 @@ fun CopySpec.setExecutablePermissions() {
val zipCompiler by task<Zip> {
dependsOn(dist)
destinationDirectory.set(file(distDir))
archiveFileName.set("kotlin-compiler-$kotlinVersion.zip")
destinationDir = file(distDir)
archiveName = "kotlin-compiler-$kotlinVersion.zip"
from(distKotlinHomeDir)
into("kotlinc")
setExecutablePermissions()
doLast {
logger.lifecycle("Compiler artifacts packed to ${archiveFile.get().asFile.absolutePath}")
logger.lifecycle("Compiler artifacts packed to $archivePath")
}
}
@@ -968,45 +802,21 @@ val zipPlugin by task<Zip> {
}
val destPath = project.findProperty("pluginZipPath") as String?
val dest = File(destPath ?: "$buildDir/kotlin-plugin.zip")
destinationDirectory.set(dest.parentFile)
archiveFileName.set(dest.name)
destinationDir = dest.parentFile
archiveName = dest.name
doFirst {
if (destPath == null) throw GradleException("Specify target zip path with 'pluginZipPath' property")
}
from(src)
into("Kotlin")
setExecutablePermissions()
doLast {
logger.lifecycle("Plugin artifacts packed to ${archiveFile.get()}")
logger.lifecycle("Plugin artifacts packed to $archivePath")
}
}
fun Project.secureZipTask(zipTask: TaskProvider<Zip>): RegisteringDomainObjectDelegateProviderWithAction<out TaskContainer, Task> {
val checkSumTask = tasks.register("${zipTask.name}Checksum", Checksum::class) {
dependsOn(zipTask)
val compilerFile = zipTask.get().outputs.files.singleFile
files = files(compilerFile)
outputDir = compilerFile.parentFile
algorithm = Checksum.Algorithm.SHA256
}
val signTask = tasks.register("${zipTask.name}Sign", Sign::class) {
description = "Signs the archive produced by the '" + zipTask.name + "' task."
sign(zipTask.get())
}
return tasks.registering {
dependsOn(checkSumTask)
dependsOn(signTask)
}
}
signing {
useGpgCmd()
}
val zipCompilerWithSignature by secureZipTask(zipCompiler)
val zipPluginWithSignature by secureZipTask(zipPlugin)
configure<IdeaModel> {
module {
excludeDirs = files(
@@ -1134,15 +944,3 @@ val Jar.outputFile: File
val Project.sourceSetsOrNull: SourceSetContainer?
get() = convention.findPlugin(JavaPluginConvention::class.java)?.sourceSets
val disableVerificationTasks = System.getProperty("disable.verification.tasks") == "true"
if (disableVerificationTasks) {
gradle.taskGraph.whenReady {
allTasks.forEach {
if (it is VerificationTask) {
logger.info("DISABLED: '$it'")
it.enabled = false
}
}
}
}

View File

@@ -5,7 +5,8 @@ buildscript {
val cacheRedirectorEnabled = findProperty("cacheRedirectorEnabled")?.toString()?.toBoolean() == true
extra["defaultSnapshotVersion"] = kotlinBuildProperties.defaultSnapshotVersion
kotlinBootstrapFrom(BootstrapOption.SpaceBootstrap(kotlinBuildProperties.kotlinBootstrapVersion!!, cacheRedirectorEnabled))
BootstrapOption.BintrayBootstrap("1.4.0-dev-1818", cacheRedirectorEnabled).applyToProject(project)
// kotlinBootstrapFrom(BootstrapOption.BintrayBootstrap(kotlinBuildProperties.kotlinBootstrapVersion!!, cacheRedirectorEnabled))
repositories {
if (cacheRedirectorEnabled) {
@@ -22,7 +23,7 @@ buildscript {
}
dependencies {
classpath("org.jetbrains.kotlin:kotlin-build-gradle-plugin:0.0.20")
classpath("org.jetbrains.kotlin:kotlin-build-gradle-plugin:0.0.17")
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${project.bootstrapKotlinVersion}")
classpath("org.jetbrains.kotlin:kotlin-sam-with-receiver:${project.bootstrapKotlinVersion}")
}
@@ -55,10 +56,6 @@ gradlePlugin {
}
}
kotlinDslPluginOptions {
experimentalWarning.set(false)
}
fun Project.getBooleanProperty(name: String): Boolean? = this.findProperty(name)?.let {
val v = it.toString()
if (v.isBlank()) true
@@ -72,6 +69,7 @@ rootProject.apply {
val isTeamcityBuild = kotlinBuildProperties.isTeamcityBuild
val intellijUltimateEnabled by extra(kotlinBuildProperties.intellijUltimateEnabled)
val intellijSeparateSdks by extra(project.getBooleanProperty("intellijSeparateSdks") ?: false)
val verifyDependencyOutput by extra( getBooleanProperty("kotlin.build.dependency.output.verification") ?: isTeamcityBuild)
extra["intellijReleaseType"] = when {
extra["versions.intellijSdk"]?.toString()?.contains("-EAP-") == true -> "snapshots"
@@ -96,9 +94,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("com.gradle.publish:plugin-publish-plugin:0.11.0")
implementation("org.jetbrains.kotlin:kotlin-build-gradle-plugin:0.0.17")
implementation("net.rubygrapefruit:native-platform:${property("versions.native-platform")}")
implementation("net.rubygrapefruit:native-platform-windows-amd64:${property("versions.native-platform")}")
@@ -107,11 +103,9 @@ dependencies {
implementation("com.github.jengelman.gradle.plugins:shadow:${rootProject.extra["versions.shadow"]}")
implementation("net.sf.proguard:proguard-gradle:6.2.2")
implementation("org.jetbrains.intellij.deps:asm-all:8.0.1")
implementation("org.jetbrains.intellij.deps:asm-all:7.0.1")
implementation("gradle.plugin.org.jetbrains.gradle.plugin.idea-ext:gradle-idea-ext:0.5")
implementation("org.gradle:test-retry-gradle-plugin:1.1.9")
}
samWithReceiver {

View File

@@ -0,0 +1,8 @@
org.gradle.jvmargs=-Duser.country=US -Dkotlin.daemon.jvm.options=-Xmx1600m -Dfile.encoding=UTF-8
cacheRedirectorEnabled=true
#buildSrc.kotlin.repo=https://jcenter.bintray.com
#buildSrc.kotlin.version=1.1.50
intellijUltimateEnabled=false

View File

@@ -0,0 +1,8 @@
org.gradle.jvmargs=-Duser.country=US -Dkotlin.daemon.jvm.options=-Xmx1600m -Dfile.encoding=UTF-8
cacheRedirectorEnabled=true
#buildSrc.kotlin.repo=https://jcenter.bintray.com
#buildSrc.kotlin.version=1.1.50
intellijUltimateEnabled=false

View File

@@ -0,0 +1,8 @@
org.gradle.jvmargs=-Duser.country=US -Dkotlin.daemon.jvm.options=-Xmx1600m -Dfile.encoding=UTF-8
cacheRedirectorEnabled=true
#buildSrc.kotlin.repo=https://jcenter.bintray.com
#buildSrc.kotlin.version=1.1.50
intellijUltimateEnabled=false

View File

@@ -1,20 +1,22 @@
@file:Suppress("PropertyName", "HasPlatformType", "UnstableApiUsage")
import org.gradle.internal.os.OperatingSystem
import org.jetbrains.kotlin.gradle.tasks.internal.CleanableStore
import java.io.Closeable
import java.io.FileWriter
import java.io.OutputStreamWriter
import java.net.URI
import java.text.SimpleDateFormat
import java.time.Duration
import java.time.Instant
import java.util.*
import javax.xml.stream.XMLOutputFactory
import org.jetbrains.kotlin.gradle.tasks.internal.CleanableStore
import org.jetbrains.kotlin.gradle.tasks.CleanDataTask
plugins {
base
}
val verifyDependencyOutput: Boolean by rootProject.extra
val intellijUltimateEnabled: Boolean by rootProject.extra
val intellijReleaseType: String by rootProject.extra
val intellijVersion = rootProject.extra["versions.intellijSdk"] as String
@@ -23,7 +25,7 @@ val androidStudioRelease = rootProject.findProperty("versions.androidStudioRelea
val androidStudioBuild = rootProject.findProperty("versions.androidStudioBuild") as String?
val intellijSeparateSdks: Boolean by rootProject.extra
val installIntellijCommunity = !intellijUltimateEnabled || intellijSeparateSdks
val installIntellijUltimate = intellijUltimateEnabled && androidStudioRelease == null
val installIntellijUltimate = intellijUltimateEnabled
val intellijVersionDelimiterIndex = intellijVersion.indexOfAny(charArrayOf('.', '-'))
if (intellijVersionDelimiterIndex == -1) {
@@ -32,6 +34,7 @@ if (intellijVersionDelimiterIndex == -1) {
val platformBaseVersion = intellijVersion.substring(0, intellijVersionDelimiterIndex)
logger.info("verifyDependencyOutput: $verifyDependencyOutput")
logger.info("intellijUltimateEnabled: $intellijUltimateEnabled")
logger.info("intellijVersion: $intellijVersion")
logger.info("androidStudioRelease: $androidStudioRelease")
@@ -142,7 +145,21 @@ dependencies {
}
}
val makeIntellijCore = buildIvyRepositoryTask(intellijCore, customDepsOrg, customDepsRepoDir)
val cleanupIntellijCore = tasks.register<CleanDataTask>("cleanupIntellijCore") {
cleanableStoreProvider = provider { CleanableStore[repoDir.resolve("intellij-core").absolutePath] }
}
val cleanupIntellijAnnotation = tasks.register<CleanDataTask>("cleanupIntellijAnnotation") {
cleanableStoreProvider = provider { CleanableStore[repoDir.resolve(intellijRuntimeAnnotations).absolutePath] }
}
val cleanupDependencies = tasks.register("cleanupDependencies") {
dependsOn(cleanupIntellijCore)
dependsOn(cleanupIntellijAnnotation)
}
val makeIntellijCore = buildIvyRepositoryTaskAndRegisterCleanupTask(intellijCore, customDepsOrg, customDepsRepoDir)
val makeIntellijAnnotations by tasks.registering(Copy::class) {
dependsOn(makeIntellijCore)
@@ -150,17 +167,12 @@ val makeIntellijAnnotations by tasks.registering(Copy::class) {
val intellijCoreRepo = CleanableStore[repoDir.resolve("intellij-core").absolutePath][intellijVersion].use()
from(intellijCoreRepo.resolve("artifacts/annotations.jar"))
val annotationsStore = CleanableStore[repoDir.resolve(intellijRuntimeAnnotations).absolutePath]
val targetDir = annotationsStore[intellijVersion].use()
val targetDir = CleanableStore[repoDir.resolve(intellijRuntimeAnnotations).absolutePath][intellijVersion].use()
into(targetDir)
val ivyFile = File(targetDir, "$intellijRuntimeAnnotations.ivy.xml")
outputs.files(ivyFile)
doFirst {
annotationsStore.cleanStore()
}
doLast {
writeIvyXml(
customDepsOrg,
@@ -179,10 +191,7 @@ val mergeSources by tasks.creating(Jar::class.java) {
dependsOn(sources)
isPreserveFileTimestamps = false
isReproducibleFileOrder = true
isZip64 = true
if (!kotlinBuildProperties.isTeamcityBuild) {
from(provider { sources.map(::zipTree) })
}
from(provider { sources.map(::zipTree) })
destinationDirectory.set(File(repoDir, sources.name))
archiveBaseName.set("intellij")
archiveClassifier.set("sources")
@@ -192,7 +201,7 @@ val mergeSources by tasks.creating(Jar::class.java) {
val sourcesFile = mergeSources.outputs.files.singleFile
val makeIde = if (androidStudioBuild != null) {
buildIvyRepositoryTask(
buildIvyRepositoryTaskAndRegisterCleanupTask(
androidStudio,
customDepsOrg,
customDepsRepoDir,
@@ -203,9 +212,9 @@ val makeIde = if (androidStudioBuild != null) {
)
} else {
val task = if (installIntellijUltimate) {
buildIvyRepositoryTask(intellijUltimate, customDepsOrg, customDepsRepoDir, null, sourcesFile)
buildIvyRepositoryTaskAndRegisterCleanupTask(intellijUltimate, customDepsOrg, customDepsRepoDir, null, sourcesFile)
} else {
buildIvyRepositoryTask(intellij, customDepsOrg, customDepsRepoDir, null, sourcesFile)
buildIvyRepositoryTaskAndRegisterCleanupTask(intellij, customDepsOrg, customDepsRepoDir, null, sourcesFile)
}
task.configure {
@@ -215,7 +224,7 @@ val makeIde = if (androidStudioBuild != null) {
task
}
val buildJpsStandalone = buildIvyRepositoryTask(jpsStandalone, customDepsOrg, customDepsRepoDir, null, sourcesFile)
val buildJpsStandalone = buildIvyRepositoryTaskAndRegisterCleanupTask(jpsStandalone, customDepsOrg, customDepsRepoDir, null, sourcesFile)
tasks.named("build") {
dependsOn(
@@ -229,15 +238,24 @@ tasks.named("build") {
if (installIntellijUltimate) {
val buildNodeJsPlugin =
buildIvyRepositoryTask(nodeJSPlugin, customDepsOrg, customDepsRepoDir, ::skipToplevelDirectory, sourcesFile)
buildIvyRepositoryTaskAndRegisterCleanupTask(nodeJSPlugin, customDepsOrg, customDepsRepoDir, ::skipToplevelDirectory, sourcesFile)
tasks.named("build") { dependsOn(buildNodeJsPlugin) }
}
tasks.named("build") { dependsOn(cleanupDependencies) }
// Task to delete legacy repo locations
tasks.register<Delete>("cleanLegacy") {
delete("$projectDir/android-dx")
delete("$projectDir/intellij-sdk")
}
tasks.named<Delete>("clean") {
//TODO specify repos to clean? Use CleanDataTask
delete(customDepsRepoDir)
}
fun buildIvyRepositoryTask(
fun buildIvyRepositoryTaskAndRegisterCleanupTask(
configuration: Configuration,
organization: String,
repoDirectory: File,
@@ -250,29 +268,29 @@ fun buildIvyRepositoryTask(
fun ResolvedArtifact.moduleDirectory(): File =
storeDirectory()[moduleVersion.id.version].use()
return tasks.register("buildIvyRepositoryFor${configuration.name.capitalize()}") {
val buildIvyRepositoryTask = tasks.register("buildIvyRepositoryFor${configuration.name.capitalize()}") {
dependsOn(configuration)
inputs.files(configuration)
outputs.upToDateWhen {
val repoMarker = configuration.resolvedConfiguration.resolvedArtifacts.single().moduleDirectory().resolve(".marker")
repoMarker.exists()
if (verifyDependencyOutput) {
outputs.dir(
provider {
configuration.resolvedConfiguration.resolvedArtifacts.single().moduleDirectory()
}
)
} else {
outputs.upToDateWhen {
configuration.resolvedConfiguration.resolvedArtifacts.single()
.moduleDirectory()
.exists()
}
}
doFirst {
val artifact = configuration.resolvedConfiguration.resolvedArtifacts.single()
val moduleDirectory = artifact.moduleDirectory()
configuration.resolvedConfiguration.resolvedArtifacts.single().run {
val moduleDirectory = moduleDirectory()
val artifactsDirectory = File(moduleDirectory(), "artifacts")
artifact.storeDirectory().cleanStore()
val repoMarker = File(moduleDirectory, ".marker")
if (repoMarker.exists()) {
logger.info("Path ${repoMarker.absolutePath} already exists, skipping unpacking.")
return@doFirst
}
with(artifact) {
val artifactsDirectory = File(moduleDirectory, "artifacts")
logger.info("Unpacking ${file.name} into ${artifactsDirectory.absolutePath}")
copy {
val fileTree = when (extension) {
@@ -326,14 +344,22 @@ fun buildIvyRepositoryTask(
)
}
}
repoMarker.createNewFile()
}
}
}
}
fun CleanableStore.cleanStore() = cleanDir(Instant.now().minus(Duration.ofDays(30)))
val cleanupIvyRepositoryTask = tasks.register<CleanDataTask>("cleanupIvyRepositoryFor${configuration.name.capitalize()}") {
cleanableStoreProvider = provider {
configuration.resolvedConfiguration.resolvedArtifacts.single().storeDirectory()
}
}
cleanupDependencies {
dependsOn(cleanupIvyRepositoryTask)
}
return buildIvyRepositoryTask
}
fun writeIvyXml(
organization: String,
@@ -354,7 +380,7 @@ fun writeIvyXml(
val ivyFile = targetDir.resolve("$fileName.ivy.xml")
ivyFile.parentFile.mkdirs()
with(XMLWriter(ivyFile.writer())) {
with(XMLWriter(FileWriter(ivyFile))) {
document("UTF-8", "1.0") {
element("ivy-module") {
attribute("version", "2.0")

View File

@@ -20,13 +20,15 @@ buildscript {
}
}
dependencies {
classpath("org.jetbrains.kotlin:kotlin-build-gradle-plugin:0.0.20")
classpath("org.jetbrains.kotlin:kotlin-build-gradle-plugin:0.0.17")
}
}
def buildProperties = BuildPropertiesKt.getKotlinBuildPropertiesForSettings(settings)
def projectVersions = file("../gradle/versions.properties").text
BuildCacheKt.setupBuildCache(settings)
include "prepare-deps"
def target_AppCode_Clion = buildProperties.includeCidrPlugins && !projectVersions.contains("versions.androidStudioRelease")
@@ -46,12 +48,12 @@ if (target_AppCode_Clion) {
} else if (target_AndroidStudio) {
logger.info("Including modules for AS (mobile plugin) in buildSrc/settings.gradle")
include ":prepare-deps:appcode-binaries"
include ":prepare-deps:cocoa-common-binaries"
include ":prepare-deps:lldb-framework"
include ":prepare-deps:lldb-frontend"
project(":prepare-deps:appcode-binaries").projectDir =
file("${buildProperties.propertiesProvider.rootProjectDir}/kotlin-ultimate/buildSrc/prepare-deps/appcode-binaries")
project(":prepare-deps:cocoa-common-binaries").projectDir =
file("${buildProperties.propertiesProvider.rootProjectDir}/kotlin-ultimate/buildSrc/prepare-deps/cocoa-common-binaries")
project(":prepare-deps:lldb-framework").projectDir =
file("${buildProperties.propertiesProvider.rootProjectDir}/kotlin-ultimate/buildSrc/prepare-deps/lldb-framework")
project(":prepare-deps:lldb-frontend").projectDir =
@@ -69,4 +71,4 @@ if (target_AppCode_Clion) {
} else {
logger.info("Not including extra modules in buildSrc/settings.gradle")
}
}

View File

@@ -1,72 +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.
*/
import org.gradle.api.GradleException
import org.gradle.api.tasks.*
import org.gradle.api.tasks.testing.Test
import java.io.File
// You can see "How To" via link: https://jetbrains.quip.com/xQ2WAUy9bZmy/How-to-use-AggregateTest-task
open class AggregateTest : Test() { // Inherit from Test to see test results in IDEA Test viewer
private var patterns: MutableMap<String, MutableList<String>> = mutableMapOf()
@InputFile
lateinit var testPatternFile: File
init {
// Set empty FileCollection to avoid NPE when initializing a base 'Test' class
classpath = project.objects.fileCollection()
testClassesDirs = project.objects.fileCollection()
project.gradle.taskGraph.whenReady {
if (allTasks.filterIsInstance<AggregateTest>().isNotEmpty()) {
initPatterns()
allTasks.filterIsInstance<Test>().forEach { testTask -> subTaskConfigure(testTask) }
if (!project.gradle.startParameter.taskNames.all { project.tasks.findByPath(it) is AggregateTest }) {
logger.warn("Please, don't use AggregateTest and non-AggregateTest test tasks together. You can get incorrect results.")
}
}
}
}
private fun initPatterns() {
if (!testPatternFile.exists())
throw GradleException("File with test patterns is not found")
testPatternFile
.readLines()
.asSequence()
.filter { it.isNotEmpty() }
.forEach { line ->
// patternType is exclude or include value
val (pattern, patternType) = line.split(',').map { it.trim() }
patterns.getOrPut(patternType) { mutableListOf() }.add(pattern)
}
}
private fun subTaskConfigure(testTask: Test) {
testTask.outputs.upToDateWhen { false }
testTask.ignoreFailures = true
testTask.filter {
isFailOnNoMatchingTests = false
patterns["include"]?.let {
it.forEach { pattern ->
includeTestsMatching(pattern)
}
}
patterns["exclude"]?.let {
it.forEach { pattern ->
excludeTestsMatching(pattern)
}
}
}
}
@Override
@TaskAction
override fun executeTests() {
// Do nothing
}
}

View File

@@ -15,6 +15,4 @@ val KotlinBuildProperties.relocation: Boolean get() = postProcessing
val KotlinBuildProperties.proguard: Boolean get() = postProcessing && getBoolean("kotlin.build.proguard", isTeamcityBuild)
val KotlinBuildProperties.jarCompression: Boolean get() = getBoolean("kotlin.build.jar.compression", isTeamcityBuild)
val KotlinBuildProperties.ignoreTestFailures: Boolean get() = getBoolean("ignoreTestFailures", isTeamcityBuild)
val KotlinBuildProperties.jarCompression: Boolean get() = getBoolean("kotlin.build.jar.compression", isTeamcityBuild)

View File

@@ -56,7 +56,7 @@ var Project.javaHome: String?
fun Project.generator(fqName: String, sourceSet: SourceSet? = null) = smartJavaExec {
classpath = (sourceSet ?: testSourceSet).runtimeClasspath
mainClass.set(fqName)
main = fqName
workingDir = rootDir
systemProperty("line.separator", "\n")
}

View File

@@ -26,7 +26,7 @@ fun CompatibilityPredicate.or(other: CompatibilityPredicate): CompatibilityPredi
}
enum class Platform : CompatibilityPredicate {
P183, P191, P192, P193, P201, P202, P203;
P183, P191, P192, P193, P201;
val version: Int = name.drop(1).toInt()
@@ -47,14 +47,10 @@ enum class Ide(val platform: Platform) : CompatibilityPredicate {
IJ192(Platform.P192),
IJ193(Platform.P193),
IJ201(Platform.P201),
IJ202(Platform.P202),
IJ203(Platform.P203),
AS35(Platform.P183),
AS36(Platform.P192),
AS40(Platform.P193),
AS41(Platform.P201),
AS42(Platform.P202);
AS40(Platform.P193);
val kind = Kind.values().first { it.shortName == name.take(2) }
val version = name.dropWhile { !it.isDigit() }.toInt()

View File

@@ -23,10 +23,6 @@ fun JavaExec.passClasspathInJar() {
dependsOn(classpath)
inputs.files(classpath)
inputs.property("main", main)
archiveFileName.set("$main.${this@passClasspathInJar.name}.classpath.container.jar")
destinationDirectory.set(temporaryDir)
doFirst {
val classPathString = classpath.joinToString(" ") { project.file(it).toURI().toString() }
manifest {
@@ -38,11 +34,16 @@ fun JavaExec.passClasspathInJar() {
)
}
}
archiveName = "$main.${this@passClasspathInJar.name}.classpath.container.$extension"
destinationDir = temporaryDir
}
dependsOn(jarTask)
main = "-jar"
classpath = project.files()
args = listOf(jarTask.outputs.files.singleFile.path) + args.orEmpty()
doFirst {
main = "-jar"
classpath = project.files()
args = listOf(jarTask.outputs.files.singleFile.path) + args.orEmpty()
}
}

View File

@@ -6,29 +6,14 @@ import org.gradle.api.Task
import org.gradle.api.artifacts.ConfigurablePublishArtifact
import org.gradle.api.artifacts.Configuration
import org.gradle.api.artifacts.ConfigurationContainer
import org.gradle.api.artifacts.PublishArtifact
import org.gradle.api.artifacts.component.ProjectComponentIdentifier
import org.gradle.api.attributes.Bundling
import org.gradle.api.attributes.Category
import org.gradle.api.attributes.LibraryElements
import org.gradle.api.attributes.Usage
import org.gradle.api.component.AdhocComponentWithVariants
import org.gradle.api.file.DuplicatesStrategy
import org.gradle.api.plugins.BasePluginConvention
import org.gradle.api.plugins.JavaPlugin
import org.gradle.api.plugins.JavaPlugin.*
import org.gradle.api.plugins.JavaPluginExtension
import org.gradle.api.publish.PublishingExtension
import org.gradle.api.publish.maven.MavenPublication
import org.gradle.api.publish.tasks.GenerateModuleMetadata
import org.gradle.api.tasks.TaskProvider
import org.gradle.api.tasks.Upload
import org.gradle.api.tasks.javadoc.Javadoc
import org.gradle.jvm.tasks.Jar
import org.gradle.api.artifacts.dsl.DependencyHandler
import org.gradle.kotlin.dsl.*
import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSetContainer
import plugins.KotlinBuildPublishingPlugin
private const val MAGIC_DO_NOT_CHANGE_TEST_JAR_TASK_NAME = "testJar"
@@ -41,7 +26,7 @@ fun Project.testsJar(body: Jar.() -> Unit = {}): Jar {
pluginManager.withPlugin("java") {
from(testSourceSet.output)
}
archiveClassifier.set("tests")
classifier = "tests"
body()
project.addArtifact(testsJarCfg, this, this)
}
@@ -71,26 +56,20 @@ fun Project.noDefaultJar() {
}
}
fun <T : Task> Project.runtimeJarArtifactBy(
task: TaskProvider<T>,
artifactRef: Any,
body: ConfigurablePublishArtifact.() -> Unit = {}
) {
fun Project.runtimeJarArtifactBy(task: Task, artifactRef: Any, body: ConfigurablePublishArtifact.() -> Unit = {}) {
addArtifact("archives", task, artifactRef, body)
addArtifact("runtimeJar", task, artifactRef, body)
configurations.findByName("runtime")?.let {
addArtifact(it.name, task, artifactRef, body)
addArtifact(it, task, artifactRef, body)
}
}
fun Project.runtimeJar(body: Jar.() -> Unit = {}): TaskProvider<Jar> = runtimeJar(getOrCreateTask("jar", body)) { }
fun Project.runtimeJar(body: Jar.() -> Unit = {}): TaskProvider<Jar> = runtimeJar(getOrCreateTask("jar", body), { })
fun <T : Jar> Project.runtimeJar(task: TaskProvider<T>, body: T.() -> Unit = {}): TaskProvider<T> {
tasks.named<Jar>("jar").configure {
removeArtifacts(configurations.getOrCreate("archives"), this)
}
task.configure {
configurations.findByName("embedded")?.let { embedded ->
dependsOn(embedded)
@@ -99,47 +78,19 @@ fun <T : Jar> Project.runtimeJar(task: TaskProvider<T>, body: T.() -> Unit = {})
}
}
setupPublicJar(project.the<BasePluginConvention>().archivesBaseName)
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
setDuplicatesStrategy(DuplicatesStrategy.EXCLUDE)
body()
project.runtimeJarArtifactBy(this, this)
}
project.runtimeJarArtifactBy(task, task)
val runtimeJar = configurations.maybeCreate("runtimeJar").apply {
isCanBeConsumed = true
isCanBeResolved = false
attributes {
attribute(Category.CATEGORY_ATTRIBUTE, objects.named(Category.LIBRARY))
attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage.JAVA_RUNTIME))
attribute(Bundling.BUNDLING_ATTRIBUTE, objects.named(Bundling.EXTERNAL))
attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, objects.named(LibraryElements.JAR))
}
}
configurePublishedComponent {
withVariantsFromConfiguration(configurations[RUNTIME_ELEMENTS_CONFIGURATION_NAME]) { skip() }
addVariantsFromConfiguration(runtimeJar) { }
}
return task
}
fun Project.sourcesJar(body: Jar.() -> Unit = {}): TaskProvider<Jar> {
configure<JavaPluginExtension> {
withSourcesJar()
}
val sourcesJar = getOrCreateTask<Jar>("sourcesJar") {
fun Project.mainJavaPluginSourceSet() = findJavaPluginConvention()?.sourceSets?.findByName("main")
fun Project.mainKotlinSourceSet() =
(extensions.findByName("kotlin") as? KotlinSourceSetContainer)?.sourceSets?.findByName("main")
fun Project.sources() = mainJavaPluginSourceSet()?.allSource ?: mainKotlinSourceSet()?.kotlin
val task = tasks.register<Jar>("sourcesJar") {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
archiveClassifier.set("sources")
from(project.sources())
from(project.mainSourceSet.allSource)
project.configurations.findByName("embedded")?.let { embedded ->
from(provider {
@@ -148,7 +99,10 @@ fun Project.sourcesJar(body: Jar.() -> Unit = {}): TaskProvider<Jar> {
.map { it.id.componentIdentifier }
.filterIsInstance<ProjectComponentIdentifier>()
.mapNotNull {
project(it.projectPath).sources()
project(it.projectPath)
.findJavaPluginConvention()
?.mainSourceSet
?.allSource
}
})
}
@@ -156,21 +110,13 @@ fun Project.sourcesJar(body: Jar.() -> Unit = {}): TaskProvider<Jar> {
body()
}
addArtifact("archives", sourcesJar)
addArtifact("sources", sourcesJar)
addArtifact("archives", task)
addArtifact("sources", task)
configurePublishedComponent {
addVariantsFromConfiguration(configurations[SOURCES_ELEMENTS_CONFIGURATION_NAME]) { }
}
return sourcesJar
return task
}
fun Project.javadocJar(body: Jar.() -> Unit = {}): TaskProvider<Jar> {
configure<JavaPluginExtension> {
withJavadocJar()
}
val javadocTask = getOrCreateTask<Jar>("javadocJar") {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
archiveClassifier.set("javadoc")
@@ -182,40 +128,9 @@ fun Project.javadocJar(body: Jar.() -> Unit = {}): TaskProvider<Jar> {
}
addArtifact("archives", javadocTask)
configurePublishedComponent {
addVariantsFromConfiguration(configurations[JAVADOC_ELEMENTS_CONFIGURATION_NAME]) { }
}
return javadocTask
}
fun Project.modularJar(body: Jar.() -> Unit): TaskProvider<Jar> {
val modularJar = configurations.maybeCreate("modularJar").apply {
isCanBeConsumed = true
isCanBeResolved = false
attributes {
attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage.JAVA_RUNTIME))
attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, objects.named("modular-jar"))
}
}
val modularJarTask = getOrCreateTask<Jar>("modularJar") {
archiveClassifier.set("modular")
body()
}
addArtifact("modularJar", modularJarTask)
addArtifact("archives", modularJarTask)
configurePublishedComponent {
addVariantsFromConfiguration(modularJar) { mapToMavenScope("runtime") }
}
return modularJarTask
}
fun Project.standardPublicJars() {
runtimeJar()
@@ -223,22 +138,7 @@ fun Project.standardPublicJars() {
javadocJar()
}
fun Project.publish(moduleMetadata: Boolean = false, configure: MavenPublication.() -> Unit = { }) {
apply<KotlinBuildPublishingPlugin>()
if (!moduleMetadata) {
tasks.withType<GenerateModuleMetadata> {
enabled = false
}
}
val publication = extensions.findByType<PublishingExtension>()
?.publications
?.findByName(KotlinBuildPublishingPlugin.PUBLICATION_NAME) as MavenPublication
publication.configure()
}
fun Project.publishWithLegacyMavenPlugin(body: Upload.() -> Unit = {}): Upload {
fun Project.publish(body: Upload.() -> Unit = {}): Upload {
apply<plugins.PublishedKotlinModule>()
if (artifactsRemovedDiagnosticFlag) {
@@ -255,87 +155,12 @@ fun Project.publishWithLegacyMavenPlugin(body: Upload.() -> Unit = {}): Upload {
}
}
fun Project.idePluginDependency(block: () -> Unit) {
val shouldActivate = rootProject.findProperty("publish.ide.plugin.dependencies")?.toString()?.toBoolean() == true
if (shouldActivate) {
block()
}
}
fun Project.publishProjectJars(projects: List<String>, libraryDependencies: List<String> = emptyList()) {
apply<JavaPlugin>()
val fatJarContents by configurations.creating
dependencies {
for (projectName in projects) {
fatJarContents(project(projectName)) { isTransitive = false }
}
for (libraryDependency in libraryDependencies) {
fatJarContents(libraryDependency)
}
}
publish()
val jar: Jar by tasks
jar.apply {
dependsOn(fatJarContents)
from {
fatJarContents.map(::zipTree)
}
}
sourcesJar {
from {
projects.map {
project(it).mainSourceSet.allSource
}
}
}
javadocJar()
}
fun Project.publishTestJar(projectName: String) {
apply<JavaPlugin>()
val fatJarContents by configurations.creating
dependencies {
fatJarContents(project(projectName, configuration = "tests-jar")) { isTransitive = false }
}
publish()
val jar: Jar by tasks
jar.apply {
dependsOn(fatJarContents)
from {
fatJarContents.map(::zipTree)
}
}
sourcesJar {
from {
project(projectName).testSourceSet.allSource
}
}
javadocJar()
}
fun ConfigurationContainer.getOrCreate(name: String): Configuration = findByName(name) ?: create(name)
fun Jar.setupPublicJar(baseName: String, classifier: String = "") {
val buildNumber = project.rootProject.extra["buildNumber"] as String
this.archiveBaseName.set(baseName)
this.archiveClassifier.set(classifier)
this.baseName = baseName
this.classifier = classifier
manifest.attributes.apply {
put("Implementation-Vendor", "JetBrains")
put("Implementation-Title", baseName)
@@ -354,26 +179,9 @@ fun Project.addArtifact(configuration: Configuration, task: Task, artifactRef: A
fun Project.addArtifact(configurationName: String, task: Task, artifactRef: Any, body: ConfigurablePublishArtifact.() -> Unit = {}) =
addArtifact(configurations.getOrCreate(configurationName), task, artifactRef, body)
fun <T : Task> Project.addArtifact(
configurationName: String,
task: TaskProvider<T>,
body: ConfigurablePublishArtifact.() -> Unit = {}
): PublishArtifact {
fun <T : Task> Project.addArtifact(configurationName: String, task: TaskProvider<T>, body: ConfigurablePublishArtifact.() -> Unit = {}) {
configurations.maybeCreate(configurationName)
return artifacts.add(configurationName, task, body)
}
fun <T : Task> Project.addArtifact(
configurationName: String,
task: TaskProvider<T>,
artifactRef: Any,
body: ConfigurablePublishArtifact.() -> Unit = {}
): PublishArtifact {
configurations.maybeCreate(configurationName)
return artifacts.add(configurationName, artifactRef) {
builtBy(task)
body()
}
artifacts.add(configurationName, task, body)
}
fun Project.cleanArtifacts() {
@@ -383,6 +191,3 @@ fun Project.cleanArtifacts() {
}
}
}
fun Project.configurePublishedComponent(configure: AdhocComponentWithVariants.() -> Unit) =
(components.findByName(KotlinBuildPublishingPlugin.ADHOC_COMPONENT_NAME) as AdhocComponentWithVariants?)?.apply(configure)

View File

@@ -1,8 +1,3 @@
/*
* 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.
*/
@file:Suppress("unused")
// usages in build scripts are not tracked properly
@@ -27,15 +22,6 @@ val Project.intellijRepo get() =
else -> "https://www.jetbrains.com/intellij-repository/releases"
}
val Project.internalBootstrapRepo: String? get() =
when {
bootstrapKotlinRepo?.startsWith("https://buildserver.labs.intellij.net") == true ->
bootstrapKotlinRepo!!.replace("artifacts/content/maven", "artifacts/content/internal/repo")
else -> "https://teamcity.jetbrains.com/guestAuth/app/rest/builds/buildType:(id:Kotlin_KotlinPublic_Compiler),number:$bootstrapKotlinVersion," +
"branch:default:any/artifacts/content/internal/repo/"
}
fun Project.commonDep(coord: String): String {
val parts = coord.split(':')
return when (parts.size) {
@@ -102,11 +88,9 @@ fun Project.kotlinStdlib(suffix: String? = null, classifier: String? = null): An
dependencies.project(listOfNotNull(":kotlin-stdlib", suffix).joinToString("-"), classifier)
}
fun Project.kotlinBuiltins(): Any = kotlinBuiltins(forJvm = false)
fun Project.kotlinBuiltins(forJvm: Boolean): Any =
fun Project.kotlinBuiltins(): Any =
if (kotlinBuildProperties.useBootstrapStdlib) "org.jetbrains.kotlin:builtins:$bootstrapKotlinVersion"
else dependencies.project(":core:builtins", configuration = "runtimeElementsJvm".takeIf { forJvm })
else dependencies.project(":core:builtins")
fun DependencyHandler.projectTests(name: String): ProjectDependency = project(name, configuration = "tests-jar")
fun DependencyHandler.projectRuntimeJar(name: String): ProjectDependency = project(name, configuration = "runtimeJar")

View File

@@ -11,19 +11,17 @@ import java.io.File
val kotlinEmbeddableRootPackage = "org.jetbrains.kotlin"
val packagesToRelocate =
listOf(
"com.intellij",
"com.google",
"com.sampullara",
"org.apache",
"org.jdom",
"org.picocontainer",
"org.jline",
"org.fusesource",
"net.jpountz",
"one.util.streamex",
"kotlinx.collections.immutable"
)
listOf( "com.intellij",
"com.google",
"com.sampullara",
"org.apache",
"org.jdom",
"org.picocontainer",
"org.jline",
"org.fusesource",
"kotlinx.coroutines",
"net.jpountz",
"one.util.streamex")
// The shaded compiler "dummy" is used to rewrite dependencies in projects that are used with the embeddable compiler
// on the runtime and use some shaded dependencies from the compiler

View File

@@ -80,8 +80,6 @@ fun Project.androidDxJar() = "org.jetbrains.kotlin:android-dx:${rootProject.extr
fun Project.jpsBuildTest() = "com.jetbrains.intellij.idea:jps-build-test:${rootProject.extra["versions.intellijSdk"]}"
fun Project.kotlinxCollectionsImmutable() = "org.jetbrains.kotlinx:kotlinx-collections-immutable-jvm:${rootProject.extra["versions.kotlinx-collections-immutable"]}"
/**
* Runtime version of annotations that are already in Kotlin stdlib (historically Kotlin has older version of this one).
*
@@ -167,7 +165,7 @@ fun Project.runIdeTask(name: String, ideaPluginDir: File, ideaSandboxDir: File,
classpath = mainSourceSet.runtimeClasspath
mainClass.set("com.intellij.idea.Main")
main = "com.intellij.idea.Main"
workingDir = File(intellijRootDir(), "bin")
@@ -179,15 +177,13 @@ fun Project.runIdeTask(name: String, ideaPluginDir: File, ideaSandboxDir: File,
"-Didea.debug.mode=true",
"-Didea.system.path=$ideaSandboxDir",
"-Didea.config.path=$ideaSandboxConfigDir",
"-Didea.tooling.debug=true",
"-Dfus.internal.test.mode=true",
"-Dapple.laf.useScreenMenuBar=true",
"-Dapple.awt.graphics.UseQuartz=true",
"-Dsun.io.useCanonCaches=false",
"-Dplugin.path=${ideaPluginDir.absolutePath}"
)
if (Platform[201].orHigher() && !isIntellijUltimateSdkAvailable()) {
if (Platform[201].orHigher()) {
jvmArgs("-Didea.platform.prefix=Idea")
}

View File

@@ -1,76 +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.
*/
import com.gradle.publish.PluginBundleExtension
import com.gradle.publish.PluginConfig
import org.gradle.api.Project
import org.gradle.api.publish.PublicationContainer
import org.gradle.api.publish.PublishingExtension
import org.gradle.api.publish.maven.MavenPublication
import org.gradle.api.publish.maven.tasks.PublishToMavenRepository
import org.gradle.api.tasks.bundling.Jar
import org.gradle.kotlin.dsl.*
import plugins.KotlinBuildPublishingPlugin
import plugins.configureRepository
import java.util.*
internal const val PLUGIN_MARKER_SUFFIX = ".gradle.plugin"
@UseExperimental(ExperimentalStdlibApi::class)
fun Project.publishPluginMarkers(withEmptyJars: Boolean = true) {
val pluginDevelopment = extensions.getByType<PluginBundleExtension>()
val publishingExtension = extensions.getByType<PublishingExtension>()
val mainPublication = publishingExtension.publications[KotlinBuildPublishingPlugin.PUBLICATION_NAME] as MavenPublication
pluginDevelopment.plugins.forEach { declaration ->
val markerPublication = createMavenMarkerPublication(declaration, mainPublication, publishingExtension.publications)
if (withEmptyJars) {
addEmptyJarArtifacts(markerPublication)
}
tasks.named<PublishToMavenRepository>(
"publish${markerPublication.name.capitalize(Locale.ROOT)}PublicationTo${KotlinBuildPublishingPlugin.REPOSITORY_NAME}Repository"
).configureRepository()
}
}
fun Project.addEmptyJarArtifacts(publication: MavenPublication) {
val emptyJar = getOrCreateTask<Jar>("emptyJar") {
archiveBaseName.set("empty")
}
publication.artifact(emptyJar.get()) { }
publication.artifact(emptyJar.get()) { classifier = "sources" }
publication.artifact(emptyJar.get()) { classifier = "javadoc" }
}
// Based on code from `java-gradle-plugin`
// https://github.com/gradle/gradle/blob/v6.4.0/subprojects/plugin-development/src/main/java/org/gradle/plugin/devel/plugins/MavenPluginPublishPlugin.java#L84
private fun createMavenMarkerPublication(
declaration: PluginConfig,
coordinates: MavenPublication,
publications: PublicationContainer
): MavenPublication {
return publications.create<MavenPublication>(declaration.name.toString() + "PluginMarkerMaven") {
val pluginId: String = declaration.id
artifactId = pluginId + PLUGIN_MARKER_SUFFIX
groupId = pluginId
pom.withXml {
val root = asElement()
val document = root.ownerDocument
val dependencies = root.appendChild(document.createElement("dependencies"))
val dependency = dependencies.appendChild(document.createElement("dependency"))
val groupId = dependency.appendChild(document.createElement("groupId"))
groupId.textContent = coordinates.groupId
val artifactId = dependency.appendChild(document.createElement("artifactId"))
artifactId.textContent = coordinates.artifactId
val version = dependency.appendChild(document.createElement("version"))
version.textContent = coordinates.version
}
pom.name.set(declaration.displayName)
pom.description.set(declaration.description)
}
}

View File

@@ -1,160 +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 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
import org.gradle.api.publish.maven.MavenPublication
import org.gradle.api.publish.maven.plugins.MavenPublishPlugin
import org.gradle.api.publish.maven.tasks.PublishToMavenRepository
import org.gradle.api.tasks.TaskProvider
import org.gradle.kotlin.dsl.*
import org.gradle.plugins.signing.SigningExtension
import org.gradle.plugins.signing.SigningPlugin
import java.net.URI
import java.util.*
import javax.inject.Inject
class KotlinBuildPublishingPlugin @Inject constructor(
private val componentFactory: SoftwareComponentFactory
) : Plugin<Project> {
override fun apply(target: Project): Unit = with(target) {
apply<MavenPublishPlugin>()
apply<SigningPlugin>()
val publishedRuntime = configurations.maybeCreate(RUNTIME_CONFIGURATION).apply {
isCanBeConsumed = false
isCanBeResolved = false
attributes {
attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage.JAVA_RUNTIME))
}
}
val publishedCompile = configurations.maybeCreate(COMPILE_CONFIGURATION).apply {
isCanBeConsumed = false
isCanBeResolved = false
attributes {
attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage.JAVA_API))
}
}
val kotlinLibraryComponent = componentFactory.adhoc(ADHOC_COMPONENT_NAME) as AdhocComponentWithVariants
components.add(kotlinLibraryComponent)
kotlinLibraryComponent.addVariantsFromConfiguration(publishedCompile) { mapToMavenScope("compile") }
kotlinLibraryComponent.addVariantsFromConfiguration(publishedRuntime) { mapToMavenScope("runtime") }
pluginManager.withPlugin("java-base") {
val runtimeElements by configurations
val apiElements by configurations
publishedRuntime.extendsFrom(runtimeElements)
publishedCompile.extendsFrom(apiElements)
kotlinLibraryComponent.addVariantsFromConfiguration(runtimeElements) {
mapToMavenScope("runtime")
if (configurationVariant.artifacts.any { JavaBasePlugin.UNPUBLISHABLE_VARIANT_ARTIFACTS.contains(it.type) }) {
skip()
}
}
}
configure<PublishingExtension> {
publications {
create<MavenPublication>(PUBLICATION_NAME) {
from(kotlinLibraryComponent)
pom {
packaging = "jar"
name.set(humanReadableName(project))
description.set(project.description ?: humanReadableName(project))
url.set("https://kotlinlang.org/")
licenses {
license {
name.set("The Apache License, Version 2.0")
url.set("http://www.apache.org/licenses/LICENSE-2.0.txt")
}
}
scm {
url.set("https://github.com/JetBrains/kotlin")
connection.set("scm:git:https://github.com/JetBrains/kotlin.git")
developerConnection.set("scm:git:https://github.com/JetBrains/kotlin.git")
}
developers {
developer {
name.set("Kotlin Team")
organization.set("JetBrains")
organizationUrl.set("https://www.jetbrains.com")
}
}
}
}
}
repositories {
maven {
name = REPOSITORY_NAME
url = file("${project.rootDir}/build/repo").toURI()
}
}
}
configure<SigningExtension> {
setRequired(provider {
project.findProperty("signingRequired")?.toString()?.toBoolean()
?: project.property("isSonatypeRelease") as Boolean
})
sign(extensions.getByType<PublishingExtension>().publications[PUBLICATION_NAME])
}
tasks.register("install") {
dependsOn(tasks.named("publishToMavenLocal"))
}
tasks.named<PublishToMavenRepository>("publish${PUBLICATION_NAME}PublicationTo${REPOSITORY_NAME}Repository")
.configureRepository()
}
companion object {
const val PUBLICATION_NAME = "Main"
const val REPOSITORY_NAME = "Maven"
const val ADHOC_COMPONENT_NAME = "kotlinLibrary"
const val COMPILE_CONFIGURATION = "publishedCompile"
const val RUNTIME_CONFIGURATION = "publishedRuntime"
@UseExperimental(ExperimentalStdlibApi::class)
fun humanReadableName(project: Project) =
project.name.split("-").joinToString(separator = " ") { it.capitalize(Locale.ROOT) }
}
}
fun TaskProvider<PublishToMavenRepository>.configureRepository() = configure {
dependsOn(project.rootProject.tasks.named("preparePublication"))
doFirst {
val preparePublication = project.rootProject.tasks.named("preparePublication").get()
val username: String? by preparePublication.extra
val password: String? by preparePublication.extra
val repoUrl: String by preparePublication.extra
repository.apply {
url = project.uri(repoUrl)
if (url.scheme != "file" && username != null && password != null) {
credentials {
this.username = username
this.password = password
}
}
}
}
}

View File

@@ -31,18 +31,12 @@ open class PublishedKotlinModule : Plugin<Project> {
plugins.apply("maven")
configurations.maybeCreate("publishedRuntime").apply {
val publishedRuntime by configurations.creating {
the<MavenPluginConvention>()
.conf2ScopeMappings
.addMapping(0, this, Conf2ScopeMappingContainer.RUNTIME)
}
configurations.maybeCreate("publishedCompile").apply {
the<MavenPluginConvention>()
.conf2ScopeMappings
.addMapping(0, this, Conf2ScopeMappingContainer.COMPILE)
}
if (!project.hasProperty("prebuiltJar")) {
plugins.apply("signing")
@@ -52,7 +46,6 @@ open class PublishedKotlinModule : Plugin<Project> {
configure<SigningExtension> {
isRequired = signingRequired
sign(configurations["archives"])
useGpgCmd()
}
tasks.named<Sign>("signArchives").configure {

View File

@@ -23,15 +23,3 @@ fun DependencyHandler.publishedRuntime(
): ExternalModuleDependency =
addDependencyTo(this, "publishedRuntime", dependencyNotation, dependencyConfiguration)
val NamedDomainObjectContainer<Configuration>.publishedCompile: NamedDomainObjectProvider<Configuration> get() = named("publishedCompile")
fun DependencyHandler.publishedCompile(dependencyNotation: Any): Dependency? =
add("publishedCompile", dependencyNotation)
fun DependencyHandler.publishedCompile(
dependencyNotation: String,
dependencyConfiguration: Action<ExternalModuleDependency>
): ExternalModuleDependency =
addDependencyTo(this, "publishedCompile", dependencyNotation, dependencyConfiguration)

View File

@@ -31,47 +31,6 @@ import java.lang.Character.isUpperCase
import java.nio.file.Files
import java.nio.file.Path
fun Task.dependsOnKotlinPluginInstall() {
dependsOn(
":kotlin-allopen:install",
":kotlin-noarg:install",
":kotlin-sam-with-receiver:install",
":kotlin-android-extensions:install",
":kotlin-parcelize-compiler:install",
":kotlin-build-common:install",
":kotlin-compiler-embeddable:install",
":native:kotlin-native-utils:install",
":kotlin-util-klib:install",
":kotlin-util-io:install",
":kotlin-compiler-runner:install",
":kotlin-daemon-embeddable:install",
":kotlin-daemon-client:install",
":kotlin-gradle-plugin-api:install",
":kotlin-gradle-plugin:install",
":kotlin-gradle-plugin-model:install",
":kotlin-reflect:install",
":kotlin-annotation-processing-gradle:install",
":kotlin-test:kotlin-test-common:install",
":kotlin-test:kotlin-test-annotations-common:install",
":kotlin-test:kotlin-test-jvm:install",
":kotlin-test:kotlin-test-js:install",
":kotlin-test:kotlin-test-junit:install",
":kotlin-gradle-subplugin-example:install",
":kotlin-stdlib-common:install",
":kotlin-stdlib:install",
":kotlin-stdlib-jdk8:install",
":kotlin-stdlib-js:install",
":examples:annotation-processor-example:install",
":kotlin-script-runtime:install",
":kotlin-scripting-common:install",
":kotlin-scripting-jvm:install",
":kotlin-scripting-compiler-embeddable:install",
":kotlin-scripting-compiler-impl-embeddable:install",
":kotlin-test-js-runner:install",
":native:kotlin-klib-commonizer-embeddable:install"
)
}
fun Project.projectTest(
taskName: String = "test",
parallel: Boolean = false,
@@ -120,20 +79,21 @@ fun Project.projectTest(
}
}
if (project.findProperty("kotlin.test.instrumentation.disable")?.toString()?.toBoolean() != true) {
doFirst {
val agent = tasks.findByPath(":test-instrumenter:jar")!!.outputs.files.singleFile
val args = project.findProperty("kotlin.test.instrumentation.args")?.let { "=$it" }.orEmpty()
jvmArgs("-javaagent:$agent$args")
}
dependsOn(":test-instrumenter:jar")
doFirst {
val agent = tasks.findByPath(":test-instrumenter:jar")!!.outputs.files.singleFile
val args = project.findProperty("kotlin.test.instrumentation.args")?.let { "=$it" }.orEmpty()
jvmArgs("-javaagent:$agent$args")
}
dependsOn(":test-instrumenter:jar")
jvmArgs(
"-ea",
"-XX:+HeapDumpOnOutOfMemoryError",
"-XX:+UseCodeCacheFlushing",
"-XX:ReservedCodeCacheSize=256m",
"-XX:ReservedCodeCacheSize=128m",
"-Djna.nosys=true"
)
@@ -146,11 +106,6 @@ fun Project.projectTest(
environment("PROJECT_BUILD_DIR", buildDir)
systemProperty("jps.kotlin.home", rootProject.extra["distKotlinHomeDir"]!!)
systemProperty("kotlin.ni", if (rootProject.hasProperty("newInferenceTests")) "true" else "false")
systemProperty("org.jetbrains.kotlin.skip.muted.tests", if (rootProject.hasProperty("skipMutedTests")) "true" else "false")
if (Platform[202].orHigher()) {
systemProperty("idea.ignore.disabled.plugins", "true")
}
var subProjectTempRoot: Path? = null
doFirst {
@@ -199,10 +154,6 @@ object TaskUtils {
fun useAndroidJar(task: Task) {
task.useAndroidConfiguration(systemPropertyName = "android.jar", configName = "androidJar")
}
fun useAndroidEmulator(task: Task) {
task.useAndroidConfiguration(systemPropertyName = "android.sdk", configName = "androidEmulator")
}
}
private fun Task.useAndroidConfiguration(systemPropertyName: String, configName: String) {

View File

@@ -1,14 +1,14 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
ext {
isD8Enabled = project.findProperty('android.enableD8').toBoolean()
}
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.5.3'
classpath 'com.android.tools.build:gradle:3.3.2'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
apply plugin: 'com.android.application'
@@ -19,7 +19,7 @@ repositories {
}
android {
compileSdkVersion 26
compileSdkVersion 19
buildToolsVersion "28.0.3"
defaultConfig {
@@ -51,7 +51,7 @@ android {
dexOptions {
dexInProcess false
javaMaxHeapSize "1500m"
javaMaxHeapSize "1200m"
maxProcessCount 4
additionalParameters "--debug"
}
@@ -60,42 +60,21 @@ android {
resultsDir = "build/test/results"
}
if (isD8Enabled) {
compileOptions {
sourceCompatibility = 1.8
targetCompatibility = 1.8
}
}
flavorDimensions "box"
productFlavors {
common0 {
ktest0 {
dimension "box"
}
common1 {
ktest1 {
dimension "box"
}
common2 {
ktest2 {
dimension "box"
}
reflect0 {
dimension "box"
}
if (isD8Enabled) {
jvm80 {
dimension "box"
}
reflectjvm80 {
dimension "box"
}
}
}
}
@@ -103,9 +82,9 @@ android {
task jarTestFolders() {
println "Jar folders..."
new File("${projectDir}/libs/").listFiles().each { File file ->
if (file.isDirectory()) {
if (file.isDirectory() && !file.name.equals("test")) {
println "Jar '${file.name}' folder..."
ant.jar(basedir: "libs/${file.name}/", destfile: "libs/" + file.name + ".jar")
ant.jar(basedir: "libs/${file.name}/", destfile: "libs/test/" + file.name + ".jar")
}
}
}
@@ -115,18 +94,11 @@ tasks.withType(JavaCompile) {
}
dependencies {
implementation fileTree(dir: 'libs', include: ['kotlin-test.jar', 'kotlin-stdlib.jar'])
implementation fileTree(dir: 'libs', include: ['*.jar'])
androidTestImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
android.applicationVariants.all { variant ->
variant.productFlavors.each {
def configuration = configurations.getByName(it.name + 'Implementation').name
add(configuration, project.fileTree(dir: 'libs', include: [it.name + ".jar"]))
if (it.name.startsWith("reflect")) {
add(configuration, project.fileTree(dir: 'libs', include: ['kotlin-reflect.jar']))
}
}
}
ktest0Implementation fileTree(dir: 'libs/test', include: ['libtest0.jar'])
ktest1Implementation fileTree(dir: 'libs/test', include: ['libtest1.jar'])
ktest2Implementation fileTree(dir: 'libs/test', include: ['libtest2.jar'])
}

View File

@@ -1,3 +1,3 @@
#don't try to download android specific tools within gradle: licence acceptance will be required
android.builder.sdkDownload=false
android.enableD8=true
android.enableD8=false

View File

@@ -1,4 +1,3 @@
import TaskUtils.useAndroidEmulator
plugins {
kotlin("jvm")
@@ -6,33 +5,32 @@ plugins {
}
dependencies {
compile(project(":compiler:util"))
compile(project(":compiler:cli"))
compile(project(":compiler:frontend"))
compile(project(":compiler:backend"))
compile(kotlinStdlib())
compile(project(":kotlin-reflect"))
compile(projectTests(":compiler:tests-common"))
compile(commonDep("junit:junit"))
Platform[193].orLower {
compileOnly(intellijDep()) { includeJars("openapi") }
}
testCompile(project(":compiler:incremental-compilation-impl"))
testCompile(project(":core:descriptors"))
testCompile(project(":core:descriptors.jvm"))
testCompile(project(":compiler:util"))
testCompile(project(":compiler:cli"))
testCompile(project(":compiler:frontend"))
testCompile(project(":compiler:backend"))
testCompile(project(":compiler:incremental-compilation-impl"))
testCompile(project(":compiler:frontend.java"))
testCompile(kotlinStdlib())
testCompile(project(":kotlin-reflect"))
testCompile(projectTests(":compiler:tests-common"))
testCompile(commonDep("junit:junit"))
testCompile(projectTests(":jps-plugin"))
testCompile(commonDep("junit:junit"))
Platform[193].orLower {
testCompile(intellijDep()) { includeJars("openapi", rootProject = rootProject) }
}
testCompile(intellijDep()) { includeJars("util", "idea", "idea_rt", rootProject = rootProject) }
Platform[202].orHigher {
testCompile(intellijDep()) { includeJars("groovy", rootProject = rootProject) }
}
Platform[201].orLower {
testCompile(intellijDep()) { includeJars("groovy-all", rootProject = rootProject) }
testCompile(intellijDep()) { includeJars("util", "idea", "idea_rt", "groovy-all", rootProject = rootProject) }
Platform[191].orLower {
testCompile(intellijDep()) { includeJars("jps-builders") }
}
Platform[192].orHigher {
testCompile(intellijPluginDep("java")) { includeJars("jps-builders") }
@@ -42,7 +40,7 @@ dependencies {
}
sourceSets {
"main" { }
"main" { projectDefault() }
"test" { projectDefault() }
}
@@ -61,7 +59,6 @@ projectTest {
}
workingDir = rootDir
useAndroidEmulator(this)
}
val generateAndroidTests by generator("org.jetbrains.kotlin.android.tests.CodegenTestsOnAndroidGenerator")

View File

@@ -19,8 +19,10 @@ package org.jetbrains.kotlin.android.tests
import com.intellij.util.PlatformUtils
import junit.framework.TestCase
import junit.framework.TestSuite
import org.jetbrains.kotlin.android.tests.download.SDKDownloader
import org.jetbrains.kotlin.android.tests.emulator.Emulator
import org.jetbrains.kotlin.android.tests.gradle.GradleRunner
import org.jetbrains.kotlin.android.tests.run.PermissionManager
import org.junit.Assert
import org.w3c.dom.Element
import org.xml.sax.SAXException
@@ -37,6 +39,8 @@ class CodegenTestsOnAndroidRunner private constructor(private val pathManager: P
private fun runTestsInEmulator(): TestSuite {
val rootSuite = TestSuite("Root")
downloadDependencies()
val emulatorType = if (isTeamcity) Emulator.ARM else Emulator.X86
println("Using $emulatorType emulator!")
val emulator = Emulator(pathManager, emulatorType)
@@ -52,16 +56,16 @@ class CodegenTestsOnAndroidRunner private constructor(private val pathManager: P
try {
emulator.waitEmulatorStart()
runTestsOnEmulator(gradleRunner, TestSuite("D8")).apply {
runTestsOnEmulator(gradleRunner, TestSuite("Dex")).apply {
rootSuite.addTest(this)
}
renameFlavorFolder()
enableD8(false)
runTestsOnEmulator(gradleRunner, TestSuite("DX")).apply {
enableD8(true)
runTestsOnEmulator(gradleRunner, TestSuite("D8")).apply {
(0 until this.countTestCases()).forEach {
val testCase = testAt(it) as TestCase
testCase.name += "_DX"
testCase.name += "_D8"
}
rootSuite.addTest(this)
}
@@ -102,14 +106,14 @@ class CodegenTestsOnAndroidRunner private constructor(private val pathManager: P
testCases.forEach { aCase -> suite.addTest(aCase) }
Assert.assertNotEquals("There is no test results in report", 0, testCases.size.toLong())
}
} catch (e: Throwable) {
} catch (e: Exception) {
throw RuntimeException("Can't parse test results in $reportFolder\n$resultOutput", e)
}
}
private fun renameFlavorFolder() {
val reportFolder = File(flavorFolder())
reportFolder.renameTo(File(reportFolder.parentFile, reportFolder.name + "_d8"))
reportFolder.renameTo(File(reportFolder.parentFile, reportFolder.name + "_dex"))
}
private fun flavorFolder() = pathManager.tmpFolder + "/build/test/results/connected/flavors"
@@ -130,6 +134,18 @@ class CodegenTestsOnAndroidRunner private constructor(private val pathManager: P
}
private fun downloadDependencies() {
val rootForAndroidDependencies = File(pathManager.dependenciesRoot)
if (!rootForAndroidDependencies.exists()) {
rootForAndroidDependencies.mkdirs()
}
val downloader = SDKDownloader(pathManager)
downloader.downloadAll()
downloader.unzipAll()
PermissionManager.setPermissions(pathManager)
}
companion object {
@JvmStatic

View File

@@ -0,0 +1,98 @@
/*
* 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.android.tests;
import org.jetbrains.kotlin.android.tests.download.SDKDownloader;
import java.io.File;
public class PathManager {
private final String tmpFolder;
private final String rootFolder;
public PathManager(String rootFolder, String tmpFolder) {
this.tmpFolder = tmpFolder;
this.rootFolder = rootFolder;
}
public String getPlatformFolderInAndroidSdk() {
return getAndroidSdkRoot() + "/platforms";
}
public String getAndroidAvdRoot() {
String androidEmulatorRoot = getAndroidSdkRoot() + "/emulatoravd";
new File(androidEmulatorRoot).mkdirs();
return androidEmulatorRoot;
}
public String getPlatformToolsFolderInAndroidSdk() {
return getAndroidSdkRoot() + "/platform-tools";
}
public String getToolsFolderInAndroidSdk() {
return getAndroidSdkRoot() + "/tools";
}
public String getEmulatorFolderInAndroidSdk() {
return getAndroidSdkRoot() + "/emulator";
}
public String getBuildToolsFolderInAndroidSdk() {
return getAndroidSdkRoot() + "/build-tools";
}
public String getOutputForCompiledFiles(int index) {
return tmpFolder + "/libs/libtest" + index;
}
public String getLibsFolderInAndroidTmpFolder() {
return tmpFolder + "/libs";
}
public String getSrcFolderInAndroidTmpFolder() {
return tmpFolder + "/src";
}
public String getAndroidTmpFolder() {
return tmpFolder;
}
public String getAndroidSdkRoot() {
return getDependenciesRoot() + "/android-sdk";
}
public String getDependenciesRoot() {
return rootFolder + "/dependencies/android.tests.dependencies";
}
public String getGradleBinFolder() {
return getDependenciesRoot() + "/gradle-" + SDKDownloader.GRADLE_VERSION + "/bin";
}
public String getRootForDownload() {
return getDependenciesRoot() + "/download";
}
public String getAndroidModuleRoot() {
return rootFolder + "/compiler/android-tests/android-module";
}
public String getTmpFolder() {
return tmpFolder;
}
}

View File

@@ -0,0 +1,269 @@
/*
* 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.android.tests.download;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileUtil;
import org.jetbrains.kotlin.android.tests.PathManager;
import org.jetbrains.kotlin.android.tests.run.RunUtils;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class SDKDownloader {
private final String platformZipPath;
private final String armImage;
private final String x86Image;
private final String platformToolsZipPath;
private final String skdToolsZipPath;
private final String buildToolsZipPath;
private final String gradleZipPath;
private final String emulatorZipPath;
private final PathManager pathManager;
private static final String PLATFORM_TOOLS = "28.0.1";
private static final String SDK_TOOLS = "4333796"; //"26.1.1";
public static final String BUILD_TOOLS = "28.0.3";
private static final int ANDROID_VERSION = 19;
public static final String GRADLE_VERSION = "5.1.1";
public static final String EMULATOR_TOOLS_VERSION = "5264690"; //"28.0.23";
public SDKDownloader(PathManager pathManager) {
this.pathManager = pathManager;
platformZipPath = pathManager.getRootForDownload() + "/platform" + ANDROID_VERSION + ".zip";
armImage = pathManager.getRootForDownload() + "/arm-image.zip";
x86Image = pathManager.getRootForDownload() + "/x86-image.zip";
platformToolsZipPath = pathManager.getRootForDownload() + "/platform-tools" + PLATFORM_TOOLS + ".zip";
skdToolsZipPath = pathManager.getRootForDownload() + "/sdk-tools" + SDK_TOOLS + ".zip";
buildToolsZipPath = pathManager.getRootForDownload() + "/build-tools" + BUILD_TOOLS + ".zip";
gradleZipPath = pathManager.getRootForDownload() + "/gradle" + GRADLE_VERSION + ".zip";
emulatorZipPath = pathManager.getRootForDownload() + "/emulator" + EMULATOR_TOOLS_VERSION + ".zip";
}
public void downloadPlatform() {
download("https://dl-ssl.google.com/android/repository/android-" + ANDROID_VERSION + "_r04.zip", platformZipPath); //Same for all platforms
}
private void downloadAbi() {
download("https://dl.google.com/android/repository/sys-img/android/armeabi-v7a-" + ANDROID_VERSION + "_r05.zip", armImage); //Same for all platforms
download("https://dl.google.com/android/repository/sys-img/android/x86-" + ANDROID_VERSION + "_r06.zip", x86Image); //Same for all platforms
}
public void downloadPlatformTools() {
download(getDownloadUrl("https://dl-ssl.google.com/android/repository/platform-tools_r" + PLATFORM_TOOLS), platformToolsZipPath);
}
public void downloadSdkTools() {
download("https://dl.google.com/android/repository/sdk-tools-" + getPlatformName() + "-" + SDK_TOOLS + ".zip",
skdToolsZipPath);
}
public void downloadBuildTools() {
download(getDownloadUrl("https://dl.google.com/android/repository/build-tools_r" + BUILD_TOOLS), buildToolsZipPath);
}
public void downloadEmulator() {
download("https://dl.google.com/android/repository/emulator-" + getPlatformName() + "-" + EMULATOR_TOOLS_VERSION + ".zip",
emulatorZipPath);
}
public void downloadGradle() {
download("https://services.gradle.org/distributions/gradle-" + GRADLE_VERSION + "-bin.zip", gradleZipPath);
}
private static String getDownloadUrl(String prefix) {
String suffix;
if (SystemInfo.isWindows) {
suffix = "-windows.zip";
}
else if (SystemInfo.isMac) {
suffix = "-macosx.zip";
}
else if (SystemInfo.isUnix) {
suffix = "-linux.zip";
}
else {
throw new IllegalStateException("Your operating system isn't supported yet.");
}
return prefix + suffix;
}
private static String getPlatformName() {
if (SystemInfo.isWindows) {
return "windows";
}
else if (SystemInfo.isMac) {
return "darwin";
}
else if (SystemInfo.isUnix) {
return "linux";
}
else {
throw new IllegalStateException("Your operating system isn't supported yet.");
}
}
public void downloadAll() {
downloadSdkTools();
downloadAbi();
downloadPlatform();
downloadPlatformTools();
downloadBuildTools();
downloadGradle();
downloadEmulator();
}
public void unzipAll() {
String androidSdkRoot = pathManager.getAndroidSdkRoot();
unzip(platformZipPath, pathManager.getPlatformFolderInAndroidSdk());
new File(pathManager.getPlatformFolderInAndroidSdk() + "/android-4.4.2").renameTo(new File(pathManager.getPlatformFolderInAndroidSdk() + "/android-" + ANDROID_VERSION));
unzip(armImage, androidSdkRoot + "/system-images/android-" + ANDROID_VERSION + "/default/");
unzip(x86Image, androidSdkRoot + "/system-images/android-" + ANDROID_VERSION + "/default/");
unzip(platformToolsZipPath, androidSdkRoot);
unzip(skdToolsZipPath, androidSdkRoot);
unzip(gradleZipPath, pathManager.getDependenciesRoot());
//BUILD TOOLS
String buildTools = androidSdkRoot + "/build-tools/";
unzip(buildToolsZipPath, buildTools);
unzip(emulatorZipPath, androidSdkRoot);
}
public void deleteAll() {
delete(platformZipPath);
delete(platformToolsZipPath);
delete(skdToolsZipPath);
delete(buildToolsZipPath);
delete(armImage);
delete(x86Image);
delete(gradleZipPath);
}
private static void download(String urlString, String output) {
System.out.println("Start downloading: " + urlString + " to " + output);
OutputStream outStream = null;
URLConnection urlConnection;
InputStream is;
try {
URL Url;
byte[] buf;
int read;
//int written = 0;
Url = new URL(urlString);
File outputFile = new File(output);
outputFile.getParentFile().mkdirs();
if (outputFile.exists()) {
System.out.println("File was already downloaded: " + output);
return;
}
outputFile.createNewFile();
FileOutputStream outputStream = new FileOutputStream(outputFile);
outStream = new BufferedOutputStream(outputStream);
urlConnection = Url.openConnection();
is = urlConnection.getInputStream();
buf = new byte[1024];
while ((read = is.read(buf)) != -1) {
outStream.write(buf, 0, read);
//written += read;
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
finally {
RunUtils.close(outStream);
}
System.out.println("Finish downloading: " + urlString + " to " + output);
}
protected void unzip(String pathToFile, String outputFolder) {
System.out.println("Start unzipping: " + pathToFile + " to " + outputFolder);
String pathToUnzip;
if (outputFolder.equals(pathManager.getPlatformFolderInAndroidSdk())) {
pathToUnzip = outputFolder;
}
else {
pathToUnzip = outputFolder + "/" + FileUtil.getNameWithoutExtension(new File(pathToFile));
}
if (new File(pathToUnzip).listFiles() != null) {
System.out.println("File was already unzipped: " + pathToFile);
return;
}
try {
byte[] buf = new byte[1024];
ZipEntry zipEntry = null;
try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(pathToFile))) {
zipEntry = zipInputStream.getNextEntry();
while (zipEntry != null) {
String entryName = zipEntry.getName();
int n;
File outputFile = new File(outputFolder + "/" + entryName);
if (zipEntry.isDirectory()) {
outputFile.mkdirs();
zipInputStream.closeEntry();
zipEntry = zipInputStream.getNextEntry();
continue;
}
else {
File parentFile = outputFile.getParentFile();
if (parentFile != null && !parentFile.exists()) {
parentFile.mkdirs();
}
outputFile.createNewFile();
}
try (FileOutputStream fileOutputStream = new FileOutputStream(outputFile)) {
while ((n = zipInputStream.read(buf, 0, 1024)) > -1) {
fileOutputStream.write(buf, 0, n);
}
}
zipInputStream.closeEntry();
zipEntry = zipInputStream.getNextEntry();
}
}
catch (IOException e) {
if (zipEntry != null) {
System.err.println("Entry name: " + zipEntry.getName());
}
e.printStackTrace();
}
}
catch (Exception e) {
e.printStackTrace();
}
System.out.println("Finish unzipping: " + pathToFile + " to " + outputFolder);
}
private static void delete(String filePath) {
new File(filePath).delete();
}
}

View File

@@ -48,8 +48,8 @@ public class Emulator {
private GeneralCommandLine getCreateCommand() {
GeneralCommandLine commandLine = new GeneralCommandLine();
String androidCmdName = SystemInfo.isWindows ? "avdmanager.bat" : "avdmanager";
commandLine.setExePath(pathManager.getToolsFolderInAndroidSdk() + "/bin/" + androidCmdName);
String androidCmdName = SystemInfo.isWindows ? "android.bat" : "android";
commandLine.setExePath(pathManager.getToolsFolderInAndroidSdk() + "/" + androidCmdName);
commandLine.addParameter("create");
commandLine.addParameter("avd");
commandLine.addParameter("--force");

View File

@@ -31,8 +31,8 @@ public class GradleRunner {
public GradleRunner(PathManager pathManager) {
listOfCommands = new ArrayList<>();
String cmdName = SystemInfo.isWindows ? "gradlew.bat" : "gradlew";
listOfCommands.add(pathManager.getTmpFolder() + "/" + cmdName);
String cmdName = SystemInfo.isWindows ? "gradle.bat" : "gradle";
listOfCommands.add(pathManager.getGradleBinFolder() + "/" + cmdName);
listOfCommands.add("--no-daemon");
listOfCommands.add("--build-file");
listOfCommands.add(pathManager.getTmpFolder() + "/build.gradle");

View File

@@ -0,0 +1,64 @@
/*
* 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.android.tests.run;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.openapi.util.SystemInfo;
import org.jetbrains.kotlin.android.tests.PathManager;
import org.jetbrains.kotlin.android.tests.download.SDKDownloader;
import java.io.File;
public class PermissionManager {
private PermissionManager() {
}
public static void setPermissions(PathManager pathManager) {
if (!SystemInfo.isWindows) {
setExecPermissionForSimpleNamedFiles(new File(pathManager.getToolsFolderInAndroidSdk()));
setExecPermissionForSimpleNamedFiles(new File(pathManager.getBuildToolsFolderInAndroidSdk() + "/" + SDKDownloader.BUILD_TOOLS));
setExecPermissionForSimpleNamedFiles(new File(pathManager.getPlatformToolsFolderInAndroidSdk()));
setExecPermissionForSimpleNamedFiles(new File(pathManager.getToolsFolderInAndroidSdk() +"/bin"));
setExecPermissionForSimpleNamedFiles(new File(pathManager.getEmulatorFolderInAndroidSdk()));
setExecPermissionForSimpleNamedFiles(new File(pathManager.getEmulatorFolderInAndroidSdk() +"/bin"));
setExecPermissionForSimpleNamedFiles(new File(pathManager.getEmulatorFolderInAndroidSdk() +"/bin64"));
setExecPermissionForSimpleNamedFiles(new File(pathManager.getEmulatorFolderInAndroidSdk() +"/qemu/linux-x86_64"));
setExecPermissionForSimpleNamedFiles(new File(pathManager.getAndroidSdkRoot() + "/system-images/android-19/default/armeabi-v7a/"));
RunUtils.execute(generateChmodCmd(pathManager.getGradleBinFolder() + "/gradle"));
}
}
private static void setExecPermissionForSimpleNamedFiles(File folder) {
File[] files = folder.listFiles();
if (files != null) {
for (File file : files) {
if (file.isFile() && !file.getName().contains(".")) {
RunUtils.execute(generateChmodCmd(file.getAbsolutePath()));
}
}
}
}
private static GeneralCommandLine generateChmodCmd(String path) {
GeneralCommandLine commandLine = new GeneralCommandLine();
commandLine.setExePath("chmod");
commandLine.addParameter("a+x");
commandLine.addParameter(path);
return commandLine;
}
}

View File

@@ -25,7 +25,7 @@ import org.junit.runners.AllTests;
import java.io.File;
//@RunWith(AllTests.class)
@RunWith(AllTests.class)
public class AndroidRunner {
private static PathManager pathManager;

View File

@@ -17,6 +17,7 @@
package org.jetbrains.kotlin.android.tests
import com.intellij.openapi.util.Ref
import org.jetbrains.kotlin.codegen.CodegenTestCase
import org.jetbrains.kotlin.load.kotlin.PackagePartClassUtils
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
@@ -46,21 +47,18 @@ internal fun patchFilesAndAddTest(
val newPackagePrefix = testFile.path.replace("\\\\|-|\\.|/".toRegex(), "_")
val oldPackage = Ref<FqName>()
val isJvmName = Ref<Boolean>(false)
val isSingle = testFiles.size == 1
val resultFiles = testFiles.map {
val fileName = if (isSingle) it.name else testFile.name.substringBeforeLast(".kt") + "/" + it.name
TestClassInfo(
fileName,
changePackage(newPackagePrefix, it.content, oldPackage, isJvmName),
changePackage(newPackagePrefix, it.content, oldPackage),
oldPackage.get(),
isJvmName.get(),
getGeneratedClassName(File(fileName), it.content, newPackagePrefix, oldPackage.get())
)
}
val packages =
resultFiles.map { OldPackageAndNew(it.oldPackage, it.newPackagePartClassId.parent()) }
.sortedByDescending { it.oldFqName.asString().length }
resultFiles.map { OldPackageAndNew(it.oldPackage, it.newClassId.parent()) }.sortedByDescending { it.oldFqName.asString().length }
//If files contain any val or var declaration with same name as any package name
// then use old conservative renaming scheme, otherwise use aggressive one
@@ -97,7 +95,7 @@ internal fun patchFilesAndAddTest(
/*replace all Class.forName*/
resultFiles.forEach { file ->
file.content = resultFiles.fold(file.content) { r, param ->
patchClassForName(param.newPackagePartClassId, param.oldPackage, r, conservativeRenameScheme)
patchClassForName(param.newClassId, param.oldPackage, r, conservativeRenameScheme)
}
}
@@ -106,13 +104,6 @@ internal fun patchFilesAndAddTest(
file.content = file.content.patchSelfImports(file.newPackage)
}
//patch root package parts usages in strings
resultFiles.forEach { file ->
file.content = resultFiles.fold(file.content) { r, param ->
patchRootPartNamesInStrings(param.newPackagePartClassId, param.oldPackage, param.isJvmName, r)
}
}
val boxFiles = resultFiles.filter { hasBoxMethod(it.content) }
if (boxFiles.size != 1) {
println("Several box methods in $testFile")
@@ -120,22 +111,22 @@ internal fun patchFilesAndAddTest(
filesHolder.addTest(
resultFiles.filter { resultFile -> resultFile.name.endsWith(".kt") || resultFile.name.endsWith(".kts") },
TestInfo("", boxFiles.last().newPackagePartClassId, testFile)
TestInfo("", boxFiles.last().newClassId, testFile)
)
return boxFiles.last().newPackagePartClassId
return boxFiles.last().newClassId
}
private fun hasBoxMethod(text: String): Boolean {
return text.contains("fun box()")
}
class TestClassInfo(val name: String, var content: String, val oldPackage: FqName, val isJvmName: Boolean, val newPackagePartClassId: FqName) {
val newPackage = newPackagePartClassId.parent()
class TestClassInfo(val name: String, var content: String, val oldPackage: FqName, val newClassId: FqName) {
val newPackage = newClassId.parent()
}
private fun changePackage(newPackagePrefix: String, text: String, oldPackage: Ref<FqName>, isJvmName: Ref<Boolean>): String {
private fun changePackage(newPackagePrefix: String, text: String, oldPackage: Ref<FqName>): String {
val matcher = packagePattern.matcher(text)
if (matcher.find()) {
val oldPackageName = matcher.toMatchResult().group(1)
@@ -147,7 +138,6 @@ private fun changePackage(newPackagePrefix: String, text: String, oldPackage: Re
if (text.contains("@file:")) {
val index = text.lastIndexOf("@file:")
val packageDirectiveIndex = text.indexOf("\n", index)
isJvmName.set(true)
return text.substring(0, packageDirectiveIndex + 1) + packageDirective + text.substring(packageDirectiveIndex + 1)
} else {
return packageDirective + text
@@ -180,19 +170,6 @@ private fun patchClassForName(className: FqName, oldPackage: FqName, text: Strin
)
}
private fun patchRootPartNamesInStrings(
className: FqName,
oldPackage: FqName,
isJvmName: Boolean,
text: String
): String {
if (!oldPackage.isRoot || isJvmName) return text
return text.replace(
("\"" + oldPackage.child(className.shortName()).asString()).toRegex(),
"\"" + className.asString()
)
}
private fun patchPackages(newPackage: FqName, oldPackage: FqName, text: String): String {
if (oldPackage.isRoot) return text

View File

@@ -5,9 +5,7 @@
package org.jetbrains.kotlin.android.tests
import com.intellij.openapi.Disposable
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.FileUtilRt
import org.jetbrains.kotlin.cli.common.output.writeAllTo
@@ -19,102 +17,50 @@ import org.jetbrains.kotlin.codegen.GenerationUtils
import org.jetbrains.kotlin.codegen.forTestCompile.ForTestCompileRuntime
import org.jetbrains.kotlin.config.CommonConfigurationKeys
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.config.JvmTarget
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.test.*
import org.junit.Assert
import org.junit.Ignore
import java.io.File
import java.io.FileWriter
import java.io.IOException
import kotlin.test.assertTrue
data class ConfigurationKey(val kind: ConfigurationKind, val jdkKind: TestJdkKind, val configuration: String)
class CodegenTestsOnAndroidGenerator private constructor(private val pathManager: PathManager) {
@Ignore
class CodegenTestsOnAndroidGenerator private constructor(private val pathManager: PathManager) : CodegenTestCase() {
private var writtenFilesCount = 0
private var currentModuleIndex = 1
private val pathFilter: String? = System.getProperties().getProperty("kotlin.test.android.path.filter")
private val pendingUnitTestGenerators = hashMapOf<String, UnitTestFileWriter>()
private val pendingUnitTestGenerators = hashMapOf<Int, UnitTestFileWriter>()
//keep it globally to avoid test grouping on TC
private val generatedTestNames = hashSetOf<String>()
private val COMMON = FlavorConfig("common", 3);
private val REFLECT = FlavorConfig("reflect", 1);
private val JVM8 = FlavorConfig("jvm8", 1);
private val JVM8REFLECT = FlavorConfig("reflectjvm8", 1);
class FlavorConfig(private val prefix: String, val limit: Int) {
private var writtenFilesCount = 0
fun printStatistics() {
println("FlavorTestCompiler: $prefix, generated file count: $writtenFilesCount")
}
fun getFlavorForNewFiles(newFilesCount: Int): String {
writtenFilesCount += newFilesCount
//2500 files per folder that would be used by flavor to avoid multidex usage,
// each folder would be jared by build.gradle script
val index = writtenFilesCount / 2500
return getFlavorName(index, prefix).also {
assertTrue("Please Add new flavor in build.gradle for $it") { index < limit }
}
}
private fun getFlavorName(index: Int, prefix: String): String {
return prefix + index
}
fun getFlavorUnitTestFilePath(index: Int): String {
return pathManager.srcFolderInAndroidTmpFolder + "/androidTestKtest$index/java/" + testClassPackage.replace(
".",
"/"
) + "/" + testClassName + "$index.java"
}
private fun prepareAndroidModuleAndGenerateTests(skipSdkDirWriting: Boolean) {
prepareAndroidModule(skipSdkDirWriting)
private fun prepareAndroidModuleAndGenerateTests() {
prepareAndroidModule()
generateTestsAndFlavourSuites()
}
private fun prepareAndroidModule(skipSdkDirWriting: Boolean) {
private fun prepareAndroidModule() {
FileUtil.copyDir(File(pathManager.androidModuleRoot), File(pathManager.tmpFolder))
if (!skipSdkDirWriting) {
writeAndroidSkdToLocalProperties(pathManager)
}
writeAndroidSkdToLocalProperties(pathManager)
println("Copying kotlin-stdlib.jar and kotlin-reflect.jar in android module...")
copyKotlinRuntimeJars()
copyGradleWrapperAndPatch()
}
private fun copyGradleWrapperAndPatch() {
val projectRoot = File(pathManager.tmpFolder)
val target = File(projectRoot, "gradle/wrapper")
File("./gradle/wrapper/").copyRecursively(target)
val gradlew = File(projectRoot, "gradlew")
File("./gradlew").copyTo(gradlew).also {
if (!SystemInfo.isWindows) {
it.setExecutable(true)
}
}
File("./gradlew.bat").copyTo(File(projectRoot, "gradlew.bat"));
val file = File(target, "gradle-wrapper.properties")
file.readLines().map {
when {
it.startsWith("distributionUrl") -> "distributionUrl=https\\://services.gradle.org/distributions/gradle-$GRADLE_VERSION-bin.zip"
it.startsWith("distributionSha256Sum") -> "distributionSha256Sum=$GRADLE_SHA_256"
else -> it
}
}.let { lines ->
FileWriter(file).use { fw ->
lines.forEach { line ->
fw.write("$line\n")
}
}
}
}
private fun copyKotlinRuntimeJars() {
FileUtil.copy(
ForTestCompileRuntime.runtimeJarForTests(),
@@ -150,15 +96,9 @@ class CodegenTestsOnAndroidGenerator private constructor(private val pathManager
holders.values.forEach {
it.writeFilesOnDisk()
}
COMMON.printStatistics()
REFLECT.printStatistics()
JVM8.printStatistics()
JVM8REFLECT.printStatistics()
}
internal inner class FilesWriter(
private val flavorConfig: FlavorConfig,
private val configuration: CompilerConfiguration
) {
private val rawFiles = arrayListOf<TestClassInfo>()
@@ -173,40 +113,38 @@ class CodegenTestsOnAndroidGenerator private constructor(private val pathManager
}
fun writeFilesOnDisk() {
val disposable = Disposer.newDisposable()
val disposable = TestDisposable()
val environment = KotlinCoreEnvironment.createForTests(
disposable,
configuration.copy().apply { put(CommonConfigurationKeys.MODULE_NAME, "android-module-" + currentModuleIndex++) },
EnvironmentConfigFiles.JVM_CONFIG_FILES
)
try {
writeFiles(
rawFiles.map {
try {
CodegenTestFiles.create(it.name, it.content, environment.project).psiFile
} catch (e: Throwable) {
throw RuntimeException("Error on processing ${it.name}:\n${it.content}", e)
}
}, environment, unitTestDescriptions
)
} finally {
rawFiles.clear()
unitTestDescriptions.clear()
Disposer.dispose(disposable)
}
writeFiles(
rawFiles.map {
try {
CodegenTestFiles.create(it.name, it.content, environment.project).psiFile
} catch (e: Throwable) {
throw RuntimeException("Error on processing ${it.name}:\n${it.content}", e)
}
}, environment
)
Disposer.dispose(disposable)
rawFiles.clear()
unitTestDescriptions.clear()
}
private fun writeFiles(
filesToCompile: List<KtFile>,
environment: KotlinCoreEnvironment,
unitTestDescriptions: ArrayList<TestInfo>
) {
private fun writeFiles(filesToCompile: List<KtFile>, environment: KotlinCoreEnvironment) {
if (filesToCompile.isEmpty()) return
val flavorName = flavorConfig.getFlavorForNewFiles(filesToCompile.size)
//2500 files per folder that would be used by flavor to avoid multidex usage,
// each folder would be jared by build.gradle script
writtenFilesCount += filesToCompile.size
val index = writtenFilesCount / 2500
val outputDir = File(pathManager.getOutputForCompiledFiles(index))
assertTrue("Add flavors for ktest$index", index < 3)
val outputDir = File(pathManager.getOutputForCompiledFiles(flavorName))
println("Generating ${filesToCompile.size} files into ${outputDir.name}, configuration: '${environment.configuration}'...")
val outputFiles = GenerationUtils.compileFiles(filesToCompile, environment).run { destroy(); factory }
@@ -215,10 +153,10 @@ class CodegenTestsOnAndroidGenerator private constructor(private val pathManager
outputDir.mkdirs()
}
Assert.assertTrue("Cannot create directory for compiled files", outputDir.exists())
val unitTestFileWriter = pendingUnitTestGenerators.getOrPut(flavorName) {
val unitTestFileWriter = pendingUnitTestGenerators.getOrPut(index) {
UnitTestFileWriter(
getFlavorUnitTestFolder(flavorName),
flavorName,
getFlavorUnitTestFilePath(index),
index,
generatedTestNames
)
}
@@ -226,12 +164,6 @@ class CodegenTestsOnAndroidGenerator private constructor(private val pathManager
outputFiles.writeAllTo(outputDir)
}
private fun getFlavorUnitTestFolder(flavourName: String): String {
return pathManager.srcFolderInAndroidTmpFolder +
"/androidTest${flavourName.capitalize()}/java/" +
testClassPackage.replace(".", "/") + "/"
}
fun addTest(testFiles: List<TestClassInfo>, info: TestInfo) {
rawFiles.addAll(testFiles)
unitTestDescriptions.add(info)
@@ -248,6 +180,9 @@ class CodegenTestsOnAndroidGenerator private constructor(private val pathManager
}
for (file in files) {
if (SpecialFiles.getExcludedFiles().contains(file.name)) {
continue
}
if (file.isDirectory) {
val listFiles = file.listFiles()
if (listFiles != null) {
@@ -260,9 +195,7 @@ class CodegenTestsOnAndroidGenerator private constructor(private val pathManager
continue
}
if (!InTextDirectivesUtils.isPassingTarget(TargetBackend.JVM, file) ||
InTextDirectivesUtils.isIgnoredTarget(TargetBackend.ANDROID, file)
) {
if (!InTextDirectivesUtils.isPassingTarget(TargetBackend.JVM, file)) {
continue
}
@@ -278,32 +211,23 @@ class CodegenTestsOnAndroidGenerator private constructor(private val pathManager
if (fullFileText.contains("@file:JvmPackageName(")) continue
// TODO: Support jvm assertions
if (fullFileText.contains("// KOTLIN_CONFIGURATION_FLAGS: ASSERTIONS_MODE=jvm")) continue
val targets = InTextDirectivesUtils.findLinesWithPrefixesRemoved(fullFileText, "// JVM_TARGET:")
.also { it.remove(JvmTarget.JVM_1_6.description) }
val isJvm8Target =
if (targets.isEmpty()) false
else if (targets.contains(JvmTarget.JVM_1_8.description) && targets.size == 1) true
else continue //TODO: support other targets on Android
// TODO: support JVM 8 test with D8
if (fullFileText.contains("// JVM_TARGET")) continue
// TODO: support SKIP_JDK6 on new platforms
if (fullFileText.contains("// SKIP_JDK6")) continue
if (hasBoxMethod(fullFileText)) {
val testFiles = createTestFiles(file, fullFileText)
val kind = KotlinBaseTest.extractConfigurationKind(testFiles)
val jdkKind = KotlinBaseTest.getTestJdkKind(testFiles)
val kind = extractConfigurationKind(testFiles)
val jdkKind = getTestJdkKind(testFiles)
val keyConfiguration = CompilerConfiguration()
KotlinBaseTest.updateConfigurationByDirectivesInTestFiles(testFiles, keyConfiguration)
updateConfigurationByDirectivesInTestFiles(testFiles, keyConfiguration)
val key = ConfigurationKey(kind, jdkKind, keyConfiguration.toString())
val compiler = if (isJvm8Target) {
if (kind.withReflection) JVM8REFLECT else JVM8
} else if (kind.withReflection) REFLECT else COMMON
val filesHolder = holders.getOrPut(key) {
FilesWriter(compiler, KotlinTestUtils.newConfiguration(kind, jdkKind, KotlinTestUtils.getAnnotationsJar()).apply {
FilesWriter(KotlinTestUtils.newConfiguration(kind, jdkKind, KotlinTestUtils.getAnnotationsJar()).apply {
println("Creating new configuration by $key")
KotlinBaseTest.updateConfigurationByDirectivesInTestFiles(testFiles, this)
updateConfigurationByDirectivesInTestFiles(testFiles, this)
})
}
@@ -313,12 +237,19 @@ class CodegenTestsOnAndroidGenerator private constructor(private val pathManager
}
}
private fun createTestFiles(file: File, expectedText: String): List<KotlinBaseTest.TestFile> =
CodegenTestCase.createTestFilesFromFile(file, expectedText, "kotlin.coroutines", false, TargetBackend.JVM)
private fun createTestFiles(file: File, expectedText: String): List<TestFile> =
TestFiles.createTestFiles(
file.name,
expectedText,
object : TestFiles.TestFileFactoryNoModules<TestFile>() {
override fun create(fileName: String, text: String, directives: Directives): TestFile {
return TestFile(fileName, text, directives)
}
}, false,
"kotlin.coroutines"
)
companion object {
const val GRADLE_VERSION = "5.6.4" // update GRADLE_SHA_256 on change
const val GRADLE_SHA_256 = "1f3067073041bc44554d0efe5d402a33bc3d3c93cc39ab684f308586d732a80d"
const val testClassPackage = "org.jetbrains.kotlin.android.tests"
const val testClassName = "CodegenTestCaseOnAndroid"
const val baseTestClassPackage = "org.jetbrains.kotlin.android.tests"
@@ -326,11 +257,10 @@ class CodegenTestsOnAndroidGenerator private constructor(private val pathManager
const val generatorName = "CodegenTestsOnAndroidGenerator"
@JvmOverloads
@JvmStatic
@Throws(Throwable::class)
fun generate(pathManager: PathManager, skipSdkDirWriting: Boolean = false) {
CodegenTestsOnAndroidGenerator(pathManager).prepareAndroidModuleAndGenerateTests(skipSdkDirWriting)
fun generate(pathManager: PathManager) {
CodegenTestsOnAndroidGenerator(pathManager).prepareAndroidModuleAndGenerateTests()
}
private fun hasBoxMethod(text: String): Boolean {
@@ -339,7 +269,7 @@ class CodegenTestsOnAndroidGenerator private constructor(private val pathManager
@Throws(IOException::class)
internal fun writeAndroidSkdToLocalProperties(pathManager: PathManager) {
val sdkRoot = KotlinTestUtils.getAndroidSdkSystemIndependentPath()
val sdkRoot = File(pathManager.androidSdkRoot).invariantSeparatorsPath
println("Writing android sdk to local.properties: $sdkRoot")
val file = File(pathManager.tmpFolder + "/local.properties")
FileWriter(file).use { fw -> fw.write("sdk.dir=$sdkRoot") }
@@ -351,8 +281,7 @@ class CodegenTestsOnAndroidGenerator private constructor(private val pathManager
println("Created temporary folder for android tests: " + tmpFolder.absolutePath)
val rootFolder = File("")
val pathManager = PathManager(rootFolder.absolutePath, tmpFolder.absolutePath)
generate(pathManager, true)
println("Android test project is generated into " + tmpFolder.absolutePath + " folder")
generate(pathManager)
}
}
}

View File

@@ -1,82 +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.android.tests;
import org.jetbrains.kotlin.test.KotlinTestUtils;
import java.io.File;
public class PathManager {
private final String tmpFolder;
private final String rootFolder;
public PathManager(String rootFolder, String tmpFolder) {
this.tmpFolder = tmpFolder;
this.rootFolder = rootFolder;
}
public String getPlatformFolderInAndroidSdk() {
return getAndroidSdkRoot() + "/platforms";
}
public String getAndroidAvdRoot() {
String androidEmulatorRoot = getAndroidSdkRoot() + "/compiler_box_test_avd";
new File(androidEmulatorRoot).mkdirs();
return androidEmulatorRoot;
}
public String getPlatformToolsFolderInAndroidSdk() {
return getAndroidSdkRoot() + "/platform-tools";
}
public String getToolsFolderInAndroidSdk() {
return getAndroidSdkRoot() + "/tools";
}
public String getEmulatorFolderInAndroidSdk() {
return getAndroidSdkRoot() + "/emulator";
}
public String getOutputForCompiledFiles(String flavor) {
return tmpFolder + "/libs/" + flavor;
}
public String getLibsFolderInAndroidTmpFolder() {
return tmpFolder + "/libs";
}
public String getSrcFolderInAndroidTmpFolder() {
return tmpFolder + "/src";
}
public String getAndroidTmpFolder() {
return tmpFolder;
}
public String getAndroidSdkRoot() {
return KotlinTestUtils.getAndroidSdkSystemIndependentPath();
}
public String getAndroidModuleRoot() {
return rootFolder + "/compiler/android-tests/android-module";
}
public String getTmpFolder() {
return tmpFolder;
}
}

View File

@@ -0,0 +1,93 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.android.tests;
import java.util.HashSet;
import java.util.Set;
public class SpecialFiles {
private static final Set<String> excludedFiles = new HashSet<>();
static {
fillExcludedFiles();
}
public static Set<String> getExcludedFiles() {
return excludedFiles;
}
private static void fillExcludedFiles() {
// Reflection
excludedFiles.add("enclosing");
excludedFiles.add("kt10259.kt");
excludedFiles.add("simpleClassLiteral.kt");
//UnsatisfiedLinkError
excludedFiles.add("nativePropertyAccessors.kt");
excludedFiles.add("topLevel.kt");
//Test with no reflection at runtime
excludedFiles.add("noReflectAtRuntime");
excludedFiles.add("noReflect");
excludedFiles.add("functionNtoStringNoReflect.kt");
excludedFiles.add("getDelegateWithoutReflection.kt");
// "IOOBE: Invalid index 4, size is 4" for java.lang.reflect.ParameterizedType on Android
excludedFiles.add("innerGenericTypeArgument.kt");
// Cannot change package name
excludedFiles.add("kt6990.kt");
excludedFiles.add("typeParameters.kt");
excludedFiles.add("kt13133.kt");
// StackOverflow with StringBuilder (escape())
excludedFiles.add("kt684.kt");
// Wrong enclosing info or signature after package renaming
excludedFiles.add("enclosingInfo");
excludedFiles.add("signature");
// Some classes are not visible on android
excludedFiles.add("classpath.kt");
// Out of memory
excludedFiles.add("manyNumbers.kt");
// Native methods
excludedFiles.add("external");
// Additional nested class in 'Thread' class on Android
excludedFiles.add("nestedClasses.kt");
// KT-8120
excludedFiles.add("closureOfInnerLocalClass.kt");
excludedFiles.add("closureWithSelfInstantiation.kt");
excludedFiles.add("quotedClassName.kt");
//wrong function resolution after package renaming
excludedFiles.add("apiVersionAtLeast1.kt");
//special symbols in names
excludedFiles.add("nameWithWhitespace.kt");
//some classes are moved from stdlib to compatibility package
excludedFiles.add("suspendFunction_1_2.kt");
}
private SpecialFiles() {
}
}

View File

@@ -15,11 +15,7 @@ import java.io.FileWriter
class TestInfo(val name: String, val fqName: FqName, val file: File)
class UnitTestFileWriter(
private val flavourFolder: String,
private val flavourName: String,
private val generatedTestNames: MutableSet<String>
) {
class UnitTestFileWriter(private val fileName: String, private val index: Int, private val generatedTestNames: MutableSet<String>) {
private val infos = arrayListOf<TestInfo>()
fun addTests(info: List<TestInfo>) {
@@ -27,7 +23,7 @@ class UnitTestFileWriter(
}
fun generate() {
FileWriter(File(flavourFolder, flavourName.capitalize() + ".java").also { it.parentFile.mkdirs() }).use { suite ->
FileWriter(File(fileName).also { it.parentFile.mkdirs() }).use { suite ->
val p = Printer(suite)
p.println(
"""package ${CodegenTestsOnAndroidGenerator.testClassPackage};
@@ -35,7 +31,7 @@ class UnitTestFileWriter(
|import ${CodegenTestsOnAndroidGenerator.baseTestClassPackage}.${CodegenTestsOnAndroidGenerator.baseTestClassName};
|
|/* This class is generated by ${CodegenTestsOnAndroidGenerator.generatorName}. DO NOT MODIFY MANUALLY */
|public class ${flavourName.capitalize()} extends ${CodegenTestsOnAndroidGenerator.baseTestClassName} {
|public class ${CodegenTestsOnAndroidGenerator.testClassName}$index extends ${CodegenTestsOnAndroidGenerator.baseTestClassName} {
|
""".trimMargin()
)

View File

@@ -8,6 +8,7 @@ package org.jetbrains.kotlin.backend.common
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.backend.common.bridges.findInterfaceImplementation
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.diagnostics.DiagnosticSink
import org.jetbrains.kotlin.diagnostics.Errors
@@ -23,7 +24,6 @@ import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.multiplatform.ExpectedActualResolver
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.util.getExceptionMessage
import org.jetbrains.kotlin.util.getNonPrivateTraitMembersForDelegation
import org.jetbrains.kotlin.utils.DFS
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
@@ -55,8 +55,14 @@ object CodegenUtil {
@JvmOverloads
fun getNonPrivateTraitMethods(descriptor: ClassDescriptor, copy: Boolean = true): Map<FunctionDescriptor, FunctionDescriptor> {
val result = linkedMapOf<FunctionDescriptor, FunctionDescriptor>()
for (declaration in DescriptorUtils.getAllDescriptors(descriptor.defaultType.memberScope)) {
if (declaration !is CallableMemberDescriptor) continue
val traitMember = findInterfaceImplementation(declaration)
if (traitMember == null ||
Visibilities.isPrivate(traitMember.visibility) ||
traitMember.visibility == Visibilities.INVISIBLE_FAKE) continue
for ((declaration, traitMember) in getNonPrivateTraitMembersForDelegation(descriptor)) {
assert(traitMember.modality !== Modality.ABSTRACT) { "Cannot delegate to abstract trait method: $declaration" }
// inheritedMember can be abstract here. In order for FunctionCodegen to generate the method body, we're creating a copy here
@@ -65,7 +71,7 @@ object CodegenUtil {
if (copy)
copyFunctions(
declaration, traitMember, declaration.containingDeclaration, traitMember.modality,
DescriptorVisibilities.PUBLIC, CallableMemberDescriptor.Kind.DECLARATION, true
Visibilities.PUBLIC, CallableMemberDescriptor.Kind.DECLARATION, true
)
else mapMembers(declaration, traitMember)
)
@@ -74,31 +80,33 @@ object CodegenUtil {
}
fun copyFunctions(
inheritedMember: CallableMemberDescriptor,
traitMember: CallableMemberDescriptor,
newOwner: DeclarationDescriptor,
modality: Modality,
visibility: DescriptorVisibility,
kind: CallableMemberDescriptor.Kind,
copyOverrides: Boolean
inheritedMember: CallableMemberDescriptor,
traitMember: CallableMemberDescriptor,
newOwner: DeclarationDescriptor,
modality: Modality,
visibility: Visibility,
kind: CallableMemberDescriptor.Kind,
copyOverrides: Boolean
): Map<FunctionDescriptor, FunctionDescriptor> =
mapMembers(inheritedMember.copy(newOwner, modality, visibility, kind, copyOverrides), traitMember)
private fun mapMembers(
inherited: CallableMemberDescriptor,
traitMember: CallableMemberDescriptor
): Map<FunctionDescriptor, FunctionDescriptor> = when (traitMember) {
is SimpleFunctionDescriptor -> mapOf(traitMember to inherited as FunctionDescriptor)
is PropertyDescriptor -> linkedMapOf<FunctionDescriptor, FunctionDescriptor>().also { result ->
): LinkedHashMap<FunctionDescriptor, FunctionDescriptor> {
val result = linkedMapOf<FunctionDescriptor, FunctionDescriptor>()
if (traitMember is SimpleFunctionDescriptor) {
result[traitMember] = inherited as FunctionDescriptor
} else if (traitMember is PropertyDescriptor) {
for (traitAccessor in traitMember.accessors) {
for (inheritedAccessor in (inherited as PropertyDescriptor).accessors) {
if ((inheritedAccessor is PropertyGetterDescriptor) == (traitAccessor is PropertyGetterDescriptor)) {
result[traitAccessor] = inheritedAccessor
if (inheritedAccessor::class.java == traitAccessor::class.java) { // same accessor kind
result.put(traitAccessor, inheritedAccessor)
}
}
}
}
else -> error("Unexpected member: $inherited")
return result
}
@JvmStatic

View File

@@ -16,11 +16,17 @@
package org.jetbrains.kotlin.backend.common
import org.jetbrains.kotlin.backend.common.CodegenUtil.getMemberToGenerate
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.BindingContextUtils
/**
* A platform-independent logic for generating data class synthetic methods.

View File

@@ -24,8 +24,6 @@ import org.jetbrains.kotlin.resolve.OverridingUtil
import org.jetbrains.kotlin.resolve.calls.callResolverUtil.isOrOverridesSynthesized
import org.jetbrains.kotlin.resolve.descriptorUtil.isTypeRefinementEnabled
import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.util.findImplementationFromInterface
import org.jetbrains.kotlin.util.findInterfaceImplementation
fun <Signature> generateBridgesForFunctionDescriptor(
descriptor: FunctionDescriptor,
@@ -83,4 +81,55 @@ open class DescriptorBasedFunctionHandle(val descriptor: FunctionDescriptor) : F
override fun toString(): String {
return descriptor.toString()
}
}
}
/**
* Given a fake override in a class, returns an overridden declaration with implementation in trait, such that a method delegating to that
* trait implementation should be generated into the class containing the fake override; or null if the given function is not a fake
* override of any trait implementation or such method was already generated into the superclass or is a method from Any.
*/
fun findInterfaceImplementation(descriptor: CallableMemberDescriptor): CallableMemberDescriptor? {
if (descriptor.kind.isReal) return null
if (isOrOverridesSynthesized(descriptor)) return null
val implementation = findImplementationFromInterface(descriptor) ?: return null
val immediateConcreteSuper = firstSuperMethodFromKotlin(descriptor, implementation) ?: return null
if (!DescriptorUtils.isInterface(immediateConcreteSuper.containingDeclaration)) {
// If this implementation is already generated into the superclass, we need not generate it again, it'll be inherited
return null
}
return immediateConcreteSuper
}
/**
* Given a fake override, returns an overridden non-abstract function from an interface which is the actual implementation of this function
* that should be called when the given fake override is called.
*/
fun findImplementationFromInterface(descriptor: CallableMemberDescriptor): CallableMemberDescriptor? {
val overridden = OverridingUtil.getOverriddenDeclarations(descriptor)
val filtered = OverridingUtil.filterOutOverridden(overridden)
val result = filtered.firstOrNull { it.modality != Modality.ABSTRACT } ?: return null
if (DescriptorUtils.isClassOrEnumClass(result.containingDeclaration)) return null
return result
}
/**
* Given a fake override and its implementation (non-abstract declaration) somewhere in supertypes,
* returns the first immediate super function of the given fake override which overrides that implementation.
* The returned function should be called from TImpl-bridges generated for the given fake override.
*/
fun firstSuperMethodFromKotlin(
descriptor: CallableMemberDescriptor,
implementation: CallableMemberDescriptor
): CallableMemberDescriptor? {
return descriptor.overriddenDescriptors.firstOrNull { overridden ->
overridden.modality != Modality.ABSTRACT &&
(overridden == implementation || OverridingUtil.overrides(overridden, implementation, overridden.module.isTypeRefinementEnabled()))
}
}

View File

@@ -1,15 +0,0 @@
plugins {
kotlin("jvm")
id("jps-compatible")
}
dependencies {
api(project(":core:compiler.common.jvm"))
api(project(":compiler:config.jvm"))
api(intellijCoreDep()) { includeJars("asm-all", "guava", rootProject = rootProject) }
}
sourceSets {
"main" { projectDefault() }
"test" {}
}

View File

@@ -1,450 +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.codegen;
import com.google.common.collect.ImmutableMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.builtins.PrimitiveType;
import org.jetbrains.kotlin.descriptors.Visibilities;
import org.jetbrains.kotlin.descriptors.Visibility;
import org.jetbrains.kotlin.descriptors.java.JavaVisibilities;
import org.jetbrains.kotlin.load.java.JvmAnnotationNames;
import org.jetbrains.kotlin.name.ClassId;
import org.jetbrains.kotlin.name.FqName;
import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.resolve.jvm.JvmClassName;
import org.jetbrains.kotlin.resolve.jvm.JvmPrimitiveType;
import org.jetbrains.org.objectweb.asm.AnnotationVisitor;
import org.jetbrains.org.objectweb.asm.MethodVisitor;
import org.jetbrains.org.objectweb.asm.Opcodes;
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.Map;
import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.*;
import static org.jetbrains.org.objectweb.asm.Opcodes.*;
public class AsmUtil {
private static final int NO_FLAG_LOCAL = 0;
public static final int NO_FLAG_PACKAGE_PRIVATE = 0;
@NotNull
private static final Map<Visibility, Integer> visibilityToAccessFlag = ImmutableMap.<Visibility, Integer>builder()
.put(Visibilities.Private.INSTANCE, ACC_PRIVATE)
.put(Visibilities.PrivateToThis.INSTANCE, ACC_PRIVATE)
.put(Visibilities.Protected.INSTANCE, ACC_PROTECTED)
.put(JavaVisibilities.ProtectedStaticVisibility.INSTANCE, ACC_PROTECTED)
.put(JavaVisibilities.ProtectedAndPackage.INSTANCE, ACC_PROTECTED)
.put(Visibilities.Public.INSTANCE, ACC_PUBLIC)
.put(Visibilities.Internal.INSTANCE, ACC_PUBLIC)
.put(Visibilities.Local.INSTANCE, NO_FLAG_LOCAL)
.put(JavaVisibilities.PackageVisibility.INSTANCE, NO_FLAG_PACKAGE_PRIVATE)
.build();
public static final String CAPTURED_PREFIX = "$";
public static final String THIS = "this";
public static final String THIS_IN_DEFAULT_IMPLS = "$this";
public static final String LABELED_THIS_FIELD = THIS + "_";
public static final String CAPTURED_LABELED_THIS_FIELD = CAPTURED_PREFIX + LABELED_THIS_FIELD;
public static final String INLINE_DECLARATION_SITE_THIS = "this_";
public static final String LABELED_THIS_PARAMETER = CAPTURED_PREFIX + THIS + "$";
public static final String CAPTURED_THIS_FIELD = "this$0";
public static final String RECEIVER_PARAMETER_NAME = "$receiver";
/*
This is basically an old convention. Starting from Kotlin 1.3, it was replaced with `$this_<label>`.
Note that it is still used for inlined callable references and anonymous callable extension receivers
even in 1.3.
*/
public static final String CAPTURED_RECEIVER_FIELD = "receiver$0";
// For non-inlined callable references ('kotlin.jvm.internal.CallableReference' has a 'receiver' field)
public static final String BOUND_REFERENCE_RECEIVER = "receiver";
public static final String LOCAL_FUNCTION_VARIABLE_PREFIX = "$fun$";
private static final ImmutableMap<Integer, JvmPrimitiveType> primitiveTypeByAsmSort;
private static final ImmutableMap<Type, Type> primitiveTypeByBoxedType;
static {
ImmutableMap.Builder<Integer, JvmPrimitiveType> typeBySortBuilder = ImmutableMap.builder();
ImmutableMap.Builder<Type, Type> typeByWrapperBuilder = ImmutableMap.builder();
for (JvmPrimitiveType primitiveType : JvmPrimitiveType.values()) {
Type asmType = Type.getType(primitiveType.getDesc());
typeBySortBuilder.put(asmType.getSort(), primitiveType);
typeByWrapperBuilder.put(asmTypeByFqNameWithoutInnerClasses(primitiveType.getWrapperFqName()), asmType);
}
primitiveTypeByAsmSort = typeBySortBuilder.build();
primitiveTypeByBoxedType = typeByWrapperBuilder.build();
}
private AsmUtil() {
}
@NotNull
public static String getCapturedFieldName(@NotNull String originalName) {
return CAPTURED_PREFIX + originalName;
}
@NotNull
public static String getLabeledThisName(@NotNull String callableName, @NotNull String prefix, @NotNull String defaultName) {
if (!Name.isValidIdentifier(callableName)) {
return defaultName;
}
return prefix + CommonVariableAsmNameManglingUtils.mangleNameIfNeeded(callableName);
}
@NotNull
public static Type boxType(@NotNull Type type) {
Type boxedType = boxPrimitiveType(type);
return boxedType != null ? boxedType : type;
}
@Nullable
public static Type boxPrimitiveType(@NotNull Type type) {
JvmPrimitiveType jvmPrimitiveType = primitiveTypeByAsmSort.get(type.getSort());
return jvmPrimitiveType != null ? asmTypeByFqNameWithoutInnerClasses(jvmPrimitiveType.getWrapperFqName()) : null;
}
@NotNull
public static Type unboxType(@NotNull Type boxedType) {
Type primitiveType = unboxPrimitiveTypeOrNull(boxedType);
if (primitiveType == null) {
throw new UnsupportedOperationException("Unboxing: " + boxedType);
}
return primitiveType;
}
@Nullable
public static Type unboxPrimitiveTypeOrNull(@NotNull Type boxedType) {
return primitiveTypeByBoxedType.get(boxedType);
}
public static boolean isBoxedPrimitiveType(@NotNull Type boxedType) {
return primitiveTypeByBoxedType.get(boxedType) != null;
}
@NotNull
public static Type unboxUnlessPrimitive(@NotNull Type boxedOrPrimitiveType) {
if (isPrimitive(boxedOrPrimitiveType)) return boxedOrPrimitiveType;
return unboxType(boxedOrPrimitiveType);
}
public static boolean isBoxedTypeOf(@NotNull Type boxedType, @NotNull Type unboxedType) {
return unboxPrimitiveTypeOrNull(boxedType) == unboxedType;
}
public static boolean isIntPrimitive(Type type) {
return type == Type.INT_TYPE || type == Type.SHORT_TYPE || type == Type.BYTE_TYPE || type == Type.CHAR_TYPE;
}
public static boolean isIntOrLongPrimitive(Type type) {
return isIntPrimitive(type) || type == Type.LONG_TYPE;
}
public static boolean isPrimitive(Type type) {
return type.getSort() != Type.OBJECT && type.getSort() != Type.ARRAY;
}
@NotNull
public static Type correctElementType(@NotNull Type type) {
String internalName = type.getInternalName();
assert internalName.charAt(0) == '[';
return Type.getType(internalName.substring(1));
}
@NotNull
public static Type getArrayType(@NotNull Type componentType) {
return Type.getType("[" + componentType.getDescriptor());
}
@Nullable
public static PrimitiveType asmPrimitiveTypeToLangPrimitiveType(Type type) {
JvmPrimitiveType jvmPrimitiveType = primitiveTypeByAsmSort.get(type.getSort());
return jvmPrimitiveType != null ? jvmPrimitiveType.getPrimitiveType() : null;
}
@NotNull
public static Method method(@NotNull String name, @NotNull Type returnType, @NotNull Type... parameterTypes) {
return new Method(name, Type.getMethodDescriptor(returnType, parameterTypes));
}
public static Type stringValueOfType(Type type) {
int sort = type.getSort();
return sort == Type.OBJECT || sort == Type.ARRAY
? OBJECT_TYPE
: sort == Type.BYTE || sort == Type.SHORT ? Type.INT_TYPE : type;
}
public static void genThrow(@NotNull InstructionAdapter v, @NotNull String exception, @Nullable String message) {
v.anew(Type.getObjectType(exception));
v.dup();
if (message != null) {
v.aconst(message);
v.invokespecial(exception, "<init>", "(Ljava/lang/String;)V", false);
}
else {
v.invokespecial(exception, "<init>", "()V", false);
}
v.athrow();
}
public static void genStringBuilderConstructor(InstructionAdapter v) {
v.visitTypeInsn(NEW, "java/lang/StringBuilder");
v.dup();
v.invokespecial("java/lang/StringBuilder", "<init>", "()V", false);
}
public static void genInvertBoolean(InstructionAdapter v) {
v.iconst(1);
v.xor(Type.INT_TYPE);
}
public static void numConst(int value, Type type, InstructionAdapter v) {
if (type == Type.FLOAT_TYPE) {
v.fconst(value);
}
else if (type == Type.DOUBLE_TYPE) {
v.dconst(value);
}
else if (type == Type.LONG_TYPE) {
v.lconst(value);
}
else if (type == Type.CHAR_TYPE || type == Type.BYTE_TYPE || type == Type.SHORT_TYPE || type == Type.INT_TYPE) {
v.iconst(value);
}
else {
throw new IllegalArgumentException("Primitive numeric type expected, got: " + type);
}
}
public static void swap(InstructionAdapter v, Type stackTop, Type afterTop) {
if (stackTop.getSize() == 1) {
if (afterTop.getSize() == 1) {
v.swap();
}
else {
v.dupX2();
v.pop();
}
}
else {
if (afterTop.getSize() == 1) {
v.dup2X1();
}
else {
v.dup2X2();
}
v.pop2();
}
}
public static void pushDefaultValueOnStack(@NotNull Type type, @NotNull InstructionAdapter v) {
v.visitInsn(defaultValueOpcode(type));
}
public static int defaultValueOpcode(@NotNull Type type) {
if (type.getSort() == Type.OBJECT || type.getSort() == Type.ARRAY) {
return ACONST_NULL;
}
if (type.getSort() == Type.FLOAT) {
return FCONST_0;
}
if (type.getSort() == Type.DOUBLE) {
return DCONST_0;
}
if (type.getSort() == Type.LONG) {
return LCONST_0;
}
return ICONST_0;
}
public static Type comparisonOperandType(Type left, Type right) {
if (left == Type.DOUBLE_TYPE || right == Type.DOUBLE_TYPE) return Type.DOUBLE_TYPE;
if (left == Type.FLOAT_TYPE || right == Type.FLOAT_TYPE) return Type.FLOAT_TYPE;
if (left == Type.LONG_TYPE || right == Type.LONG_TYPE) return Type.LONG_TYPE;
if (left == Type.CHAR_TYPE || right == Type.CHAR_TYPE) return Type.CHAR_TYPE;
return Type.INT_TYPE;
}
@NotNull
public static Type numberFunctionOperandType(@NotNull Type expectedType) {
if (expectedType == Type.SHORT_TYPE || expectedType == Type.BYTE_TYPE || expectedType == Type.CHAR_TYPE) {
return Type.INT_TYPE;
}
return expectedType;
}
public static void pop(@NotNull MethodVisitor v, @NotNull Type type) {
if (type.getSize() == 2) {
v.visitInsn(Opcodes.POP2);
}
else {
v.visitInsn(Opcodes.POP);
}
}
public static void pop2(@NotNull MethodVisitor v, @NotNull Type topOfStack, @NotNull Type afterTop) {
if (topOfStack.getSize() == 1 && afterTop.getSize() == 1) {
v.visitInsn(POP2);
} else {
pop(v, topOfStack);
pop(v, afterTop);
}
}
public static void pop2(@NotNull MethodVisitor v, @NotNull Type type) {
if (type.getSize() == 2) {
v.visitInsn(Opcodes.POP2);
v.visitInsn(Opcodes.POP2);
}
else {
v.visitInsn(Opcodes.POP2);
}
}
public static void dup(@NotNull InstructionAdapter v, @NotNull Type type) {
dup(v, type.getSize());
}
private static void dup(@NotNull InstructionAdapter v, int size) {
if (size == 2) {
v.dup2();
}
else if (size == 1) {
v.dup();
}
else {
throw new UnsupportedOperationException();
}
}
public static void dupx(@NotNull InstructionAdapter v, @NotNull Type type) {
dupx(v, type.getSize());
}
private static void dupx(@NotNull InstructionAdapter v, int size) {
if (size == 2) {
v.dup2X2();
}
else if (size == 1) {
v.dupX1();
}
else {
throw new UnsupportedOperationException();
}
}
// Duplicate the element afterTop and push it on the top of the stack.
public static void dupSecond(@NotNull InstructionAdapter v, @NotNull Type topOfStack, @NotNull Type afterTop) {
if (afterTop.getSize() == 0) {
return;
}
if (topOfStack.getSize() == 0) {
dup(v, afterTop);
} else if (topOfStack.getSize() == 1 && afterTop.getSize() == 1) {
v.dup2();
v.pop();
} else {
swap(v, topOfStack, afterTop);
if (topOfStack.getSize() == 1 && afterTop.getSize() == 2) {
v.dup2X1();
} else if (topOfStack.getSize() == 2 && afterTop.getSize() == 1) {
v.dupX2();
} else /* top = 2, after top = 2 */ {
v.dup2X2();
}
}
}
public static void dup(@NotNull InstructionAdapter v, @NotNull Type topOfStack, @NotNull Type afterTop) {
if (topOfStack.getSize() == 0 && afterTop.getSize() == 0) {
return;
}
if (topOfStack.getSize() == 0) {
dup(v, afterTop);
}
else if (afterTop.getSize() == 0) {
dup(v, topOfStack);
}
else if (afterTop.getSize() == 1) {
if (topOfStack.getSize() == 1) {
dup(v, 2);
}
else {
v.dup2X1();
v.pop2();
v.dupX2();
v.dupX2();
v.pop();
v.dup2X1();
}
}
else {
//Note: it's possible to write dup3 and dup4
throw new UnsupportedOperationException("Don't know how generate dup3/dup4 for: " + topOfStack + " and " + afterTop);
}
}
public static void writeAnnotationData(
@NotNull AnnotationVisitor av, @NotNull String[] data, @NotNull String[] strings
) {
AnnotationVisitor dataVisitor = av.visitArray(JvmAnnotationNames.METADATA_DATA_FIELD_NAME);
for (String string : data) {
dataVisitor.visit(null, string);
}
dataVisitor.visitEnd();
AnnotationVisitor stringsVisitor = av.visitArray(JvmAnnotationNames.METADATA_STRINGS_FIELD_NAME);
for (String string : strings) {
stringsVisitor.visit(null, string);
}
stringsVisitor.visitEnd();
}
@NotNull
public static Type asmTypeByFqNameWithoutInnerClasses(@NotNull FqName fqName) {
return Type.getObjectType(internalNameByFqNameWithoutInnerClasses(fqName));
}
@NotNull
public static Type asmTypeByClassId(@NotNull ClassId classId) {
return Type.getObjectType(classId.asString().replace('.', '$'));
}
@NotNull
public static String internalNameByFqNameWithoutInnerClasses(@NotNull FqName fqName) {
return JvmClassName.byFqNameWithoutInnerClasses(fqName).getInternalName();
}
public static void wrapJavaClassIntoKClass(@NotNull InstructionAdapter v) {
v.invokestatic(REFLECTION, "getOrCreateKotlinClass", Type.getMethodDescriptor(K_CLASS_TYPE, getType(Class.class)), false);
}
public static void wrapJavaClassesIntoKClasses(@NotNull InstructionAdapter v) {
v.invokestatic(REFLECTION, "getOrCreateKotlinClasses", Type.getMethodDescriptor(K_CLASS_ARRAY_TYPE, getType(Class[].class)), false);
}
@Nullable
public static Integer getVisibilityAccessFlag(Visibility visibility) {
return visibilityToAccessFlag.get(visibility);
}
}

View File

@@ -1,31 +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.
*/
@file:JvmName("CommonVariableAsmNameManglingUtils")
package org.jetbrains.kotlin.codegen
import org.jetbrains.kotlin.resolve.jvm.checkers.isValidDalvikCharacter
fun mangleNameIfNeeded(name: String): String {
if (name.all { it.isValidCharacter() }) {
return name
}
return buildString {
for (c in name) {
if (c.isValidCharacter()) {
append(c)
} else {
val hexString = Integer.toHexString(c.toInt())
assert(hexString.length <= 4)
append("_u").append(hexString)
}
}
}
}
private fun Char.isValidCharacter(): Boolean {
return this != '$' && this != '-' && isValidDalvikCharacter(this)
}

View File

@@ -1,43 +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.codegen.signature
import org.jetbrains.kotlin.builtins.PrimitiveType
import org.jetbrains.kotlin.codegen.AsmUtil
import org.jetbrains.kotlin.load.kotlin.JvmTypeFactory
import org.jetbrains.kotlin.resolve.jvm.AsmTypes
import org.jetbrains.org.objectweb.asm.Type
object AsmTypeFactory : JvmTypeFactory<Type> {
override fun boxType(possiblyPrimitiveType: Type): Type =
AsmUtil.boxType(possiblyPrimitiveType)
override fun createFromString(representation: String): Type =
Type.getType(representation)
override fun createPrimitiveType(primitiveType: PrimitiveType): Type =
AsmTypes.valueTypeForPrimitive(primitiveType)
override fun createObjectType(internalName: String): Type =
Type.getObjectType(internalName)
override fun toString(type: Type): String =
type.descriptor
override val javaLangClassType: Type
get() = AsmTypes.JAVA_CLASS_TYPE
}

View File

@@ -1,22 +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.
*/
@file:JvmName("DalvikIdentifierUtils")
package org.jetbrains.kotlin.resolve.jvm.checkers
fun isValidDalvikIdentifier(identifier: String): Boolean = identifier.all { isValidDalvikCharacter(it) }
// https://source.android.com/devices/tech/dalvik/dex-format.html#string-syntax
fun isValidDalvikCharacter(c: Char): Boolean = when (c) {
in 'A'..'Z' -> true
in 'a'..'z' -> true
in '0'..'9' -> true
'$', '-', '_' -> true
in '\u00a1' .. '\u1fff' -> true
in '\u2010' .. '\u2027' -> true
in '\u2030' .. '\ud7ff' -> true
in '\ue000' .. '\uffef' -> true
else -> false
}

View File

@@ -1,138 +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.types
import org.jetbrains.kotlin.codegen.AsmUtil
import org.jetbrains.kotlin.codegen.signature.AsmTypeFactory
import org.jetbrains.kotlin.load.kotlin.JvmDescriptorTypeWriter
import org.jetbrains.kotlin.load.kotlin.TypeMappingMode
import org.jetbrains.kotlin.load.kotlin.mapBuiltInType
import org.jetbrains.kotlin.resolve.jvm.AsmTypes
import org.jetbrains.kotlin.types.model.*
import org.jetbrains.org.objectweb.asm.Type
interface TypeMappingContext<Writer : JvmDescriptorTypeWriter<Type>> {
val typeContext: TypeSystemCommonBackendContextForTypeMapping
fun getClassInternalName(typeConstructor: TypeConstructorMarker): String
fun Writer.writeGenericType(type: SimpleTypeMarker, asmType: Type, mode: TypeMappingMode)
}
object AbstractTypeMapper {
fun <Writer : JvmDescriptorTypeWriter<Type>> mapClass(context: TypeMappingContext<Writer>, typeConstructor: TypeConstructorMarker): Type {
return with(context.typeContext) {
when {
typeConstructor.isClassTypeConstructor() -> {
mapType(context, typeConstructor.defaultType(), TypeMappingMode.CLASS_DECLARATION)
}
typeConstructor.isTypeParameter() -> {
mapType(context, typeConstructor.defaultType())
}
else -> error("Unknown type constructor: $typeConstructor")
}
}
}
fun <Writer : JvmDescriptorTypeWriter<Type>> mapType(
context: TypeMappingContext<Writer>,
type: KotlinTypeMarker,
mode: TypeMappingMode = TypeMappingMode.DEFAULT,
sw: Writer? = null
): Type = context.typeContext.mapType(context, type, mode, sw)
@OptIn(ExperimentalStdlibApi::class)
private fun <Writer : JvmDescriptorTypeWriter<Type>> TypeSystemCommonBackendContextForTypeMapping.mapType(
context: TypeMappingContext<Writer>,
type: KotlinTypeMarker,
mode: TypeMappingMode = TypeMappingMode.DEFAULT,
sw: Writer? = null
): Type {
if (type !is SimpleTypeMarker) {
error("Unexpected type: $type (original Kotlin type=$type of ${type.let { it::class }})")
}
if (type.isSuspendFunction()) {
val argumentsCount = type.argumentsCount()
val argumentsList = type.asArgumentList()
@Suppress("RemoveExplicitTypeArguments") // Workaround for KT-42175
val arguments = buildList<KotlinTypeMarker> {
for (i in 0 until (argumentsCount - 1)) {
this += argumentsList[i].adjustedType()
}
this += continuationTypeConstructor().typeWithArguments(argumentsList[argumentsCount - 1].adjustedType())
this += nullableAnyType()
}
val runtimeFunctionType = functionNTypeConstructor(arguments.size - 1).typeWithArguments(arguments)
return mapType(context, runtimeFunctionType, mode, sw)
}
mapBuiltInType(type, AsmTypeFactory, mode)?.let { builtInType ->
return boxTypeIfNeeded(builtInType, mode.needPrimitiveBoxing).also { asmType ->
with(context) { sw?.writeGenericType(type, asmType, mode) }
}
}
val typeConstructor = type.typeConstructor()
when {
type.isArrayOrNullableArray() -> {
val typeArgument = type.asArgumentList()[0]
val (variance, memberType) = when {
typeArgument.isStarProjection() -> Variance.OUT_VARIANCE to nullableAnyType()
else -> typeArgument.getVariance().toVariance() to typeArgument.getType()
}
require(memberType is SimpleTypeMarker)
val arrayElementType: Type
sw?.writeArrayType()
if (variance == Variance.IN_VARIANCE) {
arrayElementType = AsmTypes.OBJECT_TYPE
sw?.writeClass(arrayElementType)
} else {
arrayElementType = mapType(context, memberType, mode.toGenericArgumentMode(variance, ofArray = true), sw)
}
sw?.writeArrayEnd()
return AsmUtil.getArrayType(arrayElementType)
}
typeConstructor.isClassTypeConstructor() -> {
if (typeConstructor.isInlineClass() && !mode.needInlineClassWrapping) {
val expandedType = computeExpandedTypeForInlineClass(type)
require(expandedType is SimpleTypeMarker?)
if (expandedType != null) {
return mapType(context, expandedType, mode.wrapInlineClassesMode(), sw)
}
}
val asmType = if (mode.isForAnnotationParameter && type.isKClass())
AsmTypes.JAVA_CLASS_TYPE
else
Type.getObjectType(context.getClassInternalName(typeConstructor))
with(context) { sw?.writeGenericType(type, asmType, mode) }
return asmType
}
typeConstructor.isTypeParameter() -> {
val typeParameter = typeConstructor as TypeParameterMarker
return mapType(context, typeParameter.representativeUpperBound(), mode, null).also { asmType ->
sw?.writeTypeVariable(typeParameter.getName(), asmType)
}
}
else -> throw UnsupportedOperationException("Unknown type $type")
}
}
private fun boxTypeIfNeeded(possiblyPrimitiveType: Type, needBoxedType: Boolean): Type =
if (needBoxedType) AsmUtil.boxType(possiblyPrimitiveType) else possiblyPrimitiveType
private fun TypeVariance.toVariance(): Variance = when (this) {
TypeVariance.IN -> Variance.IN_VARIANCE
TypeVariance.OUT -> Variance.OUT_VARIANCE
TypeVariance.INV -> Variance.INVARIANT
}
}

View File

@@ -10,7 +10,6 @@ dependencies {
compile(project(":compiler:frontend"))
compile(project(":compiler:frontend.java"))
compile(project(":compiler:serialization"))
api(project(":compiler:backend.common.jvm"))
compileOnly(intellijCoreDep()) { includeJars("intellij-core", "asm-all", "guava", rootProject = rootProject) }
compileOnly(intellijDep()) { includeJars("trove4j", rootProject = rootProject) }
}

View File

@@ -27,7 +27,7 @@ class AccessorForCompanionObjectInstanceFieldDescriptor(
null, null, emptyList(), emptyList(),
companionObjectDescriptor.defaultType,
Modality.FINAL,
DescriptorVisibilities.LOCAL
Visibilities.LOCAL
)
}
@@ -41,4 +41,4 @@ class AccessorForCompanionObjectInstanceFieldDescriptor(
): FunctionDescriptorImpl {
throw UnsupportedOperationException("Accessor for companion object $companionObjectDescriptor should not be substituted")
}
}
}

Some files were not shown because too many files have changed in this diff Show More