Delete Kotlin IntelliJ IDEA plugin sources

Kotlin plugin sources were migrated to intellij-community:
https://github.com/JetBrains/intellij-community/tree/master/plugins/kotlin

Preserve `jps-plugin/testData/incremental`
because it's used in `compiler/incremental-compilation-impl/test`

Preserve `idea/testData/multiModuleHighlighting/multiplatform`
because it's used in `MppHighlightingTestDataWithGradleIT`
This commit is contained in:
Nikita Bobko
2021-07-19 18:33:33 +02:00
parent b8d74698f1
commit 39fa2b0baf
49333 changed files with 0 additions and 1160202 deletions
@@ -1,24 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="kotlin-runtime" level="project" />
<orderEntry type="module" module-name="frontend" />
<orderEntry type="module" module-name="plugin-api" />
<orderEntry type="module" module-name="allopen-cli" />
<orderEntry type="library" name="idea-full" level="project" />
<orderEntry type="library" scope="PROVIDED" name="gradle-and-groovy-plugin" level="project" />
<orderEntry type="module" module-name="idea" />
<orderEntry type="module" module-name="idea-maven" />
<orderEntry type="library" scope="PROVIDED" name="maven" level="project" />
<orderEntry type="module" module-name="cli-common" />
<orderEntry type="module" module-name="idea-jps-common" />
<orderEntry type="module" module-name="util" />
<orderEntry type="module" module-name="annotation-based-compiler-plugins-ide-support" />
</component>
</module>
@@ -1,64 +0,0 @@
description = "Kotlin AllOpen IDEA Plugin"
plugins {
kotlin("jvm")
id("jps-compatible")
}
dependencies {
compile(project(":kotlin-allopen-compiler-plugin"))
compileOnly(project(":compiler:util"))
compileOnly(project(":compiler:frontend"))
compileOnly(project(":compiler:cli-common"))
compileOnly(project(":idea"))
compileOnly(project(":idea:idea-jvm"))
compileOnly(project(":idea:idea-jps-common"))
compileOnly(project(":plugins:annotation-based-compiler-plugins-ide-support"))
compileOnly(intellijDep())
excludeInAndroidStudio(rootProject) { compileOnly(intellijPluginDep("maven")) }
compileOnly(intellijPluginDep("gradle"))
compileOnly(project(":idea:kotlin-gradle-tooling"))
testRuntime(project(":kotlin-reflect"))
testCompileOnly(project(":kotlin-serialization"))
testCompileOnly(project(":plugins:lint"))
testCompileOnly(project(":plugins:kapt3-idea"))
testCompileOnly(project(":plugins:android-extensions-compiler"))
testCompileOnly(project(":kotlin-android-extensions"))
testCompileOnly(project(":kotlin-android-extensions-runtime"))
testCompileOnly(project(":plugins:android-extensions-ide"))
testCompileOnly(project(":kotlin-allopen-compiler-plugin"))
testCompileOnly(project(":allopen-ide-plugin"))
testCompileOnly(project(":kotlin-imports-dumper-compiler-plugin"))
testCompileOnly(project(":kotlinx-serialization-compiler-plugin"))
testCompileOnly(project(":kotlinx-serialization-ide-plugin"))
testCompileOnly(project(":kotlin-sam-with-receiver-compiler-plugin"))
testCompileOnly(project(":noarg-ide-plugin"))
testCompileOnly(project(":sam-with-receiver-ide-plugin"))
testCompileOnly(project(":plugins:lombok:lombok-ide-plugin"))
testCompileOnly(project(":idea:idea-native"))
testCompileOnly(project(":idea:idea-gradle-native"))
testCompileOnly(projectTests(":idea:idea-test-framework"))
testCompileOnly(intellijDep())
testRuntimeOnly(intellijDep())
compileOnly(intellijPluginDep("java"))
testCompileOnly(intellijPluginDep("java"))
testRuntimeOnly(intellijPluginDep("java"))
}
sourceSets {
"main" { projectDefault() }
"test" { projectDefault() }
}
runtimeJar()
sourcesJar()
javadocJar()
projectTest(parallel = true)
@@ -1,39 +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.allopen.ide
import org.jetbrains.kotlin.allopen.AllOpenCommandLineProcessor
import org.jetbrains.kotlin.annotation.plugin.ide.AbstractAnnotationPluginGradleImportHandler
import org.jetbrains.kotlin.utils.PathUtil
class AllOpenGradleProjectImportHandler : AbstractAnnotationPluginGradleImportHandler<AllOpenModel>() {
override val compilerPluginId = AllOpenCommandLineProcessor.PLUGIN_ID
override val pluginName = "allopen"
override val annotationOptionName = AllOpenCommandLineProcessor.ANNOTATION_OPTION.optionName
override val pluginJarFileFromIdea = PathUtil.kotlinPathsForIdeaPlugin.allOpenPluginJarPath
override val modelKey = AllOpenProjectResolverExtension.KEY
override fun getAnnotationsForPreset(presetName: String): List<String> {
for ((name, annotations) in AllOpenCommandLineProcessor.SUPPORTED_PRESETS.entries) {
if (presetName == name) {
return annotations
}
}
return super.getAnnotationsForPreset(presetName)
}
}
@@ -1,53 +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.allopen.ide
import org.jetbrains.kotlin.allopen.AllOpenCommandLineProcessor
import org.jetbrains.kotlin.plugin.ide.CompilerPluginSetup.PluginOption
import org.jetbrains.kotlin.plugin.ide.AbstractMavenImportHandler
import org.jetbrains.kotlin.utils.PathUtil
class AllOpenMavenProjectImportHandler : AbstractMavenImportHandler() {
private companion object {
val ANNOTATION_PARAMETER_PREFIX = "all-open:${AllOpenCommandLineProcessor.ANNOTATION_OPTION.optionName}="
}
override val compilerPluginId = AllOpenCommandLineProcessor.PLUGIN_ID
override val pluginName = "allopen"
override val pluginJarFileFromIdea = PathUtil.kotlinPathsForIdeaPlugin.allOpenPluginJarPath
override fun getOptions(enabledCompilerPlugins: List<String>, compilerPluginOptions: List<String>): List<PluginOption>? {
if ("all-open" !in enabledCompilerPlugins && "spring" !in enabledCompilerPlugins) {
return null
}
val annotations = mutableListOf<String>()
for ((presetName, presetAnnotations) in AllOpenCommandLineProcessor.SUPPORTED_PRESETS) {
if (presetName in enabledCompilerPlugins) {
annotations.addAll(presetAnnotations)
}
}
annotations.addAll(compilerPluginOptions.mapNotNull { text ->
if (!text.startsWith(ANNOTATION_PARAMETER_PREFIX)) return@mapNotNull null
text.substring(ANNOTATION_PARAMETER_PREFIX.length)
})
return annotations.map { PluginOption(AllOpenCommandLineProcessor.ANNOTATION_OPTION.optionName, it) }
}
}
@@ -1,29 +0,0 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.allopen.ide
import com.intellij.openapi.util.Key
import org.jetbrains.kotlin.annotation.plugin.ide.*
class AllOpenProjectResolverExtension : AnnotationBasedPluginProjectResolverExtension<AllOpenModel>() {
companion object {
val KEY = Key<AllOpenModel>("AllOpenModel")
}
override val modelClass get() = AllOpenModel::class.java
override val userDataKey get() = KEY
}
@@ -1,67 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.allopen.ide
import org.jetbrains.kotlin.descriptors.*
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiModifier
import org.jetbrains.kotlin.annotation.plugin.ide.CachedAnnotationNames
import org.jetbrains.kotlin.annotation.plugin.ide.getAnnotationNames
import org.jetbrains.kotlin.asJava.UltraLightClassModifierExtension
import org.jetbrains.kotlin.extensions.AnnotationBasedExtension
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClass
import org.jetbrains.kotlin.psi.psiUtil.isPropertyParameter
import org.jetbrains.kotlin.util.isAnnotated
import org.jetbrains.kotlin.util.isOrdinaryClass
class AllOpenUltraLightClassModifierExtension(project: Project) :
AnnotationBasedExtension,
UltraLightClassModifierExtension {
private val cachedAnnotationsNames = CachedAnnotationNames(project, ALL_OPEN_ANNOTATION_OPTION_PREFIX)
override fun getAnnotationFqNames(modifierListOwner: KtModifierListOwner?): List<String> =
cachedAnnotationsNames.getAnnotationNames(modifierListOwner)
private val KtDeclaration.isMethodOrProperty get() = this is KtProperty || this is KtPropertyAccessor || this is KtFunction || (this is KtParameter && this.isPropertyParameter())
private fun isSuitableDeclaration(declaration: KtDeclaration): Boolean {
if (getAnnotationFqNames(declaration).isEmpty()) return false
val declarationToCheck = if (declaration.isMethodOrProperty) declaration.containingClass() else declaration
declarationToCheck ?: return false
if (!declarationToCheck.isOrdinaryClass || declarationToCheck !is KtClassOrObject) return false
if (declarationToCheck.superTypeListEntries.isEmpty() && !declarationToCheck.isAnnotated) return false
return true
}
override fun interceptModalityBuilding(
declaration: KtDeclaration,
descriptor: Lazy<DeclarationDescriptor?>,
modifier: String
): String {
//Final can be altered to Open only
if (modifier != PsiModifier.FINAL) return modifier
if (!isSuitableDeclaration(declaration)) return modifier
// Resolver will produce correct descriptor corresponding to modality from AllOpen.
// The easiest way to get new modality is to resolve the descriptor
return if ((descriptor.value as? MemberDescriptor)?.modality == Modality.OPEN) PsiModifier.OPEN else modifier
}
}
@@ -1,39 +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.allopen.ide
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.allopen.AbstractAllOpenDeclarationAttributeAltererExtension
import org.jetbrains.kotlin.allopen.AllOpenCommandLineProcessor.Companion.ANNOTATION_OPTION
import org.jetbrains.kotlin.allopen.AllOpenCommandLineProcessor.Companion.PLUGIN_ID
import org.jetbrains.kotlin.annotation.plugin.ide.CachedAnnotationNames
import org.jetbrains.kotlin.annotation.plugin.ide.getAnnotationNames
import org.jetbrains.kotlin.psi.KtModifierListOwner
internal val ALL_OPEN_ANNOTATION_OPTION_PREFIX = "plugin:$PLUGIN_ID:${ANNOTATION_OPTION.optionName}="
class IdeAllOpenDeclarationAttributeAltererExtension(val project: Project) :
AbstractAllOpenDeclarationAttributeAltererExtension() {
private val cachedAnnotationsNames = CachedAnnotationNames(project, ALL_OPEN_ANNOTATION_OPTION_PREFIX)
override fun getAnnotationFqNames(modifierListOwner: KtModifierListOwner?): List<String> {
return if (ApplicationManager.getApplication().isUnitTestMode) ANNOTATIONS_FOR_TESTS
else cachedAnnotationsNames.getAnnotationNames(modifierListOwner)
}
}
@@ -1,66 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.allopen
import com.intellij.lang.jvm.JvmModifier
import com.intellij.testFramework.LightProjectDescriptor
import org.jetbrains.kotlin.allopen.ide.ALL_OPEN_ANNOTATION_OPTION_PREFIX
import org.jetbrains.kotlin.config.LanguageVersion
import org.jetbrains.kotlin.idea.facet.KotlinFacet
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.test.KotlinProjectDescriptorWithFacet
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.test.JUnit3WithIdeaConfigurationRunner
import org.junit.runner.RunWith
@RunWith(JUnit3WithIdeaConfigurationRunner::class)
class TestAllOpenForLightClass : KotlinLightCodeInsightFixtureTestCase() {
companion object {
val allOpenAnnotationName = AbstractAllOpenDeclarationAttributeAltererExtension.ANNOTATIONS_FOR_TESTS.first()
const val targetClassName = "TargetClassName"
}
override fun getProjectDescriptor(): LightProjectDescriptor =
KotlinProjectDescriptorWithFacet(LanguageVersion.LATEST_STABLE, multiPlatform = false)
override fun setUp() {
super.setUp()
val facet = KotlinFacet.get(module) ?: error { "Facet not found" }
val configurationArguments = facet.configuration.settings.compilerArguments ?: error { "CompilerArguments not found" }
configurationArguments.pluginClasspaths = arrayOf("SomeClasspath")
configurationArguments.pluginOptions = arrayOf("$ALL_OPEN_ANNOTATION_OPTION_PREFIX$allOpenAnnotationName")
}
fun testAllOpenAnnotation() {
val file = myFixture.configureByText(
"A.kt",
"annotation class $allOpenAnnotationName\n"
+ "@$allOpenAnnotationName class $targetClassName(val e: Int)\n {"
+ " fun a() {}\n"
+ " val b = 32\n"
+ "}"
) as KtFile
val classes = file.classes
assertEquals(2, classes.size)
val targetClass = classes.firstOrNull { it.name == targetClassName }
?: error { "Expected class $targetClassName not found" }
assertFalse(targetClass.hasModifier(JvmModifier.FINAL))
targetClass.methods
.filter { !it.isConstructor }
.forEach {
assertFalse(it.hasModifier(JvmModifier.FINAL))
}
}
}
@@ -1,27 +0,0 @@
plugins {
kotlin("jvm")
id("jps-compatible")
}
dependencies {
compile(project(":compiler:util"))
compile(project(":compiler:frontend"))
compile(project(":compiler:cli-common"))
compile(project(":idea"))
compile(project(":idea:idea-jvm"))
compile(project(":idea:idea-jps-common"))
compile(project(":idea:idea-gradle"))
compile(project(":idea:idea-maven"))
api(project(":plugins:base-compiler-plugins-ide-support"))
excludeInAndroidStudio(rootProject) { compileOnly(intellijPluginDep("maven")) }
compileOnly(intellijPluginDep("gradle"))
compileOnly(intellijDep())
compileOnly(project(":idea:kotlin-gradle-tooling"))
}
sourceSets {
"main" { projectDefault() }
"test" {}
}
@@ -1,64 +0,0 @@
/*
* Copyright 2010-2021 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.annotation.plugin.ide
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.ProjectKeys
import com.intellij.openapi.externalSystem.model.project.ModuleData
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.util.Key
import org.jetbrains.kotlin.plugin.ide.CompilerPluginSetup.PluginOption
import org.jetbrains.kotlin.idea.configuration.GradleProjectImportHandler
import org.jetbrains.kotlin.idea.facet.KotlinFacet
import org.jetbrains.kotlin.plugin.ide.CompilerPluginSetup
import org.jetbrains.kotlin.plugin.ide.modifyCompilerArgumentsForPlugin
import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData
import java.io.File
abstract class AbstractAnnotationPluginGradleImportHandler<T : AnnotationBasedPluginModel> : GradleProjectImportHandler {
abstract val compilerPluginId: String
abstract val pluginName: String
abstract val annotationOptionName: String
abstract val pluginJarFileFromIdea: File
abstract val modelKey: Key<T>
override fun importBySourceSet(facet: KotlinFacet, sourceSetNode: DataNode<GradleSourceSetData>) {
modifyCompilerArgumentsForPlugin(facet, getPluginSetupBySourceSet(sourceSetNode),
compilerPluginId = compilerPluginId,
pluginName = pluginName)
}
override fun importByModule(facet: KotlinFacet, moduleNode: DataNode<ModuleData>) {
modifyCompilerArgumentsForPlugin(facet, getPluginSetupByModule(moduleNode),
compilerPluginId = compilerPluginId,
pluginName = pluginName)
}
protected open fun getAnnotationsForPreset(presetName: String): List<String> = emptyList()
protected open fun getAdditionalOptions(model: T): List<PluginOption> = emptyList()
private fun getPluginSetupByModule(
moduleNode: DataNode<ModuleData>
): CompilerPluginSetup? {
val pluginModel = moduleNode.getCopyableUserData(modelKey)?.takeIf { it.isEnabled } ?: return null
val annotations = pluginModel.annotations
val presets = pluginModel.presets
val allAnnotations = annotations + presets.flatMap { getAnnotationsForPreset(it) }
val options = allAnnotations.map { PluginOption(annotationOptionName, it) } + getAdditionalOptions(pluginModel)
// For now we can't use plugins from Gradle cause they're shaded and may have an incompatible version.
// So we use ones from the IDEA plugin.
val classpath = listOf(pluginJarFileFromIdea.absolutePath)
return CompilerPluginSetup(options, classpath)
}
private fun getPluginSetupBySourceSet(sourceSetNode: DataNode<GradleSourceSetData>) =
ExternalSystemApiUtil.findParent(sourceSetNode, ProjectKeys.MODULE)?.let { getPluginSetupByModule(it) }
}
@@ -1,56 +0,0 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.annotation.plugin.ide
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.project.ModuleData
import com.intellij.openapi.util.Key
import org.gradle.tooling.model.idea.IdeaModule
import org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension
@Suppress("unused")
abstract class AnnotationBasedPluginProjectResolverExtension<T : AnnotationBasedPluginModel> : AbstractProjectResolverExtension() {
private companion object {
private val LOG = Logger.getInstance(AnnotationBasedPluginProjectResolverExtension::class.java)
}
abstract val modelClass: Class<T>
abstract val userDataKey: Key<T>
override fun getExtraProjectModelClasses() = setOf(modelClass)
override fun getToolingExtensionsClasses() = setOf(
modelClass,
AnnotationBasedPluginProjectResolverExtension::class.java,
Unit::class.java)
override fun populateModuleExtraModels(gradleModule: IdeaModule, ideModule: DataNode<ModuleData>) {
val model = resolverCtx.getExtraProject(gradleModule, modelClass)
if (model != null) {
val (className, args) = model.dump()
@Suppress("UNCHECKED_CAST")
val refurbishedModel = Class.forName(className).constructors.single().newInstance(*args) as T
ideModule.putCopyableUserData(userDataKey, refurbishedModel)
}
super.populateModuleExtraModels(gradleModule, ideModule)
}
}
@@ -1,41 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.annotation.plugin.ide
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectRootModificationTracker
import com.intellij.psi.util.CachedValue
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.util.containers.ContainerUtil
import org.jetbrains.kotlin.psi.KtElement
import java.util.concurrent.ConcurrentMap
fun CachedAnnotationNames.getAnnotationNames(element: KtElement?): List<String> {
if (element === null) return emptyList()
val module = ModuleUtilCore.findModuleForPsiElement(element) ?: return emptyList()
return getNamesForModule(module)
}
class CachedAnnotationNames(project: Project, private val annotationOptionPrefix: String) {
private val cache: CachedValue<ConcurrentMap<Module, List<String>>> = cachedValue(project) {
CachedValueProvider.Result.create(
ContainerUtil.createConcurrentWeakMap<Module, List<String>>(),
ProjectRootModificationTracker.getInstance(project)
)
}
fun getNamesForModule(module: Module): List<String> {
return cache.value.getOrPut(module) { module.getSpecialAnnotations(annotationOptionPrefix) }
}
private fun <T> cachedValue(project: Project, result: () -> CachedValueProvider.Result<T>): CachedValue<T> {
return CachedValuesManager.getManager(project).createCachedValue(result, false)
}
}
@@ -1,29 +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.annotation.plugin.ide
import com.intellij.openapi.module.Module
fun Module.getSpecialAnnotations(prefix: String): List<String> {
val kotlinFacet = org.jetbrains.kotlin.idea.facet.KotlinFacet.get(this) ?: return emptyList()
val commonArgs = kotlinFacet.configuration.settings.compilerArguments ?: return emptyList()
return commonArgs.pluginOptions
?.filter { it.startsWith(prefix) }
?.map { it.substring(prefix.length) }
?: emptyList()
}
@@ -1,23 +0,0 @@
plugins {
kotlin("jvm")
id("jps-compatible")
}
dependencies {
implementation(project(":idea"))
implementation(project(":idea:idea-jvm"))
implementation(project(":idea:idea-jps-common"))
implementation(project(":idea:idea-gradle"))
implementation(project(":idea:idea-maven"))
excludeInAndroidStudio(rootProject) { compileOnly(intellijPluginDep("maven")) }
compileOnly(intellijPluginDep("gradle"))
compileOnly(intellijDep())
compileOnly(project(":idea:kotlin-gradle-tooling"))
}
sourceSets {
"main" { projectDefault() }
"test" {}
}
@@ -1,56 +0,0 @@
/*
* Copyright 2010-2021 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.plugin.ide
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.ProjectKeys
import com.intellij.openapi.externalSystem.model.project.ModuleData
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.util.Key
import org.jetbrains.kotlin.idea.configuration.GradleProjectImportHandler
import org.jetbrains.kotlin.idea.facet.KotlinFacet
import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData
import java.io.File
abstract class AbstractGradleImportHandler<T> : GradleProjectImportHandler {
abstract val modelKey: Key<T>
abstract val pluginJarFileFromIdea: File
abstract val compilerPluginId: String
abstract val pluginName: String
abstract fun getOptions(model: T): List<CompilerPluginSetup.PluginOption>?
override fun importBySourceSet(facet: KotlinFacet, sourceSetNode: DataNode<GradleSourceSetData>) {
modifyCompilerArgumentsForPlugin(
facet, getPluginSetupBySourceSet(sourceSetNode),
compilerPluginId = compilerPluginId,
pluginName = pluginName
)
}
override fun importByModule(facet: KotlinFacet, moduleNode: DataNode<ModuleData>) {
modifyCompilerArgumentsForPlugin(
facet, getPluginSetupByModule(moduleNode),
compilerPluginId = compilerPluginId,
pluginName = pluginName
)
}
private fun getPluginSetupByModule(moduleNode: DataNode<ModuleData>): CompilerPluginSetup? {
val pluginModel = moduleNode.getCopyableUserData(modelKey) ?: return null
val options = getOptions(pluginModel) ?: return null
// For now we can't use plugins from Gradle cause they're shaded and may have an incompatible version.
// So we use ones from the IDEA plugin.
val classpath = listOf(pluginJarFileFromIdea.absolutePath)
return CompilerPluginSetup(options, classpath)
}
private fun getPluginSetupBySourceSet(sourceSetNode: DataNode<GradleSourceSetData>) =
ExternalSystemApiUtil.findParent(sourceSetNode, ProjectKeys.MODULE)?.let { getPluginSetupByModule(it) }
}
@@ -1,68 +0,0 @@
/*
* Copyright 2010-2021 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.plugin.ide
import org.jdom.Element
import org.jdom.Text
import org.jetbrains.idea.maven.project.MavenProject
import org.jetbrains.kotlin.idea.facet.KotlinFacet
import org.jetbrains.kotlin.idea.maven.MavenProjectImportHandler
import org.jetbrains.kotlin.idea.maven.KotlinMavenImporter.Companion.KOTLIN_PLUGIN_GROUP_ID
import org.jetbrains.kotlin.idea.maven.KotlinMavenImporter.Companion.KOTLIN_PLUGIN_ARTIFACT_ID
import java.io.File
import org.jetbrains.kotlin.plugin.ide.CompilerPluginSetup.PluginOption
abstract class AbstractMavenImportHandler : MavenProjectImportHandler {
abstract val compilerPluginId: String
abstract val pluginName: String
abstract val pluginJarFileFromIdea: File
override fun invoke(facet: KotlinFacet, mavenProject: MavenProject) {
modifyCompilerArgumentsForPlugin(
facet, getPluginSetup(mavenProject),
compilerPluginId = compilerPluginId,
pluginName = pluginName
)
}
abstract fun getOptions(enabledCompilerPlugins: List<String>, compilerPluginOptions: List<String>): List<PluginOption>?
protected open fun getOptions(
mavenProject: MavenProject,
enabledCompilerPlugins: List<String>,
compilerPluginOptions: List<String>
): List<PluginOption>? = getOptions(enabledCompilerPlugins, compilerPluginOptions)
private fun getPluginSetup(mavenProject: MavenProject): CompilerPluginSetup? {
val kotlinPlugin = mavenProject.plugins.firstOrNull {
it.groupId == KOTLIN_PLUGIN_GROUP_ID && it.artifactId == KOTLIN_PLUGIN_ARTIFACT_ID
} ?: return null
val configuration = kotlinPlugin.configurationElement ?: return null
val enabledCompilerPlugins = configuration.getElement("compilerPlugins")
?.getElements()
?.flatMap { plugin -> plugin.content.mapNotNull { (it as? Text)?.text } }
?: emptyList()
val compilerPluginOptions = configuration.getElement("pluginOptions")
?.getElements()
?.flatMap { it.content }
?.mapTo(mutableListOf()) { (it as Text).text }
?: mutableListOf<String>()
// We can't use the plugin from Gradle as it may have the incompatible version
val classpath = listOf(pluginJarFileFromIdea.absolutePath)
val options = getOptions(mavenProject, enabledCompilerPlugins, compilerPluginOptions) ?: return null
return CompilerPluginSetup(options, classpath)
}
private fun Element.getElement(name: String) = content.firstOrNull { it is Element && it.name == name } as? Element
@Suppress("UNCHECKED_CAST")
private fun Element.getElements() = content.filterIsInstance<Element>()
}
@@ -1,48 +0,0 @@
/*
* Copyright 2010-2021 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.plugin.ide
import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments
import org.jetbrains.kotlin.idea.facet.KotlinFacet
import java.io.File
class CompilerPluginSetup(val options: List<PluginOption>, val classpath: List<String>) {
class PluginOption(val key: String, val value: String)
}
fun modifyCompilerArgumentsForPlugin(
facet: KotlinFacet,
setup: CompilerPluginSetup?,
compilerPluginId: String,
pluginName: String
) {
val facetSettings = facet.configuration.settings
// investigate why copyBean() sometimes throws exceptions
val commonArguments = facetSettings.compilerArguments ?: CommonCompilerArguments.DummyImpl()
/** See [CommonCompilerArguments.PLUGIN_OPTION_FORMAT] **/
val newOptionsForPlugin = setup?.options?.map { "plugin:$compilerPluginId:${it.key}=${it.value}" } ?: emptyList()
val oldAllPluginOptions =
(commonArguments.pluginOptions ?: emptyArray()).filterTo(mutableListOf()) { !it.startsWith("plugin:$compilerPluginId:") }
val newAllPluginOptions = oldAllPluginOptions + newOptionsForPlugin
val oldPluginClasspaths = (commonArguments.pluginClasspaths ?: emptyArray()).filterTo(mutableListOf()) {
val lastIndexOfFile = it.lastIndexOfAny(charArrayOf('/', File.separatorChar))
if (lastIndexOfFile < 0) {
return@filterTo true
}
!it.drop(lastIndexOfFile + 1).matches("(kotlin-)?(maven-)?$pluginName-.*\\.jar".toRegex())
}
val newPluginClasspaths = oldPluginClasspaths + (setup?.classpath ?: emptyList())
commonArguments.pluginOptions = newAllPluginOptions.toTypedArray()
commonArguments.pluginClasspaths = newPluginClasspaths.toTypedArray()
facetSettings.compilerArguments = commonArguments
}
-30
View File
@@ -1,30 +0,0 @@
plugins {
kotlin("jvm")
id("jps-compatible")
}
dependencies {
compile(kotlinStdlib())
compileOnly(project(":compiler:frontend"))
compileOnly(project(":idea")) { isTransitive = false }
compileOnly(project(":idea:kotlin-gradle-tooling"))
compileOnly(project(":idea:idea-core"))
compileOnly(project(":idea:idea-gradle"))
compileOnly(intellijDep())
compileOnly(intellijPluginDep("java"))
compileOnly(intellijPluginDep("gradle"))
compileOnly(intellijPluginDep("android"))
}
sourceSets {
"main" { projectDefault() }
"test" {}
}
runtimeJar()
sourcesJar()
javadocJar()
@@ -1,49 +0,0 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.kapt.idea
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.project.ModuleData
import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments
import org.jetbrains.kotlin.idea.configuration.GradleProjectImportHandler
import org.jetbrains.kotlin.idea.facet.KotlinFacet
import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData
import java.io.File
import java.util.*
class KaptGradleProjectImportHandler : GradleProjectImportHandler {
override fun importBySourceSet(facet: KotlinFacet, sourceSetNode: DataNode<GradleSourceSetData>) {
modifyCompilerArgumentsForPlugin(facet)
}
override fun importByModule(facet: KotlinFacet, moduleNode: DataNode<ModuleData>) {
modifyCompilerArgumentsForPlugin(facet)
}
private fun modifyCompilerArgumentsForPlugin(facet: KotlinFacet) {
val facetSettings = facet.configuration.settings
// Can't reuse const in Kapt3CommandLineProcessor, we don't have Kapt in the IDEA plugin
val compilerPluginId = "org.jetbrains.kotlin.kapt3"
val compilerArguments = facetSettings.compilerArguments ?: CommonCompilerArguments.DummyImpl()
val newPluginOptions = (compilerArguments.pluginOptions ?: emptyArray()).filter { !it.startsWith("plugin:$compilerPluginId:") }
val newPluginClasspath = (compilerArguments.pluginClasspaths ?: emptyArray()).filter { !isKaptCompilerPluginPath(it) }
fun List<String>.toArrayIfNotEmpty() = takeIf { it.isNotEmpty() }?.toTypedArray()
compilerArguments.pluginOptions = newPluginOptions.toArrayIfNotEmpty()
compilerArguments.pluginClasspaths = newPluginClasspath.toArrayIfNotEmpty()
facetSettings.compilerArguments = compilerArguments
}
private fun isKaptCompilerPluginPath(path: String): Boolean {
val lastIndexOfFile = path.lastIndexOfAny(charArrayOf('/', File.separatorChar)).takeIf { it >= 0 } ?: return false
val fileName = path.drop(lastIndexOfFile + 1).lowercase()
return fileName.matches("kotlin\\-annotation\\-processing(\\-gradle)?\\-[0-9].*\\.jar".toRegex())
}
}
@@ -1,87 +0,0 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.kapt.idea
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.ProjectKeys
import com.intellij.openapi.externalSystem.model.project.*
import org.gradle.tooling.model.idea.IdeaModule
import org.jetbrains.kotlin.idea.framework.GRADLE_SYSTEM_ID
import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData
import org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension
@Suppress("unused")
class KaptProjectResolverExtension : AbstractProjectResolverExtension() {
private companion object {
private val LOG = Logger.getInstance(KaptProjectResolverExtension::class.java)
}
override fun getExtraProjectModelClasses() = setOf(KaptGradleModel::class.java)
override fun getToolingExtensionsClasses() = setOf(KaptModelBuilderService::class.java, Unit::class.java)
override fun populateModuleExtraModels(gradleModule: IdeaModule, ideModule: DataNode<ModuleData>) {
val kaptModel = resolverCtx.getExtraProject(gradleModule, KaptGradleModel::class.java)
if (kaptModel != null && kaptModel.isEnabled) {
for (sourceSet in kaptModel.sourceSets) {
val parentDataNode = ideModule.findParentForSourceSetDataNode(sourceSet.sourceSetName) ?: continue
fun addSourceSet(path: String, type: ExternalSystemSourceType) {
val contentRootData = ContentRootData(GRADLE_SYSTEM_ID, path)
contentRootData.storePath(type, path)
parentDataNode.createChild(ProjectKeys.CONTENT_ROOT, contentRootData)
}
val sourceType =
if (sourceSet.isTest) ExternalSystemSourceType.TEST_GENERATED else ExternalSystemSourceType.SOURCE_GENERATED
sourceSet.generatedSourcesDirFile?.let { addSourceSet(it.absolutePath, sourceType) }
sourceSet.generatedKotlinSourcesDirFile?.let { addSourceSet(it.absolutePath, sourceType) }
sourceSet.generatedClassesDirFile?.let { generatedClassesDir ->
val libraryData = LibraryData(GRADLE_SYSTEM_ID, "kaptGeneratedClasses")
val existingNode =
parentDataNode.children.map { (it.data as? LibraryDependencyData)?.target }
.firstOrNull { it?.externalName == libraryData.externalName }
if (existingNode != null) {
existingNode.addPath(LibraryPathType.BINARY, generatedClassesDir.absolutePath)
} else {
libraryData.addPath(LibraryPathType.BINARY, generatedClassesDir.absolutePath)
val libraryDependencyData = LibraryDependencyData(parentDataNode.data, libraryData, LibraryLevel.MODULE)
parentDataNode.createChild(ProjectKeys.LIBRARY_DEPENDENCY, libraryDependencyData)
}
}
}
}
super.populateModuleExtraModels(gradleModule, ideModule)
}
private fun DataNode<ModuleData>.findParentForSourceSetDataNode(sourceSetName: String): DataNode<ModuleData>? {
val moduleName = data.id
for (child in children) {
val gradleSourceSetData = child.data as? GradleSourceSetData ?: continue
if (gradleSourceSetData.id == "$moduleName:$sourceSetName") {
@Suppress("UNCHECKED_CAST")
return child as? DataNode<ModuleData>
}
}
return this
}
}
@@ -1,53 +0,0 @@
description = "Kotlinx Serialization IDEA Plugin"
plugins {
kotlin("jvm")
id("jps-compatible")
}
dependencies {
compileOnly(project(":js:js.translator"))
compile(project(":kotlinx-serialization-compiler-plugin"))
compile(project(":idea"))
compile(project(":idea:idea-gradle"))
compile(project(":idea:idea-maven"))
compile(project(":plugins:annotation-based-compiler-plugins-ide-support"))
compileOnly(intellijDep())
compileOnly(intellijPluginDep("java"))
excludeInAndroidStudio(rootProject) { compileOnly(intellijPluginDep("maven")) }
compileOnly(intellijPluginDep("gradle"))
testCompile(toolsJar())
testCompile(projectTests(":idea"))
testCompile(projectTests(":compiler:tests-common"))
testCompile(projectTests(":idea:idea-test-framework"))
testCompile(project(":kotlin-test:kotlin-test-junit"))
testCompile(commonDep("junit:junit"))
testCompile(projectTests(":idea:idea-frontend-independent"))
testImplementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.1.0")
testRuntimeOnly(intellijCoreDep()) { includeJars("intellij-core") }
testRuntime(project(":allopen-ide-plugin"))
testRuntime(project(":plugins:parcelize:parcelize-ide"))
testRuntime(project(":sam-with-receiver-ide-plugin"))
testRuntime(project(":noarg-ide-plugin"))
testRuntime(project(":plugins:lombok:lombok-ide-plugin"))
testCompile(intellijDep())
testCompile(intellijPluginDep("java"))
}
sourceSets {
"main" { projectDefault() }
"test" { projectDefault() }
}
runtimeJar()
testsJar()
projectTest(parallel = true) {
workingDir = rootDir
}
@@ -1,2 +0,0 @@
extract.json.to.property=Extract Json format creation to property
replace.with.default.json.format=Replace with default Json format instance
@@ -1,96 +0,0 @@
/*
* Copyright 2010-2021 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.kotlinx.serialization.compiler.diagnostic
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.calls.callUtil.getReceiverExpression
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.checkers.CallChecker
import org.jetbrains.kotlin.resolve.calls.checkers.CallCheckerContext
import org.jetbrains.kotlin.resolve.calls.model.DefaultValueArgument
import org.jetbrains.kotlin.resolve.calls.model.ExpressionValueArgument
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.ResolvedValueArgument
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.idea.refactoring.fqName.fqName
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.unpackFunctionLiteral
import org.jetbrains.kotlin.resolve.BindingContext
class JsonFormatRedundantDiagnostic : CallChecker {
private val jsonFqName = FqName("kotlinx.serialization.json.Json")
private val jsonDefaultFqName = FqName("kotlinx.serialization.json.Json.Default")
private val parameterNameFrom = Name.identifier("from")
private val parameterNameBuilderAction = Name.identifier("builderAction")
override fun check(resolvedCall: ResolvedCall<*>, reportOn: PsiElement, context: CallCheckerContext) {
val functionDescriptor = resolvedCall.resultingDescriptor as? SimpleFunctionDescriptor ?: return
val bindingContext = context.trace.bindingContext
if (isJsonFormatCreation(functionDescriptor)) {
if (isDefaultFormat(resolvedCall, bindingContext)) {
context.trace.report(SerializationErrors.JSON_FORMAT_REDUNDANT_DEFAULT.on(resolvedCall.call.callElement))
}
return
}
val receiverExpression = resolvedCall.getReceiverExpression() ?: return
val receiverResolvedCall = receiverExpression.getResolvedCall(bindingContext) ?: return
val receiverFunctionDescriptor = receiverResolvedCall.resultingDescriptor as? SimpleFunctionDescriptor ?: return
if (isJsonFormatCreation(receiverFunctionDescriptor) && !isDefaultFormat(receiverResolvedCall, bindingContext)) {
context.trace.report(SerializationErrors.JSON_FORMAT_REDUNDANT.on(receiverExpression.originalElement))
}
}
private fun isJsonFormatCreation(descriptor: SimpleFunctionDescriptor): Boolean {
return descriptor.importableFqName == jsonFqName
}
private fun isDefaultFormat(resolvedCall: ResolvedCall<*>, context: BindingContext): Boolean {
var defaultFrom = false
var emptyBuilder = false
resolvedCall.valueArguments.forEach { (paramDesc, arg) ->
when (paramDesc.name) {
parameterNameFrom -> defaultFrom = isDefaultFormatArgument(arg, context)
parameterNameBuilderAction -> emptyBuilder = isEmptyFunctionArgument(arg)
}
}
return defaultFrom && emptyBuilder
}
private fun isDefaultFormatArgument(arg: ResolvedValueArgument, context: BindingContext): Boolean {
if (arg is DefaultValueArgument) return true
if (arg !is ExpressionValueArgument) return false
val expression = arg.valueArgument?.getArgumentExpression() ?: return false
val fqName = context[BindingContext.EXPRESSION_TYPE_INFO, expression]?.type?.fqName ?: return false
return fqName == jsonDefaultFqName
}
private fun isEmptyFunctionArgument(arg: ResolvedValueArgument): Boolean {
if (arg !is ExpressionValueArgument) {
return false
}
val argumentExpression = arg.valueArgument?.getArgumentExpression() ?: return false
val blockExpression = if (argumentExpression is KtNamedFunction) {
// anonymous functions
argumentExpression.bodyBlockExpression ?: return true
} else {
// function literal
argumentExpression.unpackFunctionLiteral()?.bodyExpression
}
return blockExpression?.statements?.isEmpty() ?: false
}
}
@@ -1,20 +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.kotlinx.serialization.compiler.diagnostic
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlinx.serialization.idea.getIfEnabledOn
class SerializationPluginIDEDeclarationChecker : SerializationPluginDeclarationChecker() {
override fun serializationPluginEnabledOn(descriptor: ClassDescriptor): Boolean {
// In the IDE, plugin is always in the classpath, but enabled only if corresponding compiler settings
// were imported into project model from Gradle.
return getIfEnabledOn(descriptor) { true } == true
}
override val isIde: Boolean
get() = true
}
@@ -1,42 +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.kotlinx.serialization.compiler.extensions
import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext
import org.jetbrains.kotlin.codegen.ImplementationBodyCodegen
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.ir.ObsoleteDescriptorBasedAPI
import org.jetbrains.kotlin.ir.declarations.IrModuleFragment
import org.jetbrains.kotlin.js.translate.context.TranslationContext
import org.jetbrains.kotlin.js.translate.declaration.DeclarationBodyVisitor
import org.jetbrains.kotlin.psi.KtPureClassOrObject
import org.jetbrains.kotlinx.serialization.idea.runIfEnabledIn
import org.jetbrains.kotlinx.serialization.idea.runIfEnabledOn
class SerializationIDECodegenExtension : SerializationCodegenExtension() {
override fun generateClassSyntheticParts(codegen: ImplementationBodyCodegen) =
runIfEnabledOn(codegen.descriptor) { super.generateClassSyntheticParts(codegen) }
}
class SerializationIDEJsExtension : SerializationJsExtension() {
override fun generateClassSyntheticParts(
declaration: KtPureClassOrObject,
descriptor: ClassDescriptor,
translator: DeclarationBodyVisitor,
context: TranslationContext
) = runIfEnabledOn(descriptor) {
super.generateClassSyntheticParts(declaration, descriptor, translator, context)
}
}
class SerializationIDEIrExtension : SerializationLoweringExtension() {
@OptIn(ObsoleteDescriptorBasedAPI::class)
override fun generate(moduleFragment: IrModuleFragment, pluginContext: IrPluginContext) {
runIfEnabledIn(pluginContext.moduleDescriptor) {
super.generate(moduleFragment, pluginContext)
}
}
}
@@ -1,25 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlinx.serialization.compiler.extensions
import org.jetbrains.kotlin.container.StorageComponentContainer
import org.jetbrains.kotlin.container.useInstance
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.extensions.StorageComponentContainerContributor
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlinx.serialization.compiler.diagnostic.JsonFormatRedundantDiagnostic
import org.jetbrains.kotlinx.serialization.compiler.diagnostic.SerializationPluginIDEDeclarationChecker
class SerializationIDEContainerContributor : StorageComponentContainerContributor {
override fun registerModuleComponents(
container: StorageComponentContainer,
platform: TargetPlatform,
moduleDescriptor: ModuleDescriptor
) {
container.useInstance(SerializationPluginIDEDeclarationChecker())
container.useInstance(JsonFormatRedundantDiagnostic())
}
}
@@ -1,73 +0,0 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlinx.serialization.compiler.extensions
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.descriptors.SimpleFunctionDescriptor
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.lazy.LazyClassContext
import org.jetbrains.kotlin.resolve.lazy.declarations.ClassMemberDeclarationProvider
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlinx.serialization.idea.getIfEnabledOn
import org.jetbrains.kotlinx.serialization.idea.runIfEnabledOn
import java.util.*
class SerializationIDEResolveExtension : SerializationResolveExtension() {
override fun getSyntheticNestedClassNames(thisDescriptor: ClassDescriptor): List<Name> =
getIfEnabledOn(thisDescriptor) { super.getSyntheticNestedClassNames(thisDescriptor) } ?: emptyList()
override fun getPossibleSyntheticNestedClassNames(thisDescriptor: ClassDescriptor): List<Name>? {
val enabled = getIfEnabledOn(thisDescriptor) { true } ?: false
return if (enabled) super.getPossibleSyntheticNestedClassNames(thisDescriptor)
else emptyList()
}
override fun getSyntheticFunctionNames(thisDescriptor: ClassDescriptor): List<Name> =
getIfEnabledOn(thisDescriptor) { super.getSyntheticFunctionNames(thisDescriptor) } ?: emptyList()
override fun generateSyntheticClasses(
thisDescriptor: ClassDescriptor,
name: Name,
ctx: LazyClassContext,
declarationProvider: ClassMemberDeclarationProvider,
result: MutableSet<ClassDescriptor>
) = runIfEnabledOn(thisDescriptor) {
super.generateSyntheticClasses(thisDescriptor, name, ctx, declarationProvider, result)
}
override fun getSyntheticCompanionObjectNameIfNeeded(thisDescriptor: ClassDescriptor): Name? = getIfEnabledOn(thisDescriptor) {
super.getSyntheticCompanionObjectNameIfNeeded(thisDescriptor)
}
override fun addSyntheticSupertypes(thisDescriptor: ClassDescriptor, supertypes: MutableList<KotlinType>) =
runIfEnabledOn(thisDescriptor) {
super.addSyntheticSupertypes(thisDescriptor, supertypes)
}
override fun generateSyntheticMethods(
thisDescriptor: ClassDescriptor,
name: Name,
bindingContext: BindingContext,
fromSupertypes: List<SimpleFunctionDescriptor>,
result: MutableCollection<SimpleFunctionDescriptor>
) = runIfEnabledOn(thisDescriptor) {
super.generateSyntheticMethods(thisDescriptor, name, bindingContext, fromSupertypes, result)
}
override fun generateSyntheticProperties(
thisDescriptor: ClassDescriptor,
name: Name,
bindingContext: BindingContext,
fromSupertypes: ArrayList<PropertyDescriptor>,
result: MutableSet<PropertyDescriptor>
) = runIfEnabledOn(thisDescriptor) {
super.generateSyntheticProperties(thisDescriptor, name, bindingContext, fromSupertypes, result)
}
}
@@ -1,22 +0,0 @@
/*
* Copyright 2010-2021 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.kotlinx.serialization.idea
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.PropertyKey
import org.jetbrains.kotlin.util.AbstractKotlinBundle
@NonNls
private const val BUNDLE = "messages.KotlinSerializationBundle"
object KotlinSerializationBundle : AbstractKotlinBundle(BUNDLE) {
@JvmStatic
fun message(@NonNls @PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any): String = getMessage(key, *params)
@JvmStatic
fun htmlMessage(@NonNls @PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any): String =
getMessage(key, *params).withHtml()
}
@@ -1,24 +0,0 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlinx.serialization.idea
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.project.ModuleData
import org.jetbrains.kotlin.idea.configuration.GradleProjectImportHandler
import org.jetbrains.kotlin.idea.facet.KotlinFacet
import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData
class KotlinSerializationGradleImportHandler : GradleProjectImportHandler {
override fun importBySourceSet(facet: KotlinFacet, sourceSetNode: DataNode<GradleSourceSetData>) {
KotlinSerializationImportHandler.modifyCompilerArguments(facet, PLUGIN_GRADLE_JAR)
}
override fun importByModule(facet: KotlinFacet, moduleNode: DataNode<ModuleData>) {
KotlinSerializationImportHandler.modifyCompilerArguments(facet, PLUGIN_GRADLE_JAR)
}
private val PLUGIN_GRADLE_JAR = "kotlin-serialization"
}
@@ -1,53 +0,0 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlinx.serialization.idea
import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments
import org.jetbrains.kotlin.idea.facet.KotlinFacet
import org.jetbrains.kotlin.utils.PathUtil
import java.io.File
internal object KotlinSerializationImportHandler {
private const val pluginJpsJarName = "kotlinx-serialization-compiler-plugin.jar"
val PLUGIN_JPS_JAR: String
get() = File(PathUtil.kotlinPathsForIdeaPlugin.libPath, pluginJpsJarName).absolutePath
fun isPluginJarPath(path: String): Boolean {
return path.endsWith(pluginJpsJarName)
}
fun modifyCompilerArguments(facet: KotlinFacet, buildSystemPluginJar: String) {
val facetSettings = facet.configuration.settings
val commonArguments = facetSettings.compilerArguments ?: CommonCompilerArguments.DummyImpl()
var pluginWasEnabled = false
val oldPluginClasspaths = (commonArguments.pluginClasspaths ?: emptyArray()).filterTo(mutableListOf()) {
val lastIndexOfFile = it.lastIndexOfAny(charArrayOf('/', File.separatorChar))
if (lastIndexOfFile < 0) {
return@filterTo true
}
val match = it.drop(lastIndexOfFile + 1).matches("$buildSystemPluginJar-.*\\.jar".toRegex())
if (match) pluginWasEnabled = true
!match
}
val newPluginClasspaths = if (pluginWasEnabled) oldPluginClasspaths + PLUGIN_JPS_JAR else oldPluginClasspaths
commonArguments.pluginClasspaths = newPluginClasspaths.toTypedArray()
facetSettings.compilerArguments = commonArguments
}
}
@@ -1,23 +0,0 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlinx.serialization.idea
import org.jetbrains.kotlin.plugin.ide.AbstractMavenImportHandler
import org.jetbrains.kotlin.plugin.ide.CompilerPluginSetup
import java.io.File
class KotlinSerializationMavenImportHandler : AbstractMavenImportHandler() {
override val compilerPluginId: String = "org.jetbrains.kotlinx.serialization"
override val pluginName: String = "serialization"
override val pluginJarFileFromIdea: File
get() = File(KotlinSerializationImportHandler.PLUGIN_JPS_JAR)
override fun getOptions(
enabledCompilerPlugins: List<String>,
compilerPluginOptions: List<String>
): List<CompilerPluginSetup.PluginOption>? =
if ("kotlinx-serialization" in enabledCompilerPlugins) emptyList() else null
}
@@ -1,29 +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.kotlinx.serialization.idea
import org.jetbrains.kotlin.analyzer.ModuleInfo
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.idea.core.unwrapModuleSourceInfo
import org.jetbrains.kotlin.idea.facet.KotlinFacet
import org.jetbrains.kotlin.resolve.descriptorUtil.module
private fun isEnabledIn(moduleDescriptor: ModuleDescriptor): Boolean {
val module = moduleDescriptor.getCapability(ModuleInfo.Capability)?.unwrapModuleSourceInfo()?.module ?: return false
val facet = KotlinFacet.get(module) ?: return false
val pluginClasspath = facet.configuration.settings.compilerArguments?.pluginClasspaths ?: return false
if (pluginClasspath.none(KotlinSerializationImportHandler::isPluginJarPath)) return false
return true
}
fun <T> getIfEnabledOn(clazz: ClassDescriptor, body: () -> T): T? {
return if (isEnabledIn(clazz.module)) body() else null
}
fun runIfEnabledOn(clazz: ClassDescriptor, body: () -> Unit) { getIfEnabledOn<Unit>(clazz, body) }
fun runIfEnabledIn(moduleDescriptor: ModuleDescriptor, block: () -> Unit) { if (isEnabledIn(moduleDescriptor)) block() }
@@ -1,42 +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.kotlinx.serialization.idea.quickfixes
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.quickfix.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory
import org.jetbrains.kotlin.idea.util.ImportInsertHelperImpl
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlinx.serialization.compiler.diagnostic.SerializationErrors
import org.jetbrains.kotlinx.serialization.compiler.resolve.SerializationAnnotations
internal class AddKotlinxSerializationTransientImportQuickFix(expression: PsiElement) :
KotlinQuickFixAction<PsiElement>(expression) {
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
// Do not use Helper itself because it does not insert import on conflict;
// so it will always fail because k.jvm.Transient is always in auto-import
ImportInsertHelperImpl.addImport(project, file, SerializationAnnotations.serialTransientFqName, allUnder = false)
}
override fun getFamilyName(): String = text
override fun getText(): String = "Import ${SerializationAnnotations.serialTransientFqName}"
object Factory : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
if (diagnostic.factory != SerializationErrors.INCORRECT_TRANSIENT) return null
val castedDiagnostic = SerializationErrors.INCORRECT_TRANSIENT.cast(diagnostic)
val element = castedDiagnostic.psiElement
return AddKotlinxSerializationTransientImportQuickFix(element)
}
}
}
@@ -1,39 +0,0 @@
/*
* Copyright 2010-2021 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.kotlinx.serialization.idea.quickfixes
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.quickfix.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlinx.serialization.compiler.diagnostic.SerializationErrors
import org.jetbrains.kotlinx.serialization.idea.KotlinSerializationBundle
internal class JsonRedundantDefaultQuickFix(expression: KtCallExpression) : KotlinQuickFixAction<KtCallExpression>(expression) {
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val call = element as? KtCallExpression ?: return
val callee = call.calleeExpression ?: return
call.replace(callee)
}
override fun getFamilyName(): String = text
override fun getText(): String = KotlinSerializationBundle.message("replace.with.default.json.format")
object Factory : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
if (diagnostic.factory != SerializationErrors.JSON_FORMAT_REDUNDANT_DEFAULT) return null
val castedDiagnostic = SerializationErrors.JSON_FORMAT_REDUNDANT_DEFAULT.cast(diagnostic)
val element: KtCallExpression = castedDiagnostic.psiElement as? KtCallExpression ?: return null
return JsonRedundantDefaultQuickFix(element)
}
}
}
@@ -1,79 +0,0 @@
/*
* Copyright 2010-2021 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.kotlinx.serialization.idea.quickfixes
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.ScrollType
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.quickfix.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory
import org.jetbrains.kotlin.idea.refactoring.chooseContainerElementIfNecessary
import org.jetbrains.kotlin.idea.refactoring.getExtractionContainers
import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.*
import org.jetbrains.kotlin.idea.refactoring.introduce.introduceProperty.KotlinIntroducePropertyHandler
import org.jetbrains.kotlin.idea.refactoring.introduce.showErrorHintByKey
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getOutermostParentContainedIn
import org.jetbrains.kotlinx.serialization.compiler.diagnostic.SerializationErrors
import org.jetbrains.kotlinx.serialization.idea.KotlinSerializationBundle
internal class JsonRedundantQuickFix(expression: KtCallExpression) : KotlinQuickFixAction<KtCallExpression>(expression) {
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
editor ?: return
val element = element ?: return
selectContainer(element, project, editor) {
editor.scrollingModel.scrollToCaret(ScrollType.MAKE_VISIBLE)
val outermostParent = element.getOutermostParentContainedIn(it)
if (outermostParent == null) {
showErrorHintByKey(project, editor, "cannot.refactor.no.container", text)
return@selectContainer
}
KotlinIntroducePropertyHandler().doInvoke(project, editor, file, listOf(element), outermostParent)
}
}
override fun getFamilyName(): String = text
override fun getText(): String = KotlinSerializationBundle.message("extract.json.to.property")
object Factory : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
if (diagnostic.factory != SerializationErrors.JSON_FORMAT_REDUNDANT) return null
val castedDiagnostic = SerializationErrors.JSON_FORMAT_REDUNDANT.cast(diagnostic)
val element: KtCallExpression = castedDiagnostic.psiElement as? KtCallExpression ?: return null
return JsonRedundantQuickFix(element)
}
}
private fun selectContainer(element: PsiElement, project: Project, editor: Editor, onSelect: (PsiElement) -> Unit) {
val parent = element.parent ?: throw AssertionError("Should have at least one parent")
val containers = parent.getExtractionContainers(strict = true, includeAll = true)
.filter { it is KtClassBody || (it is KtFile && !it.isScript()) }
if (containers.isEmpty()) {
showErrorHintByKey(project, editor, "cannot.refactor.no.container", text)
return
}
chooseContainerElementIfNecessary(
containers,
editor,
KotlinBundle.message("title.select.target.code.block"),
true,
{ it },
{ onSelect(it) }
)
}
}
@@ -1,18 +0,0 @@
/*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlinx.serialization.idea.quickfixes
import org.jetbrains.kotlin.idea.quickfix.QuickFixContributor
import org.jetbrains.kotlin.idea.quickfix.QuickFixes
import org.jetbrains.kotlinx.serialization.compiler.diagnostic.SerializationErrors
class SerializationQuickFixContributor : QuickFixContributor {
override fun registerQuickFixes(quickFixes: QuickFixes) {
quickFixes.register(SerializationErrors.INCORRECT_TRANSIENT, AddKotlinxSerializationTransientImportQuickFix.Factory)
quickFixes.register(SerializationErrors.JSON_FORMAT_REDUNDANT_DEFAULT, JsonRedundantDefaultQuickFix.Factory)
quickFixes.register(SerializationErrors.JSON_FORMAT_REDUNDANT, JsonRedundantQuickFix.Factory)
}
}
@@ -1,26 +0,0 @@
/*
* Copyright 2010-2021 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.kotlinx.serialization.idea
import org.jetbrains.kotlin.ObsoleteTestInfrastructure
import org.jetbrains.kotlin.checkers.AbstractDiagnosticsTest
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
import org.jetbrains.kotlin.cli.jvm.config.JvmClasspathRoot
import org.jetbrains.kotlin.extensions.StorageComponentContainerContributor
import org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationIDEContainerContributor
@OptIn(ObsoleteTestInfrastructure::class)
abstract class AbstractSerializationPluginIdeDiagnosticTest : AbstractDiagnosticsTest() {
private val coreLibraryPath = getSerializationCoreLibraryJar()!!
private val jsonLibraryPath = getSerializationJsonLibraryJar()!!
override fun setupEnvironment(environment: KotlinCoreEnvironment) {
if (!StorageComponentContainerContributor.getInstances(project).any { it is SerializationIDEContainerContributor }) {
StorageComponentContainerContributor.registerExtension(project, SerializationIDEContainerContributor())
}
environment.updateClasspath(listOf(JvmClasspathRoot(coreLibraryPath), JvmClasspathRoot(jsonLibraryPath)))
}
}
@@ -1,26 +0,0 @@
/*
* Copyright 2010-2021 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.kotlinx.serialization.idea
import org.jetbrains.kotlin.idea.quickfix.AbstractQuickFixTest
import org.jetbrains.kotlin.idea.test.ConfigLibraryUtil
abstract class AbstractSerializationQuickFixTest : AbstractQuickFixTest() {
override fun setUp() {
super.setUp()
val coreJar = getSerializationCoreLibraryJar()!!
val jsonJar = getSerializationJsonLibraryJar()!!
ConfigLibraryUtil.addLibrary(module, "Serialization core", coreJar.parentFile.absolutePath, arrayOf(coreJar.name))
ConfigLibraryUtil.addLibrary(module, "Serialization JSON", jsonJar.parentFile.absolutePath, arrayOf(jsonJar.name))
}
override fun tearDown() {
ConfigLibraryUtil.removeLibrary(module, "Serialization JSON")
ConfigLibraryUtil.removeLibrary(module, "Serialization core")
super.tearDown()
}
}
@@ -1,18 +0,0 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlinx.serialization.idea
import junit.framework.TestCase
import org.jetbrains.kotlin.idea.caches.lightClasses.annotations.KOTLINX_SERIALIZABLE_FQ_NAME
import org.jetbrains.kotlin.idea.caches.lightClasses.annotations.KOTLINX_SERIALIZER_FQ_NAME
import org.jetbrains.kotlinx.serialization.compiler.resolve.SerializationAnnotations
class AnnotationNamesConsistencyTest : TestCase() {
fun testConsistency() {
assertEquals(KOTLINX_SERIALIZABLE_FQ_NAME, SerializationAnnotations.serializableAnnotationFqName)
assertEquals(KOTLINX_SERIALIZER_FQ_NAME, SerializationAnnotations.serializerAnnotationFqName)
}
}
@@ -1,44 +0,0 @@
/*
* Copyright 2010-2021 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.kotlinx.serialization.idea
import junit.framework.TestCase
import org.jetbrains.kotlin.utils.PathUtil
import org.jetbrains.kotlinx.serialization.compiler.diagnostic.VersionReader
import org.junit.Test
import java.io.File
import kotlin.test.assertTrue
class RuntimeLibraryInClasspathTest {
private val runtimeLibraryPath = getSerializationCoreLibraryJar()
@Test
fun testRuntimeLibraryExists() {
TestCase.assertNotNull(
"kotlinx-serialization runtime library is not found. Make sure it is present in test classpath",
runtimeLibraryPath
)
}
@Test
fun testRuntimeHasSufficientVersion() {
val version = VersionReader.getVersionsFromManifest(runtimeLibraryPath!!)
assertTrue(version.currentCompilerMatchRequired(), "Runtime version too high")
assertTrue(version.implementationVersionMatchSupported(), "Runtime version too low")
}
}
internal fun getSerializationCoreLibraryJar(): File? = try {
PathUtil.getResourcePathForClass(Class.forName("kotlinx.serialization.KSerializer"))
} catch (e: ClassNotFoundException) {
null
}
internal fun getSerializationJsonLibraryJar(): File? = try {
PathUtil.getResourcePathForClass(Class.forName("kotlinx.serialization.json.Json"))
} catch (e: ClassNotFoundException) {
null
}
@@ -1,36 +0,0 @@
/*
* Copyright 2010-2021 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.kotlinx.serialization.idea;
import com.intellij.testFramework.TestDataPath;
import org.jetbrains.kotlin.test.JUnit3RunnerWithInners;
import org.jetbrains.kotlin.test.KotlinTestUtils;
import org.jetbrains.kotlin.test.util.KtTestUtil;
import org.jetbrains.kotlin.test.TestMetadata;
import org.junit.runner.RunWith;
import java.io.File;
import java.util.regex.Pattern;
/** This class is generated by {@link org.jetbrains.kotlin.generators.tests.TestsPackage}. DO NOT MODIFY MANUALLY */
@SuppressWarnings("all")
@TestMetadata("plugins/kotlin-serialization/kotlin-serialization-ide/testData/diagnostics")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
public class SerializationPluginIdeDiagnosticTestGenerated extends AbstractSerializationPluginIdeDiagnosticTest {
private void runTest(String testDataFilePath) throws Exception {
KotlinTestUtils.runTest(this::doTest, this, testDataFilePath);
}
public void testAllFilesPresentInDiagnostics() throws Exception {
KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("plugins/kotlin-serialization/kotlin-serialization-ide/testData/diagnostics"), Pattern.compile("^(.+)\\.kt$"), null, true);
}
@TestMetadata("JsonRedundantFormat.kt")
public void testJsonRedundantFormat() throws Exception {
runTest("plugins/kotlin-serialization/kotlin-serialization-ide/testData/diagnostics/JsonRedundantFormat.kt");
}
}
@@ -1,41 +0,0 @@
/*
* Copyright 2010-2021 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.kotlinx.serialization.idea;
import com.intellij.testFramework.TestDataPath;
import org.jetbrains.kotlin.test.JUnit3RunnerWithInners;
import org.jetbrains.kotlin.test.KotlinTestUtils;
import org.jetbrains.kotlin.test.util.KtTestUtil;
import org.jetbrains.kotlin.test.TestMetadata;
import org.junit.runner.RunWith;
import java.io.File;
import java.util.regex.Pattern;
/** This class is generated by {@link org.jetbrains.kotlin.generators.tests.TestsPackage}. DO NOT MODIFY MANUALLY */
@SuppressWarnings("all")
@TestMetadata("plugins/kotlin-serialization/kotlin-serialization-ide/testData/quickfix")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
public class SerializationQuickFixTestGenerated extends AbstractSerializationQuickFixTest {
private void runTest(String testDataFilePath) throws Exception {
KotlinTestUtils.runTest(this::doTest, this, testDataFilePath);
}
public void testAllFilesPresentInQuickfix() throws Exception {
KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("plugins/kotlin-serialization/kotlin-serialization-ide/testData/quickfix"), Pattern.compile("^([\\w\\-_]+)\\.kt$"), null, true);
}
@TestMetadata("DefaultFormat.kt")
public void testDefaultFormat() throws Exception {
runTest("plugins/kotlin-serialization/kotlin-serialization-ide/testData/quickfix/DefaultFormat.kt");
}
@TestMetadata("DefaultFormatWithAlias.kt")
public void testDefaultFormatWithAlias() throws Exception {
runTest("plugins/kotlin-serialization/kotlin-serialization-ide/testData/quickfix/DefaultFormatWithAlias.kt");
}
}
@@ -1,82 +0,0 @@
// !DIAGNOSTICS: -UNUSED_PARAMETER,-UNUSED_VARIABLE,-EXPERIMENTAL_API_USAGE
// SKIP_TXT
// FILE: test.kt
import kotlinx.serialization.*
import kotlinx.serialization.json.*
object Instance
val defaultWarn = <!JSON_FORMAT_REDUNDANT_DEFAULT!>Json {}<!>
val receiverWarn = <!JSON_FORMAT_REDUNDANT!>Json {encodeDefaults = true}<!>.encodeToString(Instance)
val noWarnFormat = Json {encodeDefaults = true}
val receiverNoWarn = noWarnFormat.encodeToString(Instance)
val defaultNoWarn = Json.encodeToString(Instance)
class SomeContainerClass {
val memberDefaultWarn = <!JSON_FORMAT_REDUNDANT_DEFAULT!>Json {}<!>
val memberReceiverWarn = <!JSON_FORMAT_REDUNDANT!>Json {encodeDefaults = true}<!>.encodeToString(Instance)
val memberNoWarnFormat = Json {encodeDefaults = true}
val memberReceiverNoWarn = noWarnFormat.encodeToString(Instance)
val memberDefaultNoWarn = Json.encodeToString(Instance)
fun testDefaultWarnings() {
<!JSON_FORMAT_REDUNDANT_DEFAULT!>Json {}<!>
<!JSON_FORMAT_REDUNDANT_DEFAULT!>Json() {}<!>
<!JSON_FORMAT_REDUNDANT_DEFAULT!>Json {}<!>.encodeToString(Any())
<!JSON_FORMAT_REDUNDANT_DEFAULT!>Json {}<!>.encodeToString(Instance)
<!JSON_FORMAT_REDUNDANT_DEFAULT!>Json { /*some comment*/ }<!>.encodeToString(Instance)
val localDefaultFormat = <!JSON_FORMAT_REDUNDANT_DEFAULT!>Json {}<!>
<!JSON_FORMAT_REDUNDANT_DEFAULT!>Json(Json.Default) {}<!>
<!JSON_FORMAT_REDUNDANT_DEFAULT!>Json(Json) {}<!>
<!JSON_FORMAT_REDUNDANT_DEFAULT!>Json(Json.Default, {})<!>
<!JSON_FORMAT_REDUNDANT_DEFAULT!>Json(builderAction = {})<!>
<!JSON_FORMAT_REDUNDANT_DEFAULT!>Json(builderAction = fun JsonBuilder.() {})<!>
<!JSON_FORMAT_REDUNDANT_DEFAULT!>Json(builderAction = fun JsonBuilder.() = Unit)<!>
"{}".let {
<!JSON_FORMAT_REDUNDANT_DEFAULT!>Json {}<!>.decodeFromString<Any>(it)
}
}
fun testReceiverWarnings() {
<!JSON_FORMAT_REDUNDANT!>Json {encodeDefaults = true}<!>.encodeToString(Instance)
val encoded = <!JSON_FORMAT_REDUNDANT!>Json {encodeDefaults = true}<!>.encodeToString(Instance)
<!JSON_FORMAT_REDUNDANT!>Json {encodeDefaults = true}<!>.decodeFromString<Any>("{}")
<!JSON_FORMAT_REDUNDANT!>Json {encodeDefaults = true}<!>.hashCode()
<!JSON_FORMAT_REDUNDANT!>Json {encodeDefaults = true}<!>.toString()
<!JSON_FORMAT_REDUNDANT!>Json(noWarnFormat) {encodeDefaults = true}<!>.encodeToString(Instance)
<!JSON_FORMAT_REDUNDANT!>Json(builderAction = {encodeDefaults = true})<!>.encodeToString(Instance)
<!JSON_FORMAT_REDUNDANT!>Json(noWarnFormat, {encodeDefaults = true})<!>.encodeToString(Instance)
<!JSON_FORMAT_REDUNDANT!>Json(builderAction = fun JsonBuilder.() {encodeDefaults = true})<!>.encodeToString(Instance)
"{}".let {
<!JSON_FORMAT_REDUNDANT!>Json {encodeDefaults = true}<!>.decodeFromString<Any>(it)
}
}
fun testReceiverNoWarnings() {
val localFormat = Json {encodeDefaults = true}
localFormat.encodeToString(Instance)
localFormat.decodeFromString<Any>("{}")
localFormat.hashCode()
localFormat.toString()
}
fun testDefaultNoWarnings() {
val localDefault = Json
Json.encodeToString(Instance)
Json.decodeFromString<Any>("{}")
Json.hashCode()
Json.toString()
Json(builderAction = this::builder)
Json(Json.Default, this::builder)
}
private fun builder(builder: JsonBuilder) {
//now its empty builder
}
}
@@ -1,7 +0,0 @@
// "Replace with default Json format instance" "true"
import kotlinx.serialization.*
import kotlinx.serialization.json.*
fun foo() {
<caret>Json {}.encodeToString(Any())
}
@@ -1,7 +0,0 @@
// "Replace with default Json format instance" "true"
import kotlinx.serialization.*
import kotlinx.serialization.json.*
fun foo() {
Json.encodeToString(Any())
}
@@ -1,8 +0,0 @@
// "Replace with default Json format instance" "true"
import kotlinx.serialization.*
import kotlinx.serialization.json.*
import kotlinx.serialization.json.Json as Alias
fun foo() {
<caret>Alias {}
}
@@ -1,8 +0,0 @@
// "Replace with default Json format instance" "true"
import kotlinx.serialization.*
import kotlinx.serialization.json.*
import kotlinx.serialization.json.Json as Alias
fun foo() {
Alias
}
-29
View File
@@ -1,29 +0,0 @@
plugins {
java
kotlin("jvm")
id("jps-compatible")
}
dependencies {
compile(project(":compiler:frontend"))
compile(project(":idea"))
compile(project(":idea:idea-jvm"))
compile(project(":idea:idea-core"))
compile(project(":idea:idea-android"))
compile(project(":plugins:uast-kotlin"))
compileOnly(project(":kotlin-android-extensions-runtime"))
compileOnly(intellijDep())
compileOnly(intellijPluginDep("android"))
}
sourceSets {
"main" {
java.srcDirs("android-annotations/src",
"lint-api/src",
"lint-checks/src",
"lint-idea/src")
}
"test" {}
}
@@ -1,34 +0,0 @@
description = "Lombok IDE plugin"
plugins {
kotlin("jvm")
id("jps-compatible")
}
dependencies {
implementation(project(":plugins:lombok:lombok-compiler-plugin"))
implementation(project(":plugins:base-compiler-plugins-ide-support"))
compileOnly(project(":idea"))
compileOnly(project(":idea:idea-jvm"))
compileOnly(project(":idea:idea-jps-common"))
compileOnly(project(":idea:idea-maven"))
compileOnly(project(":idea:idea-gradle"))
compileOnly(intellijDep())
excludeInAndroidStudio(rootProject) { compileOnly(intellijPluginDep("maven")) }
compileOnly(intellijPluginDep("gradle"))
compileOnly(project(":idea:kotlin-gradle-tooling"))
}
sourceSets {
"main" { projectDefault() }
"test" { projectDefault() }
}
runtimeJar()
sourcesJar()
javadocJar()
projectTest(parallel = true)
@@ -1,29 +0,0 @@
/*
* Copyright 2010-2021 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.lombok.ide
import com.intellij.openapi.util.Key
import org.jetbrains.kotlin.lombok.LombokCommandLineProcessor
import org.jetbrains.kotlin.lombok.LombokCommandLineProcessor.Companion.CONFIG_FILE_OPTION
import org.jetbrains.kotlin.plugin.ide.AbstractGradleImportHandler
import org.jetbrains.kotlin.plugin.ide.CompilerPluginSetup
import org.jetbrains.kotlin.utils.PathUtil
import java.io.File
class LombokGradleProjectImportHandler : AbstractGradleImportHandler<LombokModel>() {
override val modelKey: Key<LombokModel> = LombokGradleProjectResolverExtension.KEY
override val pluginJarFileFromIdea: File = PathUtil.kotlinPathsForIdeaPlugin.lombokPluginJarPath
override val compilerPluginId: String = LombokCommandLineProcessor.PLUGIN_ID
override val pluginName: String = "lombok"
override fun getOptions(model: LombokModel): List<CompilerPluginSetup.PluginOption> =
listOfNotNull(
model.configurationFile?.let {
CompilerPluginSetup.PluginOption(CONFIG_FILE_OPTION.optionName, it.path)
}
)
}
@@ -1,41 +0,0 @@
/*
* Copyright 2010-2021 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.lombok.ide
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.project.ModuleData
import com.intellij.openapi.util.Key
import org.gradle.tooling.model.idea.IdeaModule
import org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension
class LombokGradleProjectResolverExtension : AbstractProjectResolverExtension() {
private val modelClass: Class<LombokModel> = LombokModel::class.java
private val userDataKey: Key<LombokModel> = KEY
override fun getExtraProjectModelClasses() = setOf(modelClass)
override fun getToolingExtensionsClasses() = setOf(
modelClass,
LombokGradleProjectResolverExtension::class.java,
Unit::class.java
)
override fun populateModuleExtraModels(gradleModule: IdeaModule, ideModule: DataNode<ModuleData>) {
val model = resolverCtx.getExtraProject(gradleModule, modelClass)
if (model != null) {
ideModule.putCopyableUserData(userDataKey, model)
}
super.populateModuleExtraModels(gradleModule, ideModule)
}
companion object {
val KEY = Key<LombokModel>("LombokModel")
}
}
@@ -1,49 +0,0 @@
/*
* Copyright 2010-2021 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.lombok.ide
import org.jetbrains.idea.maven.project.MavenProject
import org.jetbrains.kotlin.lombok.LombokCommandLineProcessor
import org.jetbrains.kotlin.lombok.LombokCommandLineProcessor.Companion.CONFIG_FILE_OPTION
import org.jetbrains.kotlin.plugin.ide.AbstractMavenImportHandler
import org.jetbrains.kotlin.plugin.ide.CompilerPluginSetup.PluginOption
import org.jetbrains.kotlin.utils.PathUtil
import java.io.File
class LombokMavenProjectImportHandler : AbstractMavenImportHandler() {
override val compilerPluginId: String = LombokCommandLineProcessor.PLUGIN_ID
override val pluginName: String = MAVEN_SUBPLUGIN_NAME
override val pluginJarFileFromIdea: File = PathUtil.kotlinPathsForIdeaPlugin.lombokPluginJarPath
override fun getOptions(
mavenProject: MavenProject,
enabledCompilerPlugins: List<String>,
compilerPluginOptions: List<String>
): List<PluginOption>? {
if (!enabledCompilerPlugins.contains(pluginName)) return null
return compilerPluginOptions.mapNotNull { option ->
if (option.startsWith(CONFIG_FILE_PREFIX)) {
val location = File(option.substring(CONFIG_FILE_PREFIX.length))
val correctedLocation =
if (!location.isAbsolute) File(mavenProject.directory, location.path)
else location
PluginOption(CONFIG_FILE_OPTION.optionName, correctedLocation.absolutePath)
} else {
null
}
}
}
override fun getOptions(enabledCompilerPlugins: List<String>, compilerPluginOptions: List<String>): List<PluginOption>? {
throw NotImplementedError("Shouldn't be called")
}
companion object {
private const val MAVEN_SUBPLUGIN_NAME = "lombok"
private val CONFIG_FILE_PREFIX = "$MAVEN_SUBPLUGIN_NAME:${CONFIG_FILE_OPTION.optionName}="
}
}
-64
View File
@@ -1,64 +0,0 @@
description = "Kotlin NoArg IDEA Plugin"
plugins {
kotlin("jvm")
id("jps-compatible")
}
dependencies {
compile(project(":kotlin-noarg-compiler-plugin"))
compileOnly(project(":compiler:util"))
compileOnly(project(":compiler:frontend"))
compileOnly(project(":compiler:frontend.java"))
compileOnly(project(":compiler:backend"))
compileOnly(project(":compiler:cli-common"))
compileOnly(project(":idea"))
compileOnly(project(":idea:idea-jps-common"))
compileOnly(project(":plugins:annotation-based-compiler-plugins-ide-support"))
compileOnly(intellijDep())
excludeInAndroidStudio(rootProject) { compileOnly(intellijPluginDep("maven")) }
compileOnly(intellijPluginDep("gradle"))
compileOnly(project(":idea:kotlin-gradle-tooling"))
testRuntime(project(":kotlin-reflect"))
testCompileOnly(project(":kotlin-serialization"))
testCompileOnly(project(":plugins:lint"))
testCompileOnly(project(":plugins:kapt3-idea"))
testCompileOnly(project(":plugins:android-extensions-compiler"))
testCompileOnly(project(":kotlin-android-extensions"))
testCompileOnly(project(":kotlin-android-extensions-runtime"))
testCompileOnly(project(":plugins:android-extensions-ide"))
testCompileOnly(project(":kotlin-allopen-compiler-plugin"))
testCompileOnly(project(":allopen-ide-plugin"))
testCompileOnly(project(":kotlin-imports-dumper-compiler-plugin"))
testCompileOnly(project(":kotlinx-serialization-compiler-plugin"))
testCompileOnly(project(":kotlinx-serialization-ide-plugin"))
testCompileOnly(project(":kotlin-sam-with-receiver-compiler-plugin"))
testCompileOnly(project(":sam-with-receiver-ide-plugin"))
testCompileOnly(project(":idea:idea-native"))
testCompileOnly(project(":idea:idea-gradle-native"))
testCompileOnly(projectTests(":idea:idea-test-framework"))
testCompileOnly(intellijDep())
testRuntimeOnly(intellijDep())
compileOnly(intellijPluginDep("java"))
testCompileOnly(intellijPluginDep("java"))
testRuntimeOnly(intellijPluginDep("java"))
}
sourceSets {
"main" { projectDefault() }
"test" { projectDefault() }
}
runtimeJar()
sourcesJar()
javadocJar()
projectTest(parallel = true)
@@ -1,20 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.noarg.ide
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.annotation.plugin.ide.CachedAnnotationNames
import org.jetbrains.kotlin.annotation.plugin.ide.getAnnotationNames
import org.jetbrains.kotlin.noarg.AbstractNoArgExpressionCodegenExtension
import org.jetbrains.kotlin.psi.KtModifierListOwner
class IdeNoArgExpressionCodegenExtension(project: Project) : AbstractNoArgExpressionCodegenExtension(invokeInitializers = false) {
private val cachedAnnotationsNames = CachedAnnotationNames(project, NO_ARG_ANNOTATION_OPTION_PREFIX)
override fun getAnnotationFqNames(modifierListOwner: KtModifierListOwner?): List<String> =
cachedAnnotationsNames.getAnnotationNames(modifierListOwner)
}
@@ -1,24 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.noarg.ide
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.annotation.plugin.ide.CachedAnnotationNames
import org.jetbrains.kotlin.annotation.plugin.ide.getAnnotationNames
import org.jetbrains.kotlin.noarg.NoArgCommandLineProcessor
import org.jetbrains.kotlin.noarg.diagnostic.AbstractNoArgDeclarationChecker
import org.jetbrains.kotlin.psi.KtModifierListOwner
internal val NO_ARG_ANNOTATION_OPTION_PREFIX =
"plugin:${NoArgCommandLineProcessor.PLUGIN_ID}:${NoArgCommandLineProcessor.ANNOTATION_OPTION.optionName}="
class IdeNoArgDeclarationChecker(project: Project) : AbstractNoArgDeclarationChecker(false) {
private val cachedAnnotationNames = CachedAnnotationNames(project, NO_ARG_ANNOTATION_OPTION_PREFIX)
override fun getAnnotationFqNames(modifierListOwner: KtModifierListOwner?): List<String> =
cachedAnnotationNames.getAnnotationNames(modifierListOwner)
}
@@ -1,35 +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.noarg.ide
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.container.StorageComponentContainer
import org.jetbrains.kotlin.container.useInstance
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.extensions.StorageComponentContainerContributor
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.jvm.isJvm
class IdeNoArgComponentContainerContributor(val project: Project) : StorageComponentContainerContributor {
override fun registerModuleComponents(
container: StorageComponentContainer, platform: TargetPlatform, moduleDescriptor: ModuleDescriptor
) {
if (!platform.isJvm()) return
container.useInstance(IdeNoArgDeclarationChecker(project))
}
}
@@ -1,46 +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.noarg.ide
import org.jetbrains.kotlin.annotation.plugin.ide.AbstractAnnotationPluginGradleImportHandler
import org.jetbrains.kotlin.plugin.ide.CompilerPluginSetup.PluginOption
import org.jetbrains.kotlin.noarg.NoArgCommandLineProcessor
import org.jetbrains.kotlin.utils.PathUtil
class NoArgGradleProjectImportHandler : AbstractAnnotationPluginGradleImportHandler<NoArgModel>() {
override val compilerPluginId = NoArgCommandLineProcessor.PLUGIN_ID
override val pluginName = "noarg"
override val annotationOptionName = NoArgCommandLineProcessor.ANNOTATION_OPTION.optionName
override val pluginJarFileFromIdea = PathUtil.kotlinPathsForIdeaPlugin.noArgPluginJarPath
override val modelKey = NoArgProjectResolverExtension.KEY
override fun getAdditionalOptions(model: NoArgModel): List<PluginOption> {
return listOf(PluginOption(
NoArgCommandLineProcessor.INVOKE_INITIALIZERS_OPTION.optionName,
model.invokeInitializers.toString()))
}
override fun getAnnotationsForPreset(presetName: String): List<String> {
for ((name, annotations) in NoArgCommandLineProcessor.SUPPORTED_PRESETS.entries) {
if (presetName == name) {
return annotations
}
}
return super.getAnnotationsForPreset(presetName)
}
}
@@ -1,63 +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.noarg.ide
import org.jetbrains.kotlin.plugin.ide.CompilerPluginSetup.PluginOption
import org.jetbrains.kotlin.noarg.NoArgCommandLineProcessor
import org.jetbrains.kotlin.plugin.ide.AbstractMavenImportHandler
import org.jetbrains.kotlin.utils.PathUtil
class NoArgMavenProjectImportHandler : AbstractMavenImportHandler() {
private companion object {
val ANNOTATATION_PARAMETER_PREFIX = "no-arg:${NoArgCommandLineProcessor.ANNOTATION_OPTION.optionName}="
val INVOKEINITIALIZERS_PARAMETER_PREFIX = "no-arg:${NoArgCommandLineProcessor.INVOKE_INITIALIZERS_OPTION.optionName}="
}
override val compilerPluginId = NoArgCommandLineProcessor.PLUGIN_ID
override val pluginName = "noarg"
override val pluginJarFileFromIdea = PathUtil.kotlinPathsForIdeaPlugin.noArgPluginJarPath
override fun getOptions(enabledCompilerPlugins: List<String>, compilerPluginOptions: List<String>): List<PluginOption>? {
if ("no-arg" !in enabledCompilerPlugins && "jpa" !in enabledCompilerPlugins) {
return null
}
val annotations = mutableListOf<String>()
for ((presetName, presetAnnotations) in NoArgCommandLineProcessor.SUPPORTED_PRESETS) {
if (presetName in enabledCompilerPlugins) {
annotations.addAll(presetAnnotations)
}
}
annotations.addAll(compilerPluginOptions.mapNotNull { text ->
if (!text.startsWith(ANNOTATATION_PARAMETER_PREFIX)) return@mapNotNull null
text.substring(ANNOTATATION_PARAMETER_PREFIX.length)
})
val options = annotations.mapTo(mutableListOf()) { PluginOption(NoArgCommandLineProcessor.ANNOTATION_OPTION.optionName, it) }
val invokeInitializerOptionValue = compilerPluginOptions
.firstOrNull { it.startsWith(INVOKEINITIALIZERS_PARAMETER_PREFIX) }
?.drop(INVOKEINITIALIZERS_PARAMETER_PREFIX.length) == "true"
if (invokeInitializerOptionValue) {
options.add(PluginOption(NoArgCommandLineProcessor.INVOKE_INITIALIZERS_OPTION.optionName, "true"))
}
return options
}
}
@@ -1,29 +0,0 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.noarg.ide
import com.intellij.openapi.util.Key
import org.jetbrains.kotlin.annotation.plugin.ide.*
class NoArgProjectResolverExtension : AnnotationBasedPluginProjectResolverExtension<NoArgModel>() {
companion object {
val KEY = Key<NoArgModel>("NoArgModel")
}
override val modelClass get() = NoArgModel::class.java
override val userDataKey get() = KEY
}
@@ -1,73 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.noarg.ide
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.annotation.plugin.ide.CachedAnnotationNames
import org.jetbrains.kotlin.annotation.plugin.ide.getAnnotationNames
import org.jetbrains.kotlin.asJava.UltraLightClassModifierExtension
import org.jetbrains.kotlin.asJava.classes.KtUltraLightClass
import org.jetbrains.kotlin.asJava.classes.createGeneratedMethodFromDescriptor
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.extensions.AnnotationBasedExtension
import org.jetbrains.kotlin.noarg.AbstractNoArgExpressionCodegenExtension
import org.jetbrains.kotlin.noarg.AbstractNoArgExpressionCodegenExtension.Companion.isZeroParameterConstructor
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.util.isAnnotated
import org.jetbrains.kotlin.util.isOrdinaryClass
class NoArgUltraLightClassModifierExtension(project: Project) :
AnnotationBasedExtension,
UltraLightClassModifierExtension {
private val cachedAnnotationsNames = CachedAnnotationNames(project, NO_ARG_ANNOTATION_OPTION_PREFIX)
override fun getAnnotationFqNames(modifierListOwner: KtModifierListOwner?): List<String> =
cachedAnnotationsNames.getAnnotationNames(modifierListOwner)
private fun isSuitableDeclaration(declaration: KtDeclaration): Boolean {
if (getAnnotationFqNames(declaration).isEmpty()) return false
if (!declaration.isOrdinaryClass || declaration !is KtClassOrObject) return false
if (declaration.allConstructors.isEmpty()) return false
if (declaration.allConstructors.any { it.getValueParameters().isEmpty() }) return false
if (declaration.superTypeListEntries.isEmpty() && !declaration.isAnnotated) return false
return true
}
override fun interceptMethodsBuilding(
declaration: KtDeclaration,
descriptor: Lazy<DeclarationDescriptor?>,
containingDeclaration: KtUltraLightClass,
methodsList: MutableList<KtLightMethod>
) {
val parentClass = containingDeclaration as? KtUltraLightClass ?: return
if (methodsList.any { it.isConstructor && it.parameters.isEmpty() }) return
if (!isSuitableDeclaration(declaration)) return
val descriptorValue = descriptor.value ?: return
val classDescriptor = (descriptorValue as? ClassDescriptor)
?: descriptorValue.containingDeclaration as? ClassDescriptor
?: return
if (!classDescriptor.hasSpecialAnnotation(declaration)) return
if (classDescriptor.constructors.any { isZeroParameterConstructor(it) }) return
val constructorDescriptor = AbstractNoArgExpressionCodegenExtension.createNoArgConstructorDescriptor(classDescriptor)
methodsList.add(parentClass.createGeneratedMethodFromDescriptor(constructorDescriptor))
}
}
@@ -1,74 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.noarg
import com.intellij.testFramework.LightProjectDescriptor
import org.jetbrains.kotlin.config.LanguageVersion
import org.jetbrains.kotlin.idea.facet.KotlinFacet
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.test.KotlinProjectDescriptorWithFacet
import org.jetbrains.kotlin.noarg.ide.NO_ARG_ANNOTATION_OPTION_PREFIX
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.test.JUnit3WithIdeaConfigurationRunner
import org.junit.runner.RunWith
private const val targetClassName = "TargetClassName"
private const val baseClassName = "BaseClassName"
private const val noArgAnnotationName = "HelloNoArg"
@RunWith(JUnit3WithIdeaConfigurationRunner::class)
class TestNoArgForLightClass : KotlinLightCodeInsightFixtureTestCase() {
override fun getProjectDescriptor(): LightProjectDescriptor =
KotlinProjectDescriptorWithFacet(LanguageVersion.LATEST_STABLE, multiPlatform = false)
override fun setUp() {
super.setUp()
val facet = KotlinFacet.get(module) ?: error { "Facet not found" }
val configurationArguments = facet.configuration.settings.compilerArguments ?: error { "CompilerArguments not found" }
configurationArguments.pluginClasspaths = arrayOf("SomeClasspath")
configurationArguments.pluginOptions = arrayOf("$NO_ARG_ANNOTATION_OPTION_PREFIX$noArgAnnotationName")
}
fun testNoArgAnnotation() {
val file = myFixture.configureByText(
"A.kt",
"annotation class $noArgAnnotationName\n"
+ "@$noArgAnnotationName class $targetClassName(val e: Int)"
) as KtFile
val classes = file.classes
assertEquals(2, classes.size)
val targetClass = classes.firstOrNull { it.name == targetClassName }
?: error { "Expected class $targetClassName not found" }
val constructors = targetClass.constructors
assertEquals(constructors.size, 2)
assertTrue(constructors.any { it.parameters.isEmpty() })
}
fun testNoArgDerivedAnnotation() {
val file = myFixture.configureByText(
"A.kt",
"annotation class $noArgAnnotationName\n"
+ "@$noArgAnnotationName class $baseClassName(val e: Int)\n"
+ "class $targetClassName(val k: Int) : $baseClassName(k)"
) as KtFile
val classes = file.classes
assertEquals(3, classes.size)
val targetClass = classes.firstOrNull { it.name == targetClassName }
?: error { "Expected class $targetClassName not found" }
val constructors = targetClass.constructors
assertEquals(constructors.size, 2)
assertTrue(constructors.any { it.parameters.isEmpty() })
}
}
@@ -1,35 +0,0 @@
description = "Kotlin SamWithReceiver IDEA Plugin"
plugins {
kotlin("jvm")
id("jps-compatible")
}
dependencies {
compile(project(":kotlin-sam-with-receiver-compiler-plugin"))
compileOnly(project(":plugins:annotation-based-compiler-plugins-ide-support"))
compileOnly(project(":compiler:util"))
compileOnly(project(":compiler:frontend"))
compileOnly(project(":compiler:frontend.java"))
compileOnly(project(":idea:idea-core"))
compileOnly(project(":idea"))
compileOnly(project(":idea:idea-jvm"))
compileOnly(intellijDep()) { includeJars("platform-api", "extensions", "util") }
compileOnly(intellijDep("gradle"))
compileOnly(project(":idea:kotlin-gradle-tooling"))
}
sourceSets {
"main" { projectDefault() }
"test" {}
}
runtimeJar()
sourcesJar()
javadocJar()
@@ -1,77 +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.samWithReceiver.ide
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectRootModificationTracker
import com.intellij.psi.util.CachedValueProvider.Result
import com.intellij.psi.util.CachedValuesManager
import com.intellij.util.containers.ContainerUtil
import org.jetbrains.kotlin.analyzer.ModuleInfo
import org.jetbrains.kotlin.annotation.plugin.ide.getSpecialAnnotations
import org.jetbrains.kotlin.container.StorageComponentContainer
import org.jetbrains.kotlin.container.useInstance
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.extensions.StorageComponentContainerContributor
import org.jetbrains.kotlin.idea.caches.project.ModuleProductionSourceInfo
import org.jetbrains.kotlin.idea.caches.project.ScriptDependenciesInfo
import org.jetbrains.kotlin.idea.caches.project.ScriptModuleInfo
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.samWithReceiver.SamWithReceiverCommandLineProcessor.Companion.ANNOTATION_OPTION
import org.jetbrains.kotlin.samWithReceiver.SamWithReceiverCommandLineProcessor.Companion.PLUGIN_ID
import org.jetbrains.kotlin.samWithReceiver.SamWithReceiverResolverExtension
class IdeSamWithReceiverComponentContributor(val project: Project) : StorageComponentContainerContributor {
private companion object {
val ANNOTATION_OPTION_PREFIX = "plugin:$PLUGIN_ID:${ANNOTATION_OPTION.optionName}="
}
private val cache = CachedValuesManager.getManager(project).createCachedValue({
Result.create(
ContainerUtil.createConcurrentWeakMap<Module, List<String>>(),
ProjectRootModificationTracker.getInstance(
project
)
)
}, /* trackValue = */ false)
private fun getAnnotationsForModule(module: Module): List<String> {
return cache.value.getOrPut(module) { module.getSpecialAnnotations(ANNOTATION_OPTION_PREFIX) }
}
override fun registerModuleComponents(
container: StorageComponentContainer,
platform: TargetPlatform,
moduleDescriptor: ModuleDescriptor
) {
if (!platform.isJvm()) return
val moduleInfo = moduleDescriptor.getCapability(ModuleInfo.Capability)
val annotations =
when (moduleInfo) {
is ScriptModuleInfo -> moduleInfo.scriptDefinition.annotationsForSamWithReceivers
is ScriptDependenciesInfo.ForFile -> moduleInfo.scriptDefinition.annotationsForSamWithReceivers
is ModuleProductionSourceInfo -> getAnnotationsForModule(moduleInfo.module)
else -> null
} ?: return
container.useInstance(SamWithReceiverResolverExtension(annotations))
}
}
@@ -1,39 +0,0 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.samWithReceiver.ide
import org.jetbrains.kotlin.annotation.plugin.ide.AbstractAnnotationPluginGradleImportHandler
import org.jetbrains.kotlin.samWithReceiver.SamWithReceiverCommandLineProcessor
import org.jetbrains.kotlin.utils.PathUtil
class SamWithReceiverGradleProjectImportHandler : AbstractAnnotationPluginGradleImportHandler<SamWithReceiverModel>() {
override val compilerPluginId = SamWithReceiverCommandLineProcessor.PLUGIN_ID
override val pluginName = "sam-with-receiver"
override val annotationOptionName = SamWithReceiverCommandLineProcessor.ANNOTATION_OPTION.optionName
override val pluginJarFileFromIdea = PathUtil.kotlinPathsForIdeaPlugin.samWithReceiverJarPath
override val modelKey = SamWithReceiverProjectResolverExtension.KEY
override fun getAnnotationsForPreset(presetName: String): List<String> {
for ((name, annotations) in SamWithReceiverCommandLineProcessor.SUPPORTED_PRESETS.entries) {
if (presetName == name) {
return annotations
}
}
return super.getAnnotationsForPreset(presetName)
}
}
@@ -1,53 +0,0 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.samWithReceiver.ide
import org.jetbrains.kotlin.plugin.ide.CompilerPluginSetup.PluginOption
import org.jetbrains.kotlin.plugin.ide.AbstractMavenImportHandler
import org.jetbrains.kotlin.samWithReceiver.SamWithReceiverCommandLineProcessor
import org.jetbrains.kotlin.utils.PathUtil
class SamWithReceiverMavenProjectImportHandler : AbstractMavenImportHandler() {
private companion object {
val ANNOTATION_PARAMETER_PREFIX = "sam-with-receiver:${SamWithReceiverCommandLineProcessor.ANNOTATION_OPTION.optionName}="
}
override val compilerPluginId = SamWithReceiverCommandLineProcessor.PLUGIN_ID
override val pluginName = "samWithReceiver"
override val pluginJarFileFromIdea = PathUtil.kotlinPathsForIdeaPlugin.samWithReceiverJarPath
override fun getOptions(enabledCompilerPlugins: List<String>, compilerPluginOptions: List<String>): List<PluginOption>? {
if ("sam-with-receiver" !in enabledCompilerPlugins) {
return null
}
val annotations = mutableListOf<String>()
for ((presetName, presetAnnotations) in SamWithReceiverCommandLineProcessor.SUPPORTED_PRESETS) {
if (presetName in enabledCompilerPlugins) {
annotations.addAll(presetAnnotations)
}
}
annotations.addAll(compilerPluginOptions.mapNotNull { text ->
if (!text.startsWith(ANNOTATION_PARAMETER_PREFIX)) return@mapNotNull null
text.substring(ANNOTATION_PARAMETER_PREFIX.length)
})
return annotations.map { PluginOption(SamWithReceiverCommandLineProcessor.ANNOTATION_OPTION.optionName, it) }
}
}
@@ -1,29 +0,0 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.samWithReceiver.ide
import com.intellij.openapi.util.Key
import org.jetbrains.kotlin.annotation.plugin.ide.*
class SamWithReceiverProjectResolverExtension : AnnotationBasedPluginProjectResolverExtension<SamWithReceiverModel>() {
companion object {
val KEY = Key<SamWithReceiverModel>("SamWithReceiverModel")
}
override val modelClass get() = SamWithReceiverModel::class.java
override val userDataKey get() = KEY
}
@@ -1,23 +0,0 @@
description = "Kotlin Scripting IDEA Plugin"
plugins {
kotlin("jvm")
id("jps-compatible")
}
dependencies {
compile(project(":kotlin-scripting-intellij"))
compileOnly(project(":idea:idea-gradle"))
compileOnly(project(":idea:idea-core"))
compileOnly(intellijDep())
compileOnly(intellijDep("gradle"))
}
sourceSets {
"main" { projectDefault() }
"test" {}
}
runtimeJar()
@@ -1,76 +0,0 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.scripting.idea.plugin
import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments
import org.jetbrains.kotlin.idea.configuration.GradleProjectImportHandler
import org.jetbrains.kotlin.idea.facet.KotlinFacet
import org.jetbrains.kotlin.scripting.KOTLIN_SCRIPTING_PLUGIN_ID
import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData
import java.io.File
class ScriptingGradleProjectImportHandler : GradleProjectImportHandler {
val compilerPluginId = KOTLIN_SCRIPTING_PLUGIN_ID
val gradlePluginJars = listOf(
"scripting-gradle", // obsolete artifact name, only for compatibility with 1.2.5x, where it was introduced (and immediately dropped afterwards)
"scripting-compiler",
"scripting-compiler-embeddable"
)
override fun importBySourceSet(
facet: KotlinFacet,
sourceSetNode: com.intellij.openapi.externalSystem.model.DataNode<GradleSourceSetData>
) {
modifyCompilerArgumentsForPlugin(facet, compilerPluginId, gradlePluginJars)
}
override fun importByModule(
facet: KotlinFacet,
moduleNode: com.intellij.openapi.externalSystem.model.DataNode<com.intellij.openapi.externalSystem.model.project.ModuleData>
) {
modifyCompilerArgumentsForPlugin(facet, compilerPluginId, gradlePluginJars)
}
}
// NOTE: partially copied from idePluginUtil.kt, it is not possible to reuse it right now without refactoring
internal fun modifyCompilerArgumentsForPlugin(
facet: KotlinFacet,
compilerPluginId: String,
pluginJarNames: List<String>
) {
val facetSettings = facet.configuration.settings
// investigate why copyBean() sometimes throws exceptions
val commonArguments = facetSettings.compilerArguments ?: CommonCompilerArguments.DummyImpl()
// TODO: find out where new options should come from (or maybe they are not needed here at all)
// val newOptionsForPlugin = setup?.options?.map { "plugin:$compilerPluginId:${it.key}=${it.value}" } ?: emptyList()
val oldAllPluginOptions = (commonArguments.pluginOptions ?: emptyArray()).filterTo(mutableListOf()) { !it.startsWith("plugin:$compilerPluginId:") }
val newAllPluginOptions = oldAllPluginOptions // + newOptionsForPlugin
val filterRegexes = pluginJarNames.map {
"(kotlin-)?(maven-)?$it-.*\\.jar".toRegex()
}
val oldPluginClasspaths = (commonArguments.pluginClasspaths ?: emptyArray()).filterTo(mutableListOf()) {
val lastIndexOfFile = it.lastIndexOfAny(charArrayOf('/', File.separatorChar))
if (lastIndexOfFile < 0) {
return@filterTo true
}
!it.drop(lastIndexOfFile + 1).let { fileName ->
filterRegexes.any { fileName.matches(it) }
}
}
// TODO: find out how to make it - see comment to the newOptionsForPlugin above
val newPluginClasspaths = oldPluginClasspaths // + (setup?.classpath ?: emptyList())
commonArguments.pluginOptions = newAllPluginOptions.toTypedArray()
commonArguments.pluginClasspaths = newPluginClasspaths.toTypedArray()
facetSettings.compilerArguments = commonArguments
}
-26
View File
@@ -1,26 +0,0 @@
plugins {
kotlin("jvm")
id("jps-compatible")
}
dependencies {
implementation(kotlinStdlib())
implementation(project(":compiler:psi"))
implementation(project(":compiler:light-classes"))
// BEWARE: UAST should not depend on IJ platform so that it can work in Android Lint CLI mode (where IDE is not available)
compileOnly(intellijCoreDep()) { includeJars("intellij-core", "asm-all", rootProject = rootProject) }
compileOnly(intellijPluginDep("java")) { includeJars("java-api", "java-impl") }
testImplementation(commonDep("junit:junit"))
testCompileOnly(intellijPluginDep("java")) { includeJars("java-api", "java-impl") }
testImplementation(projectTests(":compiler:tests-common"))
testCompileOnly(intellijDep()) { includeJars("uast-tests") }
}
sourceSets {
"main" { projectDefault() }
"test" { projectDefault() }
}
testsJar ()
@@ -1,65 +0,0 @@
/*
* Copyright 2010-2021 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.uast.kotlin
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.psi.*
import org.jetbrains.uast.*
interface BaseKotlinConverter {
fun convertAnnotation(
annotationEntry: KtAnnotationEntry,
givenParent: UElement?
): UAnnotation
fun convertDeclaration(
element: PsiElement,
givenParent: UElement?,
requiredTypes: Array<out Class<out UElement>>
): UElement?
fun convertReceiverParameter(receiver: KtTypeReference): UParameter? {
val call = (receiver.parent as? KtCallableDeclaration) ?: return null
if (call.receiverTypeReference != receiver) return null
return call.toUElementOfType<UMethod>()?.uastParameters?.firstOrNull()
}
fun convertExpression(
expression: KtExpression,
givenParent: UElement?,
requiredTypes: Array<out Class<out UElement>>
): UExpression?
fun convertEntry(
entry: KtStringTemplateEntry,
givenParent: UElement?,
requiredTypes: Array<out Class<out UElement>>
): UExpression? {
return with(requiredTypes) {
if (entry is KtStringTemplateEntryWithExpression) {
expr<UExpression> {
convertOrEmpty(entry.expression, givenParent)
}
} else {
expr<ULiteralExpression> {
if (entry is KtEscapeStringTemplateEntry)
KotlinStringULiteralExpression(entry, givenParent, entry.unescapedValue)
else
KotlinStringULiteralExpression(entry, givenParent)
}
}
}
}
fun convertOrEmpty(expression: KtExpression?, parent: UElement?): UExpression {
return expression?.let { convertExpression(it, parent, DEFAULT_EXPRESSION_TYPES_LIST) } ?: UastEmptyExpression(parent)
}
fun convertOrNull(expression: KtExpression?, parent: UElement?): UExpression? {
return if (expression != null) convertExpression(expression, parent, DEFAULT_EXPRESSION_TYPES_LIST) else null
}
}
@@ -1,34 +0,0 @@
/*
* Copyright 2010-2021 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.uast.kotlin
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiType
import org.jetbrains.kotlin.psi.KtDoubleColonExpression
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtTypeReference
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UExpression
interface BaseKotlinUastResolveProviderService {
fun isJvmElement(psiElement: PsiElement): Boolean
val baseKotlinConverter: BaseKotlinConverter
fun convertParent(uElement: UElement): UElement?
fun getReferenceVariants(ktExpression: KtExpression, nameHint: String): Sequence<PsiElement>
fun resolveToDeclaration(ktExpression: KtExpression): PsiElement?
fun resolveToType(ktTypeReference: KtTypeReference, source: UElement): PsiType?
fun getDoubleColonReceiverType(ktDoubleColonExpression: KtDoubleColonExpression, source: UElement): PsiType?
fun getExpressionType(uExpression: UExpression): PsiType?
fun evaluate(uExpression: UExpression): Any?
}
@@ -1,48 +0,0 @@
/*
* Copyright 2010-2021 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.uast.kotlin
import com.intellij.openapi.components.ServiceManager
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UastFacade
import org.jetbrains.uast.UastLanguagePlugin
import org.jetbrains.uast.kotlin.internal.KotlinUElementWithComments
abstract class KotlinAbstractUElement(
givenParent: UElement?,
baseResolveProviderServiceSupplier: BaseResolveProviderServiceSupplier? = null,
) : KotlinUElementWithComments {
protected val languagePlugin: UastLanguagePlugin? by lz {
psi?.let { UastFacade.findPlugin(it) }
}
open val baseResolveProviderService: BaseKotlinUastResolveProviderService by lz {
baseResolveProviderServiceSupplier?.get()
?: psi?.project?.let { ServiceManager.getService(it, BaseKotlinUastResolveProviderService::class.java) }
?: error("${BaseKotlinUastResolveProviderService::class.java.name} is not available")
}
final override val uastParent: UElement? by lz {
givenParent ?: convertParent()
}
protected open fun convertParent(): UElement? {
return baseResolveProviderService.convertParent(this)
}
override fun equals(other: Any?): Boolean {
if (other !is UElement) {
return false
}
return this.psi == other.psi
}
override fun hashCode(): Int {
return psi?.hashCode() ?: 0
}
}
@@ -1,30 +0,0 @@
/*
* Copyright 2010-2021 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.uast.kotlin
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.psi.KtAnnotatedExpression
import org.jetbrains.uast.UAnnotation
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UExpression
import org.jetbrains.uast.convertOpt
abstract class KotlinAbstractUExpression(
givenParent: UElement?,
baseResolveProviderServiceSupplier: BaseResolveProviderServiceSupplier? = null,
) : KotlinAbstractUElement(givenParent, baseResolveProviderServiceSupplier), UExpression {
override val javaPsi: PsiElement? = null
override val psi
get() = sourcePsi
override val uAnnotations: List<UAnnotation>
get() {
val annotatedExpression = sourcePsi?.parent as? KtAnnotatedExpression ?: return emptyList()
return annotatedExpression.annotationEntries.mapNotNull { languagePlugin?.convertOpt(it, this) }
}
}
@@ -1,29 +0,0 @@
/*
* Copyright 2010-2021 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.uast.kotlin
import org.jetbrains.kotlin.psi.KtDoWhileExpression
import org.jetbrains.uast.UDoWhileExpression
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UIdentifier
class KotlinUDoWhileExpression(
override val sourcePsi: KtDoWhileExpression,
givenParent: UElement?
) : KotlinAbstractUExpression(givenParent), UDoWhileExpression {
override val condition by lz {
baseResolveProviderService.baseKotlinConverter.convertOrEmpty(sourcePsi.condition, this)
}
override val body by lz {
baseResolveProviderService.baseKotlinConverter.convertOrEmpty(sourcePsi.body, this)
}
override val doIdentifier: UIdentifier
get() = KotlinUIdentifier(null, this)
override val whileIdentifier: UIdentifier
get() = KotlinUIdentifier(null, this)
}
@@ -1,33 +0,0 @@
/*
* Copyright 2010-2021 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.uast.kotlin
import org.jetbrains.kotlin.psi.KtIfExpression
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UIdentifier
import org.jetbrains.uast.UIfExpression
class KotlinUIfExpression(
override val sourcePsi: KtIfExpression,
givenParent: UElement?
) : KotlinAbstractUExpression(givenParent), UIfExpression, KotlinUElementWithType, KotlinEvaluatableUElement {
override val condition by lz {
baseResolveProviderService.baseKotlinConverter.convertOrEmpty(sourcePsi.condition, this)
}
override val thenExpression by lz {
baseResolveProviderService.baseKotlinConverter.convertOrNull(sourcePsi.then, this)
}
override val elseExpression by lz {
baseResolveProviderService.baseKotlinConverter.convertOrNull(sourcePsi.`else`, this)
}
override val isTernary = false
override val ifIdentifier: UIdentifier
get() = UIdentifier(null, this)
override val elseIdentifier: UIdentifier?
get() = null
}
@@ -1,26 +0,0 @@
/*
* Copyright 2010-2021 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.uast.kotlin
import org.jetbrains.kotlin.psi.KtWhileExpression
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UIdentifier
import org.jetbrains.uast.UWhileExpression
class KotlinUWhileExpression(
override val sourcePsi: KtWhileExpression,
givenParent: UElement?
) : KotlinAbstractUExpression(givenParent), UWhileExpression {
override val condition by lz {
baseResolveProviderService.baseKotlinConverter.convertOrEmpty(sourcePsi.condition, this)
}
override val body by lz {
baseResolveProviderService.baseKotlinConverter.convertOrEmpty(sourcePsi.body, this)
}
override val whileIdentifier: UIdentifier
get() = KotlinUIdentifier(null, this)
}
@@ -1,57 +0,0 @@
/*
* Copyright 2010-2021 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.uast.kotlin
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtDelegatedSuperTypeEntry
import org.jetbrains.kotlin.psi.KtModifierListOwner
import org.jetbrains.uast.*
import org.jetbrains.uast.internal.acceptList
import org.jetbrains.uast.visitor.UastVisitor
abstract class AbstractKotlinUClass(
givenParent: UElement?
) : KotlinAbstractUElement(givenParent), UClass, UAnchorOwner {
override val uastDeclarations by lz {
mutableListOf<UDeclaration>().apply {
addAll(fields)
addAll(initializers)
addAll(methods)
addAll(innerClasses)
}
}
open val ktClass: KtClassOrObject? get() = (psi as? KtLightClass)?.kotlinOrigin
override val uastSuperTypes: List<UTypeReferenceExpression>
get() = ktClass?.superTypeListEntries.orEmpty().mapNotNull { it.typeReference }.map {
KotlinUTypeReferenceExpression(it, this)
}
val delegateExpressions: List<UExpression>
get() = ktClass?.superTypeListEntries.orEmpty()
.filterIsInstance<KtDelegatedSuperTypeEntry>()
.map { KotlinSupertypeDelegationUExpression(it, this) }
override fun accept(visitor: UastVisitor) {
if (visitor.visitClass(this)) return
delegateExpressions.acceptList(visitor)
uAnnotations.acceptList(visitor)
uastDeclarations.acceptList(visitor)
visitor.afterVisitClass(this)
}
override val uAnnotations: List<UAnnotation> by lz {
(sourcePsi as? KtModifierListOwner)?.annotationEntries.orEmpty().map {
baseResolveProviderService.baseKotlinConverter.convertAnnotation(it, this)
}
}
override fun equals(other: Any?) = other is AbstractKotlinUClass && psi == other.psi
override fun hashCode() = psi.hashCode()
}
@@ -1,70 +0,0 @@
/*
* Copyright 2010-2021 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.uast.kotlin
import com.intellij.psi.PsiMethod
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.utils.SmartList
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UExpression
import org.jetbrains.uast.UIdentifier
abstract class BaseKotlinConstructorUMethod(
private val ktClass: KtClassOrObject?,
override val psi: PsiMethod,
kotlinOrigin: KtDeclaration?,
givenParent: UElement?
) : BaseKotlinUMethod(psi, kotlinOrigin, givenParent) {
override val javaPsi = psi
val isPrimary: Boolean
get() = sourcePsi is KtPrimaryConstructor || sourcePsi is KtClassOrObject
override val uastBody: UExpression? by lz {
val delegationCall: KtCallElement? = sourcePsi.let {
when {
isPrimary -> ktClass?.superTypeListEntries?.firstIsInstanceOrNull<KtSuperTypeCallEntry>()
it is KtSecondaryConstructor -> it.getDelegationCall()
else -> null
}
}
val bodyExpressions = getBodyExpressions()
if (delegationCall == null && bodyExpressions.isEmpty()) return@lz null
KotlinLazyUBlockExpression(this) { uastParent ->
SmartList<UExpression>().apply {
delegationCall?.let {
add(buildDelegationCall(it, uastParent))
}
bodyExpressions.forEach {
add(baseResolveProviderService.baseKotlinConverter.convertOrEmpty(it, uastParent))
}
}
}
}
abstract fun buildDelegationCall(delegationCall: KtCallElement, uastParent: UElement): UExpression
override val uastAnchor: UIdentifier? by lz {
KotlinUIdentifier(
javaPsi.nameIdentifier,
if (isPrimary) ktClass?.nameIdentifier else (sourcePsi as? KtSecondaryConstructor)?.getConstructorKeyword(),
this
)
}
protected open fun getBodyExpressions(): List<KtExpression> {
if (isPrimary) return getInitializers()
val bodyExpression = (sourcePsi as? KtFunction)?.bodyExpression ?: return emptyList()
if (bodyExpression is KtBlockExpression) return bodyExpression.statements
return listOf(bodyExpression)
}
protected fun getInitializers(): List<KtExpression> {
return ktClass?.getAnonymousInitializers()?.mapNotNull { it.body } ?: emptyList()
}
}
@@ -1,25 +0,0 @@
/*
* Copyright 2010-2021 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.uast.kotlin
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.uast.UElement
// This class was created as a workaround for KT-21617 to be the only constructor which includes `init` block
// when there is no primary constructors in the class.
// It is expected to have only one constructor of this type in a UClass.
abstract class BaseKotlinSecondaryConstructorWithInitializersUMethod(
ktClass: KtClassOrObject?,
psi: KtLightMethod,
givenParent: UElement?
) : BaseKotlinConstructorUMethod(ktClass, psi, psi.kotlinOrigin, givenParent) {
override fun getBodyExpressions(): List<KtExpression> {
return getInitializers() + super.getBodyExpressions()
}
}
@@ -1,23 +0,0 @@
/*
* Copyright 2010-2021 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.uast.kotlin
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.uast.*
abstract class BaseKotlinUAnnotationMethod(
psi: KtLightMethod,
givenParent: UElement?
) : BaseKotlinUMethod(psi, psi.kotlinOrigin, givenParent), UAnnotationMethod {
override val psi: KtLightMethod = unwrap<UMethod, KtLightMethod>(psi)
override val uastDefaultValue: UExpression? by lz {
val annotationParameter = sourcePsi as? KtParameter ?: return@lz null
val defaultValue = annotationParameter.defaultValue ?: return@lz null
languagePlugin?.convertElement(defaultValue, this) as? UExpression
}
}
@@ -1,111 +0,0 @@
/*
* Copyright 2010-2021 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.uast.kotlin
import com.intellij.psi.*
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtObjectDeclaration
import org.jetbrains.kotlin.utils.addIfNotNull
import org.jetbrains.uast.*
abstract class BaseKotlinUClass(
psi: KtLightClass,
givenParent: UElement?
) : AbstractKotlinUClass(givenParent), PsiClass by psi {
final override val ktClass = psi.kotlinOrigin
override val javaPsi: KtLightClass = psi
override val sourcePsi: KtClassOrObject? = ktClass
override val psi = unwrap<UClass, PsiClass>(psi)
override fun getSourceElement() = sourcePsi ?: this
override fun getOriginalElement(): PsiElement? = super.getOriginalElement()
override fun getNameIdentifier(): PsiIdentifier? = UastLightIdentifier(psi, ktClass)
override fun getContainingFile(): PsiFile? = unwrapFakeFileForLightClass(psi.containingFile)
override val uastAnchor by lazy { getIdentifierSourcePsi()?.let { KotlinUIdentifier(nameIdentifier, it, this) } }
private fun getIdentifierSourcePsi(): PsiElement? {
ktClass?.nameIdentifier?.let { return it }
(ktClass as? KtObjectDeclaration)?.getObjectKeyword()?.let { return it }
return null
}
override fun getInnerClasses(): Array<UClass> {
// filter DefaultImpls to avoid processing same methods from original interface multiple times
// filter Enum entry classes to avoid duplication with PsiEnumConstant initializer class
return psi.innerClasses.filter {
it.name != JvmAbi.DEFAULT_IMPLS_CLASS_NAME && !it.isEnumEntryLightClass
}.mapNotNull {
languagePlugin?.convertOpt<UClass>(it, this)
}.toTypedArray()
}
override fun getSuperClass(): UClass? = super.getSuperClass()
override fun getFields(): Array<UField> = super.getFields()
override fun getInitializers(): Array<UClassInitializer> = super.getInitializers()
override fun getMethods(): Array<UMethod> {
val hasPrimaryConstructor = ktClass?.hasPrimaryConstructor() ?: false
var secondaryConstructorsCount = 0
fun createUMethod(psiMethod: PsiMethod): UMethod {
return if (psiMethod is KtLightMethod &&
psiMethod.isConstructor) {
if (!hasPrimaryConstructor && secondaryConstructorsCount++ == 0)
buildSecondaryConstructorUMethod(ktClass, psiMethod, this)
else
buildPrimaryConstructorUMethod(ktClass, psiMethod, this)
} else {
languagePlugin?.convertOpt(psiMethod, this) ?: reportConvertFailure(psiMethod)
}
}
fun isDelegatedMethod(psiMethod: PsiMethod) = psiMethod is KtLightMethod && psiMethod.isDelegated
val result = ArrayList<UMethod>(javaPsi.methods.size)
val handledKtDeclarations = mutableSetOf<PsiElement>()
for (lightMethod in javaPsi.methods) {
if (isDelegatedMethod(lightMethod)) continue
val uMethod = createUMethod(lightMethod)
result.add(uMethod)
// Ensure we pick the main Kotlin origin, not the auxiliary one
val kotlinOrigin = (lightMethod as? KtLightMethod)?.kotlinOrigin ?: uMethod.sourcePsi
handledKtDeclarations.addIfNotNull(kotlinOrigin)
}
val ktDeclarations: List<KtDeclaration> = run ktDeclarations@{
ktClass?.let { return@ktDeclarations it.declarations }
(javaPsi as? KtLightClassForFacade)?.let { facade ->
return@ktDeclarations facade.files.flatMap { file -> file.declarations }
}
emptyList()
}
ktDeclarations.asSequence()
.filterNot { handledKtDeclarations.contains(it) }
.mapNotNullTo(result) {
baseResolveProviderService.baseKotlinConverter.convertDeclaration(it, this, arrayOf(UElement::class.java)) as? UMethod
}
return result.toTypedArray()
}
abstract fun buildPrimaryConstructorUMethod(ktClass: KtClassOrObject?, psi: KtLightMethod, givenParent: UElement?) : UMethod
abstract fun buildSecondaryConstructorUMethod(ktClass: KtClassOrObject?, psi: KtLightMethod, givenParent: UElement?) : UMethod
}
@@ -1,84 +0,0 @@
/*
* Copyright 2010-2021 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.uast.kotlin
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiNameIdentifierOwner
import org.jetbrains.kotlin.asJava.elements.KtLightElement
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.asJava.elements.isGetter
import org.jetbrains.kotlin.asJava.elements.isSetter
import org.jetbrains.kotlin.psi.*
import org.jetbrains.uast.*
abstract class BaseKotlinUMethod(
psi: PsiMethod,
final override val sourcePsi: KtDeclaration?,
givenParent: UElement?
) : KotlinAbstractUElement(givenParent), UMethod, UAnchorOwner, PsiMethod by psi {
override val psi: PsiMethod = unwrap<UMethod, PsiMethod>(psi)
override val javaPsi = psi
override fun getSourceElement() = sourcePsi ?: this
private val kotlinOrigin = getKotlinMemberOrigin(psi.originalElement) ?: sourcePsi
override fun getContainingFile(): PsiFile? {
kotlinOrigin?.containingFile?.let { return it }
return unwrapFakeFileForLightClass(psi.containingFile)
}
override fun getNameIdentifier() = UastLightIdentifier(psi, kotlinOrigin)
override val uAnnotations: List<UAnnotation> by lz {
psi.annotations
.mapNotNull { (it as? KtLightElement<*, *>)?.kotlinOrigin as? KtAnnotationEntry }
.map { baseResolveProviderService.baseKotlinConverter.convertAnnotation(it, this) }
}
protected val receiverTypeReference by lz {
when (sourcePsi) {
is KtCallableDeclaration -> sourcePsi
is KtPropertyAccessor -> sourcePsi.property
else -> null
}?.receiverTypeReference
}
override val uastAnchor: UIdentifier? by lz {
val identifierSourcePsi = when (val sourcePsi = sourcePsi) {
is PsiNameIdentifierOwner -> sourcePsi.nameIdentifier
is KtObjectDeclaration -> sourcePsi.getObjectKeyword()
is KtPropertyAccessor -> sourcePsi.namePlaceholder
else -> sourcePsi?.navigationElement
}
KotlinUIdentifier(nameIdentifier, identifierSourcePsi, this)
}
override val uastBody: UExpression? by lz {
if (kotlinOrigin?.canAnalyze() != true) return@lz null // EA-137193
val bodyExpression = when (sourcePsi) {
is KtFunction -> sourcePsi.bodyExpression
is KtPropertyAccessor -> sourcePsi.bodyExpression
is KtProperty -> when {
psi is KtLightMethod && psi.isGetter -> sourcePsi.getter?.bodyExpression
psi is KtLightMethod && psi.isSetter -> sourcePsi.setter?.bodyExpression
else -> null
}
else -> null
} ?: return@lz null
wrapExpressionBody(this, bodyExpression)
}
override val returnTypeReference: UTypeReferenceExpression? by lz {
(sourcePsi as? KtCallableDeclaration)?.typeReference?.let {
KotlinUTypeReferenceExpression(it, this) { javaPsi.returnType ?: UastErrorType }
}
}
}
@@ -1,44 +0,0 @@
/*
* Copyright 2010-2021 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.uast.kotlin
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.impl.light.LightPsiClassBuilder
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.uast.*
/**
* implementation of [UClass] for invalid code, when it is impossible to create a [KtLightClass]
*/
class KotlinInvalidUClass(
override val psi: PsiClass,
givenParent: UElement?
) : AbstractKotlinUClass(givenParent), PsiClass by psi {
constructor(name: String, context: PsiElement, givenParent: UElement?) : this(LightPsiClassBuilder(context, name), givenParent)
override fun getContainingFile(): PsiFile? = uastParent?.getContainingUFile()?.sourcePsi
override val sourcePsi: PsiElement? get() = null
override val uastAnchor: UIdentifier? get() = null
override val javaPsi: PsiClass get() = psi
override fun getFields(): Array<UField> = emptyArray()
override fun getInitializers(): Array<UClassInitializer> = emptyArray()
override fun getInnerClasses(): Array<UClass> = emptyArray()
override fun getMethods(): Array<UMethod> = emptyArray()
override fun getSuperClass(): UClass? = null
override fun getOriginalElement(): PsiElement? = null
}
@@ -1,41 +0,0 @@
/*
* Copyright 2010-2021 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.uast.kotlin
import com.intellij.psi.PsiAnonymousClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtObjectDeclaration
import org.jetbrains.uast.*
class KotlinUAnonymousClass(
psi: PsiAnonymousClass,
givenParent: UElement?
) : AbstractKotlinUClass(givenParent), UAnonymousClass, PsiAnonymousClass by psi {
override val psi: PsiAnonymousClass = unwrap<UAnonymousClass, PsiAnonymousClass>(psi)
override val javaPsi: PsiAnonymousClass = psi
override val sourcePsi: KtClassOrObject? = ktClass
override fun getOriginalElement(): PsiElement? = super<AbstractKotlinUClass>.getOriginalElement()
override fun getSuperClass(): UClass? = super<AbstractKotlinUClass>.getSuperClass()
override fun getFields(): Array<UField> = super<AbstractKotlinUClass>.getFields()
override fun getMethods(): Array<UMethod> = super<AbstractKotlinUClass>.getMethods()
override fun getInitializers(): Array<UClassInitializer> = super<AbstractKotlinUClass>.getInitializers()
override fun getInnerClasses(): Array<UClass> = super<AbstractKotlinUClass>.getInnerClasses()
override fun getContainingFile(): PsiFile = unwrapFakeFileForLightClass(psi.containingFile)
override val uastAnchor by lazy {
val ktClassOrObject = (psi.originalElement as? KtLightClass)?.kotlinOrigin as? KtObjectDeclaration ?: return@lazy null
KotlinUIdentifier(ktClassOrObject.getObjectKeyword(), this)
}
}
@@ -1,57 +0,0 @@
/*
* Copyright 2010-2021 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.uast.kotlin
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiRecursiveElementWalkingVisitor
import org.jetbrains.kotlin.asJava.findFacadeClass
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.uast.*
import java.util.ArrayList
class KotlinUFile(
override val psi: KtFile,
override val languagePlugin: UastLanguagePlugin
) : UFile {
override val javaPsi: PsiElement? = null
override val sourcePsi: KtFile = psi
override val uAnnotations: List<UAnnotation> by lz {
sourcePsi.annotationEntries.mapNotNull { languagePlugin.convertOpt(it, this) }
}
override val packageName: String by lz {
sourcePsi.packageFqName.asString()
}
override val allCommentsInFile by lz {
val comments = ArrayList<UComment>(0)
sourcePsi.accept(object : PsiRecursiveElementWalkingVisitor() {
override fun visitComment(comment: PsiComment) {
comments += UComment(comment, this@KotlinUFile)
}
})
comments
}
override val imports: List<UImportStatement> by lz {
sourcePsi.importDirectives.mapNotNull { languagePlugin.convertOpt(it, this@KotlinUFile) }
}
override val classes: List<UClass> by lz {
val facadeOrScriptClass = if (sourcePsi.isScript()) sourcePsi.script?.toLightClass() else sourcePsi.findFacadeClass()
val facadeOrScriptUClass = facadeOrScriptClass?.toUClass()?.let { listOf(it) } ?: emptyList()
val classes = sourcePsi.declarations.mapNotNull { (it as? KtClassOrObject)?.toLightClass()?.toUClass() }
facadeOrScriptUClass + classes
}
private fun PsiClass.toUClass() = languagePlugin.convertOpt<UClass>(this, this@KotlinUFile)
}
@@ -1,63 +0,0 @@
/*
* Copyright 2010-2021 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.uast.kotlin
import com.intellij.openapi.application.ApplicationManager
import com.intellij.psi.PsiElement
import com.intellij.psi.impl.source.tree.LeafPsiElement
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UIdentifier
import org.jetbrains.uast.toUElement
class KotlinUIdentifier constructor(
javaPsiSupplier: () -> PsiElement?,
override val sourcePsi: PsiElement?,
givenParent: UElement?
) : UIdentifier(sourcePsi, givenParent) {
override val javaPsi: PsiElement? by lazy(javaPsiSupplier) // don't know any real need to call it in production
override val psi: PsiElement?
get() = javaPsi ?: sourcePsi
init {
if (ApplicationManager.getApplication().isUnitTestMode && !acceptableSourcePsi(sourcePsi))
throw KotlinExceptionWithAttachments(
"sourcePsi should be physical leaf element but got $sourcePsi of (${sourcePsi?.javaClass})"
).withAttachment("sourcePsi.text", sourcePsi?.text)
}
private fun acceptableSourcePsi(sourcePsi: PsiElement?): Boolean {
if (sourcePsi == null) return true
if (sourcePsi is LeafPsiElement) return true
if (sourcePsi is KtElement && sourcePsi.firstChild == null) return true
// string literals could be identifiers of calls e.g. `"main" {}` in gradle.kts
if (sourcePsi is KtStringTemplateExpression && sourcePsi.parent is KtCallExpression) return true
return false
}
override val uastParent: UElement? by lazy {
if (givenParent != null) return@lazy givenParent
val parent = sourcePsi?.parent ?: return@lazy null
getIdentifierParentForCall(parent) ?: parent.toUElement()
}
private fun getIdentifierParentForCall(parent: PsiElement): UElement? {
val parentParent = parent.parent
if (parentParent is KtCallElement && parentParent.calleeExpression == parent) { // method identifiers in calls
return parentParent.toUElement()
}
(generateSequence(parent) { it.parent }.take(3).find { it is KtTypeReference && it.parent is KtConstructorCalleeExpression })?.let {
return it.parent.parent.toUElement()
}
return null
}
constructor(javaPsi: PsiElement?, sourcePsi: PsiElement?, uastParent: UElement?) : this({ javaPsi }, sourcePsi, uastParent)
constructor(sourcePsi: PsiElement?, uastParent: UElement?) : this({ null }, sourcePsi, uastParent)
}
@@ -1,56 +0,0 @@
/*
* Copyright 2010-2021 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.uast.kotlin
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtImportDirective
import org.jetbrains.kotlin.psi.KtReferenceExpression
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedElementSelector
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UImportStatement
import org.jetbrains.uast.USimpleNameReferenceExpression
import org.jetbrains.uast.kotlin.internal.DelegatedMultiResolve
class KotlinUImportStatement(
override val psi: KtImportDirective,
givenParent: UElement?
) : KotlinAbstractUElement(givenParent), UImportStatement, DelegatedMultiResolve {
override val javaPsi: PsiElement? = null
override val sourcePsi: KtImportDirective = psi
override val isOnDemand: Boolean = sourcePsi.isAllUnder
private val importRef: ImportReference? by lz {
sourcePsi.importedReference?.let {
ImportReference(it, sourcePsi.name ?: sourcePsi.text, this, sourcePsi)
}
}
override val importReference: UElement? = importRef
override fun resolve(): PsiElement? = importRef?.resolve()
private class ImportReference(
override val psi: KtExpression,
override val identifier: String,
givenParent: UElement?,
private val importDirective: KtImportDirective
) : KotlinAbstractUExpression(givenParent), USimpleNameReferenceExpression {
override val sourcePsi: KtExpression = psi
override val resolvedName: String = identifier
override fun asRenderString(): String = importDirective.importedFqName?.asString() ?: sourcePsi.text
override fun resolve(): PsiElement? {
val reference = sourcePsi.getQualifiedElementSelector() as? KtReferenceExpression ?: return null
return baseResolveProviderService.resolveToDeclaration(reference)
}
}
}
@@ -1,20 +0,0 @@
/*
* Copyright 2010-2021 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.uast.kotlin
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiNameIdentifierOwner
import org.jetbrains.kotlin.asJava.elements.KtLightIdentifier
import org.jetbrains.kotlin.psi.KtDeclaration
class UastLightIdentifier(
lightOwner: PsiNameIdentifierOwner,
ktDeclaration: KtDeclaration?
) : KtLightIdentifier(lightOwner, ktDeclaration) {
override fun getContainingFile(): PsiFile {
return unwrapFakeFileForLightClass(super.getContainingFile())
}
}
@@ -1,25 +0,0 @@
/*
* Copyright 2010-2021 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.uast.kotlin
import org.jetbrains.kotlin.psi.KtArrayAccessExpression
import org.jetbrains.uast.UArrayAccessExpression
import org.jetbrains.uast.UElement
abstract class KotlinAbstractUArrayAccessExpression(
override val sourcePsi: KtArrayAccessExpression,
givenParent: UElement?
) : KotlinAbstractUExpression(givenParent), UArrayAccessExpression, KotlinUElementWithType, KotlinEvaluatableUElement {
override val receiver by lz {
baseResolveProviderService.baseKotlinConverter.convertOrEmpty(sourcePsi.arrayExpression, this)
}
override val indices by lz {
sourcePsi.indexExpressions.map {
baseResolveProviderService.baseKotlinConverter.convertOrEmpty(it, this)
}
}
}
@@ -1,19 +0,0 @@
/*
* Copyright 2010-2021 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.uast.kotlin
import org.jetbrains.kotlin.psi.KtBlockExpression
import org.jetbrains.uast.UBlockExpression
import org.jetbrains.uast.UElement
abstract class KotlinAbstractUBlockExpression(
override val sourcePsi: KtBlockExpression,
givenParent: UElement?
) : KotlinAbstractUExpression(givenParent), UBlockExpression, KotlinUElementWithType {
override val expressions by lz {
sourcePsi.statements.map { baseResolveProviderService.baseKotlinConverter.convertOrEmpty(it, this) }
}
}
@@ -1,39 +0,0 @@
/*
* Copyright 2010-2021 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.uast.kotlin
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import org.jetbrains.kotlin.psi.KtSimpleNameExpression
import org.jetbrains.uast.UElement
import org.jetbrains.uast.USimpleNameReferenceExpression
import org.jetbrains.uast.internal.acceptList
import org.jetbrains.uast.toUElement
import org.jetbrains.uast.visitor.UastVisitor
abstract class KotlinAbstractUSimpleReferenceExpression(
override val sourcePsi: KtSimpleNameExpression,
givenParent: UElement?
) : KotlinAbstractUExpression(givenParent), USimpleNameReferenceExpression, KotlinUElementWithType, KotlinEvaluatableUElement {
protected val resolvedDeclaration: PsiElement? by lz { baseResolveProviderService.resolveToDeclaration(sourcePsi) }
override val identifier get() = sourcePsi.getReferencedName()
override fun resolve() = resolvedDeclaration
override val resolvedName: String?
get() = (resolvedDeclaration as? PsiNamedElement)?.name
override fun accept(visitor: UastVisitor) {
visitor.visitSimpleNameReferenceExpression(this)
uAnnotations.acceptList(visitor)
visitor.afterVisitSimpleNameReferenceExpression(this)
}
override val referenceNameElement: UElement? by lz { sourcePsi.getIdentifier()?.toUElement() }
}
@@ -1,16 +0,0 @@
/*
* Copyright 2010-2021 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.uast.kotlin
import org.jetbrains.uast.UExpression
interface KotlinEvaluatableUElement : UExpression {
val baseResolveProviderService: BaseKotlinUastResolveProviderService
override fun evaluate(): Any? {
return baseResolveProviderService.evaluate(this)
}
}
@@ -1,32 +0,0 @@
/*
* Copyright 2010-2021 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.uast.kotlin
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.psi.KtAnonymousInitializer
import org.jetbrains.uast.*
class KotlinLazyUBlockExpression(
override val uastParent: UElement?,
expressionProducer: (expressionParent: UElement) -> List<UExpression>
) : UBlockExpression {
override val psi: PsiElement? get() = null
override val javaPsi: PsiElement? get() = null
override val sourcePsi: PsiElement? get() = null
override val uAnnotations: List<UAnnotation> = emptyList()
override val expressions by lz { expressionProducer(this) }
companion object {
fun create(initializers: List<KtAnonymousInitializer>, uastParent: UElement): UBlockExpression {
val languagePlugin = uastParent.getLanguagePlugin()
return KotlinLazyUBlockExpression(uastParent) { expressionParent ->
initializers.map {
languagePlugin.convertOpt(it.body, expressionParent) ?: UastEmptyExpression(expressionParent)
}
}
}
}
}
@@ -1,37 +0,0 @@
/*
* Copyright 2010-2021 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.uast.kotlin
import com.intellij.psi.PsiLanguageInjectionHost
import org.jetbrains.kotlin.psi.KtStringTemplateExpression
import org.jetbrains.uast.*
import org.jetbrains.uast.expressions.UInjectionHost
class KotlinStringTemplateUPolyadicExpression(
override val sourcePsi: KtStringTemplateExpression,
givenParent: UElement?
) : KotlinAbstractUExpression(givenParent),
UPolyadicExpression,
KotlinUElementWithType,
KotlinEvaluatableUElement,
UInjectionHost {
override val operands: List<UExpression> by lz {
sourcePsi.entries.map {
baseResolveProviderService.baseKotlinConverter.convertEntry(
it,
this,
DEFAULT_EXPRESSION_TYPES_LIST
)!!
}.takeIf { it.isNotEmpty() } ?: listOf(KotlinStringULiteralExpression(sourcePsi, this, ""))
}
override val operator = UastBinaryOperator.PLUS
override val psiLanguageInjectionHost: PsiLanguageInjectionHost get() = sourcePsi
override val isString: Boolean get() = true
override fun asRenderString(): String = if (operands.isEmpty()) "\"\"" else super<UPolyadicExpression>.asRenderString()
override fun asLogString(): String = if (operands.isEmpty()) "UPolyadicExpression (value = \"\")" else super.asLogString()
}
@@ -1,32 +0,0 @@
/*
* Copyright 2010-2021 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.uast.kotlin
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiType
import org.jetbrains.kotlin.psi.KtEscapeStringTemplateEntry
import org.jetbrains.uast.UElement
import org.jetbrains.uast.ULiteralExpression
import org.jetbrains.uast.kotlin.internal.KotlinFakeUElement
import org.jetbrains.uast.wrapULiteral
class KotlinStringULiteralExpression(
override val sourcePsi: PsiElement,
givenParent: UElement?,
val text: String
) : KotlinAbstractUExpression(givenParent), ULiteralExpression, KotlinUElementWithType, KotlinFakeUElement {
constructor(psi: PsiElement, uastParent: UElement?)
: this(psi, uastParent, if (psi is KtEscapeStringTemplateEntry) psi.unescapedValue else psi.text)
override val value: String
get() = text
override fun evaluate() = value
override fun getExpressionType(): PsiType = PsiType.getJavaLangString(sourcePsi.manager, sourcePsi.resolveScope)
override fun unwrapToSourcePsi(): List<PsiElement> = listOfNotNull(wrapULiteral(this).sourcePsi)
}

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