Cleanup 191 extension files (KTI-240)

This commit is contained in:
Yunir Salimzyanov
2020-06-01 16:11:14 +03:00
parent 7ab7ca5ff0
commit 3b9000cc0c
93 changed files with 0 additions and 6878 deletions
@@ -1,125 +0,0 @@
/*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.codeInsight.moveUpDown
import com.intellij.application.options.CodeStyle
import com.intellij.codeInsight.editorActions.moveLeftRight.MoveElementLeftAction
import com.intellij.codeInsight.editorActions.moveLeftRight.MoveElementRightAction
import com.intellij.codeInsight.editorActions.moveUpDown.MoveStatementDownAction
import com.intellij.codeInsight.editorActions.moveUpDown.MoveStatementUpAction
import com.intellij.codeInsight.editorActions.moveUpDown.StatementUpDownMover
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.editor.actionSystem.EditorAction
import com.intellij.openapi.extensions.Extensions
import com.intellij.openapi.util.io.FileUtil
import com.intellij.testFramework.LightPlatformCodeInsightTestCase
import junit.framework.ComparisonFailure
import junit.framework.TestCase
import org.jetbrains.kotlin.formatter.FormatSettingsUtil
import org.jetbrains.kotlin.idea.codeInsight.upDownMover.KotlinDeclarationMover
import org.jetbrains.kotlin.idea.codeInsight.upDownMover.KotlinExpressionMover
import org.jetbrains.kotlin.idea.core.script.isScriptChangesNotifierDisabled
import org.jetbrains.kotlin.idea.formatter.kotlinCustomSettings
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightTestCase
import org.jetbrains.kotlin.test.InTextDirectivesUtils
import org.jetbrains.kotlin.test.KotlinTestUtils
import java.io.File
abstract class AbstractMoveStatementTest : AbstractCodeMoverTest() {
protected fun doTestClassBodyDeclaration(path: String) {
doTest(path, KotlinDeclarationMover::class.java)
}
protected fun doTestExpression(path: String) {
doTest(path, KotlinExpressionMover::class.java)
}
protected fun doTestExpressionWithTrailingComma(path: String) {
doTest(path, KotlinExpressionMover::class.java, true)
}
private fun doTest(path: String, defaultMoverClass: Class<out StatementUpDownMover>, trailingComma: Boolean = false) {
doTest(path, trailingComma) { isApplicableExpected, direction ->
val movers = Extensions.getExtensions(StatementUpDownMover.STATEMENT_UP_DOWN_MOVER_EP)
val info = StatementUpDownMover.MoveInfo()
val actualMover = movers.firstOrNull {
it.checkAvailable(LightPlatformCodeInsightTestCase.getEditor(), LightPlatformCodeInsightTestCase.getFile(), info, direction == "down")
} ?: error("No mover found")
assertEquals("Unmatched movers", defaultMoverClass.name, actualMover::class.java.name)
assertEquals("Invalid applicability", isApplicableExpected, info.toMove2 != null)
}
}
}
abstract class AbstractMoveLeftRightTest : AbstractCodeMoverTest() {
protected fun doTest(path: String) {
doTest(path) { _, _ -> }
}
}
@Suppress("DEPRECATION")
abstract class AbstractCodeMoverTest : KotlinLightCodeInsightTestCase() {
protected fun doTest(
path: String,
trailingComma: Boolean = false,
isApplicableChecker: (isApplicableExpected: Boolean, direction: String) -> Unit
) {
configureByFile(path)
val fileText = FileUtil.loadFile(File(path), true)
val direction = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// MOVE: ") ?: error("No MOVE directive found")
val action = when (direction) {
"up" -> MoveStatementUpAction()
"down" -> MoveStatementDownAction()
"left" -> MoveElementLeftAction()
"right" -> MoveElementRightAction()
else -> error("Unknown direction: $direction")
}
val isApplicableString = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// IS_APPLICABLE: ")
val isApplicableExpected = isApplicableString == null || isApplicableString == "true"
isApplicableChecker(isApplicableExpected, direction)
val codeStyleSettings = CodeStyle.getSettings(editor_.project!!)
try {
val configurator = FormatSettingsUtil.createConfigurator(fileText, codeStyleSettings)
configurator.configureSettings()
if (trailingComma) codeStyleSettings.kotlinCustomSettings.ALLOW_TRAILING_COMMA = true
invokeAndCheck(path, action, isApplicableExpected)
} finally {
codeStyleSettings.clearCodeStyleSettings()
}
}
private fun invokeAndCheck(path: String, action: EditorAction, isApplicableExpected: Boolean) {
val editor = editor_
val dataContext = currentEditorDataContext_
val before = editor.document.text
runWriteAction { action.actionPerformed(editor, dataContext) }
val after = editor.document.text
val actionDoesNothing = after == before
TestCase.assertEquals(isApplicableExpected, !actionDoesNothing)
if (isApplicableExpected) {
val afterFilePath = "$path.after"
try {
checkResultByFile(afterFilePath)
} catch (e: ComparisonFailure) {
KotlinTestUtils.assertEqualsToFile(File(afterFilePath), editor)
}
}
}
override fun getTestDataPath() = ""
}
@@ -1,31 +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.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
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.psi.PsiElement
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]
val libUrl = "$libSourcesRoot/$filePath"
val vf = VirtualFileManager.getInstance().refreshAndFindFileByUrl(libUrl)
?: error("Can't find library: $libUrl")
val psiFile = psiManager.findFile(vf)!!
val indexOf = psiFile.text!!.indexOf(referenceText)
val reference = psiFile.findReferenceAt(indexOf)
return reference.sure { "Couldn't find reference" }.resolve().sure { "Couldn't resolve reference" }.navigationElement!!
}
}
@@ -1,34 +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.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
import org.jetbrains.kotlin.test.JUnit3WithIdeaConfigurationRunner
import org.jetbrains.kotlin.test.KotlinTestUtils
import org.junit.runner.RunWith
import java.io.File
@RunWith(JUnit3WithIdeaConfigurationRunner::class)
class ClsStubBuilderForWrongAbiVersionTest : AbstractClsStubBuilderTest() {
val module: Module get() = myModule
fun testPackage() = testStubsForFileWithWrongAbiVersion("Wrong_packageKt")
fun testClass() = testStubsForFileWithWrongAbiVersion("ClassWithWrongAbiVersion")
private fun testStubsForFileWithWrongAbiVersion(className: String) {
val root = findTestLibraryRoot(module!!)!!
val result = root.findClassFileByName(className)
testClsStubsForFile(result, null)
}
override fun getProjectDescriptor(): LightProjectDescriptor {
return KotlinJdkAndLibraryProjectDescriptor(File(KotlinTestUtils.getTestDataPathBase() + "/cli/jvm/wrongAbiVersionLib/bin"))
}
}
@@ -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.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
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture
import org.junit.Assert
internal fun JavaCodeInsightTestFixture.checkHintType(text: String, hintType: HintType) {
configureByText("A.kt", text.trimIndent())
doHighlighting()
checkHintType(hintType)
}
internal fun JavaCodeInsightTestFixture.checkHintType(hintType: HintType) {
val hintInfo = getHintInfoFromProvider(caretOffset, file, editor)
Assert.assertNotNull("No hint available at caret", hintInfo)
Assert.assertEquals(hintType.option.name, (hintInfo as HintInfo.OptionInfo).optionName)
}
// It's crucial for this method to be conformable with IDEA internals.
// Originally copied from com.intellij.codeInsight.hints.getHintInfoFromProvider()
private fun getHintInfoFromProvider(offset: Int, file: PsiFile, editor: Editor): HintInfo? {
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 method = PsiTreeUtil.findFirstParent(element, isHintOwnedByElement) ?: return null
return provider.getHintInfo(method)
}
@@ -1,57 +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.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,236 +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.idea.quickfix
import com.intellij.facet.FacetManager
import com.intellij.facet.impl.FacetUtil
import com.intellij.openapi.module.Module
import com.intellij.openapi.roots.ModuleRootModificationUtil.updateModel
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.ui.configuration.libraryEditor.NewLibraryEditor
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.JarFileSystem
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase
import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments.Companion.DEFAULT
import org.jetbrains.kotlin.config.CompilerSettings.Companion.DEFAULT_ADDITIONAL_ARGUMENTS
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.config.LanguageVersion
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinCommonCompilerArgumentsHolder
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinCompilerSettings
import org.jetbrains.kotlin.idea.configuration.KotlinJavaModuleConfigurator
import org.jetbrains.kotlin.idea.facet.KotlinFacetType
import org.jetbrains.kotlin.idea.facet.getRuntimeLibraryVersion
import org.jetbrains.kotlin.idea.project.getLanguageVersionSettings
import org.jetbrains.kotlin.idea.project.languageVersionSettings
import org.jetbrains.kotlin.idea.test.ConfigLibraryUtil
import org.jetbrains.kotlin.idea.test.configureKotlinFacet
import org.jetbrains.kotlin.idea.versions.bundledRuntimeVersion
import org.jetbrains.kotlin.test.JUnit3WithIdeaConfigurationRunner
import org.jetbrains.kotlin.utils.KotlinPaths
import org.jetbrains.kotlin.utils.PathUtil
import org.junit.runner.RunWith
import java.io.File
@RunWith(JUnit3WithIdeaConfigurationRunner::class)
class UpdateConfigurationQuickFixTest : LightPlatformCodeInsightFixtureTestCase() {
val module: Module get() = myModule
fun testDisableInlineClasses() {
configureRuntime("mockRuntime11")
resetProjectSettings(LanguageVersion.KOTLIN_1_3)
myFixture.configureByText("foo.kt", "inline class My(val n: Int)")
assertEquals(LanguageFeature.State.ENABLED_WITH_WARNING, inlineClassesSupport)
assertTrue(myFixture.availableIntentions.none { it.text == "Disable inline classes support in the project" })
}
fun testEnableInlineClasses() {
configureRuntime("mockRuntime11")
resetProjectSettings(LanguageVersion.KOTLIN_1_3)
myFixture.configureByText("foo.kt", "inline class My(val n: Int)")
assertEquals(LanguageFeature.State.ENABLED_WITH_WARNING, inlineClassesSupport)
myFixture.launchAction(myFixture.findSingleIntention("Enable inline classes support in the project"))
assertEquals(LanguageFeature.State.ENABLED, inlineClassesSupport)
}
fun testEnableCoroutines() {
configureRuntime("mockRuntime11")
resetProjectSettings(LanguageVersion.KOTLIN_1_1)
myFixture.configureByText("foo.kt", "suspend fun foo()")
assertEquals(DEFAULT, KotlinCommonCompilerArgumentsHolder.getInstance(project).settings.coroutinesState)
assertEquals(LanguageFeature.State.ENABLED_WITH_WARNING, coroutineSupport)
myFixture.launchAction(myFixture.findSingleIntention("Enable coroutine support in the project"))
assertEquals(LanguageFeature.State.ENABLED, coroutineSupport)
}
fun testDisableCoroutines() {
configureRuntime("mockRuntime11")
resetProjectSettings(LanguageVersion.KOTLIN_1_1)
myFixture.configureByText("foo.kt", "suspend fun foo()")
assertEquals(DEFAULT, KotlinCommonCompilerArgumentsHolder.getInstance(project).settings.coroutinesState)
assertEquals(LanguageFeature.State.ENABLED_WITH_WARNING, coroutineSupport)
myFixture.launchAction(myFixture.findSingleIntention("Disable coroutine support in the project"))
assertEquals(LanguageFeature.State.ENABLED_WITH_ERROR, coroutineSupport)
}
fun testEnableCoroutinesFacet() {
configureRuntime("mockRuntime11")
val facet = configureKotlinFacet(module) {
settings.languageLevel = LanguageVersion.KOTLIN_1_1
}
resetProjectSettings(LanguageVersion.KOTLIN_1_1)
myFixture.configureByText("foo.kt", "suspend fun foo()")
assertEquals(LanguageFeature.State.ENABLED_WITH_WARNING, facet.configuration.settings.coroutineSupport)
myFixture.launchAction(myFixture.findSingleIntention("Enable coroutine support in the current module"))
assertEquals(LanguageFeature.State.ENABLED, facet.configuration.settings.coroutineSupport)
}
fun testEnableCoroutines_UpdateRuntime() {
configureRuntime("mockRuntime106")
resetProjectSettings(LanguageVersion.KOTLIN_1_1)
myFixture.configureByText("foo.kt", "suspend fun foo()")
assertEquals(LanguageFeature.State.ENABLED_WITH_WARNING, coroutineSupport)
myFixture.launchAction(myFixture.findSingleIntention("Enable coroutine support in the project"))
assertEquals(LanguageFeature.State.ENABLED, coroutineSupport)
assertEquals(bundledRuntimeVersion(), getRuntimeLibraryVersion(myFixture.module))
}
fun testIncreaseLangLevel() {
configureRuntime("mockRuntime11")
resetProjectSettings(LanguageVersion.KOTLIN_1_0)
myFixture.configureByText("foo.kt", "val x get() = 1")
myFixture.launchAction(myFixture.findSingleIntention("Set project language version to 1.1"))
assertEquals("1.1", KotlinCommonCompilerArgumentsHolder.getInstance(project).settings.languageVersion)
assertEquals("1.0", KotlinCommonCompilerArgumentsHolder.getInstance(project).settings.apiVersion)
}
fun testIncreaseLangLevelFacet() {
configureRuntime("mockRuntime11")
resetProjectSettings(LanguageVersion.KOTLIN_1_0)
configureKotlinFacet(module) {
settings.languageLevel = LanguageVersion.KOTLIN_1_0
settings.apiLevel = LanguageVersion.KOTLIN_1_0
}
myFixture.configureByText("foo.kt", "val x get() = 1")
assertEquals(LanguageVersion.KOTLIN_1_0, module.languageVersionSettings.languageVersion)
myFixture.launchAction(myFixture.findSingleIntention("Set module language version to 1.1"))
assertEquals(LanguageVersion.KOTLIN_1_1, module.languageVersionSettings.languageVersion)
}
fun testIncreaseLangAndApiLevel() {
configureRuntime("mockRuntime11")
resetProjectSettings(LanguageVersion.KOTLIN_1_0)
myFixture.configureByText("foo.kt", "val x = <caret>\"s\"::length")
myFixture.launchAction(myFixture.findSingleIntention("Set project language version to 1.1"))
assertEquals("1.1", KotlinCommonCompilerArgumentsHolder.getInstance(project).settings.languageVersion)
assertEquals("1.1", KotlinCommonCompilerArgumentsHolder.getInstance(project).settings.apiVersion)
}
fun testIncreaseLangAndApiLevel_10() {
configureRuntime("mockRuntime106")
resetProjectSettings(LanguageVersion.KOTLIN_1_0)
myFixture.configureByText("foo.kt", "val x = <caret>\"s\"::length")
myFixture.launchAction(myFixture.findSingleIntention("Set project language version to 1.1"))
assertEquals("1.1", KotlinCommonCompilerArgumentsHolder.getInstance(project).settings.languageVersion)
assertEquals("1.1", KotlinCommonCompilerArgumentsHolder.getInstance(project).settings.apiVersion)
assertEquals(bundledRuntimeVersion(), getRuntimeLibraryVersion(myFixture.module))
}
fun testIncreaseLangLevelFacet_10() {
configureRuntime("mockRuntime106")
resetProjectSettings(LanguageVersion.KOTLIN_1_0)
configureKotlinFacet(module) {
settings.languageLevel = LanguageVersion.KOTLIN_1_0
settings.apiLevel = LanguageVersion.KOTLIN_1_0
}
myFixture.configureByText("foo.kt", "val x = <caret>\"s\"::length")
assertEquals(LanguageVersion.KOTLIN_1_0, module.languageVersionSettings.languageVersion)
myFixture.launchAction(myFixture.findSingleIntention("Set module language version to 1.1"))
assertEquals(LanguageVersion.KOTLIN_1_1, module.languageVersionSettings.languageVersion)
assertEquals(bundledRuntimeVersion(), getRuntimeLibraryVersion(myFixture.module))
}
fun testAddKotlinReflect() {
configureRuntime("actualRuntime")
myFixture.configureByText(
"foo.kt", """class Foo(val prop: Any) {
fun func() {}
}
fun y01() = Foo::prop.gett<caret>er
"""
)
myFixture.launchAction(myFixture.findSingleIntention("Add 'kotlin-reflect.jar' to the classpath"))
val kotlinRuntime = KotlinJavaModuleConfigurator.instance.getKotlinLibrary(module)!!
val classes = kotlinRuntime.getFiles(OrderRootType.CLASSES).map { it.name }
assertContainsElements(classes, "kotlin-reflect.jar")
val sources = kotlinRuntime.getFiles(OrderRootType.SOURCES)
assertContainsElements(sources.map { it.name }, "kotlin-reflect-sources.jar")
}
private fun configureRuntime(path: String) {
val name = if (path == "mockRuntime106") "kotlin-runtime.jar" else "kotlin-stdlib.jar"
val sourcePath = when (path) {
"actualRuntime" -> PathUtil.kotlinPathsForIdeaPlugin.jar(KotlinPaths.Jar.StdLib)
else -> File("idea/testData/configuration/$path/$name")
}
val tempFile = File(FileUtil.createTempDirectory("kotlin-update-configuration", null), name)
FileUtil.copy(sourcePath, tempFile)
val tempVFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempFile) ?: error("Can't find file: $tempFile")
updateModel(myFixture.module) { model ->
val editor = NewLibraryEditor()
editor.name = "KotlinJavaRuntime"
editor.addRoot(JarFileSystem.getInstance().getJarRootForLocalFile(tempVFile)!!, OrderRootType.CLASSES)
ConfigLibraryUtil.addLibrary(editor, model)
}
}
private fun resetProjectSettings(version: LanguageVersion) {
KotlinCompilerSettings.getInstance(project).update {
additionalArguments = DEFAULT_ADDITIONAL_ARGUMENTS
}
KotlinCommonCompilerArgumentsHolder.getInstance(project).update {
languageVersion = version.versionString
apiVersion = version.versionString
coroutinesState = DEFAULT
}
}
private val coroutineSupport: LanguageFeature.State
get() = project.getLanguageVersionSettings().getFeatureSupport(LanguageFeature.Coroutines)
private val inlineClassesSupport: LanguageFeature.State
get() = project.getLanguageVersionSettings().getFeatureSupport(LanguageFeature.InlineClasses)
override fun tearDown() {
resetProjectSettings(LanguageVersion.LATEST_STABLE)
FacetManager.getInstance(module).getFacetByType(KotlinFacetType.TYPE_ID)?.let {
FacetUtil.deleteFacet(it)
}
ConfigLibraryUtil.removeLibrary(module, "KotlinJavaRuntime")
super.tearDown()
}
}
@@ -1,258 +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.idea.refactoring
import com.intellij.codeInsight.TargetElementUtil
import com.intellij.codeInsight.template.impl.TemplateManagerImpl
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.impl.SimpleDataContext
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.refactoring.BaseRefactoringProcessor
import com.intellij.refactoring.rename.inplace.VariableInplaceRenameHandler
import com.intellij.testFramework.LightPlatformCodeInsightTestCase
import com.intellij.testFramework.fixtures.CodeInsightTestUtil
import junit.framework.TestCase
import org.jetbrains.kotlin.idea.liveTemplates.setTemplateTestingCompat
import org.jetbrains.kotlin.idea.refactoring.rename.KotlinMemberInplaceRenameHandler
import org.jetbrains.kotlin.idea.refactoring.rename.KotlinVariableInplaceRenameHandler
import org.jetbrains.kotlin.idea.refactoring.rename.RenameKotlinImplicitLambdaParameter
import org.jetbrains.kotlin.idea.refactoring.rename.findElementForRename
import org.jetbrains.kotlin.idea.test.PluginTestCaseBase
import org.jetbrains.kotlin.psi.KtNameReferenceExpression
import org.jetbrains.kotlin.test.InTextDirectivesUtils
import org.jetbrains.kotlin.test.JUnit3WithIdeaConfigurationRunner
import org.junit.runner.RunWith
import kotlin.test.assertFalse
import kotlin.test.assertTrue
@RunWith(JUnit3WithIdeaConfigurationRunner::class)
class InplaceRenameTest : LightPlatformCodeInsightTestCase() {
override fun isRunInWriteAction(): Boolean = false
override fun getTestDataPath(): String = PluginTestCaseBase.getTestDataPathBase() + "/refactoring/rename/inplace/"
fun testLocalVal() {
doTestMemberInplaceRename("y")
}
fun testForLoop() {
doTestInplaceRename("j")
}
fun testTryCatch() {
doTestInplaceRename("e1")
}
fun testFunctionLiteral() {
doTestInplaceRename("y")
}
fun testFunctionLiteralIt() {
doTestImplicitLambdaParameter("y")
}
fun testFunctionLiteralItEndCaret() {
doTestImplicitLambdaParameter("y")
}
fun testFunctionLiteralParenthesis() {
doTestInplaceRename("y")
}
fun testLocalFunction() {
doTestMemberInplaceRename("bar")
}
fun testFunctionParameterNotInplace() {
doTestInplaceRename(null)
}
fun testGlobalFunctionNotInplace() {
doTestInplaceRename(null)
}
fun testTopLevelValNotInplace() {
doTestInplaceRename(null)
}
fun testLabelFromFunction() {
doTestMemberInplaceRename("foo")
}
fun testMultiDeclaration() {
doTestInplaceRename("foo")
}
fun testLocalVarShadowingMemberProperty() {
doTestMemberInplaceRename("name1")
}
fun testNoReformat() {
doTestMemberInplaceRename("subject2")
}
fun testInvokeToFoo() {
doTestMemberInplaceRename("foo")
}
fun testInvokeToGet() {
doTestMemberInplaceRename("get")
}
fun testInvokeToGetWithQualifiedExpr() {
doTestMemberInplaceRename("get")
}
fun testInvokeToGetWithSafeQualifiedExpr() {
doTestMemberInplaceRename("get")
}
fun testInvokeToPlus() {
doTestMemberInplaceRename("plus")
}
fun testGetToFoo() {
doTestMemberInplaceRename("foo")
}
fun testGetToInvoke() {
doTestMemberInplaceRename("invoke")
}
fun testGetToInvokeWithQualifiedExpr() {
doTestMemberInplaceRename("invoke")
}
fun testGetToInvokeWithSafeQualifiedExpr() {
doTestMemberInplaceRename("invoke")
}
fun testGetToPlus() {
doTestMemberInplaceRename("plus")
}
fun testAddQuotes() {
doTestMemberInplaceRename("is")
}
fun testAddThis() {
doTestMemberInplaceRename("foo")
}
fun testExtensionAndNoReceiver() {
doTestMemberInplaceRename("b")
}
fun testTwoExtensions() {
doTestMemberInplaceRename("example")
}
fun testQuotedLocalVar() {
doTestMemberInplaceRename("x")
}
fun testQuotedParameter() {
doTestMemberInplaceRename("x")
}
fun testEraseCompanionName() {
doTestMemberInplaceRename("")
}
fun testLocalVarRedeclaration() {
doTestMemberInplaceRename("localValB")
}
fun testLocalFunRedeclaration() {
doTestMemberInplaceRename("localFunB")
}
fun testLocalClassRedeclaration() {
doTestMemberInplaceRename("LocalClassB")
}
fun testBacktickedWithAccessors() {
doTestMemberInplaceRename("`object`")
}
fun testNoTextUsagesForLocalVar() {
doTestMemberInplaceRename("w")
}
private fun doTestImplicitLambdaParameter(newName: String) {
configureByFile(getTestName(false) + ".kt")
// This code is copy-pasted from CodeInsightTestUtil.doInlineRename() and slightly modified.
// Original method was not suitable because it expects renamed element to be reference to other or referrable
val file = getFile()!!
val editor = getEditor()!!
val element = file.findElementForRename<KtNameReferenceExpression>(editor.caretModel.offset)!!
assertNotNull(element)
val dataContext = SimpleDataContext.getSimpleContext(CommonDataKeys.PSI_ELEMENT.name, element,
getCurrentEditorDataContext())
val handler = RenameKotlinImplicitLambdaParameter()
assertTrue(handler.isRenaming(dataContext), "In-place rename not allowed for " + element)
val project = editor.project!!
setTemplateTestingCompat(project, testRootDisposable)
object : WriteCommandAction.Simple<Any>(project) {
override fun run() {
handler.invoke(project, editor, file, dataContext)
}
}.execute()
var state = TemplateManagerImpl.getTemplateState(editor)
assert(state != null)
val range = state!!.currentVariableRange
assert(range != null)
object : WriteCommandAction.Simple<Any>(project) {
override fun run() {
editor.document.replaceString(range!!.startOffset, range.endOffset, newName)
}
}.execute().throwException()
state = TemplateManagerImpl.getTemplateState(editor)
assert(state != null)
state!!.gotoEnd(false)
checkResultByFile(getTestName(false) + ".kt.after")
}
private fun doTestMemberInplaceRename(newName: String?) {
doTestInplaceRename(newName, KotlinMemberInplaceRenameHandler())
}
private fun doTestInplaceRename(newName: String?, handler: VariableInplaceRenameHandler = KotlinVariableInplaceRenameHandler()) {
configureByFile(getTestName(false) + ".kt")
val element = TargetElementUtil.findTargetElement(
myEditor,
TargetElementUtil.ELEMENT_NAME_ACCEPTED or TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED
)
assertNotNull(element)
val dataContext = SimpleDataContext.getSimpleContext(CommonDataKeys.PSI_ELEMENT.name, element!!,
getCurrentEditorDataContext())
if (newName == null) {
assertFalse(handler.isRenaming(dataContext), "In-place rename is allowed for " + element)
}
else {
try {
assertTrue(handler.isRenaming(dataContext), "In-place rename not allowed for " + element)
CodeInsightTestUtil.doInlineRename(handler, newName, getEditor(), element)
checkResultByFile(getTestName(false) + ".kt.after")
} catch (e: BaseRefactoringProcessor.ConflictsInTestsException) {
val expectedMessage = InTextDirectivesUtils.findStringWithPrefixes(myFile.text, "// SHOULD_FAIL_WITH: ")
TestCase.assertEquals(expectedMessage, e.messages.joinToString())
}
}
}
}
@@ -1,17 +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.idea.refactoring.move
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.refactoring.move.MoveHandlerDelegate
// FIX ME WHEN BUNCH 191 REMOVED
internal fun MoveHandlerDelegate.canMoveCompat(
elements: Array<out PsiElement>,
targetContainer: PsiElement?,
reference: PsiReference?
): Boolean = canMove(elements, targetContainer)