Switch to 192 platform

This commit is contained in:
Nikolay Krasko
2019-09-06 11:28:25 +03:00
parent 650a6e5cc4
commit edb700b898
83 changed files with 606 additions and 606 deletions
+5 -5
View File
@@ -1,6 +1,6 @@
191
192
183
as34_183
as35
as36_192
191
183_191
as34_183_191
as35_191
as36
@@ -28,7 +28,16 @@ abstract class BasicMap<K : Comparable<K>, V>(
keyDescriptor: KeyDescriptor<K>,
valueExternalizer: DataExternalizer<V>
) {
protected val storage = LazyStorage(storageFile, keyDescriptor, valueExternalizer)
protected val storage: LazyStorage<K, V>
private val nonCachingStorage = System.getProperty("kotlin.jps.non.caching.storage")?.toBoolean() ?: false
init {
storage = if (nonCachingStorage) {
NonCachingLazyStorage(storageFile, keyDescriptor, valueExternalizer)
} else {
CachingLazyStorage(storageFile, keyDescriptor, valueExternalizer)
}
}
fun clean() {
storage.clean()
@@ -28,16 +28,7 @@ abstract class BasicMap<K : Comparable<K>, V>(
keyDescriptor: KeyDescriptor<K>,
valueExternalizer: DataExternalizer<V>
) {
protected val storage: LazyStorage<K, V>
private val nonCachingStorage = System.getProperty("kotlin.jps.non.caching.storage")?.toBoolean() ?: false
init {
storage = if (nonCachingStorage) {
NonCachingLazyStorage(storageFile, keyDescriptor, valueExternalizer)
} else {
CachingLazyStorage(storageFile, keyDescriptor, valueExternalizer)
}
}
protected val storage = LazyStorage(storageFile, keyDescriptor, valueExternalizer)
fun clean() {
storage.clean()
@@ -26,7 +26,7 @@ internal open class ClassOneToManyMap(
override fun dumpValue(value: Collection<String>): String = value.dumpCollection()
fun add(key: FqName, value: FqName) {
storage.append(key.asString(), value.asString())
storage.append(key.asString(), listOf(value.asString()))
}
operator fun get(key: FqName): Collection<FqName> =
@@ -26,7 +26,7 @@ internal open class ClassOneToManyMap(
override fun dumpValue(value: Collection<String>): String = value.dumpCollection()
fun add(key: FqName, value: FqName) {
storage.append(key.asString(), listOf(value.asString()))
storage.append(key.asString(), value.asString())
}
operator fun get(key: FqName): Collection<FqName> =
@@ -16,107 +16,14 @@
package org.jetbrains.kotlin.incremental.storage
import com.intellij.util.io.DataExternalizer
import com.intellij.util.io.IOUtil
import com.intellij.util.io.KeyDescriptor
import com.intellij.util.io.PersistentHashMap
import java.io.DataOutput
import java.io.File
import java.io.IOException
/**
* It's lazy in a sense that PersistentHashMap is created only on write
*/
class LazyStorage<K, V>(
private val storageFile: File,
private val keyDescriptor: KeyDescriptor<K>,
private val valueExternalizer: DataExternalizer<V>
) {
@Volatile
private var storage: PersistentHashMap<K, V>? = null
@Synchronized
private fun getStorageIfExists(): PersistentHashMap<K, V>? {
if (storage != null) return storage
if (storageFile.exists()) {
storage = createMap()
return storage
}
return null
}
@Synchronized
private fun getStorageOrCreateNew(): PersistentHashMap<K, V> {
if (storage == null) {
storage = createMap()
}
return storage!!
}
interface LazyStorage<K, V> {
val keys: Collection<K>
get() = getStorageIfExists()?.allKeysWithExistingMapping ?: listOf()
operator fun contains(key: K): Boolean =
getStorageIfExists()?.containsMapping(key) ?: false
operator fun get(key: K): V? =
getStorageIfExists()?.get(key)
operator fun set(key: K, value: V) {
getStorageOrCreateNew().put(key, value)
}
fun remove(key: K) {
getStorageIfExists()?.remove(key)
}
fun append(key: K, value: String) {
append(key) { out -> IOUtil.writeUTF(out, value) }
}
fun append(key: K, value: Int) {
append(key) { out -> out.writeInt(value) }
}
@Synchronized
fun clean() {
try {
storage?.close()
}
catch (ignored: Throwable) {
}
PersistentHashMap.deleteFilesStartingWith(storageFile)
storage = null
}
@Synchronized
fun flush(memoryCachesOnly: Boolean) {
val existingStorage = storage ?: return
if (memoryCachesOnly) {
if (existingStorage.isDirty) {
existingStorage.dropMemoryCaches()
}
}
else {
existingStorage.force()
}
}
@Synchronized
fun close() {
storage?.close()
}
private fun createMap(): PersistentHashMap<K, V> =
PersistentHashMap(storageFile, keyDescriptor, valueExternalizer)
private fun append(key: K, append: (DataOutput)->Unit) {
getStorageOrCreateNew().appendData(key, append)
}
}
operator fun contains(key: K): Boolean
operator fun get(key: K): V?
operator fun set(key: K, value: V)
fun remove(key: K)
fun append(key: K, value: V)
fun clean()
fun flush(memoryCachesOnly: Boolean)
fun close()
}
@@ -0,0 +1,122 @@
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.incremental.storage
import com.intellij.util.io.DataExternalizer
import com.intellij.util.io.IOUtil
import com.intellij.util.io.KeyDescriptor
import com.intellij.util.io.PersistentHashMap
import java.io.DataOutput
import java.io.File
import java.io.IOException
/**
* It's lazy in a sense that PersistentHashMap is created only on write
*/
class LazyStorage<K, V>(
private val storageFile: File,
private val keyDescriptor: KeyDescriptor<K>,
private val valueExternalizer: DataExternalizer<V>
) {
@Volatile
private var storage: PersistentHashMap<K, V>? = null
@Synchronized
private fun getStorageIfExists(): PersistentHashMap<K, V>? {
if (storage != null) return storage
if (storageFile.exists()) {
storage = createMap()
return storage
}
return null
}
@Synchronized
private fun getStorageOrCreateNew(): PersistentHashMap<K, V> {
if (storage == null) {
storage = createMap()
}
return storage!!
}
val keys: Collection<K>
get() = getStorageIfExists()?.allKeysWithExistingMapping ?: listOf()
operator fun contains(key: K): Boolean =
getStorageIfExists()?.containsMapping(key) ?: false
operator fun get(key: K): V? =
getStorageIfExists()?.get(key)
operator fun set(key: K, value: V) {
getStorageOrCreateNew().put(key, value)
}
fun remove(key: K) {
getStorageIfExists()?.remove(key)
}
fun append(key: K, value: String) {
append(key) { out -> IOUtil.writeUTF(out, value) }
}
fun append(key: K, value: Int) {
append(key) { out -> out.writeInt(value) }
}
@Synchronized
fun clean() {
try {
storage?.close()
}
catch (ignored: Throwable) {
}
PersistentHashMap.deleteFilesStartingWith(storageFile)
storage = null
}
@Synchronized
fun flush(memoryCachesOnly: Boolean) {
val existingStorage = storage ?: return
if (memoryCachesOnly) {
if (existingStorage.isDirty) {
existingStorage.dropMemoryCaches()
}
}
else {
existingStorage.force()
}
}
@Synchronized
fun close() {
storage?.close()
}
private fun createMap(): PersistentHashMap<K, V> =
PersistentHashMap(storageFile, keyDescriptor, valueExternalizer)
private fun append(key: K, append: (DataOutput)->Unit) {
getStorageOrCreateNew().appendData(key, append)
}
}
@@ -1,29 +0,0 @@
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.incremental.storage
interface LazyStorage<K, V> {
val keys: Collection<K>
operator fun contains(key: K): Boolean
operator fun get(key: K): V?
operator fun set(key: K, value: V)
fun remove(key: K)
fun append(key: K, value: V)
fun clean()
fun flush(memoryCachesOnly: Boolean)
fun close()
}
@@ -24,7 +24,7 @@ internal class LookupMap(storage: File) : BasicMap<LookupSymbolKey, Collection<I
override fun dumpValue(value: Collection<Int>): String = value.toString()
fun add(name: String, scope: String, fileId: Int) {
storage.append(LookupSymbolKey(name, scope), fileId)
storage.append(LookupSymbolKey(name, scope), listOf(fileId))
}
operator fun get(key: LookupSymbolKey): Collection<Int>? = storage[key]
@@ -24,7 +24,7 @@ internal class LookupMap(storage: File) : BasicMap<LookupSymbolKey, Collection<I
override fun dumpValue(value: Collection<Int>): String = value.toString()
fun add(name: String, scope: String, fileId: Int) {
storage.append(LookupSymbolKey(name, scope), listOf(fileId))
storage.append(LookupSymbolKey(name, scope), fileId)
}
operator fun get(key: LookupSymbolKey): Collection<Int>? = storage[key]
@@ -41,7 +41,7 @@ internal abstract class AbstractSourceToOutputMap<Name>(
}
fun add(sourceFile: File, className: Name) {
storage.append(pathConverter.toPath(sourceFile), nameTransformer.asString(className))
storage.append(pathConverter.toPath(sourceFile), listOf(nameTransformer.asString(className)))
}
fun contains(sourceFile: File): Boolean =
@@ -41,7 +41,7 @@ internal abstract class AbstractSourceToOutputMap<Name>(
}
fun add(sourceFile: File, className: Name) {
storage.append(pathConverter.toPath(sourceFile), listOf(nameTransformer.asString(className)))
storage.append(pathConverter.toPath(sourceFile), nameTransformer.asString(className))
}
fun contains(sourceFile: File): Boolean =
+6 -3
View File
@@ -15,9 +15,6 @@ messages/**)
-outjars '<kotlin-compiler-jar>'
-dontnote **
-dontwarn com.intellij.util.ui.IsRetina*
-dontwarn com.intellij.util.ui.UIUtilities
-dontwarn com.intellij.util.RetinaImage*
-dontwarn apple.awt.*
-dontwarn dk.brics.automaton.*
-dontwarn org.fusesource.**
@@ -27,6 +24,12 @@ messages/**)
-dontwarn com.intellij.util.SnappyInitializer
-dontwarn com.intellij.util.SVGLoader
-dontwarn com.intellij.util.SVGLoader$MyTranscoder
-dontwarn com.intellij.util.ImageLoader$ImageDesc
-dontwarn com.intellij.util.ui.**
-dontwarn com.intellij.ui.**
-dontwarn com.intellij.util.IconUtil
-dontwarn com.intellij.util.ImageLoader
-dontwarn kotlinx.coroutines.flow.FlowKt__MergeKt
-dontwarn net.sf.cglib.**
-dontwarn org.objectweb.asm.** # this is ASM3, the old version that we do not use
-dontwarn com.sun.jna.NativeString
@@ -15,6 +15,9 @@ messages/**)
-outjars '<kotlin-compiler-jar>'
-dontnote **
-dontwarn com.intellij.util.ui.IsRetina*
-dontwarn com.intellij.util.ui.UIUtilities
-dontwarn com.intellij.util.RetinaImage*
-dontwarn apple.awt.*
-dontwarn dk.brics.automaton.*
-dontwarn org.fusesource.**
@@ -24,12 +27,6 @@ messages/**)
-dontwarn com.intellij.util.SnappyInitializer
-dontwarn com.intellij.util.SVGLoader
-dontwarn com.intellij.util.SVGLoader$MyTranscoder
-dontwarn com.intellij.util.ImageLoader$ImageDesc
-dontwarn com.intellij.util.ui.**
-dontwarn com.intellij.ui.**
-dontwarn com.intellij.util.IconUtil
-dontwarn com.intellij.util.ImageLoader
-dontwarn kotlinx.coroutines.flow.FlowKt__MergeKt
-dontwarn net.sf.cglib.**
-dontwarn org.objectweb.asm.** # this is ASM3, the old version that we do not use
-dontwarn com.sun.jna.NativeString
+3 -4
View File
@@ -1,14 +1,13 @@
versions.intellijSdk=191.6707.61
versions.intellijSdk=192.5728.98
versions.androidBuildTools=r23.0.1
versions.androidDxSources=5.0.0_r2
versions.idea.NodeJS=181.3494.12
versions.jar.asm-all=7.0.1
versions.jar.guava=25.1-jre
versions.jar.groovy-all=2.4.15
versions.jar.groovy-all=2.4.17
versions.jar.lombok-ast=0.2.3
versions.jar.swingx-core=1.6.2-2
versions.jar.kxml2=2.3.0
versions.jar.streamex=0.6.7
versions.jar.streamex=0.6.8
versions.jar.gson=2.8.5
versions.jar.oro=2.0.8
versions.jar.picocontainer=1.2
@@ -1,13 +1,14 @@
versions.intellijSdk=192.5728.98
versions.intellijSdk=191.6707.61
versions.androidBuildTools=r23.0.1
versions.androidDxSources=5.0.0_r2
versions.idea.NodeJS=181.3494.12
versions.jar.asm-all=7.0.1
versions.jar.guava=25.1-jre
versions.jar.groovy-all=2.4.17
versions.jar.groovy-all=2.4.15
versions.jar.lombok-ast=0.2.3
versions.jar.swingx-core=1.6.2-2
versions.jar.kxml2=2.3.0
versions.jar.streamex=0.6.8
versions.jar.streamex=0.6.7
versions.jar.gson=2.8.5
versions.jar.oro=2.0.8
versions.jar.picocontainer=1.2
@@ -9,4 +9,4 @@ import com.intellij.psi.impl.PsiModificationTrackerImpl
// BUNCH: 191
@Suppress("unused")
val PsiModificationTrackerImpl.isEnableLanguageTrackerCompat get() = isEnableLanguageTracker
val PsiModificationTrackerImpl.isEnableLanguageTrackerCompat get() = true
@@ -9,4 +9,4 @@ import com.intellij.psi.impl.PsiModificationTrackerImpl
// BUNCH: 191
@Suppress("unused")
val PsiModificationTrackerImpl.isEnableLanguageTrackerCompat get() = true
val PsiModificationTrackerImpl.isEnableLanguageTrackerCompat get() = isEnableLanguageTracker
@@ -170,7 +170,7 @@ public class KotlinConfidenceTest extends LightCompletionTestCase {
protected void complete() {
if (skipComplete.get()) return;
new CodeCompletionHandlerBase(CompletionType.BASIC, false, true, true).invokeCompletion(
getProject(), getEditor(), 0, false, false);
getProject(), getEditor(), 0, false);
LookupImpl lookup = (LookupImpl) LookupManager.getActiveLookup(myEditor);
myItems = lookup == null ? null : lookup.getItems().toArray(LookupElement.EMPTY_ARRAY);
@@ -170,7 +170,7 @@ public class KotlinConfidenceTest extends LightCompletionTestCase {
protected void complete() {
if (skipComplete.get()) return;
new CodeCompletionHandlerBase(CompletionType.BASIC, false, true, true).invokeCompletion(
getProject(), getEditor(), 0, false);
getProject(), getEditor(), 0, false, false);
LookupImpl lookup = (LookupImpl) LookupManager.getActiveLookup(myEditor);
myItems = lookup == null ? null : lookup.getItems().toArray(LookupElement.EMPTY_ARRAY);
@@ -21,6 +21,7 @@ import org.jetbrains.plugins.gradle.util.GradleConstants
import java.io.File
import java.io.Serializable
import com.intellij.openapi.externalSystem.model.Key as ExternalKey
import com.intellij.serialization.PropertyMapping
var DataNode<out ModuleData>.kotlinSourceSet: KotlinSourceSetInfo?
by CopyableDataNodeUserDataProperty(Key.create("KOTLIN_SOURCE_SET"))
@@ -28,7 +29,7 @@ var DataNode<out ModuleData>.kotlinSourceSet: KotlinSourceSetInfo?
val DataNode<ModuleData>.kotlinAndroidSourceSets: List<KotlinSourceSetInfo>?
get() = ExternalSystemApiUtil.getChildren(this, KotlinAndroidSourceSetData.KEY).firstOrNull()?.data?.sourceSetInfos
class KotlinSourceSetInfo(val kotlinModule: KotlinModule) : Serializable {
class KotlinSourceSetInfo @PropertyMapping("kotlinModule") constructor(val kotlinModule: KotlinModule) : Serializable {
var moduleId: String? = null
var gradleModuleId: String = ""
@@ -46,15 +47,15 @@ class KotlinSourceSetInfo(val kotlinModule: KotlinModule) : Serializable {
var dependsOn: List<String> = emptyList()
}
class KotlinAndroidSourceSetData(
val sourceSetInfos: List<KotlinSourceSetInfo>
class KotlinAndroidSourceSetData @PropertyMapping("sourceSetInfos") constructor(val sourceSetInfos: List<KotlinSourceSetInfo>
) : AbstractExternalEntityData(GradleConstants.SYSTEM_ID) {
companion object {
val KEY = ExternalKey.create(KotlinAndroidSourceSetData::class.java, KotlinTargetData.KEY.processingWeight + 1)
}
}
class KotlinTargetData(name: String) : AbstractNamedData(GradleConstants.SYSTEM_ID, name) {
class KotlinTargetData @PropertyMapping("externalName") constructor(externalName: String) :
AbstractNamedData(GradleConstants.SYSTEM_ID, externalName) {
var moduleIds: Set<String> = emptySet()
var archiveFile: File? = null
var konanArtifacts: Collection<KonanArtifactModel>? = null
@@ -68,4 +69,4 @@ class KotlinOutputPathsData(val paths: MultiMap<ExternalSystemSourceType, String
companion object {
val KEY = ExternalKey.create(KotlinOutputPathsData::class.java, ProjectKeys.CONTENT_ROOT.processingWeight + 1)
}
}
}
@@ -21,7 +21,6 @@ import org.jetbrains.plugins.gradle.util.GradleConstants
import java.io.File
import java.io.Serializable
import com.intellij.openapi.externalSystem.model.Key as ExternalKey
import com.intellij.serialization.PropertyMapping
var DataNode<out ModuleData>.kotlinSourceSet: KotlinSourceSetInfo?
by CopyableDataNodeUserDataProperty(Key.create("KOTLIN_SOURCE_SET"))
@@ -29,7 +28,7 @@ var DataNode<out ModuleData>.kotlinSourceSet: KotlinSourceSetInfo?
val DataNode<ModuleData>.kotlinAndroidSourceSets: List<KotlinSourceSetInfo>?
get() = ExternalSystemApiUtil.getChildren(this, KotlinAndroidSourceSetData.KEY).firstOrNull()?.data?.sourceSetInfos
class KotlinSourceSetInfo @PropertyMapping("kotlinModule") constructor(val kotlinModule: KotlinModule) : Serializable {
class KotlinSourceSetInfo(val kotlinModule: KotlinModule) : Serializable {
var moduleId: String? = null
var gradleModuleId: String = ""
@@ -47,15 +46,15 @@ class KotlinSourceSetInfo @PropertyMapping("kotlinModule") constructor(val kotli
var dependsOn: List<String> = emptyList()
}
class KotlinAndroidSourceSetData @PropertyMapping("sourceSetInfos") constructor(val sourceSetInfos: List<KotlinSourceSetInfo>
class KotlinAndroidSourceSetData(
val sourceSetInfos: List<KotlinSourceSetInfo>
) : AbstractExternalEntityData(GradleConstants.SYSTEM_ID) {
companion object {
val KEY = ExternalKey.create(KotlinAndroidSourceSetData::class.java, KotlinTargetData.KEY.processingWeight + 1)
}
}
class KotlinTargetData @PropertyMapping("externalName") constructor(externalName: String) :
AbstractNamedData(GradleConstants.SYSTEM_ID, externalName) {
class KotlinTargetData(name: String) : AbstractNamedData(GradleConstants.SYSTEM_ID, name) {
var moduleIds: Set<String> = emptySet()
var archiveFile: File? = null
var konanArtifacts: Collection<KonanArtifactModel>? = null
@@ -69,4 +68,4 @@ class KotlinOutputPathsData(val paths: MultiMap<ExternalSystemSourceType, String
companion object {
val KEY = ExternalKey.create(KotlinOutputPathsData::class.java, ProjectKeys.CONTENT_ROOT.processingWeight + 1)
}
}
}
@@ -11,6 +11,7 @@ import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsPr
import com.intellij.openapi.externalSystem.service.project.manage.AbstractProjectDataService
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtil
import com.intellij.packaging.artifacts.ModifiableArtifactModel
import com.intellij.packaging.impl.artifacts.JarArtifactType
import com.intellij.packaging.impl.elements.ProductionModuleOutputPackagingElement
import org.jetbrains.kotlin.idea.util.createPointer
@@ -27,7 +28,22 @@ class KotlinTargetDataService : AbstractProjectDataService<KotlinTargetData, Voi
for (nodeToImport in toImport) {
val targetData = nodeToImport.data
val archiveFile = targetData.archiveFile ?: continue
val artifactModel = modelsProvider.modifiableArtifactModel
//TODO(auskov) should be replaced with direct invocation of the method after migration to new API in IDEA 192
val artifactModel = try {
val oldMethod = modelsProvider.javaClass.getMethod("getModifiableArtifactModel")
oldMethod.invoke(modelsProvider) as ModifiableArtifactModel
} catch (_: Exception) {
val newMethod = modelsProvider.javaClass.getMethod("getModifiableModel", Class::class.java)
val packagingModifiableModel = newMethod.invoke(
modelsProvider,
Class.forName("com.intellij.openapi.externalSystem.project.PackagingModifiableModel")
)
packagingModifiableModel.javaClass
.getMethod("getModifiableArtifactModel")
.invoke(packagingModifiableModel) as ModifiableArtifactModel
}
val artifactName = FileUtil.getNameWithoutExtension(archiveFile)
artifactModel.findArtifact(artifactName)?.let { artifactModel.removeArtifact(it) }
artifactModel.addArtifact(artifactName, JarArtifactType.getInstance()).also {
@@ -11,7 +11,6 @@ import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsPr
import com.intellij.openapi.externalSystem.service.project.manage.AbstractProjectDataService
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtil
import com.intellij.packaging.artifacts.ModifiableArtifactModel
import com.intellij.packaging.impl.artifacts.JarArtifactType
import com.intellij.packaging.impl.elements.ProductionModuleOutputPackagingElement
import org.jetbrains.kotlin.idea.util.createPointer
@@ -28,22 +27,7 @@ class KotlinTargetDataService : AbstractProjectDataService<KotlinTargetData, Voi
for (nodeToImport in toImport) {
val targetData = nodeToImport.data
val archiveFile = targetData.archiveFile ?: continue
//TODO(auskov) should be replaced with direct invocation of the method after migration to new API in IDEA 192
val artifactModel = try {
val oldMethod = modelsProvider.javaClass.getMethod("getModifiableArtifactModel")
oldMethod.invoke(modelsProvider) as ModifiableArtifactModel
} catch (_: Exception) {
val newMethod = modelsProvider.javaClass.getMethod("getModifiableModel", Class::class.java)
val packagingModifiableModel = newMethod.invoke(
modelsProvider,
Class.forName("com.intellij.openapi.externalSystem.project.PackagingModifiableModel")
)
packagingModifiableModel.javaClass
.getMethod("getModifiableArtifactModel")
.invoke(packagingModifiableModel) as ModifiableArtifactModel
}
val artifactModel = modelsProvider.modifiableArtifactModel
val artifactName = FileUtil.getNameWithoutExtension(archiveFile)
artifactModel.findArtifact(artifactName)?.let { artifactModel.removeArtifact(it) }
artifactModel.addArtifact(artifactName, JarArtifactType.getInstance()).also {
@@ -5,14 +5,13 @@
package org.jetbrains.kotlin.idea.gradle.execution
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil.toCanonicalPath
import org.jetbrains.plugins.gradle.service.settings.GradleSettingsService
import com.intellij.openapi.module.Module
import org.jetbrains.plugins.gradle.settings.GradleProjectSettings
//BUNCH: 183
fun isDelegatedBuild(module: Module): Boolean {
val projectUrl = module.project.presentableUrl
if (projectUrl == null || !GradleSettingsService.getInstance(module.project).isDelegatedBuildEnabled(toCanonicalPath(projectUrl))) {
if (projectUrl == null || !GradleProjectSettings.isDelegatedBuildEnabled(module)) {
return false
}
return true
@@ -5,13 +5,14 @@
package org.jetbrains.kotlin.idea.gradle.execution
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil.toCanonicalPath
import org.jetbrains.plugins.gradle.service.settings.GradleSettingsService
import com.intellij.openapi.module.Module
import org.jetbrains.plugins.gradle.settings.GradleProjectSettings
//BUNCH: 183
fun isDelegatedBuild(module: Module): Boolean {
val projectUrl = module.project.presentableUrl
if (projectUrl == null || !GradleProjectSettings.isDelegatedBuildEnabled(module)) {
if (projectUrl == null || !GradleSettingsService.getInstance(module.project).isDelegatedBuildEnabled(toCanonicalPath(projectUrl))) {
return false
}
return true
@@ -90,7 +90,7 @@ class KotlinLanguageInjectionSupport : AbstractLanguageInjectionSupport() {
return true
}
override fun findCommentInjection(host: PsiElement, commentRef: Ref<PsiElement>?): BaseInjection? {
override fun findCommentInjection(host: PsiElement, commentRef: Ref<in PsiElement>?): BaseInjection? {
// Do not inject through CommentLanguageInjector, because it injects as simple injection.
// We need to behave special for interpolated strings.
return null
@@ -90,7 +90,7 @@ class KotlinLanguageInjectionSupport : AbstractLanguageInjectionSupport() {
return true
}
override fun findCommentInjection(host: PsiElement, commentRef: Ref<in PsiElement>?): BaseInjection? {
override fun findCommentInjection(host: PsiElement, commentRef: Ref<PsiElement>?): BaseInjection? {
// Do not inject through CommentLanguageInjector, because it injects as simple injection.
// We need to behave special for interpolated strings.
return null
@@ -17,7 +17,6 @@
package org.jetbrains.kotlin.idea.test;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
@@ -44,10 +43,6 @@ public abstract class KotlinLightCodeInsightFixtureTestCaseBase extends LightCod
return super.getProject();
}
public Module getModule() {
return myModule;
}
@NotNull
@Override
public Editor getEditor() {
@@ -17,6 +17,7 @@
package org.jetbrains.kotlin.idea.test;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
@@ -43,6 +44,10 @@ public abstract class KotlinLightCodeInsightFixtureTestCaseBase extends LightCod
return super.getProject();
}
public Module getModule() {
return myModule;
}
@NotNull
@Override
public Editor getEditor() {
@@ -10,6 +10,7 @@ import com.intellij.lang.LanguageExtensionPoint
import com.intellij.lang.annotation.Annotator
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.editor.Document
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.fileEditor.FileDocumentManager
@@ -19,9 +20,12 @@ import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.impl.PsiDocumentManagerBase
import com.intellij.testFramework.EdtTestUtil
import com.intellij.testFramework.PlatformTestUtil
import com.intellij.util.ThrowableRunnable
import com.intellij.testFramework.runInEdtAndWait
import com.intellij.util.ui.UIUtil
import org.jetbrains.kotlin.idea.highlighter.KotlinPsiCheckerAndHighlightingUpdater
import org.jetbrains.kotlin.idea.parameterInfo.HintType
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
@@ -73,31 +77,7 @@ fun closeProject(project: Project) {
}
fun waitForAllEditorsFinallyLoaded(project: Project) {
waitForAllEditorsFinallyLoaded(project, 5, TimeUnit.MINUTES)
}
fun waitForAllEditorsFinallyLoaded(project: Project, timeout: Long, unit: TimeUnit) {
ApplicationManager.getApplication().assertIsDispatchThread()
val deadline = unit.toMillis(timeout) + System.currentTimeMillis()
while (true) {
if (System.currentTimeMillis() > deadline) throw TimeoutException()
if (waitABitForEditorLoading(project)) break
UIUtil.dispatchAllInvocationEvents()
}
}
private fun waitABitForEditorLoading(project: Project): Boolean {
for (editor in FileEditorManager.getInstance(project).allEditors) {
if (editor is TextEditorImpl) {
try {
editor.waitForLoaded(100, TimeUnit.MILLISECONDS)
} catch (ignored: TimeoutException) {
return false
}
}
}
return true
// routing is obsolete in 192
}
fun replaceWithCustomHighlighter(parentDisposable: Disposable, fromImplementationClass: String, toImplementationClass: String) {
@@ -10,7 +10,6 @@ import com.intellij.lang.LanguageExtensionPoint
import com.intellij.lang.annotation.Annotator
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.editor.Document
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.fileEditor.FileDocumentManager
@@ -20,12 +19,9 @@ import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.impl.PsiDocumentManagerBase
import com.intellij.testFramework.EdtTestUtil
import com.intellij.testFramework.PlatformTestUtil
import com.intellij.util.ThrowableRunnable
import com.intellij.testFramework.runInEdtAndWait
import com.intellij.util.ui.UIUtil
import org.jetbrains.kotlin.idea.highlighter.KotlinPsiCheckerAndHighlightingUpdater
import org.jetbrains.kotlin.idea.parameterInfo.HintType
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
@@ -77,7 +73,31 @@ fun closeProject(project: Project) {
}
fun waitForAllEditorsFinallyLoaded(project: Project) {
// routing is obsolete in 192
waitForAllEditorsFinallyLoaded(project, 5, TimeUnit.MINUTES)
}
fun waitForAllEditorsFinallyLoaded(project: Project, timeout: Long, unit: TimeUnit) {
ApplicationManager.getApplication().assertIsDispatchThread()
val deadline = unit.toMillis(timeout) + System.currentTimeMillis()
while (true) {
if (System.currentTimeMillis() > deadline) throw TimeoutException()
if (waitABitForEditorLoading(project)) break
UIUtil.dispatchAllInvocationEvents()
}
}
private fun waitABitForEditorLoading(project: Project): Boolean {
for (editor in FileEditorManager.getInstance(project).allEditors) {
if (editor is TextEditorImpl) {
try {
editor.waitForLoaded(100, TimeUnit.MILLISECONDS)
} catch (ignored: TimeoutException) {
return false
}
}
}
return true
}
fun replaceWithCustomHighlighter(parentDisposable: Disposable, fromImplementationClass: String, toImplementationClass: String) {
+1 -1
View File
@@ -13,7 +13,7 @@ The Kotlin plugin provides language support in IntelliJ IDEA and Android Studio.
<version>@snapshot@</version>
<vendor url="http://www.jetbrains.com">JetBrains</vendor>
<idea-version since-build="191.5109.14" until-build="192.*"/>
<idea-version since-build="192.5118.30" until-build="193.*"/>
<depends>com.intellij.modules.platform</depends>
@@ -13,7 +13,7 @@ The Kotlin plugin provides language support in IntelliJ IDEA and Android Studio.
<version>@snapshot@</version>
<vendor url="http://www.jetbrains.com">JetBrains</vendor>
<idea-version since-build="192.5118.30" until-build="193.*"/>
<idea-version since-build="191.5109.14" until-build="192.*"/>
<depends>com.intellij.modules.platform</depends>
@@ -88,11 +88,11 @@ class KotlinGenerateEqualsWizard(
override fun getNonNullPanel() = null
override fun updateHashCodeMemberInfos(equalsMemberInfos: MutableCollection<KotlinMemberInfo>) {
override fun updateHashCodeMemberInfos(equalsMemberInfos: MutableCollection<out KotlinMemberInfo>) {
hashCodePanel?.table?.setMemberInfos(equalsMemberInfos.map { membersToHashCode[it.member] })
}
override fun updateNonNullMemberInfos(equalsMemberInfos: MutableCollection<KotlinMemberInfo>?) {
override fun updateNonNullMemberInfos(equalsMemberInfos: MutableCollection<out KotlinMemberInfo>?) {
}
}
@@ -88,11 +88,11 @@ class KotlinGenerateEqualsWizard(
override fun getNonNullPanel() = null
override fun updateHashCodeMemberInfos(equalsMemberInfos: MutableCollection<out KotlinMemberInfo>) {
override fun updateHashCodeMemberInfos(equalsMemberInfos: MutableCollection<KotlinMemberInfo>) {
hashCodePanel?.table?.setMemberInfos(equalsMemberInfos.map { membersToHashCode[it.member] })
}
override fun updateNonNullMemberInfos(equalsMemberInfos: MutableCollection<out KotlinMemberInfo>?) {
override fun updateNonNullMemberInfos(equalsMemberInfos: MutableCollection<KotlinMemberInfo>?) {
}
}
@@ -6,6 +6,7 @@
package org.jetbrains.kotlin.idea.highlighter.markers
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.util.ScalableIcon
import com.intellij.ui.LayeredIcon
import com.intellij.util.ui.ColorsIcon
import com.intellij.util.ui.JBUI
@@ -15,7 +16,6 @@ import javax.swing.Icon
// BUNCH: as35
// BUNCH: as34
// BUNCH: 191
internal fun createDslStyleIcon(styleId: Int): Icon {
val globalScheme = EditorColorsManager.getInstance().globalScheme
val markersColor = globalScheme.getAttributes(DslHighlighterExtension.styleById(styleId)).foregroundColor
@@ -23,7 +23,7 @@ internal fun createDslStyleIcon(styleId: Int): Icon {
val defaultIcon = KotlinIcons.DSL_MARKER_ANNOTATION
icon.setIcon(defaultIcon, 0)
icon.setIcon(
ColorsIcon(defaultIcon.iconHeight / 2, markersColor).scale(JBUI.pixScale()),
(ColorsIcon(defaultIcon.iconHeight / 2, markersColor) as ScalableIcon).scale(JBUI.pixScale()),
1,
defaultIcon.iconHeight / 2,
defaultIcon.iconWidth / 2
@@ -6,7 +6,6 @@
package org.jetbrains.kotlin.idea.highlighter.markers
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.util.ScalableIcon
import com.intellij.ui.LayeredIcon
import com.intellij.util.ui.ColorsIcon
import com.intellij.util.ui.JBUI
@@ -16,6 +15,7 @@ import javax.swing.Icon
// BUNCH: as35
// BUNCH: as34
// BUNCH: 191
internal fun createDslStyleIcon(styleId: Int): Icon {
val globalScheme = EditorColorsManager.getInstance().globalScheme
val markersColor = globalScheme.getAttributes(DslHighlighterExtension.styleById(styleId)).foregroundColor
@@ -23,7 +23,7 @@ internal fun createDslStyleIcon(styleId: Int): Icon {
val defaultIcon = KotlinIcons.DSL_MARKER_ANNOTATION
icon.setIcon(defaultIcon, 0)
icon.setIcon(
(ColorsIcon(defaultIcon.iconHeight / 2, markersColor) as ScalableIcon).scale(JBUI.pixScale()),
ColorsIcon(defaultIcon.iconHeight / 2, markersColor).scale(JBUI.pixScale()),
1,
defaultIcon.iconHeight / 2,
defaultIcon.iconWidth / 2
@@ -49,7 +49,7 @@ object PlatformUnresolvedProvider : KotlinIntentionActionFactoryWithDelegate<KtN
register(action)
}
override fun unregister(condition: Condition<IntentionAction>) {
override fun unregister(condition: Condition<in IntentionAction>) {
}
})
}
@@ -49,7 +49,7 @@ object PlatformUnresolvedProvider : KotlinIntentionActionFactoryWithDelegate<KtN
register(action)
}
override fun unregister(condition: Condition<in IntentionAction>) {
override fun unregister(condition: Condition<IntentionAction>) {
}
})
}
@@ -1,16 +1,19 @@
/*
* 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.
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.quickfix.crossLanguage
import com.intellij.codeInsight.daemon.QuickFixBundle
import com.intellij.lang.jvm.actions.AnnotationRequest
import com.intellij.lang.jvm.actions.ChangeParametersRequest
import com.intellij.lang.jvm.actions.ExpectedParameter
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.JvmPsiConversionHelper
import org.jetbrains.kotlin.asJava.elements.KtLightElement
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.SourceElement
import org.jetbrains.kotlin.descriptors.annotations.Annotations
@@ -25,12 +28,8 @@ import org.jetbrains.kotlin.load.java.NOT_NULL_ANNOTATIONS
import org.jetbrains.kotlin.load.java.NULLABLE_ANNOTATIONS
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtParameterList
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.ErrorUtils
import org.jetbrains.kotlin.types.KotlinType
internal class ChangeMethodParameters(
@@ -61,45 +60,112 @@ internal class ChangeMethodParameters(
override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean = element != null && request.isValid
private data class ParameterModification(
val name: String,
val ktType: KotlinType
)
private sealed class ParameterModification {
data class Keep(val ktParameter: KtParameter) : ParameterModification()
data class Remove(val ktParameter: KtParameter) : ParameterModification()
data class Add(
val name: String,
val ktType: KotlinType,
val expectedAnnotations: Collection<AnnotationRequest>,
val beforeAnchor: KtParameter?
) : ParameterModification()
}
private fun getParametersModifications(
private tailrec fun getParametersModifications(
target: KtNamedFunction,
expectedParameters: List<ExpectedParameter>
currentParameters: List<KtParameter>,
expectedParameters: List<ExpectedParameter>,
index: Int = 0,
collected: List<ParameterModification> = ArrayList(expectedParameters.size)
): List<ParameterModification> {
val helper = JvmPsiConversionHelper.getInstance(target.project)
return expectedParameters.mapIndexed { index, expectedParameter ->
val theType = expectedParameter.expectedTypes.firstOrNull()?.theType
val kotlinType = theType
?.let { helper.convertType(it).resolveToKotlinType(target.getResolutionFacade()) }
?: ErrorUtils.createErrorType("unknown type")
val expectedHead = expectedParameters.firstOrNull() ?: return collected + currentParameters.map { ParameterModification.Remove(it) }
ParameterModification(
expectedParameter.semanticNames.firstOrNull() ?: "param$index", kotlinType
if (expectedHead is ChangeParametersRequest.ExistingParameterWrapper) {
val expectedExistingParameter = expectedHead.existingKtParameter
if (expectedExistingParameter == null) {
LOG.error("can't find the kotlinOrigin for parameter ${expectedHead.existingParameter} at index $index")
return collected
}
val existingInTail = currentParameters.indexOf(expectedExistingParameter)
if (existingInTail == -1) {
throw IllegalArgumentException("can't find existing for parameter ${expectedHead.existingParameter} at index $index")
}
return getParametersModifications(
target,
currentParameters.subList(existingInTail + 1, currentParameters.size),
expectedParameters.subList(1, expectedParameters.size),
index,
collected
+ currentParameters.subList(0, existingInTail).map { ParameterModification.Remove(it) }
+ ParameterModification.Keep(expectedExistingParameter)
)
}
val helper = JvmPsiConversionHelper.getInstance(target.project)
val theType = expectedHead.expectedTypes.firstOrNull()?.theType ?: return emptyList()
val kotlinType = helper.convertType(theType).resolveToKotlinType(target.getResolutionFacade()) ?: return emptyList()
return getParametersModifications(
target,
currentParameters,
expectedParameters.subList(1, expectedParameters.size),
index + 1,
collected + ParameterModification.Add(
expectedHead.semanticNames.firstOrNull() ?: "param$index",
kotlinType,
expectedHead.expectedAnnotations,
currentParameters.firstOrNull { anchor ->
expectedParameters.any {
it is ChangeParametersRequest.ExistingParameterWrapper && it.existingKtParameter == anchor
}
})
)
}
private val ChangeParametersRequest.ExistingParameterWrapper.existingKtParameter
get() = (existingParameter as? KtLightElement<*, *>)?.kotlinOrigin as? KtParameter
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
if (!request.isValid) return
val target = element ?: return
val functionDescriptor = target.resolveToDescriptorIfAny(BodyResolveMode.FULL) ?: return
target.valueParameterList!!.parameters.forEach { target.valueParameterList!!.removeParameter(it) }
val parameterActions = getParametersModifications(target, request.expectedParameters)
val parameterActions = getParametersModifications(target, target.valueParameters, request.expectedParameters)
val parametersGenerated = parameterActions.let {
val parametersGenerated = parameterActions.filterIsInstance<ParameterModification.Add>().let {
it zip generateParameterList(project, functionDescriptor, it).parameters
}.toMap()
for (action in parameterActions) {
val parameter = parametersGenerated.getValue(action)
target.valueParameterList!!.addParameter(parameter)
when (action) {
is ParameterModification.Add -> {
val parameter = parametersGenerated.getValue(action)
for (expectedAnnotation in action.expectedAnnotations) {
addAnnotationEntry(parameter, expectedAnnotation, null)
}
val anchor = action.beforeAnchor
if (anchor != null) {
target.valueParameterList!!.addParameterBefore(parameter, anchor)
} else {
target.valueParameterList!!.addParameter(parameter)
}
}
is ParameterModification.Keep -> {
// Do nothing
}
is ParameterModification.Remove -> {
target.valueParameterList!!.removeParameter(action.ktParameter)
}
}
}
ShortenReferences.DEFAULT.process(target.valueParameterList!!)
@@ -108,7 +174,7 @@ internal class ChangeMethodParameters(
private fun generateParameterList(
project: Project,
functionDescriptor: FunctionDescriptor,
paramsToAdd: List<ParameterModification>
paramsToAdd: List<ParameterModification.Add>
): KtParameterList {
val newFunctionDescriptor = SimpleFunctionDescriptorImpl.create(
functionDescriptor.containingDeclaration,
@@ -159,4 +225,7 @@ internal class ChangeMethodParameters(
ChangeMethodParameters(ktNamedFunction, request)
}
}
}
private val LOG = Logger.getInstance(ChangeMethodParameters::class.java)
@@ -1,19 +1,16 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
* Copyright 2010-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.idea.quickfix.crossLanguage
import com.intellij.codeInsight.daemon.QuickFixBundle
import com.intellij.lang.jvm.actions.AnnotationRequest
import com.intellij.lang.jvm.actions.ChangeParametersRequest
import com.intellij.lang.jvm.actions.ExpectedParameter
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.JvmPsiConversionHelper
import org.jetbrains.kotlin.asJava.elements.KtLightElement
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.SourceElement
import org.jetbrains.kotlin.descriptors.annotations.Annotations
@@ -28,8 +25,12 @@ import org.jetbrains.kotlin.load.java.NOT_NULL_ANNOTATIONS
import org.jetbrains.kotlin.load.java.NULLABLE_ANNOTATIONS
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtParameterList
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.ErrorUtils
import org.jetbrains.kotlin.types.KotlinType
internal class ChangeMethodParameters(
@@ -60,112 +61,45 @@ internal class ChangeMethodParameters(
override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean = element != null && request.isValid
private sealed class ParameterModification {
data class Keep(val ktParameter: KtParameter) : ParameterModification()
data class Remove(val ktParameter: KtParameter) : ParameterModification()
data class Add(
val name: String,
val ktType: KotlinType,
val expectedAnnotations: Collection<AnnotationRequest>,
val beforeAnchor: KtParameter?
) : ParameterModification()
}
private data class ParameterModification(
val name: String,
val ktType: KotlinType
)
private tailrec fun getParametersModifications(
private fun getParametersModifications(
target: KtNamedFunction,
currentParameters: List<KtParameter>,
expectedParameters: List<ExpectedParameter>,
index: Int = 0,
collected: List<ParameterModification> = ArrayList(expectedParameters.size)
expectedParameters: List<ExpectedParameter>
): List<ParameterModification> {
val expectedHead = expectedParameters.firstOrNull() ?: return collected + currentParameters.map { ParameterModification.Remove(it) }
if (expectedHead is ChangeParametersRequest.ExistingParameterWrapper) {
val expectedExistingParameter = expectedHead.existingKtParameter
if (expectedExistingParameter == null) {
LOG.error("can't find the kotlinOrigin for parameter ${expectedHead.existingParameter} at index $index")
return collected
}
val existingInTail = currentParameters.indexOf(expectedExistingParameter)
if (existingInTail == -1) {
throw IllegalArgumentException("can't find existing for parameter ${expectedHead.existingParameter} at index $index")
}
return getParametersModifications(
target,
currentParameters.subList(existingInTail + 1, currentParameters.size),
expectedParameters.subList(1, expectedParameters.size),
index,
collected
+ currentParameters.subList(0, existingInTail).map { ParameterModification.Remove(it) }
+ ParameterModification.Keep(expectedExistingParameter)
)
}
val helper = JvmPsiConversionHelper.getInstance(target.project)
val theType = expectedHead.expectedTypes.firstOrNull()?.theType ?: return emptyList()
val kotlinType = helper.convertType(theType).resolveToKotlinType(target.getResolutionFacade()) ?: return emptyList()
return getParametersModifications(
target,
currentParameters,
expectedParameters.subList(1, expectedParameters.size),
index + 1,
collected + ParameterModification.Add(
expectedHead.semanticNames.firstOrNull() ?: "param$index",
kotlinType,
expectedHead.expectedAnnotations,
currentParameters.firstOrNull { anchor ->
expectedParameters.any {
it is ChangeParametersRequest.ExistingParameterWrapper && it.existingKtParameter == anchor
}
})
)
return expectedParameters.mapIndexed { index, expectedParameter ->
val theType = expectedParameter.expectedTypes.firstOrNull()?.theType
val kotlinType = theType
?.let { helper.convertType(it).resolveToKotlinType(target.getResolutionFacade()) }
?: ErrorUtils.createErrorType("unknown type")
ParameterModification(
expectedParameter.semanticNames.firstOrNull() ?: "param$index", kotlinType
)
}
}
private val ChangeParametersRequest.ExistingParameterWrapper.existingKtParameter
get() = (existingParameter as? KtLightElement<*, *>)?.kotlinOrigin as? KtParameter
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
if (!request.isValid) return
val target = element ?: return
val functionDescriptor = target.resolveToDescriptorIfAny(BodyResolveMode.FULL) ?: return
val parameterActions = getParametersModifications(target, target.valueParameters, request.expectedParameters)
target.valueParameterList!!.parameters.forEach { target.valueParameterList!!.removeParameter(it) }
val parameterActions = getParametersModifications(target, request.expectedParameters)
val parametersGenerated = parameterActions.filterIsInstance<ParameterModification.Add>().let {
val parametersGenerated = parameterActions.let {
it zip generateParameterList(project, functionDescriptor, it).parameters
}.toMap()
for (action in parameterActions) {
when (action) {
is ParameterModification.Add -> {
val parameter = parametersGenerated.getValue(action)
for (expectedAnnotation in action.expectedAnnotations) {
addAnnotationEntry(parameter, expectedAnnotation, null)
}
val anchor = action.beforeAnchor
if (anchor != null) {
target.valueParameterList!!.addParameterBefore(parameter, anchor)
} else {
target.valueParameterList!!.addParameter(parameter)
}
}
is ParameterModification.Keep -> {
// Do nothing
}
is ParameterModification.Remove -> {
target.valueParameterList!!.removeParameter(action.ktParameter)
}
}
val parameter = parametersGenerated.getValue(action)
target.valueParameterList!!.addParameter(parameter)
}
ShortenReferences.DEFAULT.process(target.valueParameterList!!)
@@ -174,7 +108,7 @@ internal class ChangeMethodParameters(
private fun generateParameterList(
project: Project,
functionDescriptor: FunctionDescriptor,
paramsToAdd: List<ParameterModification.Add>
paramsToAdd: List<ParameterModification>
): KtParameterList {
val newFunctionDescriptor = SimpleFunctionDescriptorImpl.create(
functionDescriptor.containingDeclaration,
@@ -225,7 +159,4 @@ internal class ChangeMethodParameters(
ChangeMethodParameters(ktNamedFunction, request)
}
}
private val LOG = Logger.getInstance(ChangeMethodParameters::class.java)
}
@@ -281,7 +281,7 @@ class KotlinElementActionsFactory : JvmElementActionsFactory() {
return listOfNotNull(changePrimaryConstructorAction, addConstructorAction)
}
override fun createAddPropertyActions(targetClass: JvmClass, request: MemberRequest.Property): List<IntentionAction> {
fun createAddPropertyActions(targetClass: JvmClass, request: MemberRequest.Property): List<IntentionAction> {
val targetContainer = targetClass.toKtClassOrFile() ?: return emptyList()
return createAddPropertyActions(
targetContainer, listOf(request.visibilityModifier),
@@ -281,7 +281,7 @@ class KotlinElementActionsFactory : JvmElementActionsFactory() {
return listOfNotNull(changePrimaryConstructorAction, addConstructorAction)
}
fun createAddPropertyActions(targetClass: JvmClass, request: MemberRequest.Property): List<IntentionAction> {
override fun createAddPropertyActions(targetClass: JvmClass, request: MemberRequest.Property): List<IntentionAction> {
val targetContainer = targetClass.toKtClassOrFile() ?: return emptyList()
return createAddPropertyActions(
targetContainer, listOf(request.visibilityModifier),
@@ -26,7 +26,7 @@ class KotlinSliceDereferenceUsage(
parent: KotlinSliceUsage,
lambdaLevel: Int
) : KotlinSliceUsage(element, parent, lambdaLevel, false) {
override fun processChildren(processor: Processor<SliceUsage>) {
override fun processChildren(processor: Processor<in SliceUsage>) {
// no children
}
@@ -26,7 +26,7 @@ class KotlinSliceDereferenceUsage(
parent: KotlinSliceUsage,
lambdaLevel: Int
) : KotlinSliceUsage(element, parent, lambdaLevel, false) {
override fun processChildren(processor: Processor<in SliceUsage>) {
override fun processChildren(processor: Processor<SliceUsage>) {
// no children
}
@@ -131,7 +131,7 @@ public abstract class AbstractFormatterTest extends LightIdeaTestCase {
String testFileExtension = expectedFileNameWithExtension.substring(expectedFileNameWithExtension.lastIndexOf("."));
String originalFileText = FileUtil.loadFile(new File(testFileName + testFileExtension), true);
CodeStyleSettings codeStyleSettings = FormatSettingsUtil.getSettings();
CodeStyleSettings codeStyleSettings = FormatSettingsUtil.getSettings(getProject());
try {
Integer rightMargin = InTextDirectivesUtils.getPrefixedInt(originalFileText, "// RIGHT_MARGIN: ");
if (rightMargin != null) {
@@ -131,7 +131,7 @@ public abstract class AbstractFormatterTest extends LightIdeaTestCase {
String testFileExtension = expectedFileNameWithExtension.substring(expectedFileNameWithExtension.lastIndexOf("."));
String originalFileText = FileUtil.loadFile(new File(testFileName + testFileExtension), true);
CodeStyleSettings codeStyleSettings = FormatSettingsUtil.getSettings(getProject());
CodeStyleSettings codeStyleSettings = FormatSettingsUtil.getSettings();
try {
Integer rightMargin = InTextDirectivesUtils.getPrefixedInt(originalFileText, "// RIGHT_MARGIN: ");
if (rightMargin != null) {
@@ -34,7 +34,7 @@ public abstract class AbstractTypingIndentationTestBase extends LightCodeInsight
String originalFileText = FileUtil.loadFile(new File(originFilePath), true);
try {
SettingsConfigurator configurator = FormatSettingsUtil.createConfigurator(originalFileText);
SettingsConfigurator configurator = FormatSettingsUtil.createConfigurator(originalFileText, getProject());
if (!inverted) {
configurator.configureSettings();
}
@@ -34,7 +34,7 @@ public abstract class AbstractTypingIndentationTestBase extends LightCodeInsight
String originalFileText = FileUtil.loadFile(new File(originFilePath), true);
try {
SettingsConfigurator configurator = FormatSettingsUtil.createConfigurator(originalFileText, getProject());
SettingsConfigurator configurator = FormatSettingsUtil.createConfigurator(originalFileText);
if (!inverted) {
configurator.configureSettings();
}
@@ -6,8 +6,8 @@
package org.jetbrains.kotlin.formatter;
import com.intellij.application.options.CodeStyle;
import com.intellij.openapi.project.Project;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.testFramework.LightPlatformTestCase;
import org.jetbrains.kotlin.idea.KotlinLanguage;
import org.jetbrains.kotlin.idea.core.formatter.KotlinCodeStyleSettings;
import org.jetbrains.kotlin.test.SettingsConfigurator;
@@ -16,8 +16,8 @@ public class FormatSettingsUtil {
private FormatSettingsUtil() {
}
public static CodeStyleSettings getSettings() {
return CodeStyle.getSettings(LightPlatformTestCase.getProject());
public static CodeStyleSettings getSettings(Project project) {
return CodeStyle.getSettings(project);
}
public static SettingsConfigurator createConfigurator(String fileText, CodeStyleSettings settings) {
@@ -26,7 +26,7 @@ public class FormatSettingsUtil {
settings.getCommonSettings(KotlinLanguage.INSTANCE));
}
public static SettingsConfigurator createConfigurator(String fileText) {
return createConfigurator(fileText, getSettings());
public static SettingsConfigurator createConfigurator(String fileText, Project project) {
return createConfigurator(fileText, getSettings(project));
}
}
@@ -6,8 +6,8 @@
package org.jetbrains.kotlin.formatter;
import com.intellij.application.options.CodeStyle;
import com.intellij.openapi.project.Project;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.testFramework.LightPlatformTestCase;
import org.jetbrains.kotlin.idea.KotlinLanguage;
import org.jetbrains.kotlin.idea.core.formatter.KotlinCodeStyleSettings;
import org.jetbrains.kotlin.test.SettingsConfigurator;
@@ -16,8 +16,8 @@ public class FormatSettingsUtil {
private FormatSettingsUtil() {
}
public static CodeStyleSettings getSettings(Project project) {
return CodeStyle.getSettings(project);
public static CodeStyleSettings getSettings() {
return CodeStyle.getSettings(LightPlatformTestCase.getProject());
}
public static SettingsConfigurator createConfigurator(String fileText, CodeStyleSettings settings) {
@@ -26,7 +26,7 @@ public class FormatSettingsUtil {
settings.getCommonSettings(KotlinLanguage.INSTANCE));
}
public static SettingsConfigurator createConfigurator(String fileText, Project project) {
return createConfigurator(fileText, getSettings(project));
public static SettingsConfigurator createConfigurator(String fileText) {
return createConfigurator(fileText, getSettings());
}
}
@@ -91,12 +91,14 @@ abstract class AbstractCodeMoverTest : LightCodeInsightTestCase() {
}
private fun invokeAndCheck(fileText: String, path: String, action: EditorAction, isApplicableExpected: Boolean) {
val codeStyleSettings = FormatSettingsUtil.getSettings()
val editor = LightPlatformCodeInsightTestCase.getEditor()
val project = editor.project!!
val codeStyleSettings = FormatSettingsUtil.getSettings(project)
val configurator = FormatSettingsUtil.createConfigurator(fileText, codeStyleSettings)
configurator.configureSettings()
try {
val editor = LightPlatformCodeInsightTestCase.getEditor()
val dataContext = LightPlatformCodeInsightTestCase.getCurrentEditorDataContext()
val before = editor.document.text
@@ -91,14 +91,12 @@ abstract class AbstractCodeMoverTest : LightCodeInsightTestCase() {
}
private fun invokeAndCheck(fileText: String, path: String, action: EditorAction, isApplicableExpected: Boolean) {
val editor = LightPlatformCodeInsightTestCase.getEditor()
val project = editor.project!!
val codeStyleSettings = FormatSettingsUtil.getSettings(project)
val codeStyleSettings = FormatSettingsUtil.getSettings()
val configurator = FormatSettingsUtil.createConfigurator(fileText, codeStyleSettings)
configurator.configureSettings()
try {
val editor = LightPlatformCodeInsightTestCase.getEditor()
val dataContext = LightPlatformCodeInsightTestCase.getCurrentEditorDataContext()
val before = editor.document.text
@@ -5,7 +5,6 @@
package org.jetbrains.kotlin.idea.decompiler.navigation
import com.intellij.openapi.module.Module
import com.intellij.openapi.roots.LibraryOrderEntry
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.OrderRootType
@@ -15,8 +14,6 @@ import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.utils.sure
abstract class AbstractNavigateFromLibrarySourcesTest : LightCodeInsightFixtureTestCase() {
val module: Module get() = myModule
protected fun navigationElementForReferenceInLibrarySource(filePath: String, referenceText: String): PsiElement {
val libraryOrderEntry = ModuleRootManager.getInstance(module!!).orderEntries.first { it is LibraryOrderEntry }
val libSourcesRoot = libraryOrderEntry.getUrls(OrderRootType.SOURCES)[0]
@@ -5,6 +5,7 @@
package org.jetbrains.kotlin.idea.decompiler.navigation
import com.intellij.openapi.module.Module
import com.intellij.openapi.roots.LibraryOrderEntry
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.OrderRootType
@@ -14,6 +15,8 @@ import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.utils.sure
abstract class AbstractNavigateFromLibrarySourcesTest : LightCodeInsightFixtureTestCase() {
val module: Module get() = myModule
protected fun navigationElementForReferenceInLibrarySource(filePath: String, referenceText: String): PsiElement {
val libraryOrderEntry = ModuleRootManager.getInstance(module!!).orderEntries.first { it is LibraryOrderEntry }
val libSourcesRoot = libraryOrderEntry.getUrls(OrderRootType.SOURCES)[0]
@@ -5,7 +5,6 @@
package org.jetbrains.kotlin.idea.decompiler.stubBuilder
import com.intellij.openapi.module.Module
import com.intellij.testFramework.LightProjectDescriptor
import org.jetbrains.kotlin.idea.decompiler.textBuilder.findTestLibraryRoot
import org.jetbrains.kotlin.idea.test.KotlinJdkAndLibraryProjectDescriptor
@@ -16,7 +15,6 @@ import java.io.File
@RunWith(JUnit3WithIdeaConfigurationRunner::class)
class ClsStubBuilderForWrongAbiVersionTest : AbstractClsStubBuilderTest() {
val module: Module get() = myModule
fun testPackage() = testStubsForFileWithWrongAbiVersion("Wrong_packageKt")
@@ -5,6 +5,7 @@
package org.jetbrains.kotlin.idea.decompiler.stubBuilder
import com.intellij.openapi.module.Module
import com.intellij.testFramework.LightProjectDescriptor
import org.jetbrains.kotlin.idea.decompiler.textBuilder.findTestLibraryRoot
import org.jetbrains.kotlin.idea.test.KotlinJdkAndLibraryProjectDescriptor
@@ -15,6 +16,7 @@ import java.io.File
@RunWith(JUnit3WithIdeaConfigurationRunner::class)
class ClsStubBuilderForWrongAbiVersionTest : AbstractClsStubBuilderTest() {
val module: Module get() = myModule
fun testPackage() = testStubsForFileWithWrongAbiVersion("Wrong_packageKt")
@@ -51,7 +51,7 @@ public class KotlinCommenterTest extends LightCodeInsightTestCase {
private void doLineCommentTest() throws Exception {
configure();
CodeStyleSettings codeStyleSettings = FormatSettingsUtil.getSettings();
CodeStyleSettings codeStyleSettings = FormatSettingsUtil.getSettings(getProject());
try {
String text = myFile.getText();
@@ -51,7 +51,7 @@ public class KotlinCommenterTest extends LightCodeInsightTestCase {
private void doLineCommentTest() throws Exception {
configure();
CodeStyleSettings codeStyleSettings = FormatSettingsUtil.getSettings(getProject());
CodeStyleSettings codeStyleSettings = FormatSettingsUtil.getSettings();
try {
String text = myFile.getText();
@@ -7,7 +7,6 @@ package org.jetbrains.kotlin.idea.parameterInfo
import com.intellij.codeInsight.hints.HintInfo
import com.intellij.codeInsight.hints.InlayParameterHintsExtension
import com.intellij.codeInsight.hints.isOwnsInlayInEditor
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
@@ -34,7 +33,7 @@ private fun getHintInfoFromProvider(offset: Int, file: PsiFile, editor: Editor):
val element = file.findElementAt(offset) ?: return null
val provider = InlayParameterHintsExtension.forLanguage(file.language) ?: return null
val isHintOwnedByElement: (PsiElement) -> Boolean = { e -> provider.getHintInfo(e) != null && e.isOwnsInlayInEditor(editor) }
val isHintOwnedByElement: (PsiElement) -> Boolean = { e -> provider.getHintInfo(e)?.isOwnedByPsiElement(e, editor) ?: false }
val method = PsiTreeUtil.findFirstParent(element, isHintOwnedByElement) ?: return null
return provider.getHintInfo(method)
@@ -7,6 +7,7 @@ package org.jetbrains.kotlin.idea.parameterInfo
import com.intellij.codeInsight.hints.HintInfo
import com.intellij.codeInsight.hints.InlayParameterHintsExtension
import com.intellij.codeInsight.hints.isOwnsInlayInEditor
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
@@ -33,7 +34,7 @@ private fun getHintInfoFromProvider(offset: Int, file: PsiFile, editor: Editor):
val element = file.findElementAt(offset) ?: return null
val provider = InlayParameterHintsExtension.forLanguage(file.language) ?: return null
val isHintOwnedByElement: (PsiElement) -> Boolean = { e -> provider.getHintInfo(e)?.isOwnedByPsiElement(e, editor) ?: false }
val isHintOwnedByElement: (PsiElement) -> Boolean = { e -> provider.getHintInfo(e) != null && e.isOwnsInlayInEditor(editor) }
val method = PsiTreeUtil.findFirstParent(element, isHintOwnedByElement) ?: return null
return provider.getHintInfo(method)
@@ -1,18 +1,17 @@
/*
* 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.
* Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.lang.jvm.actions.createChangeParametersActions
import com.intellij.lang.jvm.actions.setMethodParametersRequest
import com.intellij.lang.jvm.actions.*
import com.intellij.lang.jvm.types.JvmType
import com.intellij.psi.PsiType
import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor
import org.jetbrains.kotlin.test.JUnit3WithIdeaConfigurationRunner
import org.jetbrains.uast.UMethod
import org.jetbrains.kotlin.test.JUnit3WithIdeaConfigurationRunner
import org.junit.runner.RunWith
@RunWith(JUnit3WithIdeaConfigurationRunner::class)
@@ -20,6 +19,11 @@ class CommonIntentionActionsParametersTest : LightPlatformCodeInsightFixtureTest
override fun getProjectDescriptor() = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE_FULL_JDK
override fun setUp() {
super.setUp()
myFixture.configureByText("Anno.kt", "annotation class Anno(val i: Int)")
}
fun testSetParameters() {
myFixture.configureByText(
"foo.kt",
@@ -53,5 +57,116 @@ class CommonIntentionActionsParametersTest : LightPlatformCodeInsightFixtureTest
)
}
fun testAddParameterToTheEnd() {
myFixture.configureByText(
"foo.kt",
"""
class Foo {
fun ba<caret>r(@Anno(3) a: Int) {}
}
""".trimIndent()
)
runParametersTransformation("Change method parameters to '(a: Int, file: File)'") { currentParameters ->
currentParameters + expectedParameter(
PsiType.getTypeByName("java.io.File", project, myFixture.file.resolveScope), "file",
listOf(annotationRequest("Anno", intAttribute("i", 8)))
)
}
myFixture.checkResult(
"""
import java.io.File
class Foo {
fun bar(@Anno(3) a: Int, @Anno(i = 8) file: File) {}
}
""".trimIndent(), true
)
}
fun testAddParameterToTheBeginning() {
myFixture.configureByText(
"foo.kt",
"""
class Foo {
fun ba<caret>r(@Anno(3) a: Int) {}
}
""".trimIndent()
)
runParametersTransformation("Change method parameters to '(file: File, a: Int)'") { currentParameters ->
listOf(
expectedParameter(
PsiType.getTypeByName("java.io.File", project, myFixture.file.resolveScope), "file",
listOf(annotationRequest("Anno", intAttribute("i", 8)))
)
) + currentParameters
}
myFixture.checkResult(
"""
import java.io.File
class Foo {
fun bar(@Anno(i = 8) file: File, @Anno(3) a: Int) {}
}
""".trimIndent(), true
)
}
fun testReplaceInTheMiddle() {
myFixture.configureByText(
"foo.kt",
"""
class Foo {
fun ba<caret>r(@Anno(1) a: Int, @Anno(2) b: Int, @Anno(3) c: Int) {}
}
""".trimIndent()
)
runParametersTransformation("Change method parameters to '(a: Int, file: File, c: Int)'") { currentParameters ->
ArrayList<ExpectedParameter>(currentParameters).apply {
this[1] = expectedParameter(
PsiType.getTypeByName("java.io.File", project, myFixture.file.resolveScope), "file",
listOf(annotationRequest("Anno", intAttribute("i", 8)))
)
}
}
myFixture.checkResult(
"""
import java.io.File
class Foo {
fun bar(@Anno(1) a: Int, @Anno(i = 8) file: File, @Anno(3) c: Int) {}
}
""".trimIndent(), true
)
}
private fun runParametersTransformation(
actionName: String,
transformation: (List<ChangeParametersRequest.ExistingParameterWrapper>) -> List<ExpectedParameter>
) {
val psiMethod = myFixture.atCaret<UMethod>().javaPsi
val currentParameters = psiMethod.parameters.map { ChangeParametersRequest.ExistingParameterWrapper(it) }
myFixture.launchAction(
createChangeParametersActions(
psiMethod,
SimpleChangeParametersRequest(
transformation(currentParameters)
)
).findWithText(actionName)
)
}
}
private class SimpleChangeParametersRequest(private val list: List<ExpectedParameter>) : ChangeParametersRequest {
override fun getExpectedParameters(): List<ExpectedParameter> = list
override fun isValid(): Boolean = true
}
@@ -0,0 +1,57 @@
/*
* 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.idea.quickfix
import com.intellij.lang.jvm.actions.createChangeParametersActions
import com.intellij.lang.jvm.actions.setMethodParametersRequest
import com.intellij.lang.jvm.types.JvmType
import com.intellij.psi.PsiType
import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor
import org.jetbrains.kotlin.test.JUnit3WithIdeaConfigurationRunner
import org.jetbrains.uast.UMethod
import org.junit.runner.RunWith
@RunWith(JUnit3WithIdeaConfigurationRunner::class)
class CommonIntentionActionsParametersTest : LightPlatformCodeInsightFixtureTestCase() {
override fun getProjectDescriptor() = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE_FULL_JDK
fun testSetParameters() {
myFixture.configureByText(
"foo.kt",
"""
class Foo {
fun ba<caret>r() {}
}
""".trimIndent()
)
myFixture.launchAction(
createChangeParametersActions(
myFixture.atCaret<UMethod>().javaPsi,
setMethodParametersRequest(
linkedMapOf<String, JvmType>(
"i" to PsiType.INT,
"file" to PsiType.getTypeByName("java.io.File", project, myFixture.file.resolveScope)
).entries
)
).findWithText("Change method parameters to '(i: Int, file: File)'")
)
myFixture.checkResult(
"""
import java.io.File
class Foo {
fun bar(i: Int, file: File) {}
}
""".trimIndent(),
true
)
}
}
@@ -1,172 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.lang.jvm.actions.*
import com.intellij.lang.jvm.types.JvmType
import com.intellij.psi.PsiType
import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor
import org.jetbrains.uast.UMethod
import org.jetbrains.kotlin.test.JUnit3WithIdeaConfigurationRunner
import org.junit.runner.RunWith
@RunWith(JUnit3WithIdeaConfigurationRunner::class)
class CommonIntentionActionsParametersTest : LightPlatformCodeInsightFixtureTestCase() {
override fun getProjectDescriptor() = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE_FULL_JDK
override fun setUp() {
super.setUp()
myFixture.configureByText("Anno.kt", "annotation class Anno(val i: Int)")
}
fun testSetParameters() {
myFixture.configureByText(
"foo.kt",
"""
class Foo {
fun ba<caret>r() {}
}
""".trimIndent()
)
myFixture.launchAction(
createChangeParametersActions(
myFixture.atCaret<UMethod>().javaPsi,
setMethodParametersRequest(
linkedMapOf<String, JvmType>(
"i" to PsiType.INT,
"file" to PsiType.getTypeByName("java.io.File", project, myFixture.file.resolveScope)
).entries
)
).findWithText("Change method parameters to '(i: Int, file: File)'")
)
myFixture.checkResult(
"""
import java.io.File
class Foo {
fun bar(i: Int, file: File) {}
}
""".trimIndent(),
true
)
}
fun testAddParameterToTheEnd() {
myFixture.configureByText(
"foo.kt",
"""
class Foo {
fun ba<caret>r(@Anno(3) a: Int) {}
}
""".trimIndent()
)
runParametersTransformation("Change method parameters to '(a: Int, file: File)'") { currentParameters ->
currentParameters + expectedParameter(
PsiType.getTypeByName("java.io.File", project, myFixture.file.resolveScope), "file",
listOf(annotationRequest("Anno", intAttribute("i", 8)))
)
}
myFixture.checkResult(
"""
import java.io.File
class Foo {
fun bar(@Anno(3) a: Int, @Anno(i = 8) file: File) {}
}
""".trimIndent(), true
)
}
fun testAddParameterToTheBeginning() {
myFixture.configureByText(
"foo.kt",
"""
class Foo {
fun ba<caret>r(@Anno(3) a: Int) {}
}
""".trimIndent()
)
runParametersTransformation("Change method parameters to '(file: File, a: Int)'") { currentParameters ->
listOf(
expectedParameter(
PsiType.getTypeByName("java.io.File", project, myFixture.file.resolveScope), "file",
listOf(annotationRequest("Anno", intAttribute("i", 8)))
)
) + currentParameters
}
myFixture.checkResult(
"""
import java.io.File
class Foo {
fun bar(@Anno(i = 8) file: File, @Anno(3) a: Int) {}
}
""".trimIndent(), true
)
}
fun testReplaceInTheMiddle() {
myFixture.configureByText(
"foo.kt",
"""
class Foo {
fun ba<caret>r(@Anno(1) a: Int, @Anno(2) b: Int, @Anno(3) c: Int) {}
}
""".trimIndent()
)
runParametersTransformation("Change method parameters to '(a: Int, file: File, c: Int)'") { currentParameters ->
ArrayList<ExpectedParameter>(currentParameters).apply {
this[1] = expectedParameter(
PsiType.getTypeByName("java.io.File", project, myFixture.file.resolveScope), "file",
listOf(annotationRequest("Anno", intAttribute("i", 8)))
)
}
}
myFixture.checkResult(
"""
import java.io.File
class Foo {
fun bar(@Anno(1) a: Int, @Anno(i = 8) file: File, @Anno(3) c: Int) {}
}
""".trimIndent(), true
)
}
private fun runParametersTransformation(
actionName: String,
transformation: (List<ChangeParametersRequest.ExistingParameterWrapper>) -> List<ExpectedParameter>
) {
val psiMethod = myFixture.atCaret<UMethod>().javaPsi
val currentParameters = psiMethod.parameters.map { ChangeParametersRequest.ExistingParameterWrapper(it) }
myFixture.launchAction(
createChangeParametersActions(
psiMethod,
SimpleChangeParametersRequest(
transformation(currentParameters)
)
).findWithText(actionName)
)
}
}
private class SimpleChangeParametersRequest(private val list: List<ExpectedParameter>) : ChangeParametersRequest {
override fun getExpectedParameters(): List<ExpectedParameter> = list
override fun isValid(): Boolean = true
}
@@ -35,9 +35,6 @@ import java.io.File
@RunWith(JUnit3WithIdeaConfigurationRunner::class)
class UpdateConfigurationQuickFixTest : LightPlatformCodeInsightFixtureTestCase() {
val module: Module get() = myModule
fun testDisableInlineClasses() {
configureRuntime("mockRuntime11")
resetProjectSettings(LanguageVersion.KOTLIN_1_3)
@@ -35,6 +35,9 @@ import java.io.File
@RunWith(JUnit3WithIdeaConfigurationRunner::class)
class UpdateConfigurationQuickFixTest : LightPlatformCodeInsightFixtureTestCase() {
val module: Module get() = myModule
fun testDisableInlineClasses() {
configureRuntime("mockRuntime11")
resetProjectSettings(LanguageVersion.KOTLIN_1_3)
@@ -87,7 +87,6 @@ abstract class AbstractJavaToKotlinConverterForWebDemoTest : TestCase() {
override fun setDefaultNotNull(p0: String) = Unit
override fun setInstrumentedNotNulls(p0: List<String>) = Unit
override fun getInstrumentedNotNulls() = emptyList<String>()
override fun isJsr305Default(psiAnnotation: PsiAnnotation, p1: Array<PsiAnnotation.TargetType>) = null
})
applicationEnvironment.application.registerService(JavaClassSupers::class.java, JavaClassSupersImpl::class.java)
@@ -87,6 +87,7 @@ abstract class AbstractJavaToKotlinConverterForWebDemoTest : TestCase() {
override fun setDefaultNotNull(p0: String) = Unit
override fun setInstrumentedNotNulls(p0: List<String>) = Unit
override fun getInstrumentedNotNulls() = emptyList<String>()
override fun isJsr305Default(psiAnnotation: PsiAnnotation, p1: Array<PsiAnnotation.TargetType>) = null
})
applicationEnvironment.application.registerService(JavaClassSupers::class.java, JavaClassSupersImpl::class.java)
@@ -39,7 +39,7 @@ class KotlinUFile(
override val javaPsi: PsiElement? = null
override val sourcePsi: PsiElement? = psi
override val sourcePsi: KtFile = psi
override val allCommentsInFile by lz {
val comments = ArrayList<UComment>(0)
@@ -39,7 +39,7 @@ class KotlinUFile(
override val javaPsi: PsiElement? = null
override val sourcePsi: KtFile = psi
override val sourcePsi: PsiElement? = psi
override val allCommentsInFile by lz {
val comments = ArrayList<UComment>(0)
@@ -105,9 +105,6 @@ open class KotlinUMethod(
wrapExpressionBody(this, bodyExpression)
}
override val isOverride: Boolean
get() = (kotlinOrigin as? KtCallableDeclaration)?.hasModifier(KtTokens.OVERRIDE_KEYWORD) ?: false
override fun getBody(): PsiCodeBlock? = super<UAnnotationMethod>.getBody()
override fun getOriginalElement(): PsiElement? = super<UAnnotationMethod>.getOriginalElement()
@@ -105,6 +105,9 @@ open class KotlinUMethod(
wrapExpressionBody(this, bodyExpression)
}
override val isOverride: Boolean
get() = (kotlinOrigin as? KtCallableDeclaration)?.hasModifier(KtTokens.OVERRIDE_KEYWORD) ?: false
override fun getBody(): PsiCodeBlock? = super<UAnnotationMethod>.getBody()
override fun getOriginalElement(): PsiElement? = super<UAnnotationMethod>.getOriginalElement()
@@ -4,6 +4,7 @@ import com.intellij.psi.PsiElement
import org.jetbrains.uast.*
import org.jetbrains.uast.test.common.UElementToParentMap
import org.jetbrains.uast.test.common.kotlin.IdentifiersTestBase
import org.jetbrains.uast.test.common.visitUFileAndGetResult
import org.jetbrains.uast.test.env.assertEqualsToFile
import java.io.File
import kotlin.test.assertNotNull
@@ -4,7 +4,6 @@ import com.intellij.psi.PsiElement
import org.jetbrains.uast.*
import org.jetbrains.uast.test.common.UElementToParentMap
import org.jetbrains.uast.test.common.kotlin.IdentifiersTestBase
import org.jetbrains.uast.test.common.visitUFileAndGetResult
import org.jetbrains.uast.test.env.assertEqualsToFile
import java.io.File
import kotlin.test.assertNotNull
@@ -28,7 +28,7 @@ interface ResolveTestBase {
val resultComment = file.allCommentsInFile.find { it.text.startsWith("// RESULT:") } ?: throw IllegalArgumentException("No // RESULT tag in file")
val refText = refComment.text.substringAfter("REF:")
val parent = refComment.uastParent
val parent = refComment.uastParent!!
val matchingElement = parent.findElementByText<UResolvable>(refText)
val resolveResult = matchingElement.resolve() ?: throw IllegalArgumentException("Unresolved reference")
val resultText = resolveResult.javaClass.simpleName + (if (resolveResult is PsiNamedElement) ":${resolveResult.name}" else "")
@@ -28,7 +28,7 @@ interface ResolveTestBase {
val resultComment = file.allCommentsInFile.find { it.text.startsWith("// RESULT:") } ?: throw IllegalArgumentException("No // RESULT tag in file")
val refText = refComment.text.substringAfter("REF:")
val parent = refComment.uastParent!!
val parent = refComment.uastParent
val matchingElement = parent.findElementByText<UResolvable>(refText)
val resolveResult = matchingElement.resolve() ?: throw IllegalArgumentException("Unresolved reference")
val resultText = resolveResult.javaClass.simpleName + (if (resolveResult is PsiNamedElement) ":${resolveResult.name}" else "")