diff --git a/.bunch b/.bunch index 881679491c9..3a346ebcd9d 100644 --- a/.bunch +++ b/.bunch @@ -1,6 +1,5 @@ 182 181 173_181 -172_173_181 as31_173_181 as32_181 diff --git a/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/compiler/IdeaExtensionPoints.kt.172 b/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/compiler/IdeaExtensionPoints.kt.172 deleted file mode 100644 index 4dcaf07d36e..00000000000 --- a/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/compiler/IdeaExtensionPoints.kt.172 +++ /dev/null @@ -1,22 +0,0 @@ -/* - * 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.cli.jvm.compiler - -import com.intellij.core.CoreApplicationEnvironment -import com.intellij.openapi.extensions.ExtensionsArea -import com.intellij.psi.impl.compiled.ClsCustomNavigationPolicy - -internal object IdeaExtensionPoints { - const val IDEA_COMPATIBLE_BUILD_NUMBER = "172.9999" - - fun registerVersionSpecificAppExtensionPoints(area: ExtensionsArea) { - @Suppress("DEPRECATION") - CoreApplicationEnvironment.registerExtensionPoint(area, ClsCustomNavigationPolicy.EP_NAME, ClsCustomNavigationPolicy::class.java) - } - - fun registerVersionSpecificProjectExtensionPoints(area: ExtensionsArea) { - } -} diff --git a/compiler/compiler.pro.172 b/compiler/compiler.pro.172 deleted file mode 100644 index 25473daf51f..00000000000 --- a/compiler/compiler.pro.172 +++ /dev/null @@ -1,221 +0,0 @@ --injars ''( -!org/apache/log4j/jmx/Agent*, -!org/apache/log4j/net/JMS*, -!org/apache/log4j/net/SMTP*, -!org/apache/log4j/or/jms/MessageRenderer*, -!org/jdom/xpath/Jaxen*, -!org/jline/builtins/ssh/**, -!org/mozilla/javascript/xml/impl/xmlbeans/**, -!net/sf/cglib/**, -!META-INF/maven**, -**.class,**.properties,**.kt,**.kotlin_*,**.jnilib,**.so,**.dll,**.txt,**.caps, -META-INF/services/**,META-INF/native/**,META-INF/extensions/**,META-INF/MANIFEST.MF, -messages/**) - --outjars '' - --dontnote ** --dontwarn com.intellij.util.ui.IsRetina* --dontwarn com.intellij.util.RetinaImage* --dontwarn apple.awt.* --dontwarn dk.brics.automaton.* --dontwarn org.fusesource.** --dontwarn org.imgscalr.Scalr** --dontwarn org.xerial.snappy.SnappyBundleActivator --dontwarn com.intellij.util.CompressionUtil --dontwarn com.intellij.util.SnappyInitializer --dontwarn com.intellij.util.SVGLoader --dontwarn com.intellij.util.SVGLoader$MyTranscoder --dontwarn net.sf.cglib.** --dontwarn org.objectweb.asm.** # this is ASM3, the old version that we do not use --dontwarn com.sun.jna.NativeString --dontwarn com.sun.jna.WString --dontwarn com.intellij.psi.util.PsiClassUtil --dontwarn org.apache.hadoop.io.compress.* --dontwarn com.google.j2objc.annotations.Weak --dontwarn org.iq80.snappy.HadoopSnappyCodec$SnappyCompressionInputStream --dontwarn org.iq80.snappy.HadoopSnappyCodec$SnappyCompressionOutputStream --dontwarn com.google.common.util.concurrent.* --dontwarn org.apache.xerces.dom.** --dontwarn org.apache.xerces.util.** --dontwarn org.w3c.dom.ElementTraversal --dontwarn javaslang.match.annotation.Unapply --dontwarn javaslang.match.annotation.Patterns --dontwarn javaslang.* --dontwarn com.google.errorprone.** --dontwarn com.google.j2objc.** --dontwarn javax.crypto.** --dontwarn java.lang.invoke.MethodHandle --dontwarn org.jline.builtins.Nano$Buffer --dontwarn net.jpountz.lz4.LZ4Factory --dontwarn org.jetbrains.annotations.ReadOnly --dontwarn org.jetbrains.annotations.Mutable - -#-libraryjars '' -#-libraryjars '' -#-libraryjars '' -#-libraryjars '' -#-libraryjars '' -#-libraryjars '' - --dontoptimize --dontobfuscate - --keep class org.fusesource.** { *; } --keep class com.sun.jna.** { *; } - --keep class org.jetbrains.annotations.** { - public protected *; -} - --keep class javax.inject.** { - public protected *; -} - --keep class org.jetbrains.kotlin.** { - public protected *; -} - --keep class org.jetbrains.kotlin.compiler.plugin.** { - public protected *; -} - --keep class org.jetbrains.kotlin.extensions.** { - public protected *; -} - --keep class org.jetbrains.kotlin.protobuf.** { - public protected *; -} - --keep class org.jetbrains.kotlin.container.** { *; } - --keep class org.jetbrains.kotlin.codegen.intrinsics.IntrinsicArrayConstructorsKt { *; } - --keep class org.jetbrains.org.objectweb.asm.Opcodes { *; } - --keep class org.jetbrains.kotlin.codegen.extensions.** { - public protected *; -} - --keepclassmembers class com.intellij.openapi.vfs.VirtualFile { - public protected *; -} - --keep class com.intellij.openapi.vfs.StandardFileSystems { - public static *; -} - -# needed for jar cache cleanup in the gradle plugin and compile daemon --keepclassmembers class com.intellij.openapi.vfs.impl.ZipHandler { - public static void clearFileAccessorCache(); -} - --keep class jet.** { - public protected *; -} - --keep class com.intellij.psi.** { - public protected *; -} - -# This is needed so that the platform code which parses XML wouldn't fail, see KT-16968 -# This API is used from org.jdom.input.SAXBuilder via reflection. --keep class org.jdom.input.JAXPParserFactory { public ** createParser(...); } - -# for kdoc & dokka --keep class com.intellij.openapi.util.TextRange { *; } --keep class com.intellij.lang.impl.PsiBuilderImpl* { - public protected *; -} --keep class com.intellij.openapi.util.text.StringHash { *; } - -# for j2k --keep class com.intellij.codeInsight.NullableNotNullManager { public protected *; } - -# for gradle (see KT-12549) --keep class com.intellij.lang.properties.charset.Native2AsciiCharsetProvider { *; } - -# for kotlin-build-common (consider repacking compiler together with kotlin-build-common and remove this part afterwards) --keep class com.intellij.util.io.IOUtil { public *; } --keep class com.intellij.openapi.util.io.FileUtil { public *; } --keep class com.intellij.util.SystemProperties { public *; } --keep class com.intellij.util.containers.hash.LinkedHashMap { *; } --keep class com.intellij.util.containers.ConcurrentIntObjectMap { *; } --keep class com.intellij.util.containers.ComparatorUtil { *; } --keep class com.intellij.util.io.PersistentHashMapValueStorage { *; } --keep class com.intellij.util.io.PersistentHashMap { *; } --keep class com.intellij.util.io.BooleanDataDescriptor { *; } --keep class com.intellij.util.io.EnumeratorStringDescriptor { *; } --keep class com.intellij.util.io.ExternalIntegerKeyDescriptor { *; } --keep class com.intellij.util.containers.hash.EqualityPolicy { *; } --keep class com.intellij.util.containers.hash.EqualityPolicy.* { *; } --keep class com.intellij.util.containers.Interner { *; } --keep class gnu.trove.TIntHashSet { *; } --keep class gnu.trove.TIntIterator { *; } --keep class org.iq80.snappy.SlowMemory { *; } --keep class javaslang.match.PatternsProcessor { *; } - --keepclassmembers enum * { - public static **[] values(); - public static ** valueOf(java.lang.String); -} - --keepclassmembers class * { - ** toString(); - ** hashCode(); - void start(); - void stop(); - void dispose(); -} - --keepclassmembers class org.jetbrains.org.objectweb.asm.Opcodes { - *** ASM5; -} - --keep class org.jetbrains.org.objectweb.asm.tree.AnnotationNode { *; } --keep class org.jetbrains.org.objectweb.asm.tree.ClassNode { *; } --keep class org.jetbrains.org.objectweb.asm.tree.LocalVariableNode { *; } --keep class org.jetbrains.org.objectweb.asm.tree.MethodNode { *; } --keep class org.jetbrains.org.objectweb.asm.tree.FieldNode { *; } --keep class org.jetbrains.org.objectweb.asm.tree.ParameterNode { *; } --keep class org.jetbrains.org.objectweb.asm.tree.TypeAnnotationNode { *; } - --keep class org.jetbrains.org.objectweb.asm.signature.SignatureReader { *; } --keep class org.jetbrains.org.objectweb.asm.signature.SignatureVisitor { *; } - --keep class org.jetbrains.org.objectweb.asm.Type { - public protected *; -} - --keepclassmembers class org.jetbrains.org.objectweb.asm.ClassReader { - *** SKIP_CODE; - *** SKIP_DEBUG; - *** SKIP_FRAMES; -} - --keepclassmembers class com.intellij.openapi.project.Project { - ** getBasePath(); -} - -# for kotlin-android-extensions in maven --keep class com.intellij.openapi.module.ModuleServiceManager { public *; } - -# for building kotlin-build-common-test --keep class org.jetbrains.kotlin.build.SerializationUtilsKt { *; } - -# for tools.jar --keep class com.sun.tools.javac.** { *; } --keep class com.sun.source.** { *; } - -# for coroutines --keep class kotlinx.coroutines.** { *; } - -# for webdemo --keep class com.intellij.openapi.progress.ProgressManager { *; } - -# for kapt --keep class com.intellij.openapi.project.Project { *; } - -# remove when KT-18563 would be fixed --keep class org.jetbrains.kotlin.psi.psiUtil.PsiUtilsKt { *; } diff --git a/compiler/tests-common/tests/org/jetbrains/kotlin/test/testFramework/EdtTestUtil.kt.172 b/compiler/tests-common/tests/org/jetbrains/kotlin/test/testFramework/EdtTestUtil.kt.172 deleted file mode 100644 index 1ccf51aa3dc..00000000000 --- a/compiler/tests-common/tests/org/jetbrains/kotlin/test/testFramework/EdtTestUtil.kt.172 +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.kotlin.test.testFramework - -import org.jetbrains.annotations.TestOnly -import java.lang.reflect.InvocationTargetException -import javax.swing.SwingUtilities - -class EdtTestUtil { - companion object { - @TestOnly @JvmStatic fun runInEdtAndWait(runnable: Runnable) { - runInEdtAndWait { runnable.run() } - } - } -} - - -// Test only because in production you must use Application.invokeAndWait(Runnable, ModalityState). -// The problem is - Application logs errors, but not throws. But in tests must be thrown. -// In any case name "runInEdtAndWait" is better than "invokeAndWait". -@TestOnly -fun runInEdtAndWait(runnable: () -> Unit) { - if (SwingUtilities.isEventDispatchThread()) { - runnable() - } - else { - try { - SwingUtilities.invokeAndWait(runnable) - } - catch (e: InvocationTargetException) { - throw e.cause ?: e - } - } -} \ No newline at end of file diff --git a/compiler/tests-common/tests/org/jetbrains/kotlin/test/testFramework/KtParsingTestCase.java.172 b/compiler/tests-common/tests/org/jetbrains/kotlin/test/testFramework/KtParsingTestCase.java.172 deleted file mode 100644 index bd4eddb1898..00000000000 --- a/compiler/tests-common/tests/org/jetbrains/kotlin/test/testFramework/KtParsingTestCase.java.172 +++ /dev/null @@ -1,340 +0,0 @@ -/* - * Copyright 2000-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.kotlin.test.testFramework; - -import com.intellij.core.CoreASTFactory; -import com.intellij.lang.*; -import com.intellij.lang.impl.PsiBuilderFactoryImpl; -import com.intellij.mock.MockFileDocumentManagerImpl; -import com.intellij.openapi.Disposable; -import com.intellij.openapi.application.PathManager; -import com.intellij.openapi.editor.Document; -import com.intellij.openapi.editor.EditorFactory; -import com.intellij.openapi.extensions.ExtensionPointName; -import com.intellij.openapi.extensions.Extensions; -import com.intellij.openapi.fileEditor.FileDocumentManager; -import com.intellij.openapi.fileEditor.impl.LoadTextUtil; -import com.intellij.openapi.fileTypes.FileTypeFactory; -import com.intellij.openapi.fileTypes.FileTypeManager; -import com.intellij.openapi.progress.EmptyProgressIndicator; -import com.intellij.openapi.progress.ProgressManager; -import com.intellij.openapi.progress.impl.CoreProgressManager; -import com.intellij.openapi.util.Disposer; -import com.intellij.openapi.util.Key; -import com.intellij.openapi.util.TextRange; -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.vfs.CharsetToolkit; -import com.intellij.pom.PomModel; -import com.intellij.pom.core.impl.PomModelImpl; -import com.intellij.pom.tree.TreeAspect; -import com.intellij.psi.*; -import com.intellij.psi.impl.DebugUtil; -import com.intellij.psi.impl.PsiCachedValuesFactory; -import com.intellij.psi.impl.PsiFileFactoryImpl; -import com.intellij.psi.impl.source.resolve.reference.ReferenceProvidersRegistry; -import com.intellij.psi.impl.source.resolve.reference.ReferenceProvidersRegistryImpl; -import com.intellij.psi.impl.source.text.BlockSupportImpl; -import com.intellij.psi.impl.source.text.DiffLog; -import com.intellij.psi.util.CachedValuesManager; -import com.intellij.testFramework.LightVirtualFile; -import com.intellij.testFramework.TestDataFile; -import com.intellij.util.CachedValuesManagerImpl; -import com.intellij.util.Function; -import com.intellij.util.messages.MessageBus; -import com.intellij.util.messages.MessageBusFactory; -import junit.framework.TestCase; -import org.jetbrains.annotations.NonNls; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.kotlin.test.testFramework.mock.*; -import org.picocontainer.ComponentAdapter; -import org.picocontainer.MutablePicoContainer; - -import java.io.File; -import java.io.IOException; -import java.util.Set; - -@SuppressWarnings("ALL") -public abstract class KtParsingTestCase extends KtPlatformLiteFixture { - public static final Key HARD_REF_TO_DOCUMENT_KEY = Key.create("HARD_REF_TO_DOCUMENT_KEY"); - protected String myFilePrefix = ""; - protected String myFileExt; - protected final String myFullDataPath; - protected PsiFile myFile; - private MockPsiManager myPsiManager; - private PsiFileFactoryImpl myFileFactory; - protected Language myLanguage; - private final ParserDefinition[] myDefinitions; - private final boolean myLowercaseFirstLetter; - - protected KtParsingTestCase(@NonNls @NotNull String dataPath, @NotNull String fileExt, @NotNull ParserDefinition... definitions) { - this(dataPath, fileExt, false, definitions); - } - - protected KtParsingTestCase(@NonNls @NotNull String dataPath, @NotNull String fileExt, boolean lowercaseFirstLetter, @NotNull ParserDefinition... definitions) { - myDefinitions = definitions; - myFullDataPath = getTestDataPath() + "/" + dataPath; - myFileExt = fileExt; - myLowercaseFirstLetter = lowercaseFirstLetter; - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - initApplication(); - ComponentAdapter component = getApplication().getPicoContainer().getComponentAdapter(ProgressManager.class.getName()); - - Extensions.registerAreaClass("IDEA_PROJECT", null); - myProject = new MockProjectEx(getTestRootDisposable()); - myPsiManager = new MockPsiManager(myProject); - myFileFactory = new PsiFileFactoryImpl(myPsiManager); - MutablePicoContainer appContainer = getApplication().getPicoContainer(); - registerComponentInstance(appContainer, MessageBus.class, MessageBusFactory.newMessageBus(getApplication())); - final MockEditorFactory editorFactory = new MockEditorFactory(); - registerComponentInstance(appContainer, EditorFactory.class, editorFactory); - registerComponentInstance(appContainer, FileDocumentManager.class, new MockFileDocumentManagerImpl(new Function() { - @Override - public Document fun(CharSequence charSequence) { - return editorFactory.createDocument(charSequence); - } - }, HARD_REF_TO_DOCUMENT_KEY)); - registerComponentInstance(appContainer, PsiDocumentManager.class, new MockPsiDocumentManager()); - registerApplicationService(PsiBuilderFactory.class, new PsiBuilderFactoryImpl()); - registerApplicationService(DefaultASTFactory.class, new CoreASTFactory()); - registerApplicationService(ReferenceProvidersRegistry.class, new ReferenceProvidersRegistryImpl()); - - registerApplicationService(ProgressManager.class, new CoreProgressManager()); - - myProject.registerService(CachedValuesManager.class, new CachedValuesManagerImpl(myProject, new PsiCachedValuesFactory(myPsiManager))); - myProject.registerService(PsiManager.class, myPsiManager); - - this.registerExtensionPoint(FileTypeFactory.FILE_TYPE_FACTORY_EP, FileTypeFactory.class); - registerExtensionPoint(MetaLanguage.EP_NAME, MetaLanguage.class); - - for (ParserDefinition definition : myDefinitions) { - addExplicitExtension(LanguageParserDefinitions.INSTANCE, definition.getFileNodeType().getLanguage(), definition); - } - if (myDefinitions.length > 0) { - configureFromParserDefinition(myDefinitions[0], myFileExt); - } - - // That's for reparse routines - final PomModelImpl pomModel = new PomModelImpl(myProject); - myProject.registerService(PomModel.class, pomModel); - new TreeAspect(pomModel); - } - - public void configureFromParserDefinition(ParserDefinition definition, String extension) { - myLanguage = definition.getFileNodeType().getLanguage(); - myFileExt = extension; - addExplicitExtension(LanguageParserDefinitions.INSTANCE, this.myLanguage, definition); - registerComponentInstance( - getApplication().getPicoContainer(), FileTypeManager.class, - new KtMockFileTypeManager(new KtMockLanguageFileType(myLanguage, myFileExt))); - } - - protected void addExplicitExtension(final LanguageExtension instance, final Language language, final T object) { - instance.addExplicitExtension(language, object); - Disposer.register(myProject, new Disposable() { - @Override - public void dispose() { - instance.removeExplicitExtension(language, object); - } - }); - } - - @Override - protected void registerExtensionPoint(final ExtensionPointName extensionPointName, Class aClass) { - super.registerExtensionPoint(extensionPointName, aClass); - Disposer.register(myProject, new Disposable() { - @Override - public void dispose() { - Extensions.getRootArea().unregisterExtensionPoint(extensionPointName.getName()); - } - }); - } - - protected void registerApplicationService(final Class aClass, T object) { - getApplication().registerService(aClass, object); - Disposer.register(myProject, new Disposable() { - @Override - public void dispose() { - getApplication().getPicoContainer().unregisterComponent(aClass.getName()); - } - }); - } - - public MockProjectEx getProject() { - return myProject; - } - - public MockPsiManager getPsiManager() { - return myPsiManager; - } - - @Override - protected void tearDown() throws Exception { - super.tearDown(); - myFile = null; - myProject = null; - myPsiManager = null; - } - - protected String getTestDataPath() { - return PathManager.getHomePath(); - } - - @NotNull - public final String getTestName() { - return getTestName(myLowercaseFirstLetter); - } - - protected boolean includeRanges() { - return false; - } - - protected boolean skipSpaces() { - return false; - } - - protected boolean checkAllPsiRoots() { - return true; - } - - protected void doTest(boolean checkResult) { - String name = getTestName(); - try { - String text = loadFile(name + "." + myFileExt); - myFile = createPsiFile(name, text); - ensureParsed(myFile); - assertEquals("light virtual file text mismatch", text, ((LightVirtualFile)myFile.getVirtualFile()).getContent().toString()); - assertEquals("virtual file text mismatch", text, LoadTextUtil.loadText(myFile.getVirtualFile())); - assertEquals("doc text mismatch", text, myFile.getViewProvider().getDocument().getText()); - assertEquals("psi text mismatch", text, myFile.getText()); - ensureCorrectReparse(myFile); - if (checkResult){ - checkResult(name, myFile); - } - else{ - toParseTreeText(myFile, skipSpaces(), includeRanges()); - } - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - - protected void doTest(String suffix) throws IOException { - String name = getTestName(); - String text = loadFile(name + "." + myFileExt); - myFile = createPsiFile(name, text); - ensureParsed(myFile); - assertEquals(text, myFile.getText()); - checkResult(name + suffix, myFile); - } - - protected void doCodeTest(String code) throws IOException { - String name = getTestName(); - myFile = createPsiFile("a", code); - ensureParsed(myFile); - assertEquals(code, myFile.getText()); - checkResult(myFilePrefix + name, myFile); - } - - protected PsiFile createPsiFile(String name, String text) { - return createFile(name + "." + myFileExt, text); - } - - protected PsiFile createFile(@NonNls String name, String text) { - LightVirtualFile virtualFile = new LightVirtualFile(name, myLanguage, text); - virtualFile.setCharset(CharsetToolkit.UTF8_CHARSET); - return createFile(virtualFile); - } - - protected PsiFile createFile(LightVirtualFile virtualFile) { - return myFileFactory.trySetupPsiForFile(virtualFile, myLanguage, true, false); - } - - protected void checkResult(@NonNls @TestDataFile String targetDataName, final PsiFile file) throws IOException { - doCheckResult(myFullDataPath, file, checkAllPsiRoots(), targetDataName, skipSpaces(), includeRanges()); - } - - public static void doCheckResult(String testDataDir, - PsiFile file, - boolean checkAllPsiRoots, - String targetDataName, - boolean skipSpaces, - boolean printRanges) throws IOException { - FileViewProvider provider = file.getViewProvider(); - Set languages = provider.getLanguages(); - - if (!checkAllPsiRoots || languages.size() == 1) { - doCheckResult(testDataDir, targetDataName + ".txt", toParseTreeText(file, skipSpaces, printRanges).trim()); - return; - } - - for (Language language : languages) { - PsiFile root = provider.getPsi(language); - String expectedName = targetDataName + "." + language.getID() + ".txt"; - doCheckResult(testDataDir, expectedName, toParseTreeText(root, skipSpaces, printRanges).trim()); - } - } - - protected void checkResult(String actual) throws IOException { - String name = getTestName(); - doCheckResult(myFullDataPath, myFilePrefix + name + ".txt", actual); - } - - protected void checkResult(@TestDataFile @NonNls String targetDataName, String actual) throws IOException { - doCheckResult(myFullDataPath, targetDataName, actual); - } - - public static void doCheckResult(String fullPath, String targetDataName, String actual) throws IOException { - String expectedFileName = fullPath + File.separatorChar + targetDataName; - KtUsefulTestCase.assertSameLinesWithFile(expectedFileName, actual); - } - - protected static String toParseTreeText(PsiElement file, boolean skipSpaces, boolean printRanges) { - return DebugUtil.psiToString(file, skipSpaces, printRanges); - } - - protected String loadFile(@NonNls @TestDataFile String name) throws IOException { - return loadFileDefault(myFullDataPath, name); - } - - public static String loadFileDefault(String dir, String name) throws IOException { - return FileUtil.loadFile(new File(dir, name), CharsetToolkit.UTF8, true).trim(); - } - - public static void ensureParsed(PsiFile file) { - file.accept(new PsiElementVisitor() { - @Override - public void visitElement(PsiElement element) { - element.acceptChildren(this); - } - }); - } - - public static void ensureCorrectReparse(@NotNull PsiFile file) { - String psiToStringDefault = DebugUtil.psiToString(file, false, false); - String fileText = file.getText(); - DiffLog diffLog = (new BlockSupportImpl(file.getProject())).reparseRange( - file, file.getNode(), TextRange.allOf(fileText), fileText, new EmptyProgressIndicator(), fileText); - diffLog.performActualPsiChange(file); - - TestCase.assertEquals(psiToStringDefault, DebugUtil.psiToString(file, false, false)); - } -} \ No newline at end of file diff --git a/compiler/tests-common/tests/org/jetbrains/kotlin/test/testFramework/KtUsefulTestCase.java.172 b/compiler/tests-common/tests/org/jetbrains/kotlin/test/testFramework/KtUsefulTestCase.java.172 deleted file mode 100644 index e46292cc55f..00000000000 --- a/compiler/tests-common/tests/org/jetbrains/kotlin/test/testFramework/KtUsefulTestCase.java.172 +++ /dev/null @@ -1,501 +0,0 @@ -/* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.kotlin.test.testFramework; - -import com.intellij.openapi.Disposable; -import com.intellij.openapi.application.Application; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.application.impl.ApplicationInfoImpl; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.util.Comparing; -import com.intellij.openapi.util.Disposer; -import com.intellij.openapi.util.io.FileSystemUtil; -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.util.text.StringUtil; -import com.intellij.openapi.vfs.CharsetToolkit; -import com.intellij.rt.execution.junit.FileComparisonFailure; -import com.intellij.testFramework.TestLoggerFactory; -import com.intellij.util.ReflectionUtil; -import com.intellij.util.containers.ContainerUtil; -import com.intellij.util.containers.hash.HashMap; -import com.intellij.util.ui.UIUtil; -import gnu.trove.THashSet; -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; -import org.jetbrains.annotations.Contract; -import org.jetbrains.annotations.NonNls; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.jetbrains.kotlin.testFramework.MockComponentManagerCreationTracer; -import org.jetbrains.kotlin.types.FlexibleTypeImpl; -import org.jetbrains.kotlin.utils.ExceptionUtilsKt; -import org.junit.Assert; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Modifier; -import java.util.*; - -@SuppressWarnings("UseOfSystemOutOrSystemErr") -public abstract class KtUsefulTestCase extends TestCase { - private static final String TEMP_DIR_MARKER = "unitTest_"; - - private static final String ORIGINAL_TEMP_DIR = FileUtil.getTempDirectory(); - - private static final Map TOTAL_SETUP_COST_MILLIS = new HashMap<>(); - private static final Map TOTAL_TEARDOWN_COST_MILLIS = new HashMap<>(); - - private Application application; - - static { - Logger.setFactory(TestLoggerFactory.class); - } - - @NotNull - protected final Disposable myTestRootDisposable = new TestDisposable(); - - private static final String ourPathToKeep = null; - private final List myPathsToKeep = new ArrayList<>(); - - private String myTempDir; - - static { - // Radar #5755208: Command line Java applications need a way to launch without a Dock icon. - System.setProperty("apple.awt.UIElement", "true"); - - FlexibleTypeImpl.RUN_SLOW_ASSERTIONS = true; - } - - private boolean oldDisposerDebug; - - @Override - protected void setUp() throws Exception { - application = ApplicationManager.getApplication(); - - if (application != null && application.isDisposed()) { - MockComponentManagerCreationTracer.diagnoseDisposedButNotClearedApplication(application); - } - - super.setUp(); - - String testName = FileUtil.sanitizeFileName(getTestName(true)); - if (StringUtil.isEmptyOrSpaces(testName)) testName = ""; - testName = new File(testName).getName(); // in case the test name contains file separators - myTempDir = new File(ORIGINAL_TEMP_DIR, TEMP_DIR_MARKER + testName).getPath(); - FileUtil.resetCanonicalTempPathCache(myTempDir); - boolean isStressTest = isStressTest(); - ApplicationInfoImpl.setInStressTest(isStressTest); - // turn off Disposer debugging for performance tests - oldDisposerDebug = Disposer.setDebugMode(Disposer.isDebugMode() && !isStressTest); - } - - @Override - protected void tearDown() throws Exception { - try { - Disposer.dispose(myTestRootDisposable); - cleanupSwingDataStructures(); - cleanupDeleteOnExitHookList(); - } - finally { - Disposer.setDebugMode(oldDisposerDebug); - FileUtil.resetCanonicalTempPathCache(ORIGINAL_TEMP_DIR); - if (hasTmpFilesToKeep()) { - File[] files = new File(myTempDir).listFiles(); - if (files != null) { - for (File file : files) { - if (!shouldKeepTmpFile(file)) { - FileUtil.delete(file); - } - } - } - } - else { - FileUtil.delete(new File(myTempDir)); - } - } - - UIUtil.removeLeakingAppleListeners(); - super.tearDown(); - - resetApplicationToNull(application); - - application = null; - } - - public static void resetApplicationToNull(Application old) { - if (old != null) return; - resetApplicationToNull(); - } - - public static void resetApplicationToNull() { - try { - Field ourApplicationField = ApplicationManager.class.getDeclaredField("ourApplication"); - ourApplicationField.setAccessible(true); - ourApplicationField.set(null, null); - } - catch (Exception e) { - throw ExceptionUtilsKt.rethrow(e); - } - } - - private boolean hasTmpFilesToKeep() { - return !myPathsToKeep.isEmpty(); - } - - private boolean shouldKeepTmpFile(File file) { - String path = file.getPath(); - if (FileUtil.pathsEqual(path, ourPathToKeep)) return true; - for (String pathToKeep : myPathsToKeep) { - if (FileUtil.pathsEqual(path, pathToKeep)) return true; - } - return false; - } - - private static final Set DELETE_ON_EXIT_HOOK_DOT_FILES; - private static final Class DELETE_ON_EXIT_HOOK_CLASS; - static { - Class aClass; - try { - aClass = Class.forName("java.io.DeleteOnExitHook"); - } - catch (Exception e) { - throw new RuntimeException(e); - } - Set files = ReflectionUtil.getStaticFieldValue(aClass, Set.class, "files"); - DELETE_ON_EXIT_HOOK_CLASS = aClass; - DELETE_ON_EXIT_HOOK_DOT_FILES = files; - } - - private static void cleanupDeleteOnExitHookList() throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException { - // try to reduce file set retained by java.io.DeleteOnExitHook - List list; - synchronized (DELETE_ON_EXIT_HOOK_CLASS) { - if (DELETE_ON_EXIT_HOOK_DOT_FILES.isEmpty()) return; - list = new ArrayList<>(DELETE_ON_EXIT_HOOK_DOT_FILES); - } - for (int i = list.size() - 1; i >= 0; i--) { - String path = list.get(i); - if (FileSystemUtil.getAttributes(path) == null || new File(path).delete()) { - synchronized (DELETE_ON_EXIT_HOOK_CLASS) { - DELETE_ON_EXIT_HOOK_DOT_FILES.remove(path); - } - } - } - } - - private static void cleanupSwingDataStructures() throws Exception { - Object manager = ReflectionUtil.getDeclaredMethod(Class.forName("javax.swing.KeyboardManager"), "getCurrentManager").invoke(null); - Map componentKeyStrokeMap = ReflectionUtil.getField(manager.getClass(), manager, Hashtable.class, "componentKeyStrokeMap"); - componentKeyStrokeMap.clear(); - Map containerMap = ReflectionUtil.getField(manager.getClass(), manager, Hashtable.class, "containerMap"); - containerMap.clear(); - } - - @NotNull - public final Disposable getTestRootDisposable() { - return myTestRootDisposable; - } - - @Override - protected void runTest() throws Throwable { - Throwable[] throwables = new Throwable[1]; - - Runnable runnable = () -> { - try { - super.runTest(); - } - catch (InvocationTargetException e) { - e.fillInStackTrace(); - throwables[0] = e.getTargetException(); - } - catch (IllegalAccessException e) { - e.fillInStackTrace(); - throwables[0] = e; - } - catch (Throwable e) { - throwables[0] = e; - } - }; - - invokeTestRunnable(runnable); - - if (throwables[0] != null) { - throw throwables[0]; - } - } - - private static void invokeTestRunnable(@NotNull Runnable runnable) throws Exception { - EdtTestUtil.runInEdtAndWait(runnable); - } - - private void defaultRunBare() throws Throwable { - Throwable exception = null; - try { - long setupStart = System.nanoTime(); - setUp(); - long setupCost = (System.nanoTime() - setupStart) / 1000000; - logPerClassCost(setupCost, TOTAL_SETUP_COST_MILLIS); - - runTest(); - TestLoggerFactory.onTestFinished(true); - } - catch (Throwable running) { - TestLoggerFactory.onTestFinished(false); - exception = running; - } - finally { - try { - long teardownStart = System.nanoTime(); - tearDown(); - long teardownCost = (System.nanoTime() - teardownStart) / 1000000; - logPerClassCost(teardownCost, TOTAL_TEARDOWN_COST_MILLIS); - } - catch (Throwable tearingDown) { - if (exception == null) exception = tearingDown; - } - } - if (exception != null) throw exception; - } - - /** - * Logs the setup cost grouped by test fixture class (superclass of the current test class). - * - * @param cost setup cost in milliseconds - */ - private void logPerClassCost(long cost, Map costMap) { - Class superclass = getClass().getSuperclass(); - Long oldCost = costMap.get(superclass.getName()); - long newCost = oldCost == null ? cost : oldCost + cost; - costMap.put(superclass.getName(), newCost); - } - - @Override - public void runBare() throws Throwable { - this.defaultRunBare(); - } - - @NonNls - public static String toString(Iterable collection) { - if (!collection.iterator().hasNext()) { - return ""; - } - - StringBuilder builder = new StringBuilder(); - for (Object o : collection) { - if (o instanceof THashSet) { - builder.append(new TreeSet((THashSet)o)); - } - else { - builder.append(o); - } - builder.append("\n"); - } - return builder.toString(); - } - - private static void assertOrderedEquals(String errorMsg, @NotNull Iterable actual, @NotNull T... expected) { - Assert.assertNotNull(actual); - Assert.assertNotNull(expected); - assertOrderedEquals(errorMsg, actual, Arrays.asList(expected)); - } - - public static void assertOrderedEquals( - String erroMsg, - Iterable actual, - Collection expected) { - ArrayList list = new ArrayList<>(); - for (T t : actual) { - list.add(t); - } - if (!list.equals(new ArrayList(expected))) { - String expectedString = toString(expected); - String actualString = toString(actual); - Assert.assertEquals(erroMsg, expectedString, actualString); - Assert.fail("Warning! 'toString' does not reflect the difference.\nExpected: " + expectedString + "\nActual: " + actualString); - } - } - - public static void assertSameElements(T[] collection, T... expected) { - assertSameElements(Arrays.asList(collection), expected); - } - - public static void assertSameElements(Collection collection, T... expected) { - assertSameElements(collection, Arrays.asList(expected)); - } - - public static void assertSameElements(Collection collection, Collection expected) { - assertSameElements(null, collection, expected); - } - - public static void assertSameElements(String message, Collection collection, Collection expected) { - assertNotNull(collection); - assertNotNull(expected); - if (collection.size() != expected.size() || !new HashSet<>(expected).equals(new HashSet(collection))) { - Assert.assertEquals(message, toString(expected, "\n"), toString(collection, "\n")); - Assert.assertEquals(message, new HashSet<>(expected), new HashSet(collection)); - } - } - - public static String toString(Object[] collection, String separator) { - return toString(Arrays.asList(collection), separator); - } - - public static String toString(Collection collection, String separator) { - List list = ContainerUtil.map2List(collection, String::valueOf); - Collections.sort(list); - StringBuilder builder = new StringBuilder(); - boolean flag = false; - for (String o : list) { - if (flag) { - builder.append(separator); - } - builder.append(o); - flag = true; - } - return builder.toString(); - } - - @Contract("null, _ -> fail") - public static T assertInstanceOf(Object o, Class aClass) { - Assert.assertNotNull("Expected instance of: " + aClass.getName() + " actual: " + null, o); - Assert.assertTrue("Expected instance of: " + aClass.getName() + " actual: " + o.getClass().getName(), aClass.isInstance(o)); - @SuppressWarnings("unchecked") T t = (T)o; - return t; - } - - protected static void assertEmpty(String errorMsg, Collection collection) { - //noinspection unchecked - assertOrderedEquals(errorMsg, collection); - } - - protected static void assertSize(int expectedSize, Object[] array) { - assertEquals(toString(Arrays.asList(array)), expectedSize, array.length); - } - - public static void assertSameLines(String expected, String actual) { - String expectedText = StringUtil.convertLineSeparators(expected.trim()); - String actualText = StringUtil.convertLineSeparators(actual.trim()); - Assert.assertEquals(expectedText, actualText); - } - - protected String getTestName(boolean lowercaseFirstLetter) { - return getTestName(getName(), lowercaseFirstLetter); - } - - public static String getTestName(String name, boolean lowercaseFirstLetter) { - return name == null ? "" : KtPlatformTestUtil.getTestName(name, lowercaseFirstLetter); - } - - /** @deprecated use {@link KtPlatformTestUtil#lowercaseFirstLetter(String, boolean)} (to be removed in IDEA 17) */ - @SuppressWarnings("unused") - public static String lowercaseFirstLetter(String name, boolean lowercaseFirstLetter) { - return KtPlatformTestUtil.lowercaseFirstLetter(name, lowercaseFirstLetter); - } - - /** @deprecated use {@link KtPlatformTestUtil#isAllUppercaseName(String)} (to be removed in IDEA 17) */ - @SuppressWarnings("unused") - public static boolean isAllUppercaseName(String name) { - return KtPlatformTestUtil.isAllUppercaseName(name); - } - - public static void assertSameLinesWithFile(String filePath, String actualText) { - assertSameLinesWithFile(filePath, actualText, true); - } - - public static void assertSameLinesWithFile(String filePath, String actualText, boolean trimBeforeComparing) { - String fileText; - try { - fileText = FileUtil.loadFile(new File(filePath), CharsetToolkit.UTF8_CHARSET); - } - catch (FileNotFoundException e) { - VfsTestUtil.overwriteTestData(filePath, actualText); - throw new AssertionFailedError("No output text found. File " + filePath + " created."); - } - catch (IOException e) { - throw new RuntimeException(e); - } - String expected = StringUtil.convertLineSeparators(trimBeforeComparing ? fileText.trim() : fileText); - String actual = StringUtil.convertLineSeparators(trimBeforeComparing ? actualText.trim() : actualText); - if (!Comparing.equal(expected, actual)) { - throw new FileComparisonFailure(null, expected, actual, filePath); - } - } - - public static void clearFields(Object test) throws IllegalAccessException { - Class aClass = test.getClass(); - while (aClass != null) { - clearDeclaredFields(test, aClass); - aClass = aClass.getSuperclass(); - } - } - - private static void clearDeclaredFields(Object test, Class aClass) throws IllegalAccessException { - if (aClass == null) return; - for (Field field : aClass.getDeclaredFields()) { - @NonNls String name = field.getDeclaringClass().getName(); - if (!name.startsWith("junit.framework.") && !name.startsWith("com.intellij.testFramework.")) { - int modifiers = field.getModifiers(); - if ((modifiers & Modifier.FINAL) == 0 && (modifiers & Modifier.STATIC) == 0 && !field.getType().isPrimitive()) { - field.setAccessible(true); - field.set(test, null); - } - } - } - } - - private static boolean isPerformanceTest(@Nullable String testName, @Nullable String className) { - return testName != null && testName.contains("Performance") || - className != null && className.contains("Performance"); - } - - /** - * @return true for a test which performs A LOT of computations. - * Such test should typically avoid performing expensive checks, e.g. data structure consistency complex validations. - * If you want your test to be treated as "Stress", please mention one of these words in its name: "Stress", "Slow". - * For example: {@code public void testStressPSIFromDifferentThreads()} - */ - - private boolean isStressTest() { - return isStressTest(getName(), getClass().getName()); - } - - private static boolean isStressTest(String testName, String className) { - return isPerformanceTest(testName, className) || - containsStressWords(testName) || - containsStressWords(className); - } - - private static boolean containsStressWords(@Nullable String name) { - return name != null && (name.contains("Stress") || name.contains("Slow")); - } - - - public class TestDisposable implements Disposable { - @Override - public void dispose() { - } - - @Override - public String toString() { - String testName = getTestName(false); - return KtUsefulTestCase.this.getClass() + (StringUtil.isEmpty(testName) ? "" : ".test" + testName); - } - }; -} \ No newline at end of file diff --git a/compiler/tests-common/tests/org/jetbrains/kotlin/test/testFramework/mock/MockFileManager.java.172 b/compiler/tests-common/tests/org/jetbrains/kotlin/test/testFramework/mock/MockFileManager.java.172 deleted file mode 100644 index 3156769b134..00000000000 --- a/compiler/tests-common/tests/org/jetbrains/kotlin/test/testFramework/mock/MockFileManager.java.172 +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.kotlin.test.testFramework.mock; - -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.psi.FileViewProvider; -import com.intellij.psi.PsiDirectory; -import com.intellij.psi.PsiFile; -import com.intellij.psi.SingleRootFileViewProvider; -import com.intellij.psi.impl.PsiManagerEx; -import com.intellij.psi.impl.file.impl.FileManager; -import com.intellij.util.containers.ConcurrentWeakFactoryMap; -import com.intellij.util.containers.ContainerUtil; -import com.intellij.util.containers.FactoryMap; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.List; -import java.util.Map; - -public class MockFileManager implements FileManager { - private final PsiManagerEx myManager; - // in mock tests it's LightVirtualFile, they're only alive when they're referenced, - // and there can not be several instances representing the same file - private final FactoryMap myViewProviders = new ConcurrentWeakFactoryMap() { - @Override - protected Map createMap() { - return ContainerUtil.createConcurrentWeakKeyWeakValueMap(); - } - - @Override - protected FileViewProvider create(VirtualFile key) { - return new SingleRootFileViewProvider(myManager, key); - } - }; - - @Override - @NotNull - public FileViewProvider createFileViewProvider(@NotNull VirtualFile file, boolean eventSystemEnabled) { - return new SingleRootFileViewProvider(myManager, file, eventSystemEnabled); - } - - public MockFileManager(PsiManagerEx manager) { - myManager = manager; - } - - @Override - public void dispose() { - throw new UnsupportedOperationException("Method dispose is not yet implemented in " + getClass().getName()); - } - - @Override - @Nullable - public PsiFile findFile(@NotNull VirtualFile vFile) { - return getCachedPsiFile(vFile); - } - - @Override - @Nullable - public PsiDirectory findDirectory(@NotNull VirtualFile vFile) { - throw new UnsupportedOperationException("Method findDirectory is not yet implemented in " + getClass().getName()); - } - - @Override - public void reloadFromDisk(@NotNull PsiFile file) //Q: move to PsiFile(Impl)? - { - throw new UnsupportedOperationException("Method reloadFromDisk is not yet implemented in " + getClass().getName()); - } - - @Override - @Nullable - public PsiFile getCachedPsiFile(@NotNull VirtualFile vFile) { - FileViewProvider provider = findCachedViewProvider(vFile); - return provider.getPsi(provider.getBaseLanguage()); - } - - @Override - public void cleanupForNextTest() { - myViewProviders.clear(); - } - - @Override - public FileViewProvider findViewProvider(@NotNull VirtualFile file) { - throw new UnsupportedOperationException("Method findViewProvider is not yet implemented in " + getClass().getName()); - } - - @Override - public FileViewProvider findCachedViewProvider(@NotNull VirtualFile file) { - return myViewProviders.get(file); - } - - @Override - public void setViewProvider(@NotNull VirtualFile virtualFile, FileViewProvider fileViewProvider) { - myViewProviders.put(virtualFile, fileViewProvider); - } - - @Override - @NotNull - public List getAllCachedFiles() { - throw new UnsupportedOperationException("Method getAllCachedFiles is not yet implemented in " + getClass().getName()); - } -} diff --git a/generators/tests/org/jetbrains/kotlin/generators/tests/GenerateTests.kt.172 b/generators/tests/org/jetbrains/kotlin/generators/tests/GenerateTests.kt.172 deleted file mode 100644 index a9d60ea0823..00000000000 --- a/generators/tests/org/jetbrains/kotlin/generators/tests/GenerateTests.kt.172 +++ /dev/null @@ -1,1141 +0,0 @@ -/* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.kotlin.generators.tests - -import org.jetbrains.kotlin.AbstractDataFlowValueRenderingTest -import org.jetbrains.kotlin.addImport.AbstractAddImportTest -import org.jetbrains.kotlin.allopen.AbstractBytecodeListingTestForAllOpen -import org.jetbrains.kotlin.android.* -import org.jetbrains.kotlin.android.annotator.AbstractAndroidGutterIconTest -import org.jetbrains.kotlin.android.configure.AbstractConfigureProjectTest -import org.jetbrains.kotlin.android.folding.AbstractAndroidResourceFoldingTest -import org.jetbrains.kotlin.android.intention.AbstractAndroidIntentionTest -import org.jetbrains.kotlin.android.intention.AbstractAndroidResourceIntentionTest -import org.jetbrains.kotlin.android.lint.AbstractKotlinLintTest -import org.jetbrains.kotlin.android.parcel.AbstractParcelBytecodeListingTest -import org.jetbrains.kotlin.android.quickfix.AbstractAndroidLintQuickfixTest -import org.jetbrains.kotlin.android.quickfix.AbstractAndroidQuickFixMultiFileTest -import org.jetbrains.kotlin.android.synthetic.test.AbstractAndroidBoxTest -import org.jetbrains.kotlin.android.synthetic.test.AbstractAndroidBytecodeShapeTest -import org.jetbrains.kotlin.android.synthetic.test.AbstractAndroidSyntheticPropertyDescriptorTest -import org.jetbrains.kotlin.checkers.AbstractJavaAgainstKotlinBinariesCheckerTest -import org.jetbrains.kotlin.checkers.AbstractJavaAgainstKotlinSourceCheckerTest -import org.jetbrains.kotlin.checkers.AbstractJsCheckerTest -import org.jetbrains.kotlin.checkers.AbstractPsiCheckerTest -import org.jetbrains.kotlin.findUsages.AbstractFindUsagesTest -import org.jetbrains.kotlin.findUsages.AbstractKotlinFindUsagesWithLibraryTest -import org.jetbrains.kotlin.formatter.AbstractFormatterTest -import org.jetbrains.kotlin.formatter.AbstractTypingIndentationTestBase -import org.jetbrains.kotlin.generators.tests.generator.TestGroup -import org.jetbrains.kotlin.generators.tests.generator.testGroup -import org.jetbrains.kotlin.generators.util.KT_OR_KTS -import org.jetbrains.kotlin.generators.util.KT_OR_KTS_WITHOUT_DOTS_IN_NAME -import org.jetbrains.kotlin.generators.util.KT_WITHOUT_DOTS_IN_NAME -import org.jetbrains.kotlin.idea.AbstractExpressionSelectionTest -import org.jetbrains.kotlin.idea.AbstractKotlinTypeAliasByExpansionShortNameIndexTest -import org.jetbrains.kotlin.idea.AbstractSmartSelectionTest -import org.jetbrains.kotlin.idea.actions.AbstractGotoTestOrCodeActionTest -import org.jetbrains.kotlin.idea.caches.resolve.AbstractIdeCompiledLightClassTest -import org.jetbrains.kotlin.idea.caches.resolve.AbstractIdeLightClassTest -import org.jetbrains.kotlin.idea.caches.resolve.AbstractMultiModuleLineMarkerTest -import org.jetbrains.kotlin.idea.caches.resolve.AbstractMultiPlatformHighlightingTest -import org.jetbrains.kotlin.idea.codeInsight.* -import org.jetbrains.kotlin.idea.codeInsight.generate.AbstractCodeInsightActionTest -import org.jetbrains.kotlin.idea.codeInsight.generate.AbstractGenerateHashCodeAndEqualsActionTest -import org.jetbrains.kotlin.idea.codeInsight.generate.AbstractGenerateTestSupportMethodActionTest -import org.jetbrains.kotlin.idea.codeInsight.generate.AbstractGenerateToStringActionTest -import org.jetbrains.kotlin.idea.codeInsight.moveUpDown.AbstractMoveLeftRightTest -import org.jetbrains.kotlin.idea.codeInsight.moveUpDown.AbstractMoveStatementTest -import org.jetbrains.kotlin.idea.codeInsight.postfix.AbstractPostfixTemplateProviderTest -import org.jetbrains.kotlin.idea.codeInsight.surroundWith.AbstractSurroundWithTest -import org.jetbrains.kotlin.idea.codeInsight.unwrap.AbstractUnwrapRemoveTest -import org.jetbrains.kotlin.idea.completion.test.* -import org.jetbrains.kotlin.idea.completion.test.handlers.AbstractBasicCompletionHandlerTest -import org.jetbrains.kotlin.idea.completion.test.handlers.AbstractCompletionCharFilterTest -import org.jetbrains.kotlin.idea.completion.test.handlers.AbstractKeywordCompletionHandlerTest -import org.jetbrains.kotlin.idea.completion.test.handlers.AbstractSmartCompletionHandlerTest -import org.jetbrains.kotlin.idea.completion.test.weighers.AbstractBasicCompletionWeigherTest -import org.jetbrains.kotlin.idea.completion.test.weighers.AbstractSmartCompletionWeigherTest -import org.jetbrains.kotlin.idea.configuration.AbstractGradleConfigureProjectByChangingFileTest -import org.jetbrains.kotlin.idea.conversion.copy.AbstractJavaToKotlinCopyPasteConversionTest -import org.jetbrains.kotlin.idea.conversion.copy.AbstractLiteralKotlinToKotlinCopyPasteTest -import org.jetbrains.kotlin.idea.conversion.copy.AbstractLiteralTextToKotlinCopyPasteTest -import org.jetbrains.kotlin.idea.conversion.copy.AbstractTextJavaToKotlinCopyPasteConversionTest -import org.jetbrains.kotlin.idea.coverage.AbstractKotlinCoverageOutputFilesTest -import org.jetbrains.kotlin.idea.debugger.AbstractBeforeExtractFunctionInsertionTest -import org.jetbrains.kotlin.idea.debugger.AbstractKotlinSteppingTest -import org.jetbrains.kotlin.idea.debugger.AbstractPositionManagerTest -import org.jetbrains.kotlin.idea.debugger.AbstractSmartStepIntoTest -import org.jetbrains.kotlin.idea.debugger.evaluate.* -import org.jetbrains.kotlin.idea.decompiler.navigation.AbstractNavigateToDecompiledLibraryTest -import org.jetbrains.kotlin.idea.decompiler.navigation.AbstractNavigateToLibrarySourceTest -import org.jetbrains.kotlin.idea.decompiler.stubBuilder.AbstractClsStubBuilderTest -import org.jetbrains.kotlin.idea.decompiler.stubBuilder.AbstractLoadJavaClsStubTest -import org.jetbrains.kotlin.idea.decompiler.textBuilder.AbstractCommonDecompiledTextFromJsMetadataTest -import org.jetbrains.kotlin.idea.decompiler.textBuilder.AbstractCommonDecompiledTextTest -import org.jetbrains.kotlin.idea.decompiler.textBuilder.AbstractJsDecompiledTextFromJsMetadataTest -import org.jetbrains.kotlin.idea.decompiler.textBuilder.AbstractJvmDecompiledTextTest -import org.jetbrains.kotlin.idea.editor.AbstractMultiLineStringIndentTest -import org.jetbrains.kotlin.idea.editor.backspaceHandler.AbstractBackspaceHandlerTest -import org.jetbrains.kotlin.idea.editor.quickDoc.AbstractQuickDocProviderTest -import org.jetbrains.kotlin.idea.filters.AbstractKotlinExceptionFilterTest -import org.jetbrains.kotlin.idea.folding.AbstractKotlinFoldingTest -import org.jetbrains.kotlin.idea.hierarchy.AbstractHierarchyTest -import org.jetbrains.kotlin.idea.hierarchy.AbstractHierarchyWithLibTest -import org.jetbrains.kotlin.idea.highlighter.* -import org.jetbrains.kotlin.idea.imports.AbstractJsOptimizeImportsTest -import org.jetbrains.kotlin.idea.imports.AbstractJvmOptimizeImportsTest -import org.jetbrains.kotlin.idea.inspections.AbstractLocalInspectionTest -import org.jetbrains.kotlin.idea.inspections.AbstractMultiFileLocalInspectionTest -import org.jetbrains.kotlin.idea.intentions.AbstractConcatenatedStringGeneratorTest -import org.jetbrains.kotlin.idea.intentions.AbstractIntentionTest -import org.jetbrains.kotlin.idea.intentions.AbstractIntentionTest2 -import org.jetbrains.kotlin.idea.intentions.AbstractMultiFileIntentionTest -import org.jetbrains.kotlin.idea.intentions.declarations.AbstractJoinLinesTest -import org.jetbrains.kotlin.idea.internal.AbstractBytecodeToolWindowTest -import org.jetbrains.kotlin.idea.kdoc.AbstractKDocHighlightingTest -import org.jetbrains.kotlin.idea.kdoc.AbstractKDocTypingTest -import org.jetbrains.kotlin.idea.maven.AbstractKotlinMavenInspectionTest -import org.jetbrains.kotlin.idea.maven.configuration.AbstractMavenConfigureProjectByChangingFileTest -import org.jetbrains.kotlin.idea.navigation.* -import org.jetbrains.kotlin.idea.parameterInfo.AbstractParameterInfoTest -import org.jetbrains.kotlin.idea.quickfix.AbstractQuickFixMultiFileTest -import org.jetbrains.kotlin.idea.quickfix.AbstractQuickFixMultiModuleTest -import org.jetbrains.kotlin.idea.quickfix.AbstractQuickFixTest -import org.jetbrains.kotlin.idea.refactoring.AbstractNameSuggestionProviderTest -import org.jetbrains.kotlin.idea.refactoring.copy.AbstractCopyTest -import org.jetbrains.kotlin.idea.refactoring.copy.AbstractMultiModuleCopyTest -import org.jetbrains.kotlin.idea.refactoring.inline.AbstractInlineTest -import org.jetbrains.kotlin.idea.refactoring.introduce.AbstractExtractionTest -import org.jetbrains.kotlin.idea.refactoring.move.AbstractMoveTest -import org.jetbrains.kotlin.idea.refactoring.move.AbstractMultiModuleMoveTest -import org.jetbrains.kotlin.idea.refactoring.pullUp.AbstractPullUpTest -import org.jetbrains.kotlin.idea.refactoring.pushDown.AbstractPushDownTest -import org.jetbrains.kotlin.idea.refactoring.rename.AbstractMultiModuleRenameTest -import org.jetbrains.kotlin.idea.refactoring.rename.AbstractRenameTest -import org.jetbrains.kotlin.idea.refactoring.safeDelete.AbstractMultiModuleSafeDeleteTest -import org.jetbrains.kotlin.idea.refactoring.safeDelete.AbstractSafeDeleteTest -import org.jetbrains.kotlin.idea.repl.AbstractIdeReplCompletionTest -import org.jetbrains.kotlin.idea.resolve.* -import org.jetbrains.kotlin.idea.scratch.AbstractScratchRunActionTest -import org.jetbrains.kotlin.idea.script.AbstractScriptConfigurationCompletionTest -import org.jetbrains.kotlin.idea.script.AbstractScriptConfigurationHighlightingTest -import org.jetbrains.kotlin.idea.script.AbstractScriptConfigurationNavigationTest -import org.jetbrains.kotlin.idea.slicer.AbstractSlicerTest -import org.jetbrains.kotlin.idea.structureView.AbstractKotlinFileStructureTest -import org.jetbrains.kotlin.idea.stubs.AbstractMultiFileHighlightingTest -import org.jetbrains.kotlin.idea.stubs.AbstractResolveByStubTest -import org.jetbrains.kotlin.idea.stubs.AbstractStubBuilderTest -import org.jetbrains.kotlin.incremental.* -import org.jetbrains.kotlin.j2k.AbstractJavaToKotlinConverterForWebDemoTest -import org.jetbrains.kotlin.j2k.AbstractJavaToKotlinConverterMultiFileTest -import org.jetbrains.kotlin.j2k.AbstractJavaToKotlinConverterSingleFileTest -import org.jetbrains.kotlin.jps.build.* -import org.jetbrains.kotlin.jps.build.android.AbstractAndroidJpsTestCase -import org.jetbrains.kotlin.jps.build.dependeciestxt.actualizeMppJpsIncTestCaseDirs -import org.jetbrains.kotlin.jps.incremental.AbstractJsProtoComparisonTest -import org.jetbrains.kotlin.jps.incremental.AbstractJvmProtoComparisonTest -import org.jetbrains.kotlin.kapt3.test.AbstractClassFileToSourceStubConverterTest -import org.jetbrains.kotlin.kapt3.test.AbstractKotlinKaptContextTest -import org.jetbrains.kotlin.noarg.AbstractBlackBoxCodegenTestForNoArg -import org.jetbrains.kotlin.noarg.AbstractBytecodeListingTestForNoArg -import org.jetbrains.kotlin.psi.patternMatching.AbstractPsiUnifierTest -import org.jetbrains.kotlin.samWithReceiver.AbstractSamWithReceiverScriptTest -import org.jetbrains.kotlin.samWithReceiver.AbstractSamWithReceiverTest -import org.jetbrains.kotlin.search.AbstractAnnotatedMembersSearchTest -import org.jetbrains.kotlin.search.AbstractInheritorsSearchTest -import org.jetbrains.kotlin.shortenRefs.AbstractShortenRefsTest -import org.jetbrains.kotlin.test.TargetBackend - -fun main(args: Array) { - System.setProperty("java.awt.headless", "true") - - testGroup("idea/tests", "idea/testData") { - testClass { - model("resolve/additionalLazyResolve") - } - - testClass { - model("resolve/partialBodyResolve") - } - - testClass { - model("checker", recursive = false) - model("checker/regression") - model("checker/recovery") - model("checker/rendering") - model("checker/scripts", extension = "kts") - model("checker/duplicateJvmSignature") - model("checker/infos", testMethod = "doTestWithInfos") - model("checker/diagnosticsMessage") - } - - testClass { - model("kotlinAndJavaChecker/javaAgainstKotlin") - model("kotlinAndJavaChecker/javaWithKotlin") - } - - testClass { - model("kotlinAndJavaChecker/javaAgainstKotlin") - } - - testClass { - model("unifier") - } - - testClass { - model("checker/codeFragments", extension = "kt", recursive = false) - model("checker/codeFragments/imports", testMethod = "doTestWithImport", extension = "kt") - } - - testClass { - model("quickfix.special/codeFragmentAutoImport", extension = "kt", recursive = false) - } - - testClass { - model("checker/js") - } - - testClass { - model("quickfix", pattern = "^([\\w\\-_]+)\\.kt$", filenameStartsLowerCase = true) - } - - testClass { - model("navigation/gotoSuper", extension = "test", recursive = false) - } - - testClass { - model("navigation/gotoTypeDeclaration", extension = "test") - } - - testClass { - model("navigation/gotoDeclaration", extension = "test") - } - - testClass { - model("parameterInfo", recursive = true, excludeDirs = listOf("withLib1/sharedLib", "withLib2/sharedLib", "withLib3/sharedLib")) - } - - testClass { - model("navigation/gotoClass", testMethod = "doClassTest") - model("navigation/gotoSymbol", testMethod = "doSymbolTest") - } - - testClass { - model("decompiler/navigation/usercode") - model("decompiler/navigation/usercode", testClassName ="UsercodeWithJSModule", testMethod = "doWithJSModuleTest") - } - - testClass { - model("decompiler/navigation/usercode") - } - - testClass { - model("navigation/implementations", recursive = false) - } - - testClass { - model("navigation/gotoTestOrCode", pattern = "^(.+)\\.main\\..+\$") - } - - testClass { - model("search/inheritance") - } - - testClass { - model("search/annotations") - } - - testClass { - model("quickfix", pattern = """^(\w+)\.((before\.Main\.\w+)|(test))$""", testMethod = "doTestWithExtraFile") - } - - testClass { - model("typealiasExpansionIndex") - } - - testClass { - model("highlighter") - } - - testClass { - model("dslHighlighter") - } - - testClass { - model("usageHighlighter") - } - - testClass { - model("folding/noCollapse") - model("folding/checkCollapse", testMethod = "doSettingsFoldingTest") - } - - testClass { - model("codeInsight/surroundWith/if", testMethod = "doTestWithIfSurrounder") - model("codeInsight/surroundWith/ifElse", testMethod = "doTestWithIfElseSurrounder") - model("codeInsight/surroundWith/ifElseExpression", testMethod = "doTestWithIfElseExpressionSurrounder") - model("codeInsight/surroundWith/ifElseExpressionBraces", testMethod = "doTestWithIfElseExpressionBracesSurrounder") - model("codeInsight/surroundWith/not", testMethod = "doTestWithNotSurrounder") - model("codeInsight/surroundWith/parentheses", testMethod = "doTestWithParenthesesSurrounder") - model("codeInsight/surroundWith/stringTemplate", testMethod = "doTestWithStringTemplateSurrounder") - model("codeInsight/surroundWith/when", testMethod = "doTestWithWhenSurrounder") - model("codeInsight/surroundWith/tryCatch", testMethod = "doTestWithTryCatchSurrounder") - model("codeInsight/surroundWith/tryCatchExpression", testMethod = "doTestWithTryCatchExpressionSurrounder") - model("codeInsight/surroundWith/tryCatchFinally", testMethod = "doTestWithTryCatchFinallySurrounder") - model("codeInsight/surroundWith/tryCatchFinallyExpression", testMethod = "doTestWithTryCatchFinallyExpressionSurrounder") - model("codeInsight/surroundWith/tryFinally", testMethod = "doTestWithTryFinallySurrounder") - model("codeInsight/surroundWith/functionLiteral", testMethod = "doTestWithFunctionLiteralSurrounder") - model("codeInsight/surroundWith/withIfExpression", testMethod = "doTestWithSurroundWithIfExpression") - model("codeInsight/surroundWith/withIfElseExpression", testMethod = "doTestWithSurroundWithIfElseExpression") - } - - testClass { - model("joinLines") - } - - testClass { - model("codeInsight/breadcrumbs") - } - - testClass { - model("intentions", pattern = "^([\\w\\-_]+)\\.(kt|kts)$") - } - - testClass { - model("intentions/loopToCallChain", pattern = "^([\\w\\-_]+)\\.kt$") - } - - testClass { - model("concatenatedStringGenerator", pattern = "^([\\w\\-_]+)\\.kt$") - } - - testClass { - model("intentions", pattern = "^(inspections\\.test)$", singleClass = true) - model("inspections", pattern = "^(inspections\\.test)$", singleClass = true) - model("inspectionsLocal", pattern = "^(inspections\\.test)$", singleClass = true) - } - - testClass { - model("inspectionsLocal", pattern = "^([\\w\\-_]+)\\.(kt|kts)$") - } - - testClass { - model("hierarchy/class/type", extension = null, recursive = false, testMethod = "doTypeClassHierarchyTest") - model("hierarchy/class/super", extension = null, recursive = false, testMethod = "doSuperClassHierarchyTest") - model("hierarchy/class/sub", extension = null, recursive = false, testMethod = "doSubClassHierarchyTest") - model("hierarchy/calls/callers", extension = null, recursive = false, testMethod = "doCallerHierarchyTest") - model("hierarchy/calls/callersJava", extension = null, recursive = false, testMethod = "doCallerJavaHierarchyTest") - model("hierarchy/calls/callees", extension = null, recursive = false, testMethod = "doCalleeHierarchyTest") - model("hierarchy/overrides", extension = null, recursive = false, testMethod = "doOverrideHierarchyTest") - } - - testClass { - model("hierarchy/withLib", extension = null, recursive = false) - } - - testClass { - model("codeInsight/moveUpDown/classBodyDeclarations", pattern = KT_OR_KTS, testMethod = "doTestClassBodyDeclaration") - model("codeInsight/moveUpDown/closingBraces", testMethod = "doTestExpression") - model("codeInsight/moveUpDown/expressions", pattern = KT_OR_KTS, testMethod = "doTestExpression") - model("codeInsight/moveUpDown/parametersAndArguments", testMethod = "doTestExpression") - } - - testClass { - model("codeInsight/moveLeftRight") - } - - testClass { - model("refactoring/inline", pattern = "^(\\w+)\\.kt$") - } - - testClass { - model("codeInsight/unwrapAndRemove/removeExpression", testMethod = "doTestExpressionRemover") - model("codeInsight/unwrapAndRemove/unwrapThen", testMethod = "doTestThenUnwrapper") - model("codeInsight/unwrapAndRemove/unwrapElse", testMethod = "doTestElseUnwrapper") - model("codeInsight/unwrapAndRemove/removeElse", testMethod = "doTestElseRemover") - model("codeInsight/unwrapAndRemove/unwrapLoop", testMethod = "doTestLoopUnwrapper") - model("codeInsight/unwrapAndRemove/unwrapTry", testMethod = "doTestTryUnwrapper") - model("codeInsight/unwrapAndRemove/unwrapCatch", testMethod = "doTestCatchUnwrapper") - model("codeInsight/unwrapAndRemove/removeCatch", testMethod = "doTestCatchRemover") - model("codeInsight/unwrapAndRemove/unwrapFinally", testMethod = "doTestFinallyUnwrapper") - model("codeInsight/unwrapAndRemove/removeFinally", testMethod = "doTestFinallyRemover") - model("codeInsight/unwrapAndRemove/unwrapLambda", testMethod = "doTestLambdaUnwrapper") - model("codeInsight/unwrapAndRemove/unwrapFunctionParameter", testMethod = "doTestFunctionParameterUnwrapper") - } - - testClass { - model("codeInsight/expressionType") - } - - testClass { - model("editor/backspaceHandler") - } - - testClass { - model("editor/enterHandler/multilineString") - } - - testClass { - model("editor/quickDoc", pattern = """^([^_]+)\.(kt|java)$""") - } - - testClass { - model("refactoring/safeDelete/deleteClass/kotlinClass", testMethod = "doClassTest") - model("refactoring/safeDelete/deleteClass/kotlinClassWithJava", testMethod = "doClassTestWithJava") - model("refactoring/safeDelete/deleteClass/javaClassWithKotlin", extension = "java", testMethod = "doJavaClassTest") - model("refactoring/safeDelete/deleteObject/kotlinObject", testMethod = "doObjectTest") - model("refactoring/safeDelete/deleteFunction/kotlinFunction", testMethod = "doFunctionTest") - model("refactoring/safeDelete/deleteFunction/kotlinFunctionWithJava", testMethod = "doFunctionTestWithJava") - model("refactoring/safeDelete/deleteFunction/javaFunctionWithKotlin", testMethod = "doJavaMethodTest") - model("refactoring/safeDelete/deleteProperty/kotlinProperty", testMethod = "doPropertyTest") - model("refactoring/safeDelete/deleteProperty/kotlinPropertyWithJava", testMethod = "doPropertyTestWithJava") - model("refactoring/safeDelete/deleteProperty/javaPropertyWithKotlin", testMethod = "doJavaPropertyTest") - model("refactoring/safeDelete/deleteTypeAlias/kotlinTypeAlias", testMethod = "doTypeAliasTest") - model("refactoring/safeDelete/deleteTypeParameter/kotlinTypeParameter", testMethod = "doTypeParameterTest") - model("refactoring/safeDelete/deleteTypeParameter/kotlinTypeParameterWithJava", testMethod = "doTypeParameterTestWithJava") - model("refactoring/safeDelete/deleteValueParameter/kotlinValueParameter", testMethod = "doValueParameterTest") - model("refactoring/safeDelete/deleteValueParameter/kotlinValueParameterWithJava", testMethod = "doValueParameterTestWithJava") - } - - testClass { - model("resolve/references", pattern = KT_WITHOUT_DOTS_IN_NAME) - } - - testClass { - model("resolve/referenceInJava/binaryAndSource", extension = "java") - model("resolve/referenceInJava/sourceOnly", extension = "java") - } - - testClass { - model("resolve/referenceInJava/binaryAndSource", extension = "java") - } - - testClass { - model("resolve/referenceWithLib", recursive = false) - } - - testClass { - model("resolve/referenceInLib", recursive = false) - } - - testClass { - model("resolve/referenceToJavaWithWrongFileStructure", recursive = false) - } - - testClass { - model("findUsages/kotlin", pattern = """^(.+)\.0\.(kt|kts)$""") - model("findUsages/java", pattern = """^(.+)\.0\.java$""") - model("findUsages/propertyFiles", pattern = """^(.+)\.0\.properties$""") - } - - testClass { - model("findUsages/libraryUsages", pattern = """^(.+)\.0\.kt$""") - } - - testClass { - model("refactoring/move", extension = "test", singleClass = true) - } - - testClass { - model("refactoring/copy", extension = "test", singleClass = true) - } - - testClass { - model("refactoring/moveMultiModule", extension = "test", singleClass = true) - } - - testClass { - model("refactoring/copyMultiModule", extension = "test", singleClass = true) - } - - testClass { - model("refactoring/safeDeleteMultiModule", extension = "test", singleClass = true) - } - - testClass { - model("multiFileIntentions", extension = "test", singleClass = true, filenameStartsLowerCase = true) - } - - testClass { - model("multiFileLocalInspections", extension = "test", singleClass = true, filenameStartsLowerCase = true) - } - - testClass { - model("multiFileInspections", extension = "test", singleClass = true) - } - - testClass { - model("formatter", pattern = """^([^\.]+)\.after\.kt.*$""") - model("formatter", pattern = """^([^\.]+)\.after\.inv\.kt.*$""", - testMethod = "doTestInverted", testClassName = "FormatterInverted") - } - - testClass { - model("indentationOnNewline", pattern = """^([^\.]+)\.after\.kt.*$""", testMethod = "doNewlineTest", - testClassName = "DirectSettings") - model("indentationOnNewline", pattern = """^([^\.]+)\.after\.inv\.kt.*$""", testMethod = "doNewlineTestWithInvert", - testClassName = "InvertedSettings") - } - - testClass { - model("diagnosticMessage", recursive = false) - } - - testClass { - model("diagnosticMessage/js", recursive = false, targetBackend = TargetBackend.JS) - } - - testClass { - model("refactoring/rename", extension = "test", singleClass = true) - } - - testClass { - model("refactoring/renameMultiModule", extension = "test", singleClass = true) - } - - testClass { - model("codeInsight/outOfBlock") - } - - testClass { - model("dataFlowValueRendering") - } - - testClass { - model("copyPaste/conversion", pattern = """^([^\.]+)\.java$""") - } - - testClass { - model("copyPaste/plainTextConversion", pattern = """^([^\.]+)\.txt$""") - } - - testClass { - model("copyPaste/plainTextLiteral", pattern = """^([^\.]+)\.txt$""") - } - - testClass { - model("copyPaste/literal", pattern = """^([^\.]+)\.kt$""") - } - - testClass { - model("copyPaste/imports", pattern = KT_WITHOUT_DOTS_IN_NAME, testMethod = "doTestCopy", testClassName = "Copy", recursive = false) - model("copyPaste/imports", pattern = KT_WITHOUT_DOTS_IN_NAME, testMethod = "doTestCut", testClassName = "Cut", recursive = false) - } - - testClass { - model("copyPaste/moveDeclarations", pattern = KT_WITHOUT_DOTS_IN_NAME, testMethod = "doTest") - } - - testClass { - model("exitPoints") - } - - testClass { - model("codeInsight/lineMarker") - } - - testClass { - model("codeInsightInLibrary/lineMarker", testMethod = "doTestWithLibrary") - } - - testClass { - model("multiModuleLineMarker", extension = null, recursive = false) - } - - testClass { - model("shortenRefs", pattern = KT_WITHOUT_DOTS_IN_NAME) - } - testClass { - model("addImport", pattern = KT_WITHOUT_DOTS_IN_NAME) - } - - testClass { - model("smartSelection", testMethod = "doTestSmartSelection", pattern = KT_WITHOUT_DOTS_IN_NAME) - } - - testClass { - model("structureView/fileStructure", pattern = KT_WITHOUT_DOTS_IN_NAME) - } - - testClass { - model("expressionSelection", testMethod = "doTestExpressionSelection", pattern = KT_WITHOUT_DOTS_IN_NAME) - } - - testClass { - model("decompiler/decompiledText", pattern = """^([^\.]+)$""") - } - - testClass { - model("decompiler/decompiledTextJvm", pattern = """^([^\.]+)$""") - } - - testClass { - model("decompiler/decompiledText", pattern = """^([^\.]+)$""", targetBackend = TargetBackend.JS) - } - - testClass { - model("decompiler/decompiledTextJs", pattern = """^([^\.]+)$""", targetBackend = TargetBackend.JS) - } - - testClass { - model("decompiler/stubBuilder", extension = null, recursive = false) - } - - testClass { - model("editor/optimizeImports/jvm", pattern = KT_WITHOUT_DOTS_IN_NAME) - model("editor/optimizeImports/common", pattern = KT_WITHOUT_DOTS_IN_NAME) - } - testClass { - model("editor/optimizeImports/js", pattern = KT_WITHOUT_DOTS_IN_NAME) - model("editor/optimizeImports/common", pattern = KT_WITHOUT_DOTS_IN_NAME) - } - - testClass { - model("debugger/positionManager", recursive = false, extension = "kt", testClassName = "SingleFile") - model("debugger/positionManager", recursive = false, extension = null, testClassName = "MultiFile") - } - - testClass { - model("debugger/exceptionFilter", pattern = """^([^\.]+)$""", recursive = false) - } - - testClass { - model("debugger/smartStepInto") - } - - testClass { - model("debugger/insertBeforeExtractFunction", extension = "kt") - } - - testClass { - model("debugger/tinyApp/src/stepping/stepIntoAndSmartStepInto", pattern = KT_WITHOUT_DOTS_IN_NAME, testMethod = "doStepIntoTest", testClassName = "StepInto") - model("debugger/tinyApp/src/stepping/stepIntoAndSmartStepInto", pattern = KT_WITHOUT_DOTS_IN_NAME, testMethod = "doSmartStepIntoTest", testClassName = "SmartStepInto") - model("debugger/tinyApp/src/stepping/stepInto", pattern = KT_WITHOUT_DOTS_IN_NAME, testMethod = "doStepIntoTest", testClassName = "StepIntoOnly") - model("debugger/tinyApp/src/stepping/stepOut", pattern = KT_WITHOUT_DOTS_IN_NAME, testMethod = "doStepOutTest") - model("debugger/tinyApp/src/stepping/stepOver", pattern = KT_WITHOUT_DOTS_IN_NAME, testMethod = "doStepOverTest") - model("debugger/tinyApp/src/stepping/stepOverForce", pattern = KT_WITHOUT_DOTS_IN_NAME, testMethod = "doStepOverForceTest") - model("debugger/tinyApp/src/stepping/filters", pattern = KT_WITHOUT_DOTS_IN_NAME, testMethod = "doStepIntoTest") - model("debugger/tinyApp/src/stepping/custom", pattern = KT_WITHOUT_DOTS_IN_NAME, testMethod = "doCustomTest") - } - - testClass { - model("debugger/tinyApp/src/evaluate/singleBreakpoint", testMethod = "doSingleBreakpointTest") - model("debugger/tinyApp/src/evaluate/multipleBreakpoints", testMethod = "doMultipleBreakpointsTest") - } - - testClass { - model("stubs", extension = "kt") - } - - testClass { - model("multiFileHighlighting", recursive = false) - } - - testClass { - model("multiModuleHighlighting/multiplatform/", recursive = false, extension = null) - } - - testClass { - model("multiModuleQuickFix", recursive = false, extension = null) - } - - testClass { - model("navigation/implementations/multiModule", recursive = false, extension = null) - } - - testClass { - model("navigation/relatedSymbols/multiModule", recursive = false, extension = null) - } - - testClass { - model("navigation/gotoSuper/multiModule", recursive = false, extension = null) - } - - testClass { - model("refactoring/introduceVariable", pattern = KT_OR_KTS, testMethod = "doIntroduceVariableTest") - model("refactoring/extractFunction", pattern = KT_OR_KTS, testMethod = "doExtractFunctionTest") - model("refactoring/introduceProperty", pattern = KT_OR_KTS, testMethod = "doIntroducePropertyTest") - model("refactoring/introduceParameter", pattern = KT_OR_KTS, testMethod = "doIntroduceSimpleParameterTest") - model("refactoring/introduceLambdaParameter", pattern = KT_OR_KTS, testMethod = "doIntroduceLambdaParameterTest") - model("refactoring/introduceJavaParameter", extension = "java", testMethod = "doIntroduceJavaParameterTest") - model("refactoring/introduceTypeParameter", pattern = KT_OR_KTS, testMethod = "doIntroduceTypeParameterTest") - model("refactoring/introduceTypeAlias", pattern = KT_OR_KTS, testMethod = "doIntroduceTypeAliasTest") - model("refactoring/extractSuperclass", pattern = KT_OR_KTS_WITHOUT_DOTS_IN_NAME, testMethod = "doExtractSuperclassTest") - model("refactoring/extractInterface", pattern = KT_OR_KTS_WITHOUT_DOTS_IN_NAME, testMethod = "doExtractInterfaceTest") - } - - testClass { - model("refactoring/pullUp/k2k", extension = "kt", singleClass = true, testClassName = "K2K", testMethod = "doKotlinTest") - model("refactoring/pullUp/k2j", extension = "kt", singleClass = true, testClassName = "K2J", testMethod = "doKotlinTest") - model("refactoring/pullUp/j2k", extension = "java", singleClass = true, testClassName = "J2K", testMethod = "doJavaTest") - } - - testClass { - model("refactoring/pushDown/k2k", extension = "kt", singleClass = true, testClassName = "K2K", testMethod = "doKotlinTest") - model("refactoring/pushDown/k2j", extension = "kt", singleClass = true, testClassName = "K2J", testMethod = "doKotlinTest") - model("refactoring/pushDown/j2k", extension = "java", singleClass = true, testClassName = "J2K", testMethod = "doJavaTest") - } - - testClass { - model("debugger/selectExpression", recursive = false) - model("debugger/selectExpression/disallowMethodCalls", testMethod = "doTestWoMethodCalls") - } - - testClass { - model("coverage/outputFiles") - } - - testClass { - model("internal/toolWindow", recursive = false, extension = null) - } - - testClass("org.jetbrains.kotlin.idea.kdoc.KdocResolveTestGenerated") { - model("kdoc/resolve") - } - - testClass { - model("kdoc/highlighting") - } - - testClass { - model("kdoc/typing") - } - - testClass { - model("codeInsight/generate/testFrameworkSupport") - } - - testClass { - model("codeInsight/generate/equalsWithHashCode") - } - - testClass { - model("codeInsight/generate/secondaryConstructors") - } - - testClass { - model("codeInsight/generate/toString") - } - - testClass { - model("repl/completion") - } - - testClass { - model("codeInsight/postfix") - } - - testClass { - model("script/definition/highlighting", extension = null, recursive = false) - model("script/definition/complex", extension = null, recursive = false, testMethod = "doComplexTest") - } - - testClass { - model("script/definition/navigation", extension = null, recursive = false) - } - - testClass { - model("script/definition/completion", extension = null, recursive = false) - } - - testClass { - model("refactoring/nameSuggestionProvider") - } - - testClass { - model("slicer", singleClass = true) - } - - testClass { - model("scratch", extension = "kts", testMethod = "doCompilingTest", testClassName = "Compiling", recursive = false) - model("scratch", extension = "kts", testMethod = "doReplTest", testClassName = "Repl", recursive = false) - model("scratch/multiFile", extension = null, testMethod = "doMultiFileTest", recursive = false) - } - } - - testGroup("idea/idea-maven/test", "idea/idea-maven/testData") { - testClass { - model("configurator/jvm", extension = null, recursive = false, testMethod = "doTestWithMaven") - model("configurator/js", extension = null, recursive = false, testMethod = "doTestWithJSMaven") - } - - testClass { - model("maven-inspections", pattern = "^([\\w\\-]+).xml$", singleClass = true) - } - } - - testGroup("idea/idea-gradle/tests", "idea/testData") { - testClass { - model("configuration/gradle", extension = null, recursive = false, testMethod = "doTestGradle") - model("configuration/gsk", extension = null, recursive = false, testMethod = "doTestGradle") - } - } - - testGroup("idea/tests", "compiler/testData") { - testClass { - model("loadJava/compiledKotlin") - } - - testClass { - model("loadJava/compiledKotlin", testMethod = "doTestCompiledKotlin") - } - - testClass { - model("asJava/lightClasses", excludeDirs = listOf("delegation"), pattern = KT_OR_KTS_WITHOUT_DOTS_IN_NAME) - } - - testClass { - model("asJava/lightClasses", excludeDirs = listOf("local", "compilationErrors", "ideRegression"), pattern = KT_OR_KTS_WITHOUT_DOTS_IN_NAME) - } - } - - testGroup("idea/idea-completion/tests", "idea/idea-completion/testData") { - testClass { - model("injava", extension = "java", recursive = false) - } - - testClass { - model("injava", extension = "java", recursive = false) - } - - testClass { - model("injava/stdlib", extension = "java", recursive = false) - } - - testClass { - model("weighers/basic", pattern = KT_WITHOUT_DOTS_IN_NAME) - } - - testClass { - model("weighers/smart", pattern = KT_WITHOUT_DOTS_IN_NAME) - } - - testClass { - model("basic/common") - model("basic/js") - } - - testClass { - model("basic/common") - model("basic/java") - } - - testClass { - model("smart") - } - - testClass { - model("keywords", recursive = false) - } - - testClass { - model("basic/withLib", recursive = false) - } - - testClass { - model("handlers/basic", pattern = KT_WITHOUT_DOTS_IN_NAME) - } - - testClass { - model("handlers/smart") - } - - testClass { - model("handlers/keywords") - } - - testClass { - model("handlers/charFilter") - } - - testClass { - model("basic/multifile", extension = null, recursive = false) - } - - testClass { - model("smartMultiFile", extension = null, recursive = false) - } - - testClass("KDocCompletionTestGenerated") { - model("kdoc") - } - - testClass { - model("basic/java8") - } - - testClass { - model("incrementalResolve") - } - - testClass { - model("multiPlatform", recursive = false, extension = null) - } - } - - //TODO: move these tests into idea-completion module - testGroup("idea/tests", "idea/idea-completion/testData") { - testClass { - model("handlers/runtimeCast") - } - - testClass { - model("basic/codeFragments", extension = "kt") - } - } - - testGroup("j2k/tests", "j2k/testData") { - testClass { - model("fileOrElement", extension = "java") - } - } - testGroup("j2k/tests", "j2k/testData") { - testClass { - model("multiFile", extension = null, recursive = false) - } - } - testGroup("j2k/tests", "j2k/testData") { - testClass { - model("fileOrElement", extension = "java") - } - } - - testGroup("jps-plugin/jps-tests/test", "jps-plugin/testData") { - testClass { - model("incremental/multiModule/common", extension = null, excludeParentDirs = true) - model("incremental/multiModule/jvm", extension = null, excludeParentDirs = true) - model("incremental/pureKotlin", extension = null, recursive = false) - model("incremental/withJava", extension = null, excludeParentDirs = true) - model("incremental/inlineFunCallSite", extension = null, excludeParentDirs = true) - model("incremental/classHierarchyAffected", extension = null, excludeParentDirs = true) - } - - actualizeMppJpsIncTestCaseDirs(testDataRoot, "incremental/multiplatform/multiModule") - - testClass { - model("incremental/multiModule/common", extension = null, excludeParentDirs = true) - } - - testClass { - model( - "incremental/multiplatform/multiModule", extension = null, excludeParentDirs = true, - testClassName = "MultiplatformMultiModule", recursive = true - ) - } - - testClass { - model("incremental/lookupTracker/jvm", extension = null, recursive = false) - } - testClass { - model("incremental/lookupTracker/js", extension = null, recursive = false) - } - - testClass { - model("incremental/lazyKotlinCaches", extension = null, excludeParentDirs = true) - model("incremental/changeIncrementalOption", extension = null, excludeParentDirs = true) - } - - testClass { - model("incremental/cacheVersionChanged", extension = null, excludeParentDirs = true) - } - - testClass { - model("incremental/cacheVersionChanged", extension = null, excludeParentDirs = true) - } - } - - testGroup("jps-plugin/jps-tests/test", "jps-plugin/testData") { - fun TestGroup.TestClass.commonProtoComparisonTests() { - model("comparison/classSignatureChange", extension = null, excludeParentDirs = true) - model("comparison/classPrivateOnlyChange", extension = null, excludeParentDirs = true) - model("comparison/classMembersOnlyChanged", extension = null, excludeParentDirs = true) - model("comparison/packageMembers", extension = null, excludeParentDirs = true) - model("comparison/unchanged", extension = null, excludeParentDirs = true) - } - - testClass { - commonProtoComparisonTests() - model("comparison/jvmOnly", extension = null, excludeParentDirs = true) - } - - testClass { - commonProtoComparisonTests() - model("comparison/jsOnly", extension = null, excludeParentDirs = true) - } - } - - testGroup("compiler/incremental-compilation-impl/test", "jps-plugin/testData") { - testClass { - model("incremental/pureKotlin", extension = null, recursive = false) - model("incremental/classHierarchyAffected", extension = null, recursive = false) - model("incremental/inlineFunCallSite", extension = null, excludeParentDirs = true) - model("incremental/withJava", extension = null, excludeParentDirs = true) - model("incremental/incrementalJvmCompilerOnly", extension = null, excludeParentDirs = true) - } - - testClass { - model("incremental/pureKotlin", extension = null, recursive = false) - model("incremental/classHierarchyAffected", extension = null, recursive = false) - model("incremental/js", extension = null, excludeParentDirs = true) - } - - testClass { - model("incremental/js/friendsModuleDisabled", extension = null, recursive = false) - } - - testClass { - model("incremental/multiplatform/singleModule", extension = null, excludeParentDirs = true) - } - testClass { - model("incremental/multiplatform/singleModule", extension = null, excludeParentDirs = true) - } - } - - testGroup("plugins/android-extensions/android-extensions-compiler/test", "plugins/android-extensions/android-extensions-compiler/testData") { - testClass { - model("descriptors", recursive = false, extension = null) - } - - testClass { - model("codegen/android", recursive = false, extension = null, testMethod = "doCompileAgainstAndroidSdkTest") - model("codegen/android", recursive = false, extension = null, testMethod = "doFakeInvocationTest", testClassName = "Invoke") - } - - testClass { - model("codegen/bytecodeShape", recursive = false, extension = null) - } - - testClass { - model("parcel/codegen") - } - } - - testGroup("plugins/kapt3/kapt3-compiler/test", "plugins/kapt3/kapt3-compiler/testData") { - testClass { - model("converter") - } - - testClass { - model("kotlinRunner") - } - } - - testGroup("plugins/allopen/allopen-cli/test", "plugins/allopen/allopen-cli/testData") { - testClass { - model("bytecodeListing", extension = "kt") - } - } - - testGroup("plugins/noarg/noarg-cli/test", "plugins/noarg/noarg-cli/testData") { - testClass { - model("bytecodeListing", extension = "kt") - } - - testClass { - model("box", targetBackend = TargetBackend.JVM) - } - } - - testGroup("plugins/sam-with-receiver/sam-with-receiver-cli/test", "plugins/sam-with-receiver/sam-with-receiver-cli/testData") { - testClass { - model("diagnostics") - } - testClass { - model("script", extension = "kts") - } - } - - testGroup("plugins/android-extensions/android-extensions-idea/tests", "plugins/android-extensions/android-extensions-idea/testData") { - testClass { - model("android/completion", recursive = false, extension = null) - } - - testClass { - model("android/goto", recursive = false, extension = null) - } - - testClass { - model("android/rename", recursive = false, extension = null) - } - - testClass { - model("android/renameLayout", recursive = false, extension = null) - } - - testClass { - model("android/findUsages", recursive = false, extension = null) - } - - testClass { - model("android/usageHighlighting", recursive = false, extension = null) - } - - testClass { - model("android/extraction", recursive = false, extension = null) - } - - testClass { - model("android/parcel/checker", excludeParentDirs = true) - } - - testClass { - model("android/parcel/quickfix", pattern = """^(\w+)\.((before\.Main\.\w+)|(test))$""", testMethod = "doTestWithExtraFile") - } - } - - testGroup("idea/idea-android/tests", "idea/testData") { - testClass { - model("configuration/android-gradle", pattern = """(\w+)_before\.gradle$""", testMethod = "doTestAndroidGradle") - model("configuration/android-gsk", pattern = """(\w+)_before\.gradle.kts$""", testMethod = "doTestAndroidGradle") - } - - testClass { - model("android/intention", pattern = "^([\\w\\-_]+)\\.kt$") - } - - testClass { - model("android/resourceIntention", extension = "test", singleClass = true) - } - - testClass { - model("android/quickfix", pattern = """^(\w+)\.((before\.Main\.\w+)|(test))$""", testMethod = "doTestWithExtraFile") - } - - testClass { - model("android/lint", excludeParentDirs = true) - } - - testClass { - model("android/lintQuickfix", pattern = "^([\\w\\-_]+)\\.kt$") - } - - testClass { - model("android/folding") - } - - testClass { - model("android/gutterIcon") - } - } - - testGroup("plugins/android-extensions/android-extensions-jps/test", "plugins/android-extensions/android-extensions-jps/testData") { - testClass { - model("android", recursive = false, extension = null) - } - } -} diff --git a/idea/formatter/src/org/jetbrains/kotlin/idea/formatter/KotlinCommonCodeStyleSettings.java.172 b/idea/formatter/src/org/jetbrains/kotlin/idea/formatter/KotlinCommonCodeStyleSettings.java.172 deleted file mode 100644 index 5efe41306f5..00000000000 --- a/idea/formatter/src/org/jetbrains/kotlin/idea/formatter/KotlinCommonCodeStyleSettings.java.172 +++ /dev/null @@ -1,220 +0,0 @@ -/* - * Copyright 2000-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.formatter; - -import com.intellij.lang.Language; -import com.intellij.openapi.util.DefaultJDOMExternalizer; -import com.intellij.openapi.util.DifferenceFilter; -import com.intellij.openapi.util.InvalidDataException; -import com.intellij.openapi.util.WriteExternalException; -import com.intellij.psi.codeStyle.CodeStyleSettings; -import com.intellij.psi.codeStyle.CommonCodeStyleSettings; -import com.intellij.psi.codeStyle.LanguageCodeStyleSettingsProvider; -import com.intellij.psi.codeStyle.arrangement.ArrangementSettings; -import com.intellij.psi.codeStyle.arrangement.ArrangementUtil; -import com.intellij.util.xmlb.XmlSerializer; -import kotlin.collections.ArraysKt; -import org.jdom.Element; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.jetbrains.kotlin.idea.KotlinLanguage; -import org.jetbrains.kotlin.idea.util.ReflectionUtil; - -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.List; -import java.util.Set; - -@SuppressWarnings("UnnecessaryFinalOnLocalVariableOrParameter") -public class KotlinCommonCodeStyleSettings extends CommonCodeStyleSettings { - @ReflectionUtil.SkipInEquals - public String CODE_STYLE_DEFAULTS = null; - - private final KotlinCommonCodeStyleSettings oldDefaultSettings = null; - - private final boolean isTempForDeserialize; - - public KotlinCommonCodeStyleSettings() { - this(false); - } - - private KotlinCommonCodeStyleSettings(boolean isTempForDeserialize) { - super(KotlinLanguage.INSTANCE); - this.isTempForDeserialize = isTempForDeserialize; - } - - private static KotlinCommonCodeStyleSettings createForTempDeserialize() { - return new KotlinCommonCodeStyleSettings(true); - } - - @Override - public void readExternal(Element element) throws InvalidDataException { - if (isTempForDeserialize) { - super.readExternal(element); - return; - } - - KotlinCommonCodeStyleSettings tempDeserialize = createForTempDeserialize(); - tempDeserialize.readExternal(element); - - if (KotlinStyleGuideCodeStyle.CODE_STYLE_ID.equals(tempDeserialize.CODE_STYLE_DEFAULTS)) { - KotlinStyleGuideCodeStyle.Companion.applyToCommonSettings(this, true); - } else if (KotlinObsoleteCodeStyle.CODE_STYLE_ID.equals(tempDeserialize.CODE_STYLE_DEFAULTS)) { - KotlinObsoleteCodeStyle.Companion.applyToCommonSettings(this, true); - } - - readExternalBase(element); - } - - @Override - public void writeExternal(Element element) throws WriteExternalException { - CommonCodeStyleSettings defaultSettings = getDefaultSettings(); - - if (defaultSettings != null) { - if (KotlinStyleGuideCodeStyle.CODE_STYLE_ID.equals(CODE_STYLE_DEFAULTS)) { - KotlinStyleGuideCodeStyle.Companion.applyToCommonSettings(defaultSettings, false); - } else if (KotlinObsoleteCodeStyle.CODE_STYLE_ID.equals(CODE_STYLE_DEFAULTS)) { - KotlinObsoleteCodeStyle.Companion.applyToCommonSettings(defaultSettings, false); - } - } - - writeExternalBase(element, defaultSettings); - } - - // - private void readExternalBase(Element element) throws InvalidDataException { - super.readExternal(element); - } - - private void writeExternalBase(Element element, CommonCodeStyleSettings defaultSettings) throws WriteExternalException { - Set supportedFields = getSupportedFields(); - if (supportedFields != null) { - supportedFields.add("PARENT_SETTINGS_INSTALLED"); - supportedFields.add("FORCE_REARRANGE_MODE"); - supportedFields.add("CODE_STYLE_DEFAULTS"); - } - //noinspection deprecation - DefaultJDOMExternalizer.writeExternal(this, element, new SupportedFieldsDiffFilter(this, supportedFields, defaultSettings)); - - IndentOptions myIndentOptions = getIndentOptions(); - if (myIndentOptions != null) { - IndentOptions defaultIndentOptions = defaultSettings != null ? defaultSettings.getIndentOptions() : null; - Element indentOptionsElement = new Element(INDENT_OPTIONS_TAG); - myIndentOptions.serialize(indentOptionsElement, defaultIndentOptions); - if (!indentOptionsElement.getChildren().isEmpty()) { - element.addContent(indentOptionsElement); - } - } - - ArrangementSettings myArrangementSettings = getArrangementSettings(); - if (myArrangementSettings != null) { - Element container = new Element(ARRANGEMENT_ELEMENT_NAME); - ArrangementUtil.writeExternal(container, myArrangementSettings, myLanguage); - if (!container.getChildren().isEmpty()) { - element.addContent(container); - } - } - } - - @Override - public CommonCodeStyleSettings clone(@NotNull CodeStyleSettings rootSettings) { - CommonCodeStyleSettings commonSettings = new KotlinCommonCodeStyleSettings(); - copyPublicFieldsOwn(this, commonSettings); - - try { - Method setRootSettingsMethod = CommonCodeStyleSettings.class.getDeclaredMethod("setRootSettings", CodeStyleSettings.class); - setRootSettingsMethod.setAccessible(true); - setRootSettingsMethod.invoke(commonSettings, rootSettings); - } - catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - throw new IllegalStateException(e); - } - - commonSettings.setForceArrangeMenuAvailable(isForceArrangeMenuAvailable()); - - IndentOptions indentOptions = getIndentOptions(); - if (indentOptions != null) { - IndentOptions targetIndentOptions = commonSettings.initIndentOptions(); - targetIndentOptions.copyFrom(indentOptions); - } - - ArrangementSettings arrangementSettings = getArrangementSettings(); - if (arrangementSettings != null) { - commonSettings.setArrangementSettings(arrangementSettings.clone()); - } - - return commonSettings; - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof KotlinCommonCodeStyleSettings)) { - return false; - } - - if (!ReflectionUtil.comparePublicNonFinalFieldsWithSkip(this, obj)) { - return false; - } - - CommonCodeStyleSettings other = (CommonCodeStyleSettings) obj; - - IndentOptions options = getIndentOptions(); - if ((options == null && other.getIndentOptions() != null) || - (options != null && !options.equals(other.getIndentOptions()))) { - return false; - } - - return arrangementSettingsEqual(other); - } - // - - // - private static final String INDENT_OPTIONS_TAG = "indentOptions"; - private static final String ARRANGEMENT_ELEMENT_NAME = "arrangement"; - - private final Language myLanguage = KotlinLanguage.INSTANCE; - - @Nullable - private CommonCodeStyleSettings getDefaultSettings() { - return LanguageCodeStyleSettingsProvider.getDefaultCommonSettings(myLanguage); - } - - @Nullable - private Set getSupportedFields() { - final LanguageCodeStyleSettingsProvider provider = LanguageCodeStyleSettingsProvider.forLanguage(myLanguage); - return provider == null ? null : provider.getSupportedFields(); - } - - private static class SupportedFieldsDiffFilter extends DifferenceFilter { - private final Set mySupportedFieldNames; - - public SupportedFieldsDiffFilter( - final CommonCodeStyleSettings object, - Set supportedFiledNames, - final CommonCodeStyleSettings parentObject - ) { - super(object, parentObject); - mySupportedFieldNames = supportedFiledNames; - } - - @Override - public boolean isAccept(@NotNull Field field) { - if (mySupportedFieldNames == null || - mySupportedFieldNames.contains(field.getName())) { - return super.isAccept(field); - } - return false; - } - } - - // Can't use super.copyPublicFields because the method is internal in 181 - private static void copyPublicFieldsOwn(Object from, Object to) { - assert from != to; - com.intellij.util.ReflectionUtil.copyFields(to.getClass().getFields(), from, to); - } - // -} diff --git a/idea/ide-common/src/org/jetbrains/kotlin/compatibility/codeInsightTestFixtureImpl.kt.172 b/idea/ide-common/src/org/jetbrains/kotlin/compatibility/codeInsightTestFixtureImpl.kt.172 deleted file mode 100644 index e0a8b4bc6fe..00000000000 --- a/idea/ide-common/src/org/jetbrains/kotlin/compatibility/codeInsightTestFixtureImpl.kt.172 +++ /dev/null @@ -1,16 +0,0 @@ -/* - * 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.compatibility - -import com.intellij.openapi.Disposable -import com.intellij.testFramework.fixtures.CodeInsightTestFixture - -/** - * Method was introduced in 173 idea. Should be dropped after abandoning 172 branch. - * BUNCH: 173 - */ -@Suppress("IncompatibleAPI") -val CodeInsightTestFixture.projectDisposableEx: Disposable get() = project \ No newline at end of file diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/compiler/configuration/BaseKotlinCompilerSettings.kt.172 b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/compiler/configuration/BaseKotlinCompilerSettings.kt.172 deleted file mode 100644 index 920110fcb22..00000000000 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/compiler/configuration/BaseKotlinCompilerSettings.kt.172 +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.kotlin.idea.compiler.configuration - -import com.intellij.openapi.application.ReadAction -import com.intellij.openapi.components.PersistentStateComponent -import com.intellij.openapi.components.StoragePathMacros.PROJECT_CONFIG_DIR -import com.intellij.openapi.progress.ProcessCanceledException -import com.intellij.openapi.project.Project -import com.intellij.util.ReflectionUtil -import com.intellij.util.messages.Topic -import com.intellij.util.xmlb.SkipDefaultValuesSerializationFilters -import com.intellij.util.xmlb.XmlSerializer -import org.jdom.Element -import org.jetbrains.kotlin.cli.common.arguments.* -import org.jetbrains.kotlin.config.SettingConstants -import kotlin.reflect.KClass - -abstract class BaseKotlinCompilerSettings protected constructor(private val project: Project) : PersistentStateComponent, Cloneable { - @Suppress("LeakingThis", "UNCHECKED_CAST") - private var _settings: T = createSettings().frozen() as T - private set(value) { - field = value.frozen() as T - } - - var settings: T - get() = _settings - set(value) { - validateNewSettings(value) - _settings = value - - syncPublisher(project, KotlinCompilerSettingsListener.TOPIC).settingsChanged(value) - } - - fun update(changer: T.() -> Unit) { - @Suppress("UNCHECKED_CAST") - settings = (settings.unfrozen() as T).apply { changer() } - } - - protected fun validateInheritedFieldsUnchanged(settings: T) { - @Suppress("UNCHECKED_CAST") - val inheritedProperties = collectProperties(settings::class as KClass, true) - val defaultInstance = createSettings() - val invalidFields = inheritedProperties.filter { it.get(settings) != it.get(defaultInstance) } - if (invalidFields.isNotEmpty()) { - throw IllegalArgumentException("Following fields are expected to be left unchanged in ${settings.javaClass}: ${invalidFields.joinToString { it.name }}") - } - } - - protected open fun validateNewSettings(settings: T) { - - } - - protected abstract fun createSettings(): T - - override fun getState() = XmlSerializer.serialize(_settings, SKIP_DEFAULT_VALUES) - - override fun loadState(state: Element) { - _settings = ReflectionUtil.newInstance(_settings.javaClass).apply { - if (this is CommonCompilerArguments) { - freeArgs = ArrayList() - } - XmlSerializer.deserializeInto(this, state) - } - - syncPublisher(project, KotlinCompilerSettingsListener.TOPIC).settingsChanged(settings) - } - - public override fun clone(): Any = super.clone() - - companion object { - const val KOTLIN_COMPILER_SETTINGS_PATH = PROJECT_CONFIG_DIR + "/" + SettingConstants.KOTLIN_COMPILER_SETTINGS_FILE - - private val SKIP_DEFAULT_VALUES = SkipDefaultValuesSerializationFilters( - CommonCompilerArguments.DummyImpl(), - K2JVMCompilerArguments(), - K2JSCompilerArguments().apply { - sourceMapPrefix = "" - sourceMapEmbedSources = K2JsArgumentConstants.SOURCE_MAP_SOURCE_CONTENT_INLINING - } - ) - } -} - -interface KotlinCompilerSettingsListener { - fun settingsChanged(newSettings: T) - - companion object { - val TOPIC = Topic.create("KotlinCompilerSettingsListener", KotlinCompilerSettingsListener::class.java) - } -} - -// copied from BackgroundTaskUtils.syncPublisher in IDEA 181 -private fun syncPublisher(project: Project, topic: Topic): KotlinCompilerSettingsListener { - return ReadAction.compute { - if (project.isDisposed) throw ProcessCanceledException() - project.messageBus.syncPublisher(topic) - } -} \ No newline at end of file diff --git a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/util/compat/psi/javaPsiUtil.kt.172 b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/util/compat/psi/javaPsiUtil.kt.172 deleted file mode 100644 index 06836b3581d..00000000000 --- a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/util/compat/psi/javaPsiUtil.kt.172 +++ /dev/null @@ -1,18 +0,0 @@ -/* - * 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.core.util.compat.psi - -import com.intellij.psi.PsiMethod -import com.intellij.psi.util.PsiUtil - -/** - * Method is absent in 172. - * BUNCH: 173 - */ -@Suppress("IncompatibleAPI") -fun canBeOverridden(method: PsiMethod): Boolean { - return PsiUtil.canBeOverriden(method) -} \ No newline at end of file diff --git a/idea/idea-gradle/src/org/jetbrains/kotlin/gradle/kdsl/GradleConstants.kt.172 b/idea/idea-gradle/src/org/jetbrains/kotlin/gradle/kdsl/GradleConstants.kt.172 deleted file mode 100644 index 0e47c8a1a5d..00000000000 --- a/idea/idea-gradle/src/org/jetbrains/kotlin/gradle/kdsl/GradleConstants.kt.172 +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -@file:JvmName("GradleKotlinDSLConstants") - -package org.jetbrains.kotlin.gradle.kdsl - -const val DEFAULT_SCRIPT_NAME = "build.gradle.kts" diff --git a/idea/idea-gradle/src/org/jetbrains/kotlin/gradle/kdsl/GradleFrameworksWizardStep.form.172 b/idea/idea-gradle/src/org/jetbrains/kotlin/gradle/kdsl/GradleFrameworksWizardStep.form.172 deleted file mode 100644 index 814609f97dd..00000000000 --- a/idea/idea-gradle/src/org/jetbrains/kotlin/gradle/kdsl/GradleFrameworksWizardStep.form.172 +++ /dev/null @@ -1,55 +0,0 @@ - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
diff --git a/idea/idea-gradle/src/org/jetbrains/kotlin/gradle/kdsl/GradleFrameworksWizardStep.java.172 b/idea/idea-gradle/src/org/jetbrains/kotlin/gradle/kdsl/GradleFrameworksWizardStep.java.172 deleted file mode 100644 index 3cb08deadb5..00000000000 --- a/idea/idea-gradle/src/org/jetbrains/kotlin/gradle/kdsl/GradleFrameworksWizardStep.java.172 +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.kotlin.gradle.kdsl; - -import com.intellij.framework.addSupport.FrameworkSupportInModuleProvider; -import com.intellij.ide.util.newProjectWizard.AddSupportForFrameworksPanel; -import com.intellij.ide.util.newProjectWizard.impl.FrameworkSupportModelBase; -import com.intellij.ide.util.projectWizard.ModuleBuilder; -import com.intellij.ide.util.projectWizard.ModuleWizardStep; -import com.intellij.ide.util.projectWizard.WizardContext; -import com.intellij.openapi.Disposable; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.roots.ModifiableRootModel; -import com.intellij.openapi.roots.ui.configuration.projectRoot.LibrariesContainer; -import com.intellij.openapi.roots.ui.configuration.projectRoot.LibrariesContainerFactory; -import com.intellij.openapi.util.Disposer; -import com.intellij.openapi.util.text.StringUtil; -import com.intellij.ui.components.JBLabel; -import com.intellij.util.containers.ContainerUtil; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.kotlin.gradle.kdsl.frameworkSupport.GradleFrameworkSupportProvider; -import org.jetbrains.kotlin.gradle.kdsl.frameworkSupport.GradleJavaFrameworkSupportProvider; - -import javax.swing.*; -import java.awt.*; -import java.util.Collections; -import java.util.List; - -public class GradleFrameworksWizardStep extends ModuleWizardStep implements Disposable { - - private JPanel myPanel; - private final AddSupportForFrameworksPanel myFrameworksPanel; - private JPanel myFrameworksPanelPlaceholder; - private JPanel myOptionsPanel; - @SuppressWarnings("unused") private JBLabel myFrameworksLabel; - - public GradleFrameworksWizardStep(WizardContext context, final ModuleBuilder builder) { - - Project project = context.getProject(); - final LibrariesContainer container = LibrariesContainerFactory.createContainer(context.getProject()); - FrameworkSupportModelBase model = new FrameworkSupportModelBase(project, null, container) { - @NotNull - @Override - public String getBaseDirectoryForLibrariesPath() { - return StringUtil.notNullize(builder.getContentEntryPath()); - } - }; - - myFrameworksPanel = - new AddSupportForFrameworksPanel(Collections.emptyList(), model, true, null); - - List providers = ContainerUtil.newArrayList(); - Collections.addAll(providers, GradleFrameworkSupportProvider.EP_NAME.getExtensions()); - - myFrameworksPanel.setProviders(providers, Collections.emptySet(), Collections.singleton(GradleJavaFrameworkSupportProvider.ID)); - Disposer.register(this, myFrameworksPanel); - myFrameworksPanelPlaceholder.add(myFrameworksPanel.getMainPanel()); - - ModuleBuilder.ModuleConfigurationUpdater configurationUpdater = new ModuleBuilder.ModuleConfigurationUpdater() { - @Override - public void update(@NotNull Module module, @NotNull ModifiableRootModel rootModel) { - myFrameworksPanel.addSupport(module, rootModel); - } - }; - builder.addModuleConfigurationUpdater(configurationUpdater); - - ((CardLayout)myOptionsPanel.getLayout()).show(myOptionsPanel, "frameworks card"); - } - - @Override - public JComponent getComponent() { - return myPanel; - } - - @Override - public void updateDataModel() { - } - - @Override - public void dispose() { - } - - @Override - public void disposeUIResources() { - Disposer.dispose(this); - } -} diff --git a/idea/idea-gradle/src/org/jetbrains/kotlin/gradle/kdsl/GradleModuleBuilder.java.172 b/idea/idea-gradle/src/org/jetbrains/kotlin/gradle/kdsl/GradleModuleBuilder.java.172 deleted file mode 100644 index 48be5be61c2..00000000000 --- a/idea/idea-gradle/src/org/jetbrains/kotlin/gradle/kdsl/GradleModuleBuilder.java.172 +++ /dev/null @@ -1,491 +0,0 @@ -/* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.kotlin.gradle.kdsl; - -import com.intellij.ide.fileTemplates.FileTemplate; -import com.intellij.ide.fileTemplates.FileTemplateManager; -import com.intellij.ide.highlighter.ModuleFileType; -import com.intellij.ide.projectWizard.ProjectSettingsStep; -import com.intellij.ide.util.EditorHelper; -import com.intellij.ide.util.projectWizard.JavaModuleBuilder; -import com.intellij.ide.util.projectWizard.ModuleWizardStep; -import com.intellij.ide.util.projectWizard.SettingsStep; -import com.intellij.ide.util.projectWizard.WizardContext; -import com.intellij.openapi.Disposable; -import com.intellij.openapi.application.ModalityState; -import com.intellij.openapi.components.StorageScheme; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.externalSystem.importing.ImportSpec; -import com.intellij.openapi.externalSystem.importing.ImportSpecBuilder; -import com.intellij.openapi.externalSystem.model.ExternalSystemDataKeys; -import com.intellij.openapi.externalSystem.model.project.ProjectData; -import com.intellij.openapi.externalSystem.model.project.ProjectId; -import com.intellij.openapi.externalSystem.service.execution.ProgressExecutionMode; -import com.intellij.openapi.externalSystem.service.project.manage.ExternalProjectsManagerImpl; -import com.intellij.openapi.externalSystem.service.project.wizard.AbstractExternalModuleBuilder; -import com.intellij.openapi.externalSystem.service.project.wizard.ExternalModuleSettingsStep; -import com.intellij.openapi.externalSystem.settings.AbstractExternalSystemSettings; -import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil; -import com.intellij.openapi.externalSystem.util.ExternalSystemUtil; -import com.intellij.openapi.fileEditor.FileDocumentManager; -import com.intellij.openapi.fileEditor.impl.LoadTextUtil; -import com.intellij.openapi.module.*; -import com.intellij.openapi.options.ConfigurationException; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.project.ex.ProjectManagerEx; -import com.intellij.openapi.projectRoots.JavaSdkType; -import com.intellij.openapi.projectRoots.SdkTypeId; -import com.intellij.openapi.roots.ModifiableRootModel; -import com.intellij.openapi.roots.ui.configuration.ModulesProvider; -import com.intellij.openapi.util.Disposer; -import com.intellij.openapi.util.InvalidDataException; -import com.intellij.openapi.util.Key; -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.util.io.FileUtilRt; -import com.intellij.openapi.util.text.StringUtil; -import com.intellij.openapi.vfs.LocalFileSystem; -import com.intellij.openapi.vfs.VfsUtil; -import com.intellij.openapi.vfs.VfsUtilCore; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.psi.PsiFile; -import com.intellij.psi.PsiManager; -import com.intellij.psi.codeStyle.CodeStyleSettingsManager; -import com.intellij.util.containers.ContainerUtil; -import org.gradle.util.GradleVersion; -import org.jdom.JDOMException; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.jetbrains.kotlin.gradle.kdsl.frameworkSupport.BuildScriptDataBuilder; -import org.jetbrains.kotlin.gradle.kdsl.frameworkSupport.KotlinBuildScriptDataBuilder; -import org.jetbrains.plugins.gradle.service.settings.GradleProjectSettingsControl; -import org.jetbrains.plugins.gradle.settings.DistributionType; -import org.jetbrains.plugins.gradle.settings.GradleProjectSettings; -import org.jetbrains.plugins.gradle.util.GradleConstants; - -import javax.swing.*; -import java.io.File; -import java.io.IOException; -import java.util.Map; - -import static org.jetbrains.kotlin.gradle.kdsl.GradleKotlinDSLConstants.DEFAULT_SCRIPT_NAME; - -public class GradleModuleBuilder extends AbstractExternalModuleBuilder { - - private static final Logger LOG = Logger.getInstance(GradleModuleBuilder.class); - - private static final String TEMPLATE_GRADLE_SETTINGS = "Gradle Kotlin DSL Settings.gradle"; - private static final String TEMPLATE_GRADLE_SETTINGS_MERGE = "Gradle Settings merge.gradle"; - private static final String TEMPLATE_GRADLE_BUILD_WITH_WRAPPER = "Gradle Build Script with wrapper.gradle"; - private static final String DEFAULT_TEMPLATE_GRADLE_BUILD = "Gradle Kotlin DSL Build Script.gradle"; - - private static final String TEMPLATE_ATTRIBUTE_PROJECT_NAME = "PROJECT_NAME"; - private static final String TEMPLATE_ATTRIBUTE_MODULE_PATH = "MODULE_PATH"; - private static final String TEMPLATE_ATTRIBUTE_MODULE_FLAT_DIR = "MODULE_FLAT_DIR"; - private static final String TEMPLATE_ATTRIBUTE_MODULE_NAME = "MODULE_NAME"; - private static final String TEMPLATE_ATTRIBUTE_MODULE_GROUP = "MODULE_GROUP"; - private static final String TEMPLATE_ATTRIBUTE_MODULE_VERSION = "MODULE_VERSION"; - private static final String TEMPLATE_ATTRIBUTE_GRADLE_VERSION = "GRADLE_VERSION"; - private static final String TEMPLATE_ATTRIBUTE_BUILD_FILE_NAME = "BUILD_FILE_NAME"; - private static final Key BUILD_SCRIPT_DATA = - Key.create("gradle.module.kotlinBuildScriptData"); - - private WizardContext myWizardContext; - - @Nullable - private ProjectData myParentProject; - private boolean myInheritGroupId; - private boolean myInheritVersion; - private ProjectId myProjectId; - private String rootProjectPath; - - public GradleModuleBuilder() { - super(GradleConstants.SYSTEM_ID, new GradleProjectSettings()); - } - - @Override - public String getPresentableName() { - return "Gradle (Kotlin DSL)"; - } - - @NotNull - @Override - public Module createModule(@NotNull ModifiableModuleModel moduleModel) - throws InvalidDataException, IOException, ModuleWithNameAlreadyExists, JDOMException, ConfigurationException { - LOG.assertTrue(getName() != null); - final String originModuleFilePath = getModuleFilePath(); - LOG.assertTrue(originModuleFilePath != null); - - String moduleName; - if (myProjectId == null) { - moduleName = getName(); - } - else { - moduleName = ModuleGrouperKt.isQualifiedModuleNamesEnabled() && StringUtil.isNotEmpty(myProjectId.getGroupId()) - ? (myProjectId.getGroupId() + '.' + myProjectId.getArtifactId()) - : myProjectId.getArtifactId(); - } - Project contextProject = myWizardContext.getProject(); - String projectFileDirectory = null; - if (myWizardContext.isCreatingNewProject() || contextProject == null || contextProject.getBasePath() == null) { - projectFileDirectory = myWizardContext.getProjectFileDirectory(); - } - else if (myWizardContext.getProjectStorageFormat() == StorageScheme.DEFAULT) { - String moduleFileDirectory = getModuleFileDirectory(); - if (moduleFileDirectory != null) { - projectFileDirectory = moduleFileDirectory; - } - } - if (projectFileDirectory == null) { - projectFileDirectory = contextProject.getBasePath(); - } - if (myWizardContext.getProjectStorageFormat() == StorageScheme.DIRECTORY_BASED) { - projectFileDirectory += "/.idea/modules"; - } - String moduleFilePath = projectFileDirectory + "/" + moduleName + ModuleFileType.DOT_DEFAULT_EXTENSION; - deleteModuleFile(moduleFilePath); - final ModuleType moduleType = getModuleType(); - final Module module = moduleModel.newModule(moduleFilePath, moduleType.getId()); - setupModule(module); - return module; - } - - @Override - public void setupRootModel(final ModifiableRootModel modifiableRootModel) throws ConfigurationException { - String contentEntryPath = getContentEntryPath(); - if (StringUtil.isEmpty(contentEntryPath)) { - return; - } - File contentRootDir = new File(contentEntryPath); - FileUtilRt.createDirectory(contentRootDir); - LocalFileSystem fileSystem = LocalFileSystem.getInstance(); - VirtualFile modelContentRootDir = fileSystem.refreshAndFindFileByIoFile(contentRootDir); - if (modelContentRootDir == null) { - return; - } - - modifiableRootModel.addContentEntry(modelContentRootDir); - // todo this should be moved to generic ModuleBuilder - if (myJdk != null) { - modifiableRootModel.setSdk(myJdk); - } - else { - modifiableRootModel.inheritSdk(); - } - - final Project project = modifiableRootModel.getProject(); - if (myParentProject != null) { - rootProjectPath = myParentProject.getLinkedExternalProjectPath(); - } - else { - rootProjectPath = - FileUtil.toCanonicalPath(myWizardContext.isCreatingNewProject() ? project.getBasePath() : modelContentRootDir.getPath()); - } - assert rootProjectPath != null; - - final VirtualFile gradleBuildFile = setupGradleBuildFile(modelContentRootDir); - setupGradleSettingsFile( - rootProjectPath, modelContentRootDir, modifiableRootModel.getProject().getName(), - myProjectId == null ? modifiableRootModel.getModule().getName() : myProjectId.getArtifactId(), - myWizardContext.isCreatingNewProject() || myParentProject == null - ); - - if (gradleBuildFile != null) { - modifiableRootModel.getModule().putUserData( - BUILD_SCRIPT_DATA, new KotlinBuildScriptDataBuilder(gradleBuildFile)); - } - } - - @Override - protected void setupModule(Module module) throws ConfigurationException { - super.setupModule(module); - assert rootProjectPath != null; - - VirtualFile buildScriptFile = null; - final BuildScriptDataBuilder buildScriptDataBuilder = getBuildScriptData(module); - try { - if (buildScriptDataBuilder != null) { - buildScriptFile = buildScriptDataBuilder.getBuildScriptFile(); - String lineSeparator = lineSeparator(buildScriptFile); - String configurationPart = StringUtil.convertLineSeparators(buildScriptDataBuilder.buildConfigurationPart(), lineSeparator); - String existingText = StringUtil.trimTrailing(VfsUtilCore.loadText(buildScriptFile)); - String content = (!configurationPart.isEmpty() ? configurationPart + lineSeparator : "") + - (!existingText.isEmpty() ? existingText + lineSeparator : "") + - lineSeparator + - StringUtil.convertLineSeparators(buildScriptDataBuilder.buildMainPart(), lineSeparator); - VfsUtil.saveText(buildScriptFile, content); - } - } - catch (IOException e) { - LOG.warn("Unexpected exception on applying frameworks templates", e); - } - - final Project project = module.getProject(); - if (myWizardContext.isCreatingNewProject()) { - getExternalProjectSettings().setExternalProjectPath(rootProjectPath); - AbstractExternalSystemSettings settings = ExternalSystemApiUtil.getSettings(project, GradleConstants.SYSTEM_ID); - project.putUserData(ExternalSystemDataKeys.NEWLY_CREATED_PROJECT, Boolean.TRUE); - //noinspection unchecked - settings.linkProject(getExternalProjectSettings()); - } - else { - FileDocumentManager.getInstance().saveAllDocuments(); - final GradleProjectSettings gradleProjectSettings = getExternalProjectSettings(); - final VirtualFile finalBuildScriptFile = buildScriptFile; - Runnable runnable = () -> { - if (myParentProject == null) { - gradleProjectSettings.setExternalProjectPath(rootProjectPath); - AbstractExternalSystemSettings settings = ExternalSystemApiUtil.getSettings(project, GradleConstants.SYSTEM_ID); - //noinspection unchecked - settings.linkProject(gradleProjectSettings); - } - - ImportSpec importSpec = new ImportSpecBuilder(project, GradleConstants.SYSTEM_ID) - .use(ProgressExecutionMode.IN_BACKGROUND_ASYNC) - .createDirectoriesForEmptyContentRoots() - .useDefaultCallback() - .build(); - ExternalSystemUtil.refreshProject(rootProjectPath, importSpec); - - final PsiFile psiFile; - if (finalBuildScriptFile != null) { - psiFile = PsiManager.getInstance(project).findFile(finalBuildScriptFile); - if (psiFile != null) { - EditorHelper.openInEditor(psiFile); - } - } - }; - - // execute when current dialog is closed - ExternalSystemUtil.invokeLater(project, ModalityState.NON_MODAL, runnable); - } - } - - @Override - public ModuleWizardStep[] createWizardSteps(@NotNull WizardContext wizardContext, @NotNull ModulesProvider modulesProvider) { - myWizardContext = wizardContext; - return new ModuleWizardStep[]{ - new GradleModuleWizardStep(this, wizardContext), - new ExternalModuleSettingsStep<>( - wizardContext, this, new GradleProjectSettingsControl(getExternalProjectSettings())) - }; - } - - @Nullable - @Override - public ModuleWizardStep getCustomOptionsStep(WizardContext context, Disposable parentDisposable) { - final GradleFrameworksWizardStep step = new GradleFrameworksWizardStep(context, this); - Disposer.register(parentDisposable, step); - return step; - } - - @Override - public boolean isSuitableSdkType(SdkTypeId sdk) { - return sdk instanceof JavaSdkType; - } - - @Override - public String getParentGroup() { - return JavaModuleType.BUILD_TOOLS_GROUP; - } - - @Override - public int getWeight() { - return JavaModuleBuilder.BUILD_SYSTEM_WEIGHT; - } - - @Override - public ModuleType getModuleType() { - return StdModuleTypes.JAVA; - } - - @Nullable - private VirtualFile setupGradleBuildFile(@NotNull VirtualFile modelContentRootDir) - throws ConfigurationException { - final VirtualFile file = getOrCreateExternalProjectConfigFile(modelContentRootDir.getPath(), GradleKotlinDSLConstants.DEFAULT_SCRIPT_NAME); - - if (file != null) { - final String templateName = getExternalProjectSettings().getDistributionType() == DistributionType.WRAPPED - ? TEMPLATE_GRADLE_BUILD_WITH_WRAPPER - : DEFAULT_TEMPLATE_GRADLE_BUILD; - Map attributes = ContainerUtil.newHashMap(); - if (myProjectId != null) { - attributes.put(TEMPLATE_ATTRIBUTE_MODULE_VERSION, myProjectId.getVersion()); - attributes.put(TEMPLATE_ATTRIBUTE_MODULE_GROUP, myProjectId.getGroupId()); - attributes.put(TEMPLATE_ATTRIBUTE_GRADLE_VERSION, GradleVersion.current().getVersion()); - } - saveFile(file, templateName, attributes); - } - return file; - } - - @Nullable - public static VirtualFile setupGradleSettingsFile(@NotNull String rootProjectPath, - @NotNull VirtualFile modelContentRootDir, - String projectName, - String moduleName, - boolean renderNewFile) - throws ConfigurationException { - final VirtualFile file = getOrCreateExternalProjectConfigFile(rootProjectPath, GradleConstants.SETTINGS_FILE_NAME); - if (file == null) return null; - - if (renderNewFile) { - final String moduleDirName = VfsUtilCore.getRelativePath(modelContentRootDir, file.getParent(), '/'); - - Map attributes = ContainerUtil.newHashMap(); - attributes.put(TEMPLATE_ATTRIBUTE_PROJECT_NAME, projectName); - attributes.put(TEMPLATE_ATTRIBUTE_MODULE_PATH, moduleDirName); - attributes.put(TEMPLATE_ATTRIBUTE_MODULE_NAME, moduleName); - attributes.put(TEMPLATE_ATTRIBUTE_BUILD_FILE_NAME, DEFAULT_SCRIPT_NAME); // TODO: gradle > 4.0 doesn't need this - saveFile(file, TEMPLATE_GRADLE_SETTINGS, attributes); - } - else { - char separatorChar = file.getParent() == null || !VfsUtilCore.isAncestor(file.getParent(), modelContentRootDir, true) ? '/' : ':'; - String modulePath = VfsUtil.getPath(file, modelContentRootDir, separatorChar); - - Map attributes = ContainerUtil.newHashMap(); - attributes.put(TEMPLATE_ATTRIBUTE_MODULE_NAME, moduleName); - // check for flat structure - final String flatStructureModulePath = - modulePath != null && StringUtil.startsWith(modulePath, "../") ? StringUtil.trimStart(modulePath, "../") : null; - if (StringUtil.equals(flatStructureModulePath, modelContentRootDir.getName())) { - attributes.put(TEMPLATE_ATTRIBUTE_MODULE_FLAT_DIR, "true"); - attributes.put(TEMPLATE_ATTRIBUTE_MODULE_PATH, flatStructureModulePath); - } - else { - attributes.put(TEMPLATE_ATTRIBUTE_MODULE_PATH, modulePath); - } - - appendToFile(file, TEMPLATE_GRADLE_SETTINGS_MERGE, attributes); - } - return file; - } - - private static void saveFile(@NotNull VirtualFile file, @NotNull String templateName, @Nullable Map templateAttributes) - throws ConfigurationException { - FileTemplateManager manager = FileTemplateManager.getDefaultInstance(); - FileTemplate template = manager.getInternalTemplate(templateName); - try { - appendToFile(file, templateAttributes != null ? template.getText(templateAttributes) : template.getText()); - } - catch (IOException e) { - LOG.warn(String.format("Unexpected exception on applying template %s config", GradleConstants.SYSTEM_ID.getReadableName()), e); - throw new ConfigurationException( - e.getMessage(), String.format("Can't apply %s template config text", GradleConstants.SYSTEM_ID.getReadableName()) - ); - } - } - - private static void appendToFile(@NotNull VirtualFile file, @NotNull String templateName, @Nullable Map templateAttributes) - throws ConfigurationException { - FileTemplateManager manager = FileTemplateManager.getDefaultInstance(); - FileTemplate template = manager.getInternalTemplate(templateName); - try { - appendToFile(file, templateAttributes != null ? template.getText(templateAttributes) : template.getText()); - } - catch (IOException e) { - LOG.warn(String.format("Unexpected exception on appending template %s config", GradleConstants.SYSTEM_ID.getReadableName()), e); - throw new ConfigurationException( - e.getMessage(), String.format("Can't append %s template config text", GradleConstants.SYSTEM_ID.getReadableName()) - ); - } - } - - - @Nullable - private static VirtualFile getOrCreateExternalProjectConfigFile(@NotNull String parent, @NotNull String fileName) { - File file = new File(parent, fileName); - FileUtilRt.createIfNotExists(file); - return LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file); - } - - public void setParentProject(@Nullable ProjectData parentProject) { - myParentProject = parentProject; - } - - public boolean isInheritGroupId() { - return myInheritGroupId; - } - - public void setInheritGroupId(boolean inheritGroupId) { - myInheritGroupId = inheritGroupId; - } - - public boolean isInheritVersion() { - return myInheritVersion; - } - - public void setInheritVersion(boolean inheritVersion) { - myInheritVersion = inheritVersion; - } - - public ProjectId getProjectId() { - return myProjectId; - } - - public void setProjectId(@NotNull ProjectId projectId) { - myProjectId = projectId; - } - - @Nullable - @Override - public ModuleWizardStep modifySettingsStep(@NotNull SettingsStep settingsStep) { - if (settingsStep instanceof ProjectSettingsStep) { - final ProjectSettingsStep projectSettingsStep = (ProjectSettingsStep)settingsStep; - if (myProjectId != null) { - final JTextField moduleNameField = settingsStep.getModuleNameField(); - if (moduleNameField != null) { - moduleNameField.setText(myProjectId.getArtifactId()); - } - projectSettingsStep.setModuleName(myProjectId.getArtifactId()); - } - projectSettingsStep.bindModuleSettings(); - } - return super.modifySettingsStep(settingsStep); - } - - public static void appendToFile(@NotNull VirtualFile file, @NotNull String text) throws IOException { - String lineSeparator = lineSeparator(file); - final String existingText = StringUtil.trimTrailing(VfsUtilCore.loadText(file)); - String content = (StringUtil.isNotEmpty(existingText) ? existingText + lineSeparator : "") + - StringUtil.convertLineSeparators(text, lineSeparator); - VfsUtil.saveText(file, content); - } - - @NotNull - private static String lineSeparator(@NotNull VirtualFile file) { - String lineSeparator = LoadTextUtil.detectLineSeparator(file, true); - if (lineSeparator == null) { - lineSeparator = CodeStyleSettingsManager.getSettings(ProjectManagerEx.getInstanceEx().getDefaultProject()).getLineSeparator(); - } - return lineSeparator; - } - - @Nullable - public static BuildScriptDataBuilder getBuildScriptData(@Nullable Module module) { - return module == null ? null : module.getUserData(BUILD_SCRIPT_DATA); - } - - @Nullable - @Override - public Project createProject(String name, String path) { - Project project = super.createProject(name, path); - if (project != null) { - GradleProjectSettings settings = getExternalProjectSettings(); - ExternalProjectsManagerImpl.getInstance(project).setStoreExternally(settings.isStoreProjectFilesExternally()); - } - return project; - } -} diff --git a/idea/idea-gradle/src/org/jetbrains/kotlin/gradle/kdsl/GradleModuleWizardStep.form.172 b/idea/idea-gradle/src/org/jetbrains/kotlin/gradle/kdsl/GradleModuleWizardStep.form.172 deleted file mode 100644 index b94d1e0017f..00000000000 --- a/idea/idea-gradle/src/org/jetbrains/kotlin/gradle/kdsl/GradleModuleWizardStep.form.172 +++ /dev/null @@ -1,105 +0,0 @@ - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
diff --git a/idea/idea-gradle/src/org/jetbrains/kotlin/gradle/kdsl/GradleModuleWizardStep.java.172 b/idea/idea-gradle/src/org/jetbrains/kotlin/gradle/kdsl/GradleModuleWizardStep.java.172 deleted file mode 100644 index f540c42a4d1..00000000000 --- a/idea/idea-gradle/src/org/jetbrains/kotlin/gradle/kdsl/GradleModuleWizardStep.java.172 +++ /dev/null @@ -1,257 +0,0 @@ -/* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.kotlin.gradle.kdsl; - -import com.intellij.ide.util.PropertiesComponent; -import com.intellij.ide.util.projectWizard.ModuleWizardStep; -import com.intellij.ide.util.projectWizard.WizardContext; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.externalSystem.model.project.ProjectData; -import com.intellij.openapi.externalSystem.model.project.ProjectId; -import com.intellij.openapi.externalSystem.service.project.wizard.ExternalModuleSettingsStep; -import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.options.ConfigurationException; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.Disposer; -import com.intellij.openapi.util.text.StringUtil; -import com.intellij.openapi.wm.IdeFocusManager; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.jetbrains.plugins.gradle.service.project.wizard.GradleParentProjectForm; -import org.jetbrains.plugins.gradle.util.GradleConstants; - -import javax.swing.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -public class GradleModuleWizardStep extends ModuleWizardStep { - private static final Icon WIZARD_ICON = null; - - private static final String INHERIT_GROUP_ID_KEY = "GradleModuleWizard.inheritGroupId"; - private static final String INHERIT_VERSION_KEY = "GradleModuleWizard.inheritVersion"; - private static final String DEFAULT_VERSION = "1.0-SNAPSHOT"; - - @Nullable - private final Project myProjectOrNull; - @NotNull - private final GradleModuleBuilder myBuilder; - @NotNull - private final WizardContext myContext; - @NotNull - private final GradleParentProjectForm myParentProjectForm; - - private String myInheritedGroupId; - private String myInheritedVersion; - - private JPanel myMainPanel; - - private JTextField myGroupIdField; - private JCheckBox myInheritGroupIdCheckBox; - private JTextField myArtifactIdField; - private JTextField myVersionField; - private JCheckBox myInheritVersionCheckBox; - private JPanel myAddToPanel; - - public GradleModuleWizardStep(@NotNull GradleModuleBuilder builder, @NotNull WizardContext context) { - myProjectOrNull = context.getProject(); - myBuilder = builder; - myContext = context; - myParentProjectForm = new GradleParentProjectForm(context, parentProject -> updateComponents()); - initComponents(); - loadSettings(); - } - - private void initComponents() { - myAddToPanel.add(myParentProjectForm.getComponent()); - ActionListener updatingListener = new ActionListener() { - public void actionPerformed(ActionEvent e) { - updateComponents(); - } - }; - myInheritGroupIdCheckBox.addActionListener(updatingListener); - myInheritVersionCheckBox.addActionListener(updatingListener); - } - - @Override - public JComponent getPreferredFocusedComponent() { - return myGroupIdField; - } - - @Override - public void onStepLeaving() { - saveSettings(); - } - - private void loadSettings() { - myBuilder.setInheritGroupId(getSavedValue(INHERIT_GROUP_ID_KEY, true)); - myBuilder.setInheritVersion(getSavedValue(INHERIT_VERSION_KEY, true)); - } - - private void saveSettings() { - saveValue(INHERIT_GROUP_ID_KEY, myInheritGroupIdCheckBox.isSelected()); - saveValue(INHERIT_VERSION_KEY, myInheritVersionCheckBox.isSelected()); - } - - private static boolean getSavedValue(String key, boolean defaultValue) { - return getSavedValue(key, String.valueOf(defaultValue)).equals(String.valueOf(true)); - } - - private static String getSavedValue(String key, String defaultValue) { - String value = PropertiesComponent.getInstance().getValue(key); - return value == null ? defaultValue : value; - } - - private static void saveValue(String key, boolean value) { - saveValue(key, String.valueOf(value)); - } - - private static void saveValue(String key, String value) { - PropertiesComponent.getInstance().setValue(key, value); - } - - public JComponent getComponent() { - return myMainPanel; - } - - @Override - public boolean validate() throws ConfigurationException { - if (StringUtil.isEmptyOrSpaces(myArtifactIdField.getText())) { - ApplicationManager.getApplication().invokeLater( - () -> IdeFocusManager.getInstance(myProjectOrNull).requestFocus(myArtifactIdField, true)); - throw new ConfigurationException("Please, specify artifactId"); - } - - return true; - } - - @Override - public void updateStep() { - ProjectData parentProject = myParentProjectForm.getParentProject(); - ProjectId projectId = myBuilder.getProjectId(); - - if (projectId == null) { - setTestIfEmpty(myArtifactIdField, myBuilder.getName()); - setTestIfEmpty(myGroupIdField, parentProject == null ? myBuilder.getName() : parentProject.getGroup()); - setTestIfEmpty(myVersionField, parentProject == null ? DEFAULT_VERSION : parentProject.getVersion()); - } - else { - setTestIfEmpty(myArtifactIdField, projectId.getArtifactId()); - setTestIfEmpty(myGroupIdField, projectId.getGroupId()); - setTestIfEmpty(myVersionField, projectId.getVersion()); - } - - myInheritGroupIdCheckBox.setSelected(myBuilder.isInheritGroupId()); - myInheritVersionCheckBox.setSelected(myBuilder.isInheritVersion()); - - updateComponents(); - } - - - private void updateComponents() { - final boolean isAddToVisible = myParentProjectForm.isVisible(); - - myInheritGroupIdCheckBox.setVisible(isAddToVisible); - myInheritVersionCheckBox.setVisible(isAddToVisible); - - myParentProjectForm.updateComponents(); - ProjectData parentProject = myParentProjectForm.getParentProject(); - if (parentProject == null) { - myContext.putUserData(ExternalModuleSettingsStep.SKIP_STEP_KEY, Boolean.FALSE); - myGroupIdField.setEnabled(true); - myVersionField.setEnabled(true); - myInheritGroupIdCheckBox.setEnabled(false); - myInheritVersionCheckBox.setEnabled(false); - - setTestIfEmpty(myArtifactIdField, myBuilder.getName()); - setTestIfEmpty(myGroupIdField, ""); - setTestIfEmpty(myVersionField, DEFAULT_VERSION); - } - else { - myContext.putUserData(ExternalModuleSettingsStep.SKIP_STEP_KEY, Boolean.TRUE); - myGroupIdField.setEnabled(!myInheritGroupIdCheckBox.isSelected()); - myVersionField.setEnabled(!myInheritVersionCheckBox.isSelected()); - - if (myInheritGroupIdCheckBox.isSelected() - || myGroupIdField.getText().equals(myInheritedGroupId)) { - myGroupIdField.setText(parentProject.getGroup()); - } - if (myInheritVersionCheckBox.isSelected() - || myVersionField.getText().equals(myInheritedVersion)) { - myVersionField.setText(parentProject.getVersion()); - } - myInheritedGroupId = myGroupIdField.getText(); - myInheritedVersion = myVersionField.getText(); - - myInheritGroupIdCheckBox.setEnabled(true); - myInheritVersionCheckBox.setEnabled(true); - } - } - - public static boolean isGradleModuleExist(WizardContext myContext) { - for (Module module : myContext.getModulesProvider().getModules()) { - if (ExternalSystemApiUtil.isExternalSystemAwareModule(GradleConstants.SYSTEM_ID, module)) return true; - } - return false; - } - - @Override - public void updateDataModel() { - myContext.setProjectBuilder(myBuilder); - ProjectData parentProject = myParentProjectForm.getParentProject(); - myBuilder.setParentProject(parentProject); - - myBuilder.setProjectId(new ProjectId(myGroupIdField.getText(), - myArtifactIdField.getText(), - myVersionField.getText())); - myBuilder.setInheritGroupId(myInheritGroupIdCheckBox.isSelected()); - myBuilder.setInheritVersion(myInheritVersionCheckBox.isSelected()); - - if (StringUtil.isNotEmpty(myBuilder.getProjectId().getArtifactId())) { - myContext.setProjectName(myBuilder.getProjectId().getArtifactId()); - } - if (parentProject != null) { - myContext.setProjectFileDirectory(parentProject.getLinkedExternalProjectPath() + '/' + myContext.getProjectName()); - } - else { - if (myProjectOrNull != null) { - myContext.setProjectFileDirectory(myProjectOrNull.getBaseDir().getPath() + '/' + myContext.getProjectName()); - } - } - } - - @Override - public Icon getIcon() { - return WIZARD_ICON; - } - - private static void setTestIfEmpty(@NotNull JTextField field, @Nullable String text) { - if (StringUtil.isEmpty(field.getText())) { - field.setText(StringUtil.notNullize(text)); - } - } - - @Override - public String getHelpId() { - return "Gradle_Archetype_Dialog"; - } - - @Override - public void disposeUIResources() { - Disposer.dispose(myParentProjectForm); - } -} - diff --git a/idea/idea-gradle/src/org/jetbrains/kotlin/gradle/kdsl/frameworkSupport/BuildScriptDataBuilder.java.172 b/idea/idea-gradle/src/org/jetbrains/kotlin/gradle/kdsl/frameworkSupport/BuildScriptDataBuilder.java.172 deleted file mode 100644 index 679e583b4c3..00000000000 --- a/idea/idea-gradle/src/org/jetbrains/kotlin/gradle/kdsl/frameworkSupport/BuildScriptDataBuilder.java.172 +++ /dev/null @@ -1,158 +0,0 @@ -/* - * Copyright 2000-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.kotlin.gradle.kdsl.frameworkSupport; - -import com.intellij.openapi.util.text.StringUtil; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.util.Function; -import com.intellij.util.containers.ContainerUtil; -import org.jetbrains.annotations.NotNull; - -import java.util.List; -import java.util.Set; - -public class BuildScriptDataBuilder { - @NotNull private final VirtualFile myBuildScriptFile; - private final Set plugins = ContainerUtil.newTreeSet(); - private final Set pluginsInGroup = ContainerUtil.newTreeSet(); - private final Set repositories = ContainerUtil.newTreeSet(); - private final Set dependencies = ContainerUtil.newTreeSet(); - private final Set properties = ContainerUtil.newTreeSet(); - private final Set buildScriptProperties = ContainerUtil.newTreeSet(); - private final Set buildScriptRepositories = ContainerUtil.newTreeSet(); - private final Set buildScriptDependencies = ContainerUtil.newTreeSet(); - private final Set other = ContainerUtil.newTreeSet(); - - public BuildScriptDataBuilder(@NotNull VirtualFile buildScriptFile) { - myBuildScriptFile = buildScriptFile; - } - - @NotNull - public VirtualFile getBuildScriptFile() { - return myBuildScriptFile; - } - - public String buildConfigurationPart() { - List lines = ContainerUtil.newArrayList(); - addBuildscriptLines(lines, BuildScriptDataBuilder::padding); - if (!pluginsInGroup.isEmpty()) { - lines.add("plugins {"); - lines.addAll(ContainerUtil.map(pluginsInGroup, BuildScriptDataBuilder::padding)); - lines.add("}"); - lines.add(""); - } - return StringUtil.join(lines, "\n"); - } - - public String buildMainPart() { - List lines = ContainerUtil.newArrayList(); - if (!plugins.isEmpty()) { - lines.addAll(plugins); - lines.add(""); - } - if (!properties.isEmpty()) { - lines.addAll(properties); - lines.add(""); - } - if (!repositories.isEmpty()) { - lines.add("repositories {"); - lines.addAll(ContainerUtil.map(repositories, BuildScriptDataBuilder::padding)); - lines.add("}"); - lines.add(""); - } - if (!dependencies.isEmpty()) { - lines.add("dependencies {"); - lines.addAll(ContainerUtil.map(dependencies, BuildScriptDataBuilder::padding)); - lines.add("}"); - lines.add(""); - } - if (!other.isEmpty()) { - lines.addAll(other); - } - return StringUtil.join(lines, "\n"); - } - - private void addBuildscriptLines(@NotNull List lines, @NotNull Function padding) { - if (!buildScriptRepositories.isEmpty() || !buildScriptDependencies.isEmpty() || !buildScriptProperties.isEmpty()) { - lines.add("buildscript {"); - final List buildScriptLines = ContainerUtil.newSmartList(); - if (!buildScriptProperties.isEmpty()) { - buildScriptLines.addAll(buildScriptProperties); - buildScriptLines.add(""); - } - if (!buildScriptRepositories.isEmpty()) { - buildScriptLines.add("repositories {"); - buildScriptLines.addAll(ContainerUtil.map(buildScriptRepositories, padding)); - buildScriptLines.add("}"); - } - if (!buildScriptDependencies.isEmpty()) { - buildScriptLines.add("dependencies {"); - buildScriptLines.addAll(ContainerUtil.map(buildScriptDependencies, padding)); - buildScriptLines.add("}"); - } - lines.addAll(ContainerUtil.map(buildScriptLines, padding)); - lines.add("}"); - lines.add(""); - } - } - - public BuildScriptDataBuilder addBuildscriptPropertyDefinition(@NotNull String definition) { - buildScriptProperties.add(definition.trim()); - return this; - } - - public BuildScriptDataBuilder addBuildscriptRepositoriesDefinition(@NotNull String definition) { - buildScriptRepositories.add(definition.trim()); - return this; - } - - public BuildScriptDataBuilder addBuildscriptDependencyNotation(@NotNull String notation) { - buildScriptDependencies.add(notation.trim()); - return this; - } - - public BuildScriptDataBuilder addPluginDefinitionInPluginsGroup(@NotNull String definition) { - pluginsInGroup.add(definition.trim()); - return this; - } - - public BuildScriptDataBuilder addPluginDefinition(@NotNull String definition) { - plugins.add(definition.trim()); - return this; - } - - public BuildScriptDataBuilder addRepositoriesDefinition(@NotNull String definition) { - repositories.add(definition.trim()); - return this; - } - - public BuildScriptDataBuilder addDependencyNotation(@NotNull String notation) { - dependencies.add(notation.trim()); - return this; - } - - public BuildScriptDataBuilder addPropertyDefinition(@NotNull String definition) { - properties.add(definition.trim()); - return this; - } - - public BuildScriptDataBuilder addOther(@NotNull String definition) { - other.add(definition.trim()); - return this; - } - - private static String padding(String s) {return StringUtil.isNotEmpty(s) ? " " + s : "";} -} diff --git a/idea/idea-gradle/src/org/jetbrains/kotlin/gradle/kdsl/frameworkSupport/GradleFrameworkSupportProvider.java.172 b/idea/idea-gradle/src/org/jetbrains/kotlin/gradle/kdsl/frameworkSupport/GradleFrameworkSupportProvider.java.172 deleted file mode 100644 index cfe1c3eef59..00000000000 --- a/idea/idea-gradle/src/org/jetbrains/kotlin/gradle/kdsl/frameworkSupport/GradleFrameworkSupportProvider.java.172 +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.kotlin.gradle.kdsl.frameworkSupport; - -import com.intellij.framework.addSupport.FrameworkSupportInModuleConfigurable; -import com.intellij.framework.addSupport.FrameworkSupportInModuleProvider; -import com.intellij.ide.util.frameworkSupport.FrameworkSupportModel; -import com.intellij.openapi.extensions.ExtensionPointName; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.module.ModuleType; -import com.intellij.openapi.roots.ModifiableModelsProvider; -import com.intellij.openapi.roots.ModifiableRootModel; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import javax.swing.*; - -import static org.jetbrains.kotlin.gradle.kdsl.GradleModuleBuilder.getBuildScriptData; - -public abstract class GradleFrameworkSupportProvider extends FrameworkSupportInModuleProvider { - - public static final ExtensionPointName EP_NAME = - ExtensionPointName.create("org.jetbrains.kotlin.gradleFrameworkSupport"); - - public abstract void addSupport(@NotNull Module module, @NotNull ModifiableRootModel rootModel, - @NotNull ModifiableModelsProvider modifiableModelsProvider, - @NotNull BuildScriptDataBuilder buildScriptData); - - public JComponent createComponent() { - return null; - } - - @NotNull - @Override - public FrameworkSupportInModuleConfigurable createConfigurable(@NotNull FrameworkSupportModel model) { - return new FrameworkSupportInModuleConfigurable() { - @Nullable - @Override - public JComponent createComponent() { - return GradleFrameworkSupportProvider.this.createComponent(); - } - - @Override - public void addSupport(@NotNull Module module, - @NotNull ModifiableRootModel rootModel, - @NotNull ModifiableModelsProvider modifiableModelsProvider) { - final BuildScriptDataBuilder buildScriptData = getBuildScriptData(module); - if (buildScriptData != null) { - GradleFrameworkSupportProvider.this.addSupport(module, rootModel, modifiableModelsProvider, buildScriptData); - } - } - }; - } - - @Override - public boolean isEnabledForModuleType(@NotNull ModuleType moduleType) { - return false; - } -} diff --git a/idea/idea-gradle/src/org/jetbrains/kotlin/gradle/kdsl/frameworkSupport/GradleGroovyFrameworkSupportProvider.java.172 b/idea/idea-gradle/src/org/jetbrains/kotlin/gradle/kdsl/frameworkSupport/GradleGroovyFrameworkSupportProvider.java.172 deleted file mode 100644 index 7d9daced59c..00000000000 --- a/idea/idea-gradle/src/org/jetbrains/kotlin/gradle/kdsl/frameworkSupport/GradleGroovyFrameworkSupportProvider.java.172 +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.kotlin.gradle.kdsl.frameworkSupport; - -import com.intellij.framework.FrameworkTypeEx; -import com.intellij.framework.addSupport.FrameworkSupportInModuleProvider; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.roots.ModifiableModelsProvider; -import com.intellij.openapi.roots.ModifiableRootModel; -import icons.JetgroovyIcons; -import org.jetbrains.annotations.NotNull; - -import javax.swing.*; - -public class GradleGroovyFrameworkSupportProvider extends GradleFrameworkSupportProvider { - - public static final String ID = "groovy"; - - @NotNull - @Override - public FrameworkTypeEx getFrameworkType() { - return new FrameworkTypeEx(ID) { - @NotNull - @Override - public FrameworkSupportInModuleProvider createProvider() { - return GradleGroovyFrameworkSupportProvider.this; - } - - @NotNull - @Override - public String getPresentableName() { - return "Groovy"; - } - - @NotNull - @Override - public Icon getIcon() { - return JetgroovyIcons.Groovy.Groovy_16x16; - } - }; - } - - @Override - public void addSupport(@NotNull Module module, - @NotNull ModifiableRootModel rootModel, - @NotNull ModifiableModelsProvider modifiableModelsProvider, - @NotNull BuildScriptDataBuilder buildScriptData) { - buildScriptData - .addPluginDefinition("plugin(\"groovy\")") - .addRepositoriesDefinition("mavenCentral()") - .addDependencyNotation("compile(\"org.codehaus.groovy:groovy-all:2.3.11\")") - .addDependencyNotation("testCompile(\"junit\", \"junit\", \"4.12\")"); - } -} \ No newline at end of file diff --git a/idea/idea-gradle/src/org/jetbrains/kotlin/gradle/kdsl/frameworkSupport/GradleJavaFrameworkSupportProvider.java.172 b/idea/idea-gradle/src/org/jetbrains/kotlin/gradle/kdsl/frameworkSupport/GradleJavaFrameworkSupportProvider.java.172 deleted file mode 100644 index 0bde690ccc1..00000000000 --- a/idea/idea-gradle/src/org/jetbrains/kotlin/gradle/kdsl/frameworkSupport/GradleJavaFrameworkSupportProvider.java.172 +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2000-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.gradle.kdsl.frameworkSupport; - -import com.intellij.framework.FrameworkTypeEx; -import com.intellij.framework.addSupport.FrameworkSupportInModuleProvider; -import com.intellij.icons.AllIcons; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.roots.ModifiableModelsProvider; -import com.intellij.openapi.roots.ModifiableRootModel; -import org.jetbrains.annotations.NotNull; - -import javax.swing.*; - -public class GradleJavaFrameworkSupportProvider extends GradleFrameworkSupportProvider { - - public static final String ID = "java"; - - @NotNull - @Override - public FrameworkTypeEx getFrameworkType() { - return new FrameworkTypeEx(ID) { - @NotNull - @Override - public FrameworkSupportInModuleProvider createProvider() { - return GradleJavaFrameworkSupportProvider.this; - } - - @NotNull - @Override - public String getPresentableName() { - return "Java"; - } - - @NotNull - @Override - public Icon getIcon() { - return AllIcons.Nodes.Module; - } - }; - } - - @Override - public void addSupport(@NotNull Module module, - @NotNull ModifiableRootModel rootModel, - @NotNull ModifiableModelsProvider modifiableModelsProvider, - @NotNull BuildScriptDataBuilder buildScriptData) { - buildScriptData - .addPluginDefinition("plugin(\"java\")") - // TODO: in gradle > 4.0 it is just 'java { ... }' - .addOther("configure {\n sourceCompatibility = JavaVersion.VERSION_1_8\n}") - .addRepositoriesDefinition("mavenCentral()") - .addDependencyNotation("testCompile(\"junit\", \"junit\", \"4.12\")"); - } -} diff --git a/idea/idea-gradle/src/org/jetbrains/kotlin/gradle/kdsl/frameworkSupport/GradleKotlinFrameworkSupportProvider.kt.172 b/idea/idea-gradle/src/org/jetbrains/kotlin/gradle/kdsl/frameworkSupport/GradleKotlinFrameworkSupportProvider.kt.172 deleted file mode 100644 index e16ad485689..00000000000 --- a/idea/idea-gradle/src/org/jetbrains/kotlin/gradle/kdsl/frameworkSupport/GradleKotlinFrameworkSupportProvider.kt.172 +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.kotlin.gradle.kdsl.frameworkSupport - -import com.intellij.framework.FrameworkTypeEx -import com.intellij.framework.addSupport.FrameworkSupportInModuleProvider -import com.intellij.openapi.module.Module -import com.intellij.openapi.roots.ModifiableModelsProvider -import com.intellij.openapi.roots.ModifiableRootModel -import com.intellij.openapi.vfs.VfsUtil -import org.jetbrains.kotlin.idea.KotlinIcons -import org.jetbrains.kotlin.idea.configuration.* -import org.jetbrains.kotlin.idea.configuration.KotlinBuildScriptManipulator.Companion.GSK_KOTLIN_VERSION_PROPERTY_NAME -import org.jetbrains.kotlin.idea.configuration.KotlinBuildScriptManipulator.Companion.getCompileDependencySnippet -import org.jetbrains.kotlin.idea.configuration.KotlinBuildScriptManipulator.Companion.getKotlinGradlePluginClassPathSnippet -import org.jetbrains.kotlin.idea.versions.* -import javax.swing.Icon - -abstract class GradleKotlinDSLKotlinFrameworkSupportProvider( - val frameworkTypeId: String, - val displayName: String, - val frameworkIcon: Icon -) : GradleFrameworkSupportProvider() { - override fun getFrameworkType(): FrameworkTypeEx = object : FrameworkTypeEx(frameworkTypeId) { - override fun getIcon(): Icon = frameworkIcon - override fun getPresentableName(): String = displayName - override fun createProvider(): FrameworkSupportInModuleProvider = this@GradleKotlinDSLKotlinFrameworkSupportProvider - } - - override fun addSupport( - module: Module, - rootModel: ModifiableRootModel, - modifiableModelsProvider: ModifiableModelsProvider, - buildScriptData: BuildScriptDataBuilder - ) { - var kotlinVersion = bundledRuntimeVersion() - val additionalRepository = getRepositoryForVersion(kotlinVersion) - if (isSnapshot(bundledRuntimeVersion())) { - kotlinVersion = LAST_SNAPSHOT_VERSION - } - - if (additionalRepository != null) { - val repository = additionalRepository.toKotlinRepositorySnippet() - buildScriptData.addBuildscriptRepositoriesDefinition(repository) - buildScriptData.addRepositoriesDefinition("mavenCentral()") - buildScriptData.addRepositoriesDefinition(repository) - } - - buildScriptData - .addPropertyDefinition("val $GSK_KOTLIN_VERSION_PROPERTY_NAME: String by extra") - .addPluginDefinition(getPluginDefinition()) - .addBuildscriptRepositoriesDefinition("mavenCentral()") - .addRepositoriesDefinition("mavenCentral()") - // TODO: in gradle > 4.1 this could be single declaration e.g. 'val kotlin_version: String by extra { "1.1.11" }' - .addBuildscriptPropertyDefinition("var $GSK_KOTLIN_VERSION_PROPERTY_NAME: String by extra\n$GSK_KOTLIN_VERSION_PROPERTY_NAME = \"$kotlinVersion\"") - .addDependencyNotation(getRuntimeLibrary(rootModel)) - .addBuildscriptDependencyNotation(getKotlinGradlePluginClassPathSnippet()) - } - - protected abstract fun getRuntimeLibrary(rootModel: ModifiableRootModel): String - - protected abstract fun getPluginDefinition(): String -} - -class GradleKotlinDSLKotlinJavaFrameworkSupportProvider : - GradleKotlinDSLKotlinFrameworkSupportProvider("KOTLIN", "Kotlin (Java)", KotlinIcons.SMALL_LOGO) { - - override fun getPluginDefinition() = "plugin(\"${KotlinGradleModuleConfigurator.KOTLIN}\")" - - override fun getRuntimeLibrary(rootModel: ModifiableRootModel) = - getCompileDependencySnippet(KOTLIN_GROUP_ID, getStdlibArtifactId(rootModel.sdk, bundledRuntimeVersion())) - - override fun addSupport( - module: Module, - rootModel: ModifiableRootModel, - modifiableModelsProvider: ModifiableModelsProvider, - buildScriptData: BuildScriptDataBuilder - ) { - super.addSupport(module, rootModel, modifiableModelsProvider, buildScriptData) - val jvmTarget = getDefaultJvmTarget(rootModel.sdk, bundledRuntimeVersion()) - if (jvmTarget != null) { - buildScriptData - .addImports("import org.jetbrains.kotlin.gradle.tasks.KotlinCompile") - .addOther("tasks.withType {\n kotlinOptions.jvmTarget = \"1.8\"\n}\n") - } - } - - private fun BuildScriptDataBuilder.addImports(vararg import: String): BuildScriptDataBuilder = apply { - val text = VfsUtil.loadText(buildScriptFile) - VfsUtil.saveText(buildScriptFile, import.joinToString(separator = "\n") + "\n\n" + text) - } -} - -class GradleKotlinDSLKotlinJSFrameworkSupportProvider : - GradleKotlinDSLKotlinFrameworkSupportProvider("KOTLIN_JS", "Kotlin (JavaScript)", KotlinIcons.JS) { - - override fun getPluginDefinition(): String = "plugin(\"${KotlinJsGradleModuleConfigurator.KOTLIN_JS}\")" - - override fun getRuntimeLibrary(rootModel: ModifiableRootModel) = - getCompileDependencySnippet(KOTLIN_GROUP_ID, MAVEN_JS_STDLIB_ID.removePrefix("kotlin-")) -} diff --git a/idea/idea-gradle/src/org/jetbrains/kotlin/gradle/kdsl/frameworkSupport/KotlinBuildScriptDataBuilder.kt.172 b/idea/idea-gradle/src/org/jetbrains/kotlin/gradle/kdsl/frameworkSupport/KotlinBuildScriptDataBuilder.kt.172 deleted file mode 100644 index 950eb9ae738..00000000000 --- a/idea/idea-gradle/src/org/jetbrains/kotlin/gradle/kdsl/frameworkSupport/KotlinBuildScriptDataBuilder.kt.172 +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.kotlin.gradle.kdsl.frameworkSupport - -import com.intellij.openapi.vfs.VirtualFile -import com.intellij.util.containers.ContainerUtil - -class KotlinBuildScriptDataBuilder(buildScriptFile: VirtualFile) : BuildScriptDataBuilder(buildScriptFile) { - private val plugins: MutableSet = ContainerUtil.newTreeSet() - private val properties: MutableSet = ContainerUtil.newTreeSet() - private val repositories: MutableSet = ContainerUtil.newTreeSet() - private val dependencies: MutableSet = ContainerUtil.newTreeSet() - - private val buildScriptProperties: MutableSet = ContainerUtil.newTreeSet() - private val buildScriptRepositories: MutableSet = ContainerUtil.newTreeSet() - private val buildScriptDependencies: MutableSet = ContainerUtil.newTreeSet() - private val other: MutableSet = ContainerUtil.newTreeSet() - - override fun addPluginDefinition(definition: String): BuildScriptDataBuilder = apply { plugins.add(definition) } - - override fun addRepositoriesDefinition(definition: String): BuildScriptDataBuilder = apply { repositories.add(definition) } - - override fun addPropertyDefinition(definition: String): BuildScriptDataBuilder = apply { properties.add(definition) } - - override fun addDependencyNotation(notation: String): BuildScriptDataBuilder = apply { dependencies.add(notation) } - - override fun addBuildscriptPropertyDefinition(definition: String): BuildScriptDataBuilder = apply { buildScriptProperties.add(definition) } - - override fun addBuildscriptRepositoriesDefinition(definition: String): BuildScriptDataBuilder = apply { buildScriptRepositories.add(definition) } - - override fun addBuildscriptDependencyNotation(notation: String): BuildScriptDataBuilder = apply { buildScriptDependencies.add(notation) } - - override fun addOther(definition: String): BuildScriptDataBuilder = apply { other.add(definition) } - - override fun buildMainPart(): String = buildString { - - appendlnIfNotNull(buildBuildScriptBlock()) - - appendlnIfNotNull(buildBlock("apply", plugins)) - - if (properties.isNotEmpty()) { - properties.forEach { appendln(it) } - appendln() - } - - appendlnIfNotNull(buildBlock("repositories", repositories)) - - appendlnIfNotNull(buildBlock("dependencies", dependencies)) - - other.forEach { appendln(it) } - } - - private fun buildBuildScriptBlock(): String? = buildString { - if (buildScriptProperties.isEmpty() || buildScriptRepositories.isEmpty() || buildScriptDependencies.isEmpty()) { - return null - } - - appendln("buildscript {") - buildScriptProperties.forEach { appendln(it.withMargin) } - appendln() - appendlnIfNotNull(buildBlock("repositories", buildScriptRepositories)?.withMargin) - appendlnIfNotNull(buildBlock("dependencies", buildScriptDependencies)?.withMargin) - appendln("}") - } - - private fun buildBlock(name: String, lines: Set): String? = buildString { - if (lines.isEmpty()) { - return null - } - - appendln("$name {") - lines.forEach { appendln(it.withMargin) } - appendln("}") - } - - private val String.withMargin: String - get() = lines().joinToString(separator = "\n") { " " + it } - - private fun StringBuilder.appendlnIfNotNull(text: String?) = text?.let { appendln(it) } -} diff --git a/idea/idea-gradle/src/org/jetbrains/kotlin/idea/configuration/GradleBuildScriptManipulator.kt.172 b/idea/idea-gradle/src/org/jetbrains/kotlin/idea/configuration/GradleBuildScriptManipulator.kt.172 deleted file mode 100644 index a737dadc79a..00000000000 --- a/idea/idea-gradle/src/org/jetbrains/kotlin/idea/configuration/GradleBuildScriptManipulator.kt.172 +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.kotlin.idea.configuration - -import com.intellij.openapi.roots.DependencyScope -import com.intellij.openapi.roots.ExternalLibraryDescriptor -import com.intellij.psi.PsiElement -import com.intellij.psi.PsiFile -import org.gradle.util.GradleVersion -import org.jetbrains.plugins.gradle.frameworkSupport.BuildScriptDataBuilder - -interface GradleBuildScriptManipulator { - val scriptFile: Psi - val preferNewSyntax: Boolean - - fun isConfiguredWithOldSyntax(kotlinPluginName: String): Boolean - fun isConfigured(kotlinPluginExpression: String): Boolean - - fun configureModuleBuildScript( - kotlinPluginName: String, - kotlinPluginExpression: String, - stdlibArtifactName: String, - version: String, - jvmTarget: String? - ): Boolean - - fun configureProjectBuildScript(kotlinPluginName: String, version: String): Boolean - - fun changeCoroutineConfiguration(coroutineOption: String): PsiElement? - - fun changeLanguageVersion(version: String, forTests: Boolean): PsiElement? - - fun changeApiVersion(version: String, forTests: Boolean): PsiElement? - - fun addKotlinLibraryToModuleBuildScript( - scope: DependencyScope, - libraryDescriptor: ExternalLibraryDescriptor, - isAndroidModule: Boolean - ) - - fun getKotlinStdlibVersion(): String? - - // For settings.gradle/settings.gradle.kts - - fun addMavenCentralPluginRepository() - fun addPluginRepository(repository: RepositoryDescription) - - fun addResolutionStrategy(pluginId: String) -} - -val MIN_GRADLE_VERSION_FOR_NEW_PLUGIN_SYNTAX = GradleVersion.version("4.4") - -// Kept for compatibility reasons (pre-181.3 IDEAs) -fun GradleBuildScriptManipulator<*>.useNewSyntax(kotlinPluginName: String) = false -val BuildScriptDataBuilder.gradleVersion get() = GradleVersion.version("0.0") -fun BuildScriptDataBuilder.addPluginDefinitionInPluginsGroup(pluginId: String) {} \ No newline at end of file diff --git a/idea/idea-gradle/src/org/jetbrains/kotlin/idea/configuration/GradleKotlinFrameworkSupportProvider.kt.172 b/idea/idea-gradle/src/org/jetbrains/kotlin/idea/configuration/GradleKotlinFrameworkSupportProvider.kt.172 deleted file mode 100644 index 5973e940f59..00000000000 --- a/idea/idea-gradle/src/org/jetbrains/kotlin/idea/configuration/GradleKotlinFrameworkSupportProvider.kt.172 +++ /dev/null @@ -1,240 +0,0 @@ -/* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.kotlin.idea.configuration - -import com.intellij.framework.FrameworkTypeEx -import com.intellij.framework.addSupport.FrameworkSupportInModuleConfigurable -import com.intellij.framework.addSupport.FrameworkSupportInModuleProvider -import com.intellij.ide.util.frameworkSupport.FrameworkSupportModel -import com.intellij.openapi.module.Module -import com.intellij.openapi.projectRoots.Sdk -import com.intellij.openapi.roots.ModifiableModelsProvider -import com.intellij.openapi.roots.ModifiableRootModel -import com.intellij.psi.PsiFile -import org.jetbrains.kotlin.idea.KotlinIcons -import org.jetbrains.kotlin.idea.versions.* -import org.jetbrains.plugins.gradle.frameworkSupport.BuildScriptDataBuilder -import org.jetbrains.plugins.gradle.frameworkSupport.GradleFrameworkSupportProvider -import javax.swing.Icon -import javax.swing.JComponent -import javax.swing.JLabel - -abstract class GradleKotlinFrameworkSupportProvider( - val frameworkTypeId: String, - val displayName: String, - val frameworkIcon: Icon -) : GradleFrameworkSupportProvider() { - override fun getFrameworkType(): FrameworkTypeEx = object : FrameworkTypeEx(frameworkTypeId) { - override fun getIcon(): Icon = frameworkIcon - - override fun getPresentableName(): String = displayName - - override fun createProvider(): FrameworkSupportInModuleProvider = this@GradleKotlinFrameworkSupportProvider - } - - override fun createConfigurable(model: FrameworkSupportModel): FrameworkSupportInModuleConfigurable { - val configurable = KotlinGradleFrameworkSupportInModuleConfigurable(model, this) - return object : FrameworkSupportInModuleConfigurable() { - override fun addSupport(module: Module, rootModel: ModifiableRootModel, modifiableModelsProvider: ModifiableModelsProvider) { - configurable.addSupport(module, rootModel, modifiableModelsProvider) - } - - override fun createComponent(): JComponent = JLabel(getDescription()) - } - } - - override fun addSupport( - module: Module, - rootModel: ModifiableRootModel, - modifiableModelsProvider: ModifiableModelsProvider, - buildScriptData: BuildScriptDataBuilder - ) { - addSupport(buildScriptData, module, rootModel.sdk, true) - } - - open fun addSupport(buildScriptData: BuildScriptDataBuilder, module: Module, sdk: Sdk?, specifyPluginVersionIfNeeded: Boolean) { - var kotlinVersion = bundledRuntimeVersion() - val additionalRepository = getRepositoryForVersion(kotlinVersion) - if (isSnapshot(bundledRuntimeVersion())) { - kotlinVersion = LAST_SNAPSHOT_VERSION - } - - val useNewSyntax = buildScriptData.gradleVersion >= MIN_GRADLE_VERSION_FOR_NEW_PLUGIN_SYNTAX - if (useNewSyntax) { - if (additionalRepository != null) { - val oneLineRepository = additionalRepository.toGroovyRepositorySnippet().replace('\n', ' ') - updateSettingsScript(module) { - with(KotlinWithGradleConfigurator.getManipulator(it)) { - addPluginRepository(additionalRepository) - addMavenCentralPluginRepository() - addPluginRepository(DEFAULT_GRADLE_PLUGIN_REPOSITORY) - } - } - buildScriptData.addRepositoriesDefinition("mavenCentral()") - buildScriptData.addRepositoriesDefinition(oneLineRepository) - } - - buildScriptData.addPluginDefinitionInPluginsGroup( - getPluginExpression() + if (specifyPluginVersionIfNeeded) " version '$kotlinVersion'" else "" - ) - } else { - if (additionalRepository != null) { - val oneLineRepository = additionalRepository.toGroovyRepositorySnippet().replace('\n', ' ') - buildScriptData.addBuildscriptRepositoriesDefinition(oneLineRepository) - - buildScriptData.addRepositoriesDefinition("mavenCentral()") - buildScriptData.addRepositoriesDefinition(oneLineRepository) - } - - buildScriptData - .addPluginDefinition(KotlinWithGradleConfigurator.getGroovyApplyPluginDirective(getPluginId())) - .addBuildscriptRepositoriesDefinition("mavenCentral()") - .addBuildscriptPropertyDefinition("ext.kotlin_version = '$kotlinVersion'") - } - - buildScriptData.addRepositoriesDefinition("mavenCentral()") - - for (dependency in getDependencies(sdk)) { - buildScriptData.addDependencyNotation(KotlinWithGradleConfigurator.getGroovyDependencySnippet(dependency, "compile", !useNewSyntax)) - } - for (dependency in getTestDependencies()) { - buildScriptData.addDependencyNotation( - if (":" in dependency) - "testCompile \"$dependency\"" - else - KotlinWithGradleConfigurator.getGroovyDependencySnippet(dependency, "testCompile", !useNewSyntax) - ) - } - - if (useNewSyntax) { - updateSettingsScript(module) { updateSettingsScript(it, specifyPluginVersionIfNeeded) } - } else { - buildScriptData.addBuildscriptDependencyNotation(KotlinWithGradleConfigurator.CLASSPATH) - } - } - - protected open fun updateSettingsScript(settingsScript: PsiFile, specifyPluginVersionIfNeeded: Boolean) { } - - protected abstract fun getDependencies(sdk: Sdk?): List - protected open fun getTestDependencies(): List = listOf() - - protected abstract fun getPluginId(): String - protected abstract fun getPluginExpression(): String - - protected abstract fun getDescription(): String -} - -open class GradleKotlinJavaFrameworkSupportProvider( - frameworkTypeId: String = "KOTLIN", - displayName: String = "Kotlin (Java)" -) : GradleKotlinFrameworkSupportProvider(frameworkTypeId, displayName, KotlinIcons.SMALL_LOGO) { - - override fun getPluginId() = KotlinGradleModuleConfigurator.KOTLIN - override fun getPluginExpression() = "id 'org.jetbrains.kotlin.jvm'" - - override fun getDependencies(sdk: Sdk?) = listOf(getStdlibArtifactId(sdk, bundledRuntimeVersion())) - - override fun addSupport(buildScriptData: BuildScriptDataBuilder, module: Module, sdk: Sdk?, specifyPluginVersionIfNeeded: Boolean) { - super.addSupport(buildScriptData, module, sdk, specifyPluginVersionIfNeeded) - val jvmTarget = getDefaultJvmTarget(sdk, bundledRuntimeVersion()) - if (jvmTarget != null) { - val description = jvmTarget.description - buildScriptData.addOther("compileKotlin {\n kotlinOptions.jvmTarget = \"$description\"\n}\n\n") - buildScriptData.addOther("compileTestKotlin {\n kotlinOptions.jvmTarget = \"$description\"\n}\n") - } - } - - override fun getDescription() = "A Kotlin library or application targeting the JVM" -} - -open class GradleKotlinJSFrameworkSupportProvider( - frameworkTypeId: String = "KOTLIN_JS", - displayName: String = "Kotlin (JavaScript)" -) : GradleKotlinFrameworkSupportProvider(frameworkTypeId, displayName, KotlinIcons.JS) { - - override fun getPluginId() = KotlinJsGradleModuleConfigurator.KOTLIN_JS - override fun getPluginExpression() = "id 'kotlin2js'" - - override fun getDependencies(sdk: Sdk?) = listOf(MAVEN_JS_STDLIB_ID) - - override fun getTestDependencies() = listOf(MAVEN_JS_TEST_ID) - - override fun updateSettingsScript(settingsScript: PsiFile, specifyPluginVersionIfNeeded: Boolean) { - if (specifyPluginVersionIfNeeded) { - KotlinWithGradleConfigurator.getManipulator(settingsScript).addResolutionStrategy("kotlin2js") - } - } - - override fun getDescription() = "A Kotlin library or application targeting JavaScript" -} - -open class GradleKotlinMPPCommonFrameworkSupportProvider : - GradleKotlinFrameworkSupportProvider("KOTLIN_MPP_COMMON", "Kotlin (Multiplatform Common - Experimental)", KotlinIcons.MPP) { - override fun getPluginId() = "kotlin-platform-common" - override fun getPluginExpression() = "id 'kotlin-platform-common'" - - override fun getDependencies(sdk: Sdk?) = listOf(MAVEN_COMMON_STDLIB_ID) - override fun getTestDependencies() = listOf(MAVEN_COMMON_TEST_ID, MAVEN_COMMON_TEST_ANNOTATIONS_ID) - - override fun updateSettingsScript(settingsScript: PsiFile, specifyPluginVersionIfNeeded: Boolean) { - if (specifyPluginVersionIfNeeded) { - KotlinWithGradleConfigurator.getManipulator(settingsScript).addResolutionStrategy("kotlin-platform-common") - } - } - - override fun getDescription() = "Shared code for a Kotlin multiplatform project (targeting JVM and JS)" -} - -class GradleKotlinMPPJavaFrameworkSupportProvider - : GradleKotlinJavaFrameworkSupportProvider("KOTLIN_MPP_JVM", "Kotlin (Multiplatform JVM - Experimental)") { - - override fun getPluginId() = "kotlin-platform-jvm" - override fun getPluginExpression() = "id 'kotlin-platform-jvm'" - - override fun getDescription() = "JVM-specific code for a Kotlin multiplatform project" - override fun getTestDependencies() = listOf(MAVEN_TEST_ID, MAVEN_TEST_JUNIT_ID, "junit:junit:4.12") - - override fun addSupport(buildScriptData: BuildScriptDataBuilder, module: Module, sdk: Sdk?, specifyPluginVersionIfNeeded: Boolean) { - super.addSupport(buildScriptData, module, sdk, specifyPluginVersionIfNeeded) - val jvmTarget = getDefaultJvmTarget(sdk, bundledRuntimeVersion()) - if (jvmTarget != null) { - val description = jvmTarget.description - buildScriptData.addOther("sourceCompatibility = \"$description\"\n\n") - } - } - - override fun updateSettingsScript(settingsScript: PsiFile, specifyPluginVersionIfNeeded: Boolean) { - if (specifyPluginVersionIfNeeded) { - KotlinWithGradleConfigurator.getManipulator(settingsScript).addResolutionStrategy("kotlin-platform-jvm") - } - } -} - -class GradleKotlinMPPJSFrameworkSupportProvider - : GradleKotlinJSFrameworkSupportProvider("KOTLIN_MPP_JS", "Kotlin (Multiplatform JS - Experimental)") { - - override fun getPluginId() = "kotlin-platform-js" - override fun getPluginExpression() = "id 'kotlin-platform-js'" - - override fun updateSettingsScript(settingsScript: PsiFile, specifyPluginVersionIfNeeded: Boolean) { - if (specifyPluginVersionIfNeeded) { - KotlinWithGradleConfigurator.getManipulator(settingsScript).addResolutionStrategy("kotlin-platform-js") - } - } - - override fun getDescription() = "JavaScript-specific code for a Kotlin multiplatform project" -} diff --git a/idea/idea-gradle/src/org/jetbrains/kotlin/idea/configuration/KotlinDslGradleKotlinFrameworkSupportProvider.kt.172 b/idea/idea-gradle/src/org/jetbrains/kotlin/idea/configuration/KotlinDslGradleKotlinFrameworkSupportProvider.kt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/idea-gradle/src/org/jetbrains/kotlin/idea/configuration/KotlinGradleMultiplatformModuleBuilder.kt.172 b/idea/idea-gradle/src/org/jetbrains/kotlin/idea/configuration/KotlinGradleMultiplatformModuleBuilder.kt.172 deleted file mode 100644 index c54b6828102..00000000000 --- a/idea/idea-gradle/src/org/jetbrains/kotlin/idea/configuration/KotlinGradleMultiplatformModuleBuilder.kt.172 +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.kotlin.idea.configuration - -import com.intellij.ide.util.projectWizard.ModuleWizardStep -import com.intellij.ide.util.projectWizard.WizardContext -import com.intellij.openapi.externalSystem.service.project.wizard.ExternalModuleSettingsStep -import com.intellij.openapi.fileEditor.FileDocumentManager -import com.intellij.openapi.module.Module -import com.intellij.openapi.projectRoots.Sdk -import com.intellij.openapi.roots.ui.configuration.ModulesProvider -import com.intellij.openapi.vfs.VfsUtil -import com.intellij.openapi.vfs.VirtualFile -import org.jetbrains.kotlin.idea.KotlinIcons -import org.jetbrains.kotlin.idea.util.application.executeCommand -import org.jetbrains.kotlin.idea.util.rootManager -import org.jetbrains.plugins.gradle.frameworkSupport.BuildScriptDataBuilder -import org.jetbrains.plugins.gradle.service.project.wizard.GradleModuleBuilder -import org.jetbrains.plugins.gradle.service.settings.GradleProjectSettingsControl -import javax.swing.Icon - -class KotlinGradleMultiplatformModuleBuilder : GradleModuleBuilder() { - var commonModuleIsParent = false - var commonModuleName: String? = null - var jvmModuleName: String? = null - var jdk: Sdk? = null - var jsModuleName: String? = null - - override fun getBuilderId() = "kotlin.gradle.multiplatform" - - override fun getNodeIcon(): Icon = KotlinIcons.MPP - - override fun getPresentableName() = "Kotlin (Multiplatform - Experimental)" - - override fun getDescription() = - "Multiplatform projects allow reusing the same code between multiple platforms supported by Kotlin. Such projects are built with Gradle." - - override fun createWizardSteps(wizardContext: WizardContext, modulesProvider: ModulesProvider): Array { - super.createWizardSteps(wizardContext, modulesProvider) // initializes GradleModuleBuilder.myWizardContext - return arrayOf( - KotlinGradleMultiplatformWizardStep(this, wizardContext), - ExternalModuleSettingsStep( - wizardContext, this, GradleProjectSettingsControl(externalProjectSettings) - ) - ) - } - - override fun setupModule(module: Module) { - super.setupModule(module) - - val rootDir = module.rootManager.contentRoots.firstOrNull() ?: return - val commonDir = setupCommonModule(module, rootDir) - val platformRootDir = if (commonModuleIsParent) commonDir else rootDir - setupPlatformModule(module, platformRootDir, jvmModuleName, GradleKotlinMPPJavaFrameworkSupportProvider(), jdk) - setupPlatformModule(module, platformRootDir, jsModuleName, GradleKotlinMPPJSFrameworkSupportProvider()) - - val settingsGradle = rootDir.findChild("settings.gradle") - settingsGradle?.let { - module.project.executeCommand("Update settings.gradle") { - val doc = FileDocumentManager.getInstance().getDocument(it) ?: return@executeCommand - val includedModules = listOfNotNull(commonModuleName, jvmModuleName, jsModuleName).filter { it.isNotEmpty() }.map { - if (!commonModuleIsParent || it == commonModuleName) it - else "$commonModuleName:$it" - } - if (includedModules.isNotEmpty()) { - doc.insertString(doc.textLength, includedModules.joinToString(prefix = "include ") { "'$it'" }) - } - FileDocumentManager.getInstance().saveDocument(doc) - } - } - } - - private fun setupChildModule( - rootModule: Module, - parentDir: VirtualFile?, - childModuleName: String?, - sdk: Sdk? = null, - extendScript: (BuildScriptDataBuilder, Sdk?) -> Unit = { _, _ -> } - ): VirtualFile? { - if (parentDir == null || childModuleName.isNullOrEmpty()) return null - - val moduleDir = parentDir.createChildDirectory(this, childModuleName!!) - val buildGradle = moduleDir.createChildData(null, "build.gradle") - val buildScriptData = BuildScriptDataBuilder(buildGradle) - extendScript(buildScriptData, sdk ?: rootModule.rootManager.sdk) - VfsUtil.saveText(buildGradle, buildScriptData.build()) - return moduleDir - } - - private fun setupCommonModule( - rootModule: Module, - parentDir: VirtualFile? - ) = setupChildModule(rootModule, parentDir, commonModuleName) { builder, sdk -> - GradleKotlinMPPCommonFrameworkSupportProvider().addSupport(builder, rootModule, sdk, true) - } - - private fun setupPlatformModule( - rootModule: Module, - parentDir: VirtualFile?, - platformModuleName: String?, - supportProvider: GradleKotlinFrameworkSupportProvider, - sdk: Sdk? = null - ) = setupChildModule(rootModule, parentDir, platformModuleName, sdk) { builder, finalSdk -> - supportProvider.addSupport(builder, rootModule, finalSdk, true) - val dependency = commonModuleName ?: "" - builder.addDependencyNotation("expectedBy project(\":$dependency\")") - } -} diff --git a/idea/idea-gradle/src/org/jetbrains/kotlin/idea/configuration/gradleModuleBuilderUtils.kt.172 b/idea/idea-gradle/src/org/jetbrains/kotlin/idea/configuration/gradleModuleBuilderUtils.kt.172 deleted file mode 100644 index 166a92cd2c8..00000000000 --- a/idea/idea-gradle/src/org/jetbrains/kotlin/idea/configuration/gradleModuleBuilderUtils.kt.172 +++ /dev/null @@ -1,86 +0,0 @@ -/* - * 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.configuration - -import com.intellij.framework.addSupport.FrameworkSupportInModuleConfigurable -import com.intellij.ide.util.frameworkSupport.FrameworkSupportModel -import com.intellij.openapi.module.Module -import com.intellij.openapi.roots.ModifiableModelsProvider -import com.intellij.openapi.roots.ModifiableRootModel -import com.intellij.openapi.util.Key -import com.intellij.openapi.vfs.LocalFileSystem -import com.intellij.openapi.vfs.VfsUtil -import com.intellij.openapi.vfs.VirtualFile -import com.intellij.psi.PsiFile -import com.intellij.psi.codeStyle.CodeStyleManager -import org.jetbrains.kotlin.idea.core.copied -import org.jetbrains.kotlin.idea.refactoring.toPsiFile -import org.jetbrains.kotlin.psi.UserDataProperty -import org.jetbrains.plugins.gradle.frameworkSupport.GradleFrameworkSupportProvider -import org.jetbrains.plugins.gradle.service.project.wizard.GradleModuleBuilder -import org.jetbrains.plugins.gradle.util.GradleConstants -import java.io.File - -internal var Module.gradleModuleBuilder: GradleModuleBuilder? by UserDataProperty(Key.create("GRADLE_MODULE_BUILDER")) -private var Module.editableSettingsPsiFileCopy: PsiFile? by UserDataProperty(Key.create("EDITABLE_SETTINGS_PSI_FILE_COPY")) - -internal fun findSettingsGradleFile(module: Module): VirtualFile? { - val contentEntryPath = module.gradleModuleBuilder?.contentEntryPath ?: return null - if (contentEntryPath.isEmpty()) return null - val contentRootDir = File(contentEntryPath) - val modelContentRootDir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(contentRootDir) ?: return null - return modelContentRootDir.findChild(GradleConstants.SETTINGS_FILE_NAME) - ?: module.project.baseDir.findChild(GradleConstants.SETTINGS_FILE_NAME) -} - -// Circumvent write actions and modify the file directly -// TODO: Get rid of this hack when IDEA API allows manipulation of settings script similarly to the main script itself -internal fun updateSettingsScript(module: Module, updater: (PsiFile) -> Unit) { - val storedCopy = module.editableSettingsPsiFileCopy - val settingsPsiCopy = storedCopy ?: findSettingsGradleFile(module)?.toPsiFile(module.project)?.copied() ?: return - if (storedCopy == null) { - module.editableSettingsPsiFileCopy = settingsPsiCopy - } - updater(settingsPsiCopy) -} - -internal fun flushSettingsGradleCopy(module: Module) { - try { - val settingsFile = findSettingsGradleFile(module) - val settingsPsiCopy = module.editableSettingsPsiFileCopy - if (settingsPsiCopy != null && settingsFile != null) { - CodeStyleManager.getInstance(module.project).reformat(settingsPsiCopy) - VfsUtil.saveText(settingsFile, settingsPsiCopy.text) - } - } finally { - module.gradleModuleBuilder = null - module.editableSettingsPsiFileCopy = null - } -} - -class KotlinGradleFrameworkSupportInModuleConfigurable( - private val model: FrameworkSupportModel, - private val supportProvider: GradleFrameworkSupportProvider -) : FrameworkSupportInModuleConfigurable() { - override fun createComponent() = null - - override fun addSupport( - module: Module, - rootModel: ModifiableRootModel, - modifiableModelsProvider: ModifiableModelsProvider - ) { - val buildScriptData = GradleModuleBuilder.getBuildScriptData(module) - if (buildScriptData != null) { - val builder = model.moduleBuilder - try { - module.gradleModuleBuilder = builder as? GradleModuleBuilder - supportProvider.addSupport(module, rootModel, modifiableModelsProvider, buildScriptData) - } finally { - flushSettingsGradleCopy(module) - } - } - } -} \ No newline at end of file diff --git a/idea/idea-gradle/tests/org/jetbrains/kotlin/idea/codeInsight/gradle/GradleInspectionTest.kt.172 b/idea/idea-gradle/tests/org/jetbrains/kotlin/idea/codeInsight/gradle/GradleInspectionTest.kt.172 deleted file mode 100644 index d47e9f618e2..00000000000 --- a/idea/idea-gradle/tests/org/jetbrains/kotlin/idea/codeInsight/gradle/GradleInspectionTest.kt.172 +++ /dev/null @@ -1,408 +0,0 @@ -/* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.kotlin.idea.codeInsight.gradle - -import com.intellij.codeInspection.LocalInspectionTool -import com.intellij.codeInspection.ProblemDescriptorBase -import com.intellij.openapi.util.Ref -import com.intellij.openapi.vfs.VirtualFile -import org.jetbrains.kotlin.idea.inspections.gradle.DeprecatedGradleDependencyInspection -import org.jetbrains.kotlin.idea.inspections.gradle.DifferentKotlinGradleVersionInspection -import org.jetbrains.kotlin.idea.inspections.gradle.DifferentStdlibGradleVersionInspection -import org.jetbrains.kotlin.idea.inspections.gradle.GradleKotlinxCoroutinesDeprecationInspection -import org.jetbrains.kotlin.idea.inspections.runInspection -import org.junit.Assert -import org.junit.Test - -class GradleInspectionTest : GradleImportingTestCase() { - @Test - fun testDifferentStdlibGradleVersion() { - val localFile = createProjectSubFile( - "build.gradle", """ - group 'Again' - version '1.0-SNAPSHOT' - - buildscript { - repositories { - mavenCentral() - } - - dependencies { - classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.0.2") - } - } - - apply plugin: 'kotlin' - - dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib:1.0.3" - } - """ - ) - importProject() - - val tool = DifferentStdlibGradleVersionInspection() - val problems = getInspectionResult(tool, localFile) - - Assert.assertTrue(problems.size == 1) - Assert.assertEquals("Plugin version (1.0.2) is not the same as library version (1.0.3)", problems.single()) - } - - @Test - fun testDifferentStdlibGradleVersionWithImplementation() { - val localFile = createProjectSubFile( - "build.gradle", """ - group 'Again' - version '1.0-SNAPSHOT' - - buildscript { - repositories { - mavenCentral() - } - - dependencies { - classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.0.2") - } - } - - apply plugin: 'kotlin' - - dependencies { - implementation "org.jetbrains.kotlin:kotlin-stdlib:1.0.3" - } - """ - ) - importProject() - - val tool = DifferentStdlibGradleVersionInspection() - val problems = getInspectionResult(tool, localFile) - - Assert.assertTrue(problems.size == 1) - Assert.assertEquals("Plugin version (1.0.2) is not the same as library version (1.0.3)", problems.single()) - } - - @Test - fun testDifferentStdlibJre7GradleVersion() { - val localFile = createProjectSubFile( - "build.gradle", """ - group 'Again' - version '1.0-SNAPSHOT' - - buildscript { - repositories { - mavenCentral() - maven { - url 'http://dl.bintray.com/kotlin/kotlin-eap-1.1' - } - } - - dependencies { - classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.1.0-beta-17") - } - } - - apply plugin: 'kotlin' - - dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:1.1.0-beta-22" - } - """ - ) - importProject() - - val tool = DifferentStdlibGradleVersionInspection() - val problems = getInspectionResult(tool, localFile) - - Assert.assertTrue(problems.size == 1) - Assert.assertEquals("Plugin version (1.1.0-beta-17) is not the same as library version (1.1.0-beta-22)", problems.single()) - } - - @Test - fun testDifferentStdlibJdk7GradleVersion() { - val localFile = createProjectSubFile( - "build.gradle", """ - group 'Again' - version '1.0-SNAPSHOT' - - buildscript { - repositories { - mavenCentral() - maven { - url 'http://dl.bintray.com/kotlin/kotlin-eap-1.1' - } - } - - dependencies { - classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.1.0-beta-17") - } - } - - apply plugin: 'kotlin' - - dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.1.0-beta-22" - } - """ - ) - importProject() - - val tool = DifferentStdlibGradleVersionInspection() - val problems = getInspectionResult(tool, localFile) - - Assert.assertTrue(problems.size == 1) - Assert.assertEquals("Plugin version (1.1.0-beta-17) is not the same as library version (1.1.0-beta-22)", problems.single()) - } - - - @Test - fun testDifferentStdlibGradleVersionWithVariables() { - createProjectSubFile( - "gradle.properties", """ - |kotlin=1.0.1 - |lib_version=1.0.3""".trimMargin() - ) - val localFile = createProjectSubFile( - "build.gradle", """ - group 'Again' - version '1.0-SNAPSHOT' - - buildscript { - repositories { - mavenCentral() - } - - dependencies { - classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${'$'}kotlin") - } - } - - apply plugin: 'kotlin' - - dependencies { - compile group: 'org.jetbrains.kotlin', name: 'kotlin-stdlib', version: lib_version - } - """ - ) - importProject() - - val tool = DifferentStdlibGradleVersionInspection() - val problems = getInspectionResult(tool, localFile) - - Assert.assertTrue(problems.size == 1) - Assert.assertEquals("Plugin version (1.0.1) is not the same as library version (1.0.3)", problems.single()) - } - - @Test - fun testDifferentKotlinGradleVersion() { - createProjectSubFile("gradle.properties", """test=1.0.1""") - val localFile = createProjectSubFile( - "build.gradle", """ - group 'Again' - version '1.0-SNAPSHOT' - - buildscript { - repositories { - mavenCentral() - } - - dependencies { - classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${'$'}{test}") - } - } - - apply plugin: 'kotlin' - """ - ) - importProject() - - val tool = DifferentKotlinGradleVersionInspection() - tool.testVersionMessage = "\$PLUGIN_VERSION" - val problems = getInspectionResult(tool, localFile) - - Assert.assertTrue(problems.size == 1) - Assert.assertEquals( - "Kotlin version that is used for building with Gradle (1.0.1) differs from the one bundled into the IDE plugin (\$PLUGIN_VERSION)", - problems.single() - ) - } - - @Test - fun testJreInOldVersion() { - val localFile = createProjectSubFile( - "build.gradle", """ - group 'Again' - version '1.0-SNAPSHOT' - - buildscript { - repositories { - mavenCentral() - } - - dependencies { - classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.1.60") - } - } - - apply plugin: 'kotlin' - - dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:1.1.60" - } - """ - ) - importProject() - - val tool = DeprecatedGradleDependencyInspection() - val problems = getInspectionResult(tool, localFile) - - Assert.assertTrue(problems.isEmpty()) - } - - @Test - fun testJreIsDeprecated() { - val localFile = createProjectSubFile( - "build.gradle", """ - group 'Again' - version '1.0-SNAPSHOT' - - buildscript { - repositories { - mavenCentral() - } - - dependencies { - classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.1.60") - } - } - - apply plugin: 'kotlin' - - dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:1.2.0" - } - """ - ) - importProject() - - val tool = DeprecatedGradleDependencyInspection() - val problems = getInspectionResult(tool, localFile) - - Assert.assertTrue(problems.size == 1) - Assert.assertEquals( - "kotlin-stdlib-jre7 is deprecated since 1.2.0 and should be replaced with kotlin-stdlib-jdk7", - problems.single() - ) - } - - @Test - fun testJreIsDeprecatedWithImplementation() { - val localFile = createProjectSubFile( - "build.gradle", """ - group 'Again' - version '1.0-SNAPSHOT' - - buildscript { - repositories { - mavenCentral() - } - - dependencies { - classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.0") - } - } - - apply plugin: 'kotlin' - - dependencies { - implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:1.2.0" - } - """ - ) - importProject() - - val tool = DeprecatedGradleDependencyInspection() - val problems = getInspectionResult(tool, localFile) - - Assert.assertTrue(problems.size == 1) - Assert.assertEquals( - "kotlin-stdlib-jre7 is deprecated since 1.2.0 and should be replaced with kotlin-stdlib-jdk7", - problems.single() - ) - } - - @Test - fun testObsoleteCoroutinesUsage() { - val localFile = createProjectSubFile( - "build.gradle", """ - group 'Again' - version '1.0-SNAPSHOT' - - buildscript { - repositories { - mavenCentral() - } - - dependencies { - classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.0") - } - } - - apply plugin: 'kotlin' - - repositories { - mavenCentral() - maven { url "https://kotlin.bintray.com/kotlinx" } - } - - dependencies { - compile 'org.jetbrains.kotlinx:kotlinx-coroutines-core:0.23.4' - } - - compileKotlin { - kotlinOptions.languageVersion = "1.3" - } - """ - ) - importProject() - - val tool = GradleKotlinxCoroutinesDeprecationInspection() - val problems = getInspectionResult(tool, localFile) - - Assert.assertTrue(problems.size == 1) - Assert.assertEquals( - "Library should be updated to be compatible with Kotlin 1.3", - problems.single() - ) - } - - fun getInspectionResult(tool: LocalInspectionTool, file: VirtualFile): List { - val resultRef = Ref>() - invokeTestRunnable { - val presentation = runInspection(tool, myProject, listOf(file)) - - val foundProblems = presentation.problemElements - .values - .flatMap { it.toList() } - .mapNotNull { it as? ProblemDescriptorBase } - .map { it.descriptionTemplate } - - resultRef.set(foundProblems) - } - - return resultRef.get() - } -} \ No newline at end of file diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/debugger/NoStrataPositionManagerHelper.kt.172 b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/debugger/NoStrataPositionManagerHelper.kt.172 deleted file mode 100644 index b82231ec367..00000000000 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/debugger/NoStrataPositionManagerHelper.kt.172 +++ /dev/null @@ -1,334 +0,0 @@ -/* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.kotlin.idea.debugger - -import com.intellij.debugger.SourcePosition -import com.intellij.debugger.engine.DebugProcess -import com.intellij.debugger.jdi.VirtualMachineProxyImpl -import com.intellij.openapi.application.ApplicationManager -import com.intellij.openapi.compiler.CompilerPaths -import com.intellij.openapi.compiler.ex.CompilerPathsEx -import com.intellij.openapi.project.Project -import com.intellij.openapi.roots.ProjectFileIndex -import com.intellij.openapi.vfs.VirtualFile -import com.intellij.psi.search.GlobalSearchScope -import com.intellij.util.containers.ConcurrentWeakFactoryMap -import com.intellij.util.containers.ContainerUtil -import com.sun.jdi.Location -import com.sun.jdi.ReferenceType -import org.jetbrains.kotlin.codegen.inline.API -import org.jetbrains.kotlin.idea.caches.resolve.analyze -import org.jetbrains.kotlin.idea.debugger.evaluate.KotlinDebuggerCaches -import org.jetbrains.kotlin.idea.refactoring.getLineCount -import org.jetbrains.kotlin.idea.refactoring.getLineStartOffset -import org.jetbrains.kotlin.idea.refactoring.toPsiFile -import org.jetbrains.kotlin.idea.util.ProjectRootsUtil -import org.jetbrains.kotlin.idea.util.application.runReadAction -import org.jetbrains.kotlin.lexer.KtTokens -import org.jetbrains.kotlin.load.kotlin.VirtualFileFinder -import org.jetbrains.kotlin.name.ClassId -import org.jetbrains.kotlin.name.FqName -import org.jetbrains.kotlin.name.Name -import org.jetbrains.kotlin.name.tail -import org.jetbrains.kotlin.psi.* -import org.jetbrains.kotlin.psi.psiUtil.parents -import org.jetbrains.kotlin.resolve.inline.InlineUtil -import org.jetbrains.kotlin.resolve.jvm.JvmClassName -import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode -import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull -import org.jetbrains.kotlin.utils.getOrPutNullable -import org.jetbrains.org.objectweb.asm.* -import java.io.File -import java.util.* - -fun isInlineFunctionLineNumber(file: VirtualFile, lineNumber: Int, project: Project): Boolean { - if (ProjectRootsUtil.isProjectSourceFile(project, file)) { - val linesInFile = file.toPsiFile(project)?.getLineCount() ?: return false - return lineNumber > linesInFile - } - - return true -} - -fun readBytecodeInfo(project: Project, - jvmName: JvmClassName, - file: VirtualFile): BytecodeDebugInfo? { - return KotlinDebuggerCaches.getOrReadDebugInfoFromBytecode(project, jvmName, file) -} - -fun ktLocationInfo(location: Location, isDexDebug: Boolean, project: Project, - preferInlined: Boolean = false, locationFile: KtFile? = null): Pair { - if (isDexDebug && (locationFile == null || location.lineNumber() > locationFile.getLineCount())) { - if (!preferInlined) { - val thisFunLine = runReadAction { getLastLineNumberForLocation(location, project) } - if (thisFunLine != null && thisFunLine != location.lineNumber()) { - return thisFunLine to locationFile - } - } - - val inlinePosition = runReadAction { getOriginalPositionOfInlinedLine(location, project) } - if (inlinePosition != null) { - val (file, line) = inlinePosition - return line + 1 to file - } - } - - return location.lineNumber() to locationFile -} - -/** - * Only the first line number is stored for instruction in dex. It can be obtained through location.lineNumber(). - * This method allows to get last stored linenumber for instruction. - */ -fun getLastLineNumberForLocation(location: Location, project: Project, searchScope: GlobalSearchScope = GlobalSearchScope.allScope(project)): Int? { - val lineNumber = location.lineNumber() - val fqName = FqName(location.declaringType().name()) - val fileName = location.sourceName() - - val method = location.method() ?: return null - val name = method.name() ?: return null - val signature = method.signature() ?: return null - - val debugInfo = findAndReadClassFile(fqName, fileName, project, searchScope, { isInlineFunctionLineNumber(it, lineNumber, project) }) ?: return null - - val lineMapping = debugInfo.lineTableMapping[BytecodeMethodKey(name, signature)] ?: return null - return lineMapping.values.firstOrNull { it.contains(lineNumber) }?.last() -} - -class WeakBytecodeDebugInfoStorage : ConcurrentWeakFactoryMap() { - override fun create(key: BinaryCacheKey): BytecodeDebugInfo? { - val bytes = readClassFileImpl(key.project, key.jvmName, key.file) ?: return null - - val smapData = readDebugInfo(bytes) - val lineNumberMapping = readLineNumberTableMapping(bytes) - - return BytecodeDebugInfo(smapData, lineNumberMapping) - } - override fun createMap(): Map { - return ContainerUtil.createConcurrentWeakKeyWeakValueMap() - } -} - -class BytecodeDebugInfo(val smapData: SmapData?, val lineTableMapping: Map>>) - -data class BytecodeMethodKey(val methodName: String, val signature: String) - -data class BinaryCacheKey(val project: Project, val jvmName: JvmClassName, val file: VirtualFile) - -private fun readClassFileImpl(project: Project, - jvmName: JvmClassName, - file: VirtualFile): ByteArray? { - val fqNameWithInners = jvmName.fqNameForClassNameWithoutDollars.tail(jvmName.packageFqName) - - fun readFromLibrary(): ByteArray? { - if (!ProjectRootsUtil.isLibrarySourceFile(project, file)) return null - - val classId = ClassId(jvmName.packageFqName, Name.identifier(fqNameWithInners.asString())) - - val fileFinder = VirtualFileFinder.getInstance(project) - val classFile = fileFinder.findVirtualFileWithHeader(classId) ?: return null - return classFile.contentsToByteArray(false) - } - - fun readFromOutput(isForTestClasses: Boolean): ByteArray? { - if (!ProjectRootsUtil.isProjectSourceFile(project, file)) return null - - val module = ProjectFileIndex.SERVICE.getInstance(project).getModuleForFile(file) ?: return null - - val outputPaths = CompilerPathsEx.getOutputPaths(arrayOf(module)).toList() - val className = fqNameWithInners.asString().replace('.', '$') - var classFile = findClassFileByPaths(jvmName.packageFqName.asString(), className, outputPaths) - - if (classFile == null) { - if (!isForTestClasses) { - return null - } - - val outputDir = CompilerPaths.getModuleOutputDirectory(module, /*forTests = */ isForTestClasses) ?: return null - - val outputModeDirName = outputDir.name - // FIXME: It looks like this doesn't work anymore after Kotlin gradle plugin have stopped generating Kotlin classes in java output dir - // Originally this code did mapping like 'path/classes/test/debug' -> 'path/classes/androidTest/debug' - val androidTestOutputDir = outputDir.parent?.parent?.findChild("androidTest")?.findChild(outputModeDirName) ?: return null - - classFile = findClassFileByPath(jvmName.packageFqName.asString(), className, androidTestOutputDir.path) ?: return null - } - - return classFile.readBytes() - } - - fun readFromSourceOutput(): ByteArray? = readFromOutput(false) - - fun readFromTestOutput(): ByteArray? = readFromOutput(true) - - return readFromLibrary() ?: - readFromSourceOutput() ?: - readFromTestOutput() -} - -private fun findClassFileByPaths(packageName: String, className: String, paths: List): File? = - paths.mapNotNull { path -> findClassFileByPath(packageName, className, path) }.maxBy { it.lastModified() } - -private fun findClassFileByPath(packageName: String, className: String, outputDirPath: String): File? { - val outDirFile = File(outputDirPath).takeIf(File::exists) ?: return null - - val parentDirectory = File(outDirFile, packageName.replace(".", File.separator)) - if (!parentDirectory.exists()) return null - - if (ApplicationManager.getApplication().isUnitTestMode) { - val beforeDexFileClassFile = File(parentDirectory, className + ".class.before_dex") - if (beforeDexFileClassFile.exists()) { - return beforeDexFileClassFile - } - } - - val classFile = File(parentDirectory, className + ".class") - if (classFile.exists()) { - return classFile - } - - return null -} - -private fun readLineNumberTableMapping(bytes: ByteArray): Map>> { - val lineNumberMapping = HashMap>>() - - ClassReader(bytes).accept(object : ClassVisitor(API) { - override fun visitMethod(access: Int, name: String?, desc: String?, signature: String?, exceptions: Array?): MethodVisitor? { - if (name == null || desc == null) { - return null - } - - val methodKey = BytecodeMethodKey(name, desc) - val methodLinesMapping = HashMap>() - lineNumberMapping[methodKey] = methodLinesMapping - - return object : MethodVisitor(Opcodes.ASM5, null) { - override fun visitLineNumber(line: Int, start: Label?) { - if (start != null) { - methodLinesMapping.getOrPutNullable(start.toString(), { LinkedHashSet() }).add(line) - } - } - } - } - }, ClassReader.SKIP_FRAMES and ClassReader.SKIP_CODE) - - return lineNumberMapping -} - -internal fun getOriginalPositionOfInlinedLine(location: Location, project: Project): Pair? { - val lineNumber = location.lineNumber() - val fqName = FqName(location.declaringType().name()) - val fileName = location.sourceName() - val searchScope = GlobalSearchScope.allScope(project) - - val debugInfo = findAndReadClassFile(fqName, fileName, project, searchScope, { isInlineFunctionLineNumber(it, lineNumber, project) }) ?: - return null - val smapData = debugInfo.smapData ?: return null - - return mapStacktraceLineToSource(smapData, lineNumber, project, SourceLineKind.EXECUTED_LINE, searchScope) -} - -private fun findAndReadClassFile( - fqName: FqName, fileName: String, project: Project, searchScope: GlobalSearchScope, - fileFilter: (VirtualFile) -> Boolean): BytecodeDebugInfo? { - val internalName = fqName.asString().replace('.', '/') - val jvmClassName = JvmClassName.byInternalName(internalName) - - val file = DebuggerUtils.findSourceFileForClassIncludeLibrarySources(project, searchScope, jvmClassName, fileName) ?: return null - - val virtualFile = file.virtualFile ?: return null - if (!fileFilter(virtualFile)) return null - - return readBytecodeInfo(project, jvmClassName, virtualFile) -} - -internal fun getLocationsOfInlinedLine(type: ReferenceType, position: SourcePosition, sourceSearchScope: GlobalSearchScope): List { - val line = position.line - val file = position.file - val project = position.file.project - - val lineStartOffset = file.getLineStartOffset(line) ?: return listOf() - val element = file.findElementAt(lineStartOffset) ?: return listOf() - val ktElement = element.parents.firstIsInstanceOrNull() ?: return listOf() - - val isInInline = runReadAction { element.parents.any { it is KtFunction && it.hasModifier(KtTokens.INLINE_KEYWORD) } } - - if (!isInInline) { - // Lambdas passed to crossinline arguments are inlined when they are used in non-inlined lambdas - val isInCrossinlineArgument = isInCrossinlineArgument(ktElement) - if (!isInCrossinlineArgument) { - return listOf() - } - } - - val lines = inlinedLinesNumbers(line + 1, position.file.name, FqName(type.name()), type.sourceName(), project, sourceSearchScope) - - return lines.flatMap { type.locationsOfLine(it) } -} - -fun isInCrossinlineArgument(ktElement: KtElement): Boolean { - val argumentFunctions = runReadAction { - ktElement.parents.filter { - when (it) { - is KtFunctionLiteral -> it.parent is KtLambdaExpression && (it.parent.parent is KtValueArgument || it.parent.parent is KtLambdaArgument) - is KtFunction -> it.parent is KtValueArgument - else -> false - } - }.filterIsInstance() - } - - val bindingContext = ktElement.analyze(BodyResolveMode.PARTIAL) - return argumentFunctions.any { - val argumentDescriptor = InlineUtil.getInlineArgumentDescriptor(it, bindingContext) - argumentDescriptor?.isCrossinline ?: false - } -} - - -private fun inlinedLinesNumbers( - inlineLineNumber: Int, inlineFileName: String, - destinationTypeFqName: FqName, destinationFileName: String, - project: Project, sourceSearchScope: GlobalSearchScope): List { - val internalName = destinationTypeFqName.asString().replace('.', '/') - val jvmClassName = JvmClassName.byInternalName(internalName) - - val file = DebuggerUtils.findSourceFileForClassIncludeLibrarySources(project, sourceSearchScope, jvmClassName, destinationFileName) ?: - return listOf() - - val virtualFile = file.virtualFile ?: return listOf() - - val debugInfo = readBytecodeInfo(project, jvmClassName, virtualFile) ?: return listOf() - val smapData = debugInfo.smapData ?: return listOf() - - val smap = smapData.kotlinStrata ?: return listOf() - - val mappingsToInlinedFile = smap.fileMappings.filter { it.name == inlineFileName } - val mappingIntervals = mappingsToInlinedFile.flatMap { it.lineMappings } - - return mappingIntervals.asSequence(). - filter { rangeMapping -> rangeMapping.hasMappingForSource(inlineLineNumber) }. - map { rangeMapping -> rangeMapping.mapSourceToDest(inlineLineNumber) }. - filter { line -> line != -1 }. - toList() -} - -@Volatile var emulateDexDebugInTests: Boolean = false - -fun DebugProcess.isDexDebug() = - (emulateDexDebugInTests && ApplicationManager.getApplication().isUnitTestMode) || - (this.virtualMachineProxy as? VirtualMachineProxyImpl)?.virtualMachine?.name() == "Dalvik" // TODO: check other machine names \ No newline at end of file diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/injection/KotlinLanguageInjector.kt.172 b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/injection/KotlinLanguageInjector.kt.172 deleted file mode 100644 index b92634b207f..00000000000 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/injection/KotlinLanguageInjector.kt.172 +++ /dev/null @@ -1,380 +0,0 @@ -/* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.kotlin.idea.injection - -import com.intellij.codeInsight.AnnotationUtil -import com.intellij.lang.injection.MultiHostInjector -import com.intellij.lang.injection.MultiHostRegistrar -import com.intellij.openapi.application.ApplicationManager -import com.intellij.openapi.progress.ProgressManager -import com.intellij.openapi.project.Project -import com.intellij.openapi.util.Key -import com.intellij.psi.* -import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil -import com.intellij.psi.search.LocalSearchScope -import com.intellij.psi.search.searches.ReferencesSearch -import com.intellij.psi.util.PsiTreeUtil -import org.intellij.plugins.intelliLang.Configuration -import org.intellij.plugins.intelliLang.inject.InjectorUtils -import org.intellij.plugins.intelliLang.inject.LanguageInjectionSupport -import org.intellij.plugins.intelliLang.inject.TemporaryPlacesRegistry -import org.intellij.plugins.intelliLang.inject.config.BaseInjection -import org.intellij.plugins.intelliLang.inject.java.JavaLanguageInjectionSupport -import org.intellij.plugins.intelliLang.util.AnnotationUtilEx -import org.jetbrains.kotlin.descriptors.FunctionDescriptor -import org.jetbrains.kotlin.descriptors.annotations.Annotated -import org.jetbrains.kotlin.idea.caches.resolve.analyze -import org.jetbrains.kotlin.idea.references.KtReference -import org.jetbrains.kotlin.idea.references.mainReference -import org.jetbrains.kotlin.idea.runInReadActionWithWriteActionPriority -import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor -import org.jetbrains.kotlin.idea.util.ProjectRootsUtil -import org.jetbrains.kotlin.idea.util.application.progressIndicatorNullable -import org.jetbrains.kotlin.lexer.KtTokens -import org.jetbrains.kotlin.name.FqName -import org.jetbrains.kotlin.psi.* -import org.jetbrains.kotlin.resolve.annotations.argumentValue -import org.jetbrains.kotlin.resolve.constants.StringValue -import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode -import org.jetbrains.kotlin.utils.addToStdlib.safeAs -import java.util.* -import kotlin.collections.ArrayList - -class KotlinLanguageInjector( - val configuration: Configuration, - val project: Project, - val temporaryPlacesRegistry: TemporaryPlacesRegistry -) : MultiHostInjector { - companion object { - private val STRING_LITERALS_REGEXP = "\"([^\"]*)\"".toRegex() - private val ABSENT_KOTLIN_INJECTION = BaseInjection("ABSENT_KOTLIN_BASE_INJECTION") - } - - val kotlinSupport: KotlinLanguageInjectionSupport? by lazy { - ArrayList(InjectorUtils.getActiveInjectionSupports()).filterIsInstance(KotlinLanguageInjectionSupport::class.java).firstOrNull() - } - - private data class KotlinCachedInjection(val modificationCount: Long, val baseInjection: BaseInjection) - private var KtStringTemplateExpression.cachedInjectionWithModification: KotlinCachedInjection? by UserDataProperty( - Key.create("CACHED_INJECTION_WITH_MODIFICATION")) - - override fun getLanguagesToInject(registrar: MultiHostRegistrar, context: PsiElement) { - val ktHost: KtStringTemplateExpression = context as? KtStringTemplateExpression ?: return - if (!context.isValidHost) return - - val support = kotlinSupport ?: return - - if (!ProjectRootsUtil.isInProjectOrLibSource(ktHost)) return - - val needImmediateAnswer = with(ApplicationManager.getApplication()) { isDispatchThread && !isUnitTestMode } - val kotlinCachedInjection = ktHost.cachedInjectionWithModification - val modificationCount = PsiManager.getInstance(project).modificationTracker.modificationCount - - val baseInjection = when { - needImmediateAnswer -> { - // Can't afford long counting or typing will be laggy. Force cache reuse even if it's outdated. - kotlinCachedInjection?.baseInjection ?: ABSENT_KOTLIN_INJECTION - } - kotlinCachedInjection != null && (modificationCount == kotlinCachedInjection.modificationCount) -> - // Cache is up-to-date - kotlinCachedInjection.baseInjection - else -> { - fun computeAndCache(): BaseInjection { - val computedInjection = computeBaseInjection(ktHost, support, registrar) ?: ABSENT_KOTLIN_INJECTION - ktHost.cachedInjectionWithModification = KotlinCachedInjection(modificationCount, computedInjection) - return computedInjection - } - - if (ApplicationManager.getApplication().isReadAccessAllowed && ProgressManager.getInstance().progressIndicatorNullable == null) { - // The action cannot be canceled by caller and by internal checkCanceled() calls. - // Force creating new indicator that is canceled on write action start, otherwise there might be lags in typing. - runInReadActionWithWriteActionPriority(::computeAndCache) ?: kotlinCachedInjection?.baseInjection ?: ABSENT_KOTLIN_INJECTION - } - else { - computeAndCache() - } - } - } - - if (baseInjection == ABSENT_KOTLIN_INJECTION) { - return - } - - val language = InjectorUtils.getLanguageByString(baseInjection.injectedLanguageId) ?: return - - if (ktHost.hasInterpolation()) { - val file = ktHost.containingKtFile - val parts = splitLiteralToInjectionParts(baseInjection, ktHost) ?: return - - if (parts.ranges.isEmpty()) return - - InjectorUtils.registerInjection(language, parts.ranges, file, registrar) - InjectorUtils.registerSupport(support, false, registrar) - InjectorUtils.putInjectedFileUserData(registrar, InjectedLanguageUtil.FRANKENSTEIN_INJECTION, - if (parts.isUnparsable) java.lang.Boolean.TRUE else null) - } - else { - InjectorUtils.registerInjectionSimple(ktHost, baseInjection, support, registrar) - } - } - - @Suppress("FoldInitializerAndIfToElvis") - private fun computeBaseInjection( - ktHost: KtStringTemplateExpression, - support: KotlinLanguageInjectionSupport, - registrar: MultiHostRegistrar): BaseInjection? { - val containingFile = ktHost.containingFile - - val tempInjectedLanguage = temporaryPlacesRegistry.getLanguageFor(ktHost, containingFile) - if (tempInjectedLanguage != null) { - InjectorUtils.putInjectedFileUserData(registrar, LanguageInjectionSupport.TEMPORARY_INJECTED_LANGUAGE, tempInjectedLanguage) - return BaseInjection(support.id).apply { - injectedLanguageId = tempInjectedLanguage.id - prefix = tempInjectedLanguage.prefix - suffix = tempInjectedLanguage.suffix - } - } - - return findInjectionInfo(ktHost)?.toBaseInjection(support) - } - - override fun elementsToInjectIn(): List> { - return listOf(KtStringTemplateExpression::class.java) - } - - private fun findInjectionInfo(place: KtElement, originalHost: Boolean = true): InjectionInfo? { - return injectWithExplicitCodeInstruction(place) - ?: injectWithCall(place) - ?: injectReturnValue(place) - ?: injectWithReceiver(place) - ?: injectWithVariableUsage(place, originalHost) - ?: injectWithAnnotationEntry(place) - } - - private fun injectReturnValue(place: KtElement): InjectionInfo? { - val parent = place.parent - - tailrec fun findReturnExpression(expression: PsiElement?): KtReturnExpression? = when (expression) { - is KtReturnExpression -> expression - is KtBinaryExpression -> findReturnExpression(expression.takeIf { it.operationToken == KtTokens.ELVIS }?.parent) - is KtContainerNodeForControlStructureBody, is KtIfExpression -> findReturnExpression(expression.parent) - else -> null - } - - val returnExp = findReturnExpression(parent) ?: return null - - if (returnExp.labeledExpression != null) return null - - val callableDeclaration = PsiTreeUtil.getParentOfType(returnExp, KtDeclaration::class.java) as? KtCallableDeclaration ?: return null - if (callableDeclaration.annotationEntries.isEmpty()) return null - - val descriptor = callableDeclaration.descriptor ?: return null - return injectionInfoByAnnotation(descriptor) - } - - private fun injectWithExplicitCodeInstruction(host: KtElement): InjectionInfo? { - val support = kotlinSupport ?: return null - return InjectionInfo.fromBaseInjection(support.findCommentInjection(host)) ?: support.findAnnotationInjectionLanguageId(host) - } - - private fun injectWithReceiver(host: KtElement): InjectionInfo? { - val qualifiedExpression = host.parent as? KtDotQualifiedExpression ?: return null - if (qualifiedExpression.receiverExpression != host) return null - - val callExpression = qualifiedExpression.selectorExpression as? KtCallExpression ?: return null - val callee = callExpression.calleeExpression ?: return null - - if (isAnalyzeOff(qualifiedExpression.project)) return null - - val kotlinInjections = Configuration.getInstance().getInjections(KOTLIN_SUPPORT_ID) - - val calleeName = callee.text - val possibleNames = collectPossibleNames(kotlinInjections) - - if (calleeName !in possibleNames) { - return null - } - - for (reference in callee.references) { - ProgressManager.checkCanceled() - - val resolvedTo = reference.resolve() - if (resolvedTo is KtFunction) { - val injectionInfo = findInjection(resolvedTo.receiverTypeReference, kotlinInjections) - if (injectionInfo != null) { - return injectionInfo - } - } - } - - return null - } - - private fun collectPossibleNames(injections: List): Set { - val result = HashSet() - - for (injection in injections) { - val injectionPlaces = injection.injectionPlaces - for (place in injectionPlaces) { - val placeStr = place.toString() - val literals = STRING_LITERALS_REGEXP.findAll(placeStr).map { it.groupValues[1] } - result.addAll(literals) - } - } - - return result - } - - private fun injectWithVariableUsage(host: KtElement, originalHost: Boolean): InjectionInfo? { - // Given place is not original host of the injection so we stop to prevent stepping through indirect references - if (!originalHost) return null - - val ktHost: KtElement = host - val ktProperty = host.parent as? KtProperty ?: return null - if (ktProperty.initializer != host) return null - - if (isAnalyzeOff(ktHost.project)) return null - - val searchScope = LocalSearchScope(arrayOf(ktProperty.containingFile), "", true) - return ReferencesSearch.search(ktProperty, searchScope).asSequence().mapNotNull { psiReference -> - val element = psiReference.element as? KtElement ?: return@mapNotNull null - findInjectionInfo(element, false) - }.firstOrNull() - } - - private fun injectWithCall(host: KtElement): InjectionInfo? { - val ktHost: KtElement = host - val argument = ktHost.parent as? KtValueArgument ?: return null - - val callExpression = PsiTreeUtil.getParentOfType(ktHost, KtCallExpression::class.java) ?: return null - val callee = callExpression.calleeExpression ?: return null - - if (isAnalyzeOff(ktHost.project)) return null - - for (reference in callee.references) { - ProgressManager.checkCanceled() - - val resolvedTo = reference.resolve() - if (resolvedTo is PsiMethod) { - val injectionForJavaMethod = injectionForJavaMethod(argument, resolvedTo) - if (injectionForJavaMethod != null) { - return injectionForJavaMethod - } - } - else if (resolvedTo is KtFunction) { - val injectionForJavaMethod = injectionForKotlinCall(argument, resolvedTo, reference) - if (injectionForJavaMethod != null) { - return injectionForJavaMethod - } - } - } - - return null - } - - private fun injectionForJavaMethod(argument: KtValueArgument, javaMethod: PsiMethod): InjectionInfo? { - val argumentIndex = (argument.parent as KtValueArgumentList).arguments.indexOf(argument) - val psiParameter = javaMethod.parameterList.parameters.getOrNull(argumentIndex) ?: return null - - val injectionInfo = findInjection(psiParameter, Configuration.getInstance().getInjections(JavaLanguageInjectionSupport.JAVA_SUPPORT_ID)) - if (injectionInfo != null) { - return injectionInfo - } - - val annotations = AnnotationUtilEx.getAnnotationFrom( - psiParameter, - Configuration.getProjectInstance(psiParameter.project).advancedConfiguration.languageAnnotationPair, - true) - - if (annotations.isNotEmpty()) { - return processAnnotationInjectionInner(annotations) - } - - return null - } - - private fun injectionForKotlinCall(argument: KtValueArgument, ktFunction: KtFunction, reference: PsiReference): InjectionInfo? { - val argumentIndex = (argument.parent as KtValueArgumentList).arguments.indexOf(argument) - val ktParameter = ktFunction.valueParameters.getOrNull(argumentIndex) ?: return null - - val patternInjection = findInjection(ktParameter, Configuration.getInstance().getInjections(KOTLIN_SUPPORT_ID)) - if (patternInjection != null) { - return patternInjection - } - - // Found psi element after resolve can be obtained from compiled declaration but annotations parameters are lost there. - // Search for original descriptor from reference. - val ktReference = reference as? KtReference ?: return null - val bindingContext = ktReference.element.analyze(BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS) - val functionDescriptor = ktReference.resolveToDescriptors(bindingContext).singleOrNull() as? FunctionDescriptor ?: return null - - val parameterDescriptor = functionDescriptor.valueParameters.getOrNull(argumentIndex) ?: return null - return injectionInfoByAnnotation(parameterDescriptor) - } - - private fun injectionInfoByAnnotation(annotated: Annotated): InjectionInfo? { - val injectAnnotation = annotated.annotations.findAnnotation(FqName(AnnotationUtil.LANGUAGE)) ?: return null - - val languageId = injectAnnotation.argumentValue("value")?.safeAs()?.value ?: return null - return InjectionInfo(languageId, null, null) - } - - private fun injectWithAnnotationEntry(host: KtElement): InjectionInfo? { - val argument = host.parent as? KtValueArgument ?: return null - val annotationEntry = PsiTreeUtil.getParentOfType(host, KtAnnotationEntry::class.java) ?: return null - if (isAnalyzeOff(host.project)) return null - - val calleeReference = annotationEntry.calleeExpression?.constructorReferenceExpression?.mainReference - val callee = calleeReference?.resolve() - return when (callee) { - is KtFunction -> injectionForKotlinCall(argument, callee, calleeReference) - is PsiClass -> { - // Look for java injections for the PsiAnnotationMethod. - (argument.reference ?: argument.getArgumentName()?.referenceExpression?.mainReference) - ?.let { it.resolve() as? PsiMethod } - ?.let { findInjection(it, Configuration.getInstance().getInjections(JavaLanguageInjectionSupport.JAVA_SUPPORT_ID)) } - ?.takeIf { injectionInfo -> - // Temporary forbid injection for SpEL because of inspections that gives warnings when host language is not Java. - injectionInfo.languageId != "SpEL" - } - } - else -> null - } - } - - private fun findInjection(element: PsiElement?, injections: List): InjectionInfo? { - for (injection in injections) { - if (injection.acceptsPsiElement(element)) { - return InjectionInfo(injection.injectedLanguageId, injection.prefix, injection.suffix) - } - } - - return null - } - - private fun isAnalyzeOff(project: Project): Boolean { - return Configuration.getProjectInstance(project).advancedConfiguration.dfaOption == Configuration.DfaOption.OFF - } - - private fun processAnnotationInjectionInner(annotations: Array): InjectionInfo? { - val id = AnnotationUtilEx.calcAnnotationValue(annotations, "value") - val prefix = AnnotationUtilEx.calcAnnotationValue(annotations, "prefix") - val suffix = AnnotationUtilEx.calcAnnotationValue(annotations, "suffix") - - return InjectionInfo(id, prefix, suffix) - } -} diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/run/KotlinTestNgConfigurationProducer.java.172 b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/run/KotlinTestNgConfigurationProducer.java.172 deleted file mode 100644 index e1dda75ada2..00000000000 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/run/KotlinTestNgConfigurationProducer.java.172 +++ /dev/null @@ -1,233 +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.idea.run; - -import com.intellij.execution.JavaRunConfigurationExtensionManager; -import com.intellij.execution.Location; -import com.intellij.execution.PsiLocation; -import com.intellij.execution.actions.ConfigurationContext; -import com.intellij.execution.actions.ConfigurationFromContext; -import com.intellij.execution.junit.InheritorChooser; -import com.intellij.execution.junit2.info.MethodLocation; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.Condition; -import com.intellij.openapi.util.Ref; -import com.intellij.psi.*; -import com.intellij.psi.util.PsiClassUtil; -import com.intellij.psi.util.PsiTreeUtil; -import com.theoryinpractice.testng.configuration.TestNGConfiguration; -import com.theoryinpractice.testng.configuration.TestNGConfigurationProducer; -import com.theoryinpractice.testng.util.TestNGUtil; -import kotlin.collections.CollectionsKt; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.jetbrains.kotlin.asJava.LightClassUtilsKt; -import org.jetbrains.kotlin.idea.project.TargetPlatformDetector; -import org.jetbrains.kotlin.idea.util.ProjectRootsUtil; -import org.jetbrains.kotlin.psi.*; -import org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatform; - -import java.util.List; - -import static org.jetbrains.kotlin.asJava.LightClassUtilsKt.toLightClass; - -public class KotlinTestNgConfigurationProducer extends TestNGConfigurationProducer { - @Override - public boolean shouldReplace(ConfigurationFromContext self, ConfigurationFromContext other) { - return other.isProducedBy(TestNGConfigurationProducer.class); - } - - @Override - protected boolean setupConfigurationFromContext( - TestNGConfiguration configuration, ConfigurationContext context, Ref sourceElement - ) { - // TODO: check TestNG Pattern running first, before method/class (see TestNGInClassConfigurationProducer for logic) - // TODO: and PsiClassOwner not handled, which is in TestNGInClassConfigurationProducer - - Location location = context.getLocation(); - if (location == null) { - return false; - } - - Project project = context.getProject(); - PsiElement leaf = location.getPsiElement(); - - if (!ProjectRootsUtil.isInProjectOrLibSource(leaf)) { - return false; - } - - if (!(leaf.getContainingFile() instanceof KtFile)) { - return false; - } - - KtFile ktFile = (KtFile) leaf.getContainingFile(); - - if (TargetPlatformDetector.getPlatform(ktFile) != JvmPlatform.INSTANCE) { - return false; - } - - KtNamedDeclaration declarationToRun = getDeclarationToRun(leaf); - - if (declarationToRun instanceof KtNamedFunction) { - KtNamedFunction function = (KtNamedFunction) declarationToRun; - - @SuppressWarnings("unchecked") - KtElement owner = PsiTreeUtil.getParentOfType(function, KtFunction.class, KtClass.class); - - if (owner instanceof KtClass) { - PsiClass delegate = toLightClass((KtClass) owner); - if (delegate != null) { - for (PsiMethod method : delegate.getMethods()) { - if (method.getNavigationElement() == function) { - if (TestNGUtil.hasTest(method)) { - return configure(configuration, location, context, project, delegate, method); - } - break; - } - } - } - } - } - - if (declarationToRun instanceof KtClass) { - PsiClass delegate = toLightClass((KtClassOrObject) declarationToRun); - if (!isTestNGClass(delegate)) { - return false; - } - - return configure(configuration, location, context, project, delegate, null); - } - - return false; - } - - @Override - public void onFirstRun(ConfigurationFromContext configuration, ConfigurationContext context, Runnable startRunnable) { - KtNamedDeclaration declarationToRun = getDeclarationToRun(configuration.getSourceElement()); - final PsiNamedElement lightElement = CollectionsKt.firstOrNull(LightClassUtilsKt.toLightElements(declarationToRun)); - - // Copied from TestNGInClassConfigurationProducer.onFirstRun() - if (lightElement instanceof PsiMethod || lightElement instanceof PsiClass) { - PsiMethod psiMethod; - PsiClass containingClass; - - if (lightElement instanceof PsiMethod) { - psiMethod = (PsiMethod)lightElement; - containingClass = psiMethod.getContainingClass(); - } else { - psiMethod = null; - containingClass = (PsiClass)lightElement; - } - - InheritorChooser inheritorChooser = new InheritorChooser() { - @Override - protected void runForClasses(List classes, PsiMethod method, ConfigurationContext context, Runnable performRunnable) { - ((TestNGConfiguration)context.getConfiguration().getConfiguration()).bePatternConfiguration(classes, method); - super.runForClasses(classes, method, context, performRunnable); - } - - @Override - protected void runForClass(PsiClass aClass, - PsiMethod psiMethod, - ConfigurationContext context, - Runnable performRunnable) { - if (lightElement instanceof PsiMethod) { - Project project = psiMethod.getProject(); - MethodLocation methodLocation = new MethodLocation(project, psiMethod, PsiLocation.fromPsiElement(aClass)); - ((TestNGConfiguration)context.getConfiguration().getConfiguration()).setMethodConfiguration(methodLocation); - } else { - ((TestNGConfiguration)context.getConfiguration().getConfiguration()).setClassConfiguration(aClass); - } - super.runForClass(aClass, psiMethod, context, performRunnable); - } - }; - if (inheritorChooser.runMethodInAbstractClass(context, - startRunnable, - psiMethod, - containingClass, - new Condition() { - @Override - public boolean value(PsiClass aClass) { - return aClass.hasModifierProperty(PsiModifier.ABSTRACT) && - TestNGUtil.hasTest(aClass); - } - })) return; - } - - super.onFirstRun(configuration, context, startRunnable); - } - - @Nullable - private static KtNamedDeclaration getDeclarationToRun(@NotNull PsiElement leaf) { - if (!(leaf.getContainingFile() instanceof KtFile)) return null; - KtFile jetFile = (KtFile) leaf.getContainingFile(); - - KtNamedFunction function = PsiTreeUtil.getParentOfType(leaf, KtNamedFunction.class, false); - if (function != null) return function; - - KtClass ktClass = PsiTreeUtil.getParentOfType(leaf, KtClass.class, false); - if (ktClass != null) return ktClass; - - return getClassDeclarationInFile(jetFile); - } - - private boolean configure( - TestNGConfiguration configuration, Location location, ConfigurationContext context, Project project, - @Nullable PsiClass delegate, @Nullable PsiMethod method - ) { - if (delegate == null) { - return false; - } - - setupConfigurationModule(context, configuration); - Module originalModule = configuration.getConfigurationModule().getModule(); - configuration.setClassConfiguration(delegate); - if (method != null) { - configuration.setMethodConfiguration(PsiLocation.fromPsiElement(project, method)); - } - configuration.restoreOriginalModule(originalModule); - configuration.setName(configuration.getName()); - JavaRunConfigurationExtensionManager.getInstance().extendCreatedConfiguration(configuration, location); - return true; - } - - private static boolean isTestNGClass(PsiClass psiClass) { - return psiClass != null && PsiClassUtil.isRunnableClass(psiClass, true, false) && TestNGUtil.hasTest(psiClass); - } - - @Nullable - static KtClass getClassDeclarationInFile(KtFile jetFile) { - KtClass tempSingleDeclaration = null; - - for (KtDeclaration ktDeclaration : jetFile.getDeclarations()) { - if (ktDeclaration instanceof KtClass) { - KtClass declaration = (KtClass) ktDeclaration; - - if (tempSingleDeclaration == null) { - tempSingleDeclaration = declaration; - } - else { - // There are several class declarations in file - return null; - } - } - } - - return tempSingleDeclaration; - } -} diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/scratch/output/InlayScratchFileRenderer.kt.172 b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/scratch/output/InlayScratchFileRenderer.kt.172 deleted file mode 100644 index 503add61910..00000000000 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/scratch/output/InlayScratchFileRenderer.kt.172 +++ /dev/null @@ -1,78 +0,0 @@ -/* - * 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.scratch.output - -import com.intellij.openapi.editor.Editor -import com.intellij.openapi.editor.EditorCustomElementRenderer -import com.intellij.openapi.editor.impl.ComplementaryFontsRegistry -import com.intellij.openapi.editor.impl.FontInfo -import com.intellij.openapi.editor.markup.TextAttributes -import com.intellij.ui.Colors -import com.intellij.ui.JBColor -import java.awt.Color -import java.awt.Font -import java.awt.Graphics -import java.awt.Rectangle - -class InlayScratchFileRenderer(val text: String, private val outputType: ScratchOutputType) : EditorCustomElementRenderer { - private fun getFontInfo(editor: Editor): FontInfo { - val colorsScheme = editor.colorsScheme - val fontPreferences = colorsScheme.fontPreferences - val attributes = getAttributes() - val fontStyle = attributes.fontType - return ComplementaryFontsRegistry.getFontAbleToDisplay( - 'a'.toInt(), fontStyle, fontPreferences, FontInfo.getFontRenderContext(editor.contentComponent) - ) - } - - override fun calcWidthInPixels(editor: Editor): Int { - val fontInfo = getFontInfo(editor) - return fontInfo.fontMetrics().stringWidth(text) - } - - override fun paint(editor: Editor, g: Graphics, r: Rectangle) { - val attributes = getAttributes() - val fgColor = attributes.foregroundColor ?: return - g.color = fgColor - val fontInfo = getFontInfo(editor) - g.font = fontInfo.font - val metrics = fontInfo.fontMetrics() - g.drawString(text, r.x, r.y + metrics.ascent) - } - - private fun getAttributes(): TextAttributes { - return when (outputType) { - ScratchOutputType.OUTPUT -> userOutputAttributes - ScratchOutputType.RESULT -> normalAttributes - ScratchOutputType.ERROR -> errorAttributes - } - } - - override fun toString(): String { - return "${text.takeWhile { it.isWhitespace() }}${outputType.name}: ${text.trim()}" - } - - companion object { - private val normalAttributes = TextAttributes( - JBColor.GRAY, - null, null, null, - Font.ITALIC - ) - - private val errorAttributes = TextAttributes( - JBColor(Colors.DARK_RED, Colors.DARK_RED), - null, null, null, - Font.ITALIC - ) - - private val userOutputColor = Color(0x5C5CFF) - private val userOutputAttributes = TextAttributes( - JBColor(userOutputColor, userOutputColor), - null, null, null, - Font.ITALIC - ) - } -} \ No newline at end of file diff --git a/idea/idea-maven/test/org/jetbrains/kotlin/idea/maven/AbstractKotlinMavenInspectionTest.kt.172 b/idea/idea-maven/test/org/jetbrains/kotlin/idea/maven/AbstractKotlinMavenInspectionTest.kt.172 deleted file mode 100644 index e97c7b2f871..00000000000 --- a/idea/idea-maven/test/org/jetbrains/kotlin/idea/maven/AbstractKotlinMavenInspectionTest.kt.172 +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.kotlin.idea.maven - -import com.intellij.codeInspection.CommonProblemDescriptor -import com.intellij.codeInspection.ProblemDescriptorBase -import com.intellij.codeInspection.QuickFix -import com.intellij.ide.highlighter.JavaFileType -import com.intellij.openapi.application.ApplicationManager -import com.intellij.openapi.application.Result -import com.intellij.openapi.application.WriteAction -import com.intellij.openapi.command.CommandProcessor -import com.intellij.openapi.fileEditor.FileDocumentManager -import com.intellij.openapi.vfs.VirtualFile -import com.intellij.psi.PsiDocumentManager -import com.intellij.psi.PsiManager -import com.intellij.psi.search.FileTypeIndex -import org.jetbrains.jps.model.java.JavaSourceRootType -import org.jetbrains.kotlin.idea.inspections.runInspection -import org.jetbrains.kotlin.idea.maven.inspections.KotlinMavenPluginPhaseInspection -import org.jetbrains.kotlin.idea.refactoring.toPsiDirectory -import org.jetbrains.kotlin.idea.util.projectStructure.allModules -import org.jetbrains.kotlin.test.KotlinTestUtils -import org.jetbrains.kotlin.utils.keysToMap -import java.io.File - -abstract class AbstractKotlinMavenInspectionTest : MavenImportingTestCase() { - - override fun setUp() { - super.setUp() - repositoryPath = File(myDir, "repo").path - createStdProjectFolders() - } - - fun doTest(fileName: String) { - val pomFile = File(fileName) - val pomText = pomFile.readText() - - createPomFile(fileName) - importProject() - myProject.allModules().forEach { - setupJdkForModule(it.name) - } - - if (pomText.contains("".toRegex(RegexOption.MULTILINE))) { - mkJavaFile() - } - - val inspectionClassName = "".toRegex().find(pomText)?.groups?.get(1)?.value - ?: KotlinMavenPluginPhaseInspection::class.qualifiedName!! - val inspectionClass = Class.forName(inspectionClassName) - - val matcher = "".toRegex() - val expectedProblemsText = pomText.lines() - .filter { matcher.matches(it) } - .joinToString("\n") - - val problemElements = runInspection(inspectionClass, myProject).problemElements - val actualProblems = problemElements - .filter { it.key.name == "pom.xml" } - .values - .flatMap { it.toList() } - .mapNotNull { it as? ProblemDescriptorBase } - - val actual = actualProblems - .map { SimplifiedProblemDescription(it.descriptionTemplate, it.psiElement.text.replace("\\s+".toRegex(), "")) to it } - .sortedBy { it.first.text } - - val actualProblemsText = actual - .map { it.first } - .joinToString("\n") { ""} - - assertEquals(expectedProblemsText, actualProblemsText) - - val suggestedFixes = actual.flatMap { p -> p.second.fixes?.sortedBy { it.familyName }?.map { p.second to it } ?: emptyList() } - - val filenamePrefix = pomFile.nameWithoutExtension + ".fixed." - val fixFiles = - pomFile.parentFile.listFiles { _, name -> name.startsWith(filenamePrefix) && name.endsWith(".xml") }.sortedBy { it.name } - - val rangesToFixFiles: Map = fixFiles.keysToMap { - val fixFileName = it.name - val fixRangeStr = fixFileName.substringBeforeLast('.').substringAfterLast('.') - val numbers = fixRangeStr.split('-').map { it.toInt() } - when (numbers.size) { - 0 -> error("No number in fix file $fixFileName") - 1 -> IntRange(numbers[0], numbers[0]) - 2 -> IntRange(numbers[0], numbers[1]) - else -> error("Bad range `$fixRangeStr` in fix file $fixFileName") - } - } - - val sortedFixRanges = rangesToFixFiles.values.sortedBy { it.start } - sortedFixRanges.forEachIndexed { i, range -> - if (i > 0) { - val previous = sortedFixRanges[i - 1] - if (previous.endInclusive + 1 != range.start) { - error("Bad ranges in fix files: $previous and $range") - } - } - } - - val numberOfFixDataFiles = sortedFixRanges.lastOrNull()?.endInclusive ?: 0 - if (numberOfFixDataFiles > suggestedFixes.size) { - fail("Not all fixes were suggested by the inspection: expected count: ${fixFiles.size}, actual fixes count: ${suggestedFixes.size}") - } - if (numberOfFixDataFiles < suggestedFixes.size) { - fail("Not all fixes covered by *.fixed.N.xml files") - } - - val documentManager = PsiDocumentManager.getInstance(myProject) - val document = documentManager.getDocument(PsiManager.getInstance(myProject).findFile(myProjectPom)!!)!! - val originalText = document.text - - suggestedFixes.forEachIndexed { index, suggestedFix -> - val (problem, quickfix) = suggestedFix - val file = rangesToFixFiles.entries.first { (_, range) -> index + 1 in range }.key - - quickfix.applyFix(problem) - - KotlinTestUtils.assertEqualsToFile(file, document.text.trim()) - - ApplicationManager.getApplication().runWriteAction { - document.setText(originalText) - documentManager.commitDocument(document) - } - } - } - - private fun createPomFile(fileName: String) { - myProjectPom = myProjectRoot.findChild("pom.xml") - if (myProjectPom == null) { - myProjectPom = object : WriteAction() { - override fun run(result: Result) { - val res = myProjectRoot.createChildData(null, "pom.xml") - result.setResult(res) - } - }.execute().resultObject - } - myAllPoms.add(myProjectPom!!) - - ApplicationManager.getApplication().runWriteAction { - myProjectPom!!.setBinaryContent(File(fileName).readBytes()) - } - } - - private fun QuickFix.applyFix(desc: ProblemDescriptorBase) { - CommandProcessor.getInstance().executeCommand(myProject, { - ApplicationManager.getApplication().runWriteAction { - applyFix(myProject, desc) - - val manager = PsiDocumentManager.getInstance(myProject) - val document = manager.getDocument(PsiManager.getInstance(myProject).findFile(myProjectPom)!!)!! - manager.doPostponedOperationsAndUnblockDocument(document) - manager.commitDocument(document) - FileDocumentManager.getInstance().saveDocument(document) - - } - - println(myProjectPom.contentsToByteArray().toString(Charsets.UTF_8)) - }, "quick-fix-$name", "Kotlin") - } - - private fun mkJavaFile() { - val sourceFolder = - getContentRoots(myProject.allModules().single().name).single().getSourceFolders(JavaSourceRootType.SOURCE).single() - ApplicationManager.getApplication().runWriteAction { - val javaFile = sourceFolder.file?.toPsiDirectory(myProject)?.createFile("Test.java") ?: throw IllegalStateException() - javaFile.viewProvider.document!!.setText("class Test {}\n") - } - - assertTrue(FileTypeIndex.containsFileOfType(JavaFileType.INSTANCE, myProject.allModules().single().moduleScope)) - } - - private data class SimplifiedProblemDescription(val text: String, val elementText: String) -} \ No newline at end of file diff --git a/idea/idea-repl/src/org/jetbrains/kotlin/console/ReplOutputHandler.kt.172 b/idea/idea-repl/src/org/jetbrains/kotlin/console/ReplOutputHandler.kt.172 deleted file mode 100644 index a3a3d1d53d6..00000000000 --- a/idea/idea-repl/src/org/jetbrains/kotlin/console/ReplOutputHandler.kt.172 +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.kotlin.console - -import com.intellij.execution.process.OSProcessHandler -import com.intellij.execution.process.ProcessOutputTypes -import com.intellij.openapi.util.Key -import com.intellij.openapi.util.TextRange -import com.intellij.openapi.util.text.StringUtil -import org.jetbrains.kotlin.console.actions.logError -import org.jetbrains.kotlin.diagnostics.Severity -import org.jetbrains.kotlin.utils.repl.ReplEscapeType -import org.w3c.dom.Element -import org.xml.sax.InputSource -import java.io.ByteArrayInputStream -import java.nio.charset.Charset -import javax.xml.parsers.DocumentBuilderFactory -import org.jetbrains.kotlin.utils.repl.ReplEscapeType.* - -val XML_REPLACEMENTS: Array = arrayOf("#n", "#diez") -val SOURCE_CHARS: Array = arrayOf("\n", "#") - -data class SeverityDetails(val severity: Severity, val description: String, val range: TextRange) - -class ReplOutputHandler( - private val runner: KotlinConsoleRunner, - process: Process, - commandLine: String -) : OSProcessHandler(process, commandLine) { - - private var isBuildInfoChecked = false - private val factory = DocumentBuilderFactory.newInstance() - private val outputProcessor = ReplOutputProcessor(runner) - private val inputBuffer = StringBuilder() - - override fun isSilentlyDestroyOnClose() = true - - override fun notifyTextAvailable(text: String, key: Key<*>?) { - // hide warning about adding test folder to classpath - if (text.startsWith("warning: classpath entry points to a non-existent location")) return - - if (key == ProcessOutputTypes.STDOUT) { - inputBuffer.append(text) - val resultingText = inputBuffer.toString() - if (resultingText.endsWith("\n")) { - handleReplMessage(resultingText) - inputBuffer.setLength(0) - } - } - else { - super.notifyTextAvailable(text, key) - } - } - - private fun handleReplMessage(text: String) { - if (text.isBlank()) return - val output = try { - factory.newDocumentBuilder().parse(strToSource(text)) - } - catch (e: Exception) { - logError(ReplOutputHandler::class.java, "Couldn't parse REPL output: $text", e) - return - } - - val root = output.firstChild as Element - val outputType = ReplEscapeType.valueOfOrNull(root.getAttribute("type")) - val content = StringUtil.replace(root.textContent, XML_REPLACEMENTS, SOURCE_CHARS) - - when (outputType) { - INITIAL_PROMPT -> buildWarningIfNeededBeforeInit(content) - HELP_PROMPT -> outputProcessor.printHelp(content) - USER_OUTPUT -> outputProcessor.printUserOutput(content) - REPL_RESULT -> outputProcessor.printResultWithGutterIcon(content) - READLINE_START -> runner.isReadLineMode = true - READLINE_END -> runner.isReadLineMode = false - REPL_INCOMPLETE, - COMPILE_ERROR -> outputProcessor.highlightCompilerErrors(createCompilerMessages(content)) - RUNTIME_ERROR -> outputProcessor.printRuntimeError("${content.trim()}\n") - INTERNAL_ERROR -> outputProcessor.printInternalErrorMessage(content) - SUCCESS -> runner.commandHistory.lastUnprocessedEntry()?.entryText?.let { runner.successfulLine(it) } - null -> logError(ReplOutputHandler::class.java, "Unexpected output type:\n$outputType") - } - - if (outputType in setOf(SUCCESS, COMPILE_ERROR, INTERNAL_ERROR, RUNTIME_ERROR, READLINE_END)) { - runner.commandHistory.entryProcessed() - } - } - - private fun buildWarningIfNeededBeforeInit(content: String) { - if (!isBuildInfoChecked) { - outputProcessor.printBuildInfoWarningIfNeeded() - isBuildInfoChecked = true - } - outputProcessor.printInitialPrompt(content) - } - - private fun strToSource(s: String, encoding: Charset = Charsets.UTF_8) = InputSource(ByteArrayInputStream(s.toByteArray(encoding))) - - private fun createCompilerMessages(runtimeErrorsReport: String): List { - val compilerMessages = arrayListOf() - - val report = factory.newDocumentBuilder().parse(strToSource(runtimeErrorsReport, Charsets.UTF_16)) - val entries = report.getElementsByTagName("reportEntry") - for (i in 0..entries.length - 1) { - val reportEntry = entries.item(i) as Element - - val severityLevel = reportEntry.getAttribute("severity").toSeverity() - val rangeStart = reportEntry.getAttribute("rangeStart").toInt() - val rangeEnd = reportEntry.getAttribute("rangeEnd").toInt() - val description = reportEntry.textContent - - compilerMessages.add(SeverityDetails(severityLevel, description, TextRange(rangeStart, rangeEnd))) - } - - return compilerMessages - } - - private fun String.toSeverity() = when (this) { - "ERROR" -> Severity.ERROR - "WARNING" -> Severity.WARNING - "INFO" -> Severity.INFO - else -> throw IllegalArgumentException("Unsupported Severity: '$this'") // this case shouldn't occur - } -} \ No newline at end of file diff --git a/idea/src/META-INF/extensions/compiler.xml.172 b/idea/src/META-INF/extensions/compiler.xml.172 deleted file mode 100644 index 563d9170175..00000000000 --- a/idea/src/META-INF/extensions/compiler.xml.172 +++ /dev/null @@ -1,50 +0,0 @@ - - org.jetbrains.kotlin - - - - - - - - - - - - - - - - - - - - - diff --git a/idea/src/META-INF/gradle.xml.172 b/idea/src/META-INF/gradle.xml.172 deleted file mode 100644 index 0bc1d7b7045..00000000000 --- a/idea/src/META-INF/gradle.xml.172 +++ /dev/null @@ -1,98 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/idea/src/META-INF/plugin.xml.172 b/idea/src/META-INF/plugin.xml.172 deleted file mode 100644 index 76d29c25190..00000000000 --- a/idea/src/META-INF/plugin.xml.172 +++ /dev/null @@ -1,3037 +0,0 @@ - - org.jetbrains.kotlin - - Kotlin - -Getting Started in IntelliJ IDEA
-Getting Started in Android Studio
-Public Slack
-Issue tracker
-]]>
- @snapshot@ - JetBrains - - - - com.intellij.modules.platform - com.intellij.modules.remoteServers - - - org.jetbrains.kotlin.native.platform.deps - - JUnit - org.jetbrains.plugins.gradle - org.jetbrains.idea.maven - TestNG-J - com.intellij.copyright - org.jetbrains.android - Coverage - com.intellij.java-i18n - org.intellij.intelliLang - org.jetbrains.java.decompiler - Git4Idea - - - - - com.intellij.modules.java - JavaScriptDebugger - - - - - org.jetbrains.kotlin.idea.highlighter.KotlinBeforeResolveHighlightingPass$Factory - - - org.jetbrains.kotlin.idea.refactoring.cutPaste.MoveDeclarationsPassFactory - - - - org.jetbrains.kotlin.idea.highlighter.ScriptExternalHighlightingPass$Factory - - - org.jetbrains.kotlin.idea.completion.LookupCancelWatcher - - - org.jetbrains.kotlin.idea.project.KotlinCodeBlockModificationListener - - - org.jetbrains.kotlin.idea.caches.KotlinPackageContentModificationListener - - - org.jetbrains.kotlin.idea.completion.CompletionBindingContextProvider - org.jetbrains.kotlin.idea.completion.CompletionBindingContextProvider - - - org.jetbrains.kotlin.idea.configuration.KotlinMigrationProjectComponent - - - - - - org.jetbrains.kotlin.idea.PluginStartupComponent - - - - org.jetbrains.kotlin.idea.versions.KotlinUpdatePluginComponent - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - org.jetbrains.kotlin.idea.intentions.FoldInitializerAndIfToElvisIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ImportMemberIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ImportAllMembersIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.SpecifyTypeExplicitlyIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.SpecifyTypeExplicitlyInDestructuringAssignmentIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.RemoveExplicitTypeIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertToBlockBodyIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.conventionNameCalls.ReplaceContainsIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.conventionNameCalls.ReplaceInvokeIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.conventionNameCalls.ReplaceCallWithUnaryOperatorIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions.FoldIfToReturnAsymmetricallyIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions.UnfoldAssignmentToIfIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions.UnfoldPropertyToIfIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions.UnfoldAssignmentToWhenIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions.UnfoldPropertyToWhenIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions.UnfoldReturnToIfIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions.UnfoldReturnToWhenIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions.DoubleBangToIfThenIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions.IfThenToDoubleBangIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions.ElvisToIfThenIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions.SafeAccessToIfThenIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions.IfToWhenIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions.WhenToIfIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions.FlattenWhenIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions.EliminateWhenSubjectIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions.MergeWhenIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.RemoveUnnecessaryParenthesesIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.RemoveExplicitTypeArgumentsIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.RemoveExplicitSuperQualifierIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.RemoveCurlyBracesFromTemplateIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.InsertCurlyBracesToTemplateIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.MoveLambdaInsideParenthesesIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.InsertExplicitTypeArgumentsIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.declarations.SplitPropertyDeclarationIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.declarations.ConvertMemberToExtensionIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ReconstructTypeInCastOrIsIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.InfixCallToOrdinaryIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ToInfixCallIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ReplaceExplicitFunctionLiteralParamWithItIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ReplaceItWithExplicitFunctionLiteralParamIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ReplaceSubstringWithDropLastIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ReplaceSubstringWithSubstringAfterIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ReplaceSubstringWithSubstringBeforeIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ReplaceSubstringWithTakeIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.RemoveBracesIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.AddBracesIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertNegatedBooleanSequenceIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertBinaryExpressionWithDemorgansLawIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.SimplifyBooleanWithConstantsIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.AddForLoopIndicesIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.RemoveForLoopIndicesIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.loopToCallChain.UseWithIndexIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.SwapBinaryExpressionIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.SwapStringEqualsIgnoreCaseIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.SplitIfIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ReplaceWithOrdinaryAssignmentIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertAssertToIfWithThrowIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertIfWithThrowToAssertIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.SpecifyExplicitLambdaSignatureIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.RemoveExplicitLambdaParameterTypesIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertForEachToForLoopIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertToForEachFunctionCallIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertToStringTemplateIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertToRawStringTemplateIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.OperatorToFunctionIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertToConcatenatedStringIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertFunctionToPropertyIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertPropertyToFunctionIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertReceiverToParameterIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertParameterToReceiverIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertPropertyInitializerToGetterIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.InvertIfConditionIntention - Kotlin - - - - org.jetbrains.kotlin.idea.refactoring.move.changePackage.ChangePackageIntention - Kotlin - - - - org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.MoveDeclarationToSeparateFileIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ChangeVisibilityModifierIntention$Public - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ChangeVisibilityModifierIntention$Private - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ChangeVisibilityModifierIntention$Protected - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ChangeVisibilityModifierIntention$Internal - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.AddNameToArgumentIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ReplaceUnderscoreWithParameterNameIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.AddJvmOverloadsIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.AddJvmStaticIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.RemoveArgumentNameIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.IterateExpressionIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.UsePropertyAccessSyntaxIntention - Kotlin - - - - org.jetbrains.kotlin.idea.quickfix.AddConstModifierIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.IntroduceBackingPropertyIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.JoinDeclarationAndAssignmentIntention - Kotlin - - - - org.jetbrains.kotlin.idea.testIntegration.KotlinCreateTestIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.AddOperatorModifierIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ObjectLiteralToLambdaIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.DestructureIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.AnonymousFunctionToLambdaIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ImplementAbstractMemberIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ImplementAbstractMemberAsConstructorParameterIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.AddValVarToConstructorParameterAction$Intention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.MoveMemberToCompanionObjectIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.MoveMemberOutOfCompanionObjectIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.CreateKotlinSubClassIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ToRawStringLiteralIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ToOrdinaryStringLiteralIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.IntroduceVariableIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.RemoveSingleExpressionStringTemplateIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ReplaceUntilWithRangeToIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.RemoveEmptyParenthesesFromLambdaCallIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertCamelCaseTestFunctionToSpacedIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ReplaceSingleLineLetIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.copyConcatenatedStringToClipboard.CopyConcatenatedStringToClipboardIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ReplaceMathMaxWithCoerceAtLeastIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ReplaceMathMinWithCoerceAtMostIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertPrimaryConstructorToSecondaryIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertSecondaryConstructorToPrimaryIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ReplaceSizeCheckWithIsNotEmptyIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ReplaceSizeZeroCheckWithIsEmptyIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.RemoveEmptyClassBodyIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertEnumToSealedClassIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertSealedClassToEnumIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.RemoveRedundantCallsOfConversionMethodsIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.RemoveEmptyPrimaryConstructorIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.RemoveEmptySecondaryConstructorBodyIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertTryFinallyToUseCallIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.AddNamesToCallArgumentsIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertFunctionTypeParameterToReceiverIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertFunctionTypeReceiverToParameterIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertTwoComparisonsToRangeCheckIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertRangeCheckToTwoComparisonsIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.RenameFileToMatchClassIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertObjectLiteralToClassIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.MergeIfsIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.AddMissingDestructuringIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertToApplyIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertToWithIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertToRunIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.MovePropertyToClassBodyIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.MovePropertyToConstructorIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.AddOpenModifierIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ValToObjectIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ChopParameterListIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ChopArgumentListIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.NullableBooleanEqualityCheckToElvisIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ReplaceAddWithPlusAssignIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertClassToSealedClassIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.AddPropertyAccessorsIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.AddPropertyGetterIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.AddPropertySetterIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.MoveMemberToTopLevelIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ReplaceSubstringWithIndexingOperationIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertUnsafeCastCallToUnsafeCastIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertUnsafeCastToUnsafeCastCallIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.RemoveLabeledReturnInLambdaIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.AddLabeledReturnInLambdaIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.AddAnnotationUseSiteTargetIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.JoinParameterListIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.JoinArgumentListIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertLineCommentToBlockCommentIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertBlockCommentToLineCommentIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.IndentRawStringIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertVarargParameterToArrayIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertArrayParameterToVarargIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.LambdaToAnonymousFunctionIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.AddWhenRemainingBranchesIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertTrimMarginToTrimIndentIntention - Kotlin - - - - org.jetbrains.kotlin.idea.intentions.ConvertTrimIndentToTrimMarginIntention - Kotlin - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
diff --git a/idea/src/org/jetbrains/kotlin/idea/highlighter/KotlinRecursiveCallLineMarkerProvider.kt.172 b/idea/src/org/jetbrains/kotlin/idea/highlighter/KotlinRecursiveCallLineMarkerProvider.kt.172 deleted file mode 100644 index dfb6c46646c..00000000000 --- a/idea/src/org/jetbrains/kotlin/idea/highlighter/KotlinRecursiveCallLineMarkerProvider.kt.172 +++ /dev/null @@ -1,178 +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.idea.highlighter - -import com.intellij.codeHighlighting.Pass -import com.intellij.codeInsight.daemon.LineMarkerInfo -import com.intellij.codeInsight.daemon.LineMarkerProvider -import com.intellij.icons.AllIcons -import com.intellij.openapi.editor.markup.GutterIconRenderer -import com.intellij.openapi.progress.ProgressManager -import com.intellij.psi.PsiDocumentManager -import com.intellij.psi.PsiElement -import org.jetbrains.kotlin.descriptors.ClassDescriptor -import org.jetbrains.kotlin.descriptors.SimpleFunctionDescriptor -import org.jetbrains.kotlin.idea.caches.resolve.analyze -import org.jetbrains.kotlin.idea.inspections.RecursivePropertyAccessorInspection -import org.jetbrains.kotlin.idea.util.getReceiverTargetDescriptor -import org.jetbrains.kotlin.lexer.KtToken -import org.jetbrains.kotlin.name.Name -import org.jetbrains.kotlin.psi.* -import org.jetbrains.kotlin.psi.psiUtil.parents -import org.jetbrains.kotlin.resolve.BindingContext -import org.jetbrains.kotlin.resolve.inline.InlineUtil -import org.jetbrains.kotlin.resolve.scopes.receivers.Receiver -import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue -import org.jetbrains.kotlin.types.expressions.OperatorConventions -import org.jetbrains.kotlin.util.OperatorNameConventions -import java.util.* - -class KotlinRecursiveCallLineMarkerProvider : LineMarkerProvider { - override fun getLineMarkerInfo(element: PsiElement) = null - - override fun collectSlowLineMarkers(elements: MutableList, result: MutableCollection>) { - val markedLineNumbers = HashSet() - - for (element in elements) { - ProgressManager.checkCanceled() - if (element is KtElement) { - val lineNumber = element.getLineNumber() - if (lineNumber !in markedLineNumbers && isRecursiveCall(element)) { - markedLineNumbers.add(lineNumber) - result.add(RecursiveMethodCallMarkerInfo(element)) - } - } - } - } - - private fun getEnclosingFunction(element: KtElement, stopOnNonInlinedLambdas: Boolean): KtNamedFunction? { - for (parent in element.parents) { - when (parent) { - is KtFunctionLiteral -> if (stopOnNonInlinedLambdas && !InlineUtil.isInlinedArgument( - parent, - parent.analyze(), - false - ) - ) return null - is KtNamedFunction -> { - when (parent.parent) { - is KtBlockExpression, is KtClassBody, is KtFile, is KtScript -> return parent - else -> if (stopOnNonInlinedLambdas && !InlineUtil.isInlinedArgument(parent, parent.analyze(), false)) return null - } - } - is KtClassOrObject -> return null - } - } - return null - } - - private fun isRecursiveCall(element: KtElement): Boolean { - if (RecursivePropertyAccessorInspection.isRecursivePropertyAccess(element)) return true - if (RecursivePropertyAccessorInspection.isRecursiveSyntheticPropertyAccess(element)) return true - // Fast check for names without resolve - val resolveName = getCallNameFromPsi(element) ?: return false - val enclosingFunction = getEnclosingFunction(element, false) ?: return false - - val enclosingFunctionName = enclosingFunction.name - if (enclosingFunctionName != OperatorNameConventions.INVOKE.asString() - && enclosingFunctionName != resolveName.asString() - ) return false - - // Check that there were no not-inlined lambdas on the way to enclosing function - if (enclosingFunction != getEnclosingFunction(element, true)) return false - - val bindingContext = element.analyze() - val enclosingFunctionDescriptor = bindingContext[BindingContext.FUNCTION, enclosingFunction] ?: return false - - val call = bindingContext[BindingContext.CALL, element] ?: return false - val resolvedCall = bindingContext[BindingContext.RESOLVED_CALL, call] ?: return false - - if (resolvedCall.candidateDescriptor.original != enclosingFunctionDescriptor) return false - - fun isDifferentReceiver(receiver: Receiver?): Boolean { - if (receiver !is ReceiverValue) return false - - val receiverOwner = receiver.getReceiverTargetDescriptor(bindingContext) ?: return true - - return when (receiverOwner) { - is SimpleFunctionDescriptor -> receiverOwner != enclosingFunctionDescriptor - is ClassDescriptor -> receiverOwner != enclosingFunctionDescriptor.containingDeclaration - else -> return true - } - } - - if (isDifferentReceiver(resolvedCall.dispatchReceiver)) return false - return true - } - - private class RecursiveMethodCallMarkerInfo(callElement: KtElement) : LineMarkerInfo( - callElement, - callElement.textRange, - AllIcons.Gutter.RecursiveMethod, - Pass.LINE_MARKERS, - { "Recursive call" }, - null, - GutterIconRenderer.Alignment.RIGHT - ) { - - override fun createGutterRenderer(): GutterIconRenderer? { - return object : LineMarkerInfo.LineMarkerGutterIconRenderer(this) { - override fun getClickAction() = null // to place breakpoint on mouse click - } - } - } - -} - -private fun PsiElement.getLineNumber(): Int { - return PsiDocumentManager.getInstance(project).getDocument(containingFile)!!.getLineNumber(textOffset) -} - -private fun getCallNameFromPsi(element: KtElement): Name? { - when (element) { - is KtSimpleNameExpression -> { - val elementParent = element.getParent() - when (elementParent) { - is KtCallExpression -> return Name.identifier(element.getText()) - is KtOperationExpression -> { - val operationReference = elementParent.operationReference - if (element == operationReference) { - val node = operationReference.getReferencedNameElementType() - return if (node is KtToken) { - val conventionName = if (elementParent is KtPrefixExpression) - OperatorConventions.getNameForOperationSymbol(node, true, false) - else - OperatorConventions.getNameForOperationSymbol(node) - - conventionName ?: Name.identifier(element.getText()) - } else { - Name.identifier(element.getText()) - } - } - } - } - } - is KtArrayAccessExpression -> - return OperatorNameConventions.GET - is KtThisExpression -> - if (element.getParent() is KtCallExpression) { - return OperatorNameConventions.INVOKE - } - } - - return null -} diff --git a/idea/src/org/jetbrains/kotlin/idea/highlighter/KotlinSuspendCallLineMarkerProvider.kt.172 b/idea/src/org/jetbrains/kotlin/idea/highlighter/KotlinSuspendCallLineMarkerProvider.kt.172 deleted file mode 100644 index 282be3f7b38..00000000000 --- a/idea/src/org/jetbrains/kotlin/idea/highlighter/KotlinSuspendCallLineMarkerProvider.kt.172 +++ /dev/null @@ -1,120 +0,0 @@ -/* - * 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.highlighter - -import com.intellij.codeHighlighting.Pass -import com.intellij.codeInsight.daemon.LineMarkerInfo -import com.intellij.codeInsight.daemon.LineMarkerProvider -import com.intellij.openapi.actionSystem.AnAction -import com.intellij.openapi.editor.markup.GutterIconRenderer -import com.intellij.openapi.progress.ProgressManager -import com.intellij.psi.PsiElement -import org.jetbrains.kotlin.descriptors.FunctionDescriptor -import org.jetbrains.kotlin.descriptors.PropertyDescriptor -import org.jetbrains.kotlin.descriptors.VariableDescriptorWithAccessors -import org.jetbrains.kotlin.descriptors.accessors -import org.jetbrains.kotlin.idea.KotlinIcons -import org.jetbrains.kotlin.idea.caches.resolve.analyze -import org.jetbrains.kotlin.idea.refactoring.getLineNumber -import org.jetbrains.kotlin.psi.* -import org.jetbrains.kotlin.resolve.BindingContext -import org.jetbrains.kotlin.resolve.BindingContext.* -import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall -import org.jetbrains.kotlin.resolve.calls.checkers.isBuiltInCoroutineContext -import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe -import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode - -class KotlinSuspendCallLineMarkerProvider : LineMarkerProvider { - private class SuspendCallMarkerInfo(callElement: KtElement, message: String) : LineMarkerInfo( - callElement, - callElement.textRange, - KotlinIcons.SUSPEND_CALL, - Pass.LINE_MARKERS, - { message }, - null, - GutterIconRenderer.Alignment.RIGHT - ) { - override fun createGutterRenderer(): GutterIconRenderer? { - return object : LineMarkerInfo.LineMarkerGutterIconRenderer(this) { - override fun getClickAction(): AnAction? = null - } - } - } - - override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<*>? = null - - override fun collectSlowLineMarkers( - elements: MutableList, - result: MutableCollection> - ) { - val markedLineNumbers = HashSet() - - for (element in elements) { - ProgressManager.checkCanceled() - - if (element !is KtExpression) continue - - val containingFile = element.containingFile - if (containingFile !is KtFile || containingFile is KtCodeFragment) { - continue - } - - val lineNumber = element.getLineNumber() - if (lineNumber in markedLineNumbers) continue - if (!element.hasSuspendCalls()) continue - - markedLineNumbers += lineNumber - result += if (element is KtForExpression) { - SuspendCallMarkerInfo(element.loopRange!!, "Suspending iteration") - } else { - SuspendCallMarkerInfo(element, "Suspend function call") - } - } - } -} - -private fun KtExpression.isValidCandidateExpression(): Boolean { - if (this is KtOperationReferenceExpression || this is KtForExpression || this is KtProperty || this is KtNameReferenceExpression) return true - val parent = parent - if (parent is KtCallExpression && parent.calleeExpression == this) return true - return false -} - -fun KtExpression.hasSuspendCalls(bindingContext: BindingContext = analyze(BodyResolveMode.PARTIAL)): Boolean { - if (!isValidCandidateExpression()) return false - - return when (this) { - is KtForExpression -> { - val iteratorResolvedCall = bindingContext[LOOP_RANGE_ITERATOR_RESOLVED_CALL, loopRange] - val loopRangeHasNextResolvedCall = bindingContext[LOOP_RANGE_HAS_NEXT_RESOLVED_CALL, loopRange] - val loopRangeNextResolvedCall = bindingContext[LOOP_RANGE_NEXT_RESOLVED_CALL, loopRange] - listOf(iteratorResolvedCall, loopRangeHasNextResolvedCall, loopRangeNextResolvedCall).any { - it?.resultingDescriptor?.isSuspend == true - } - } - is KtProperty -> { - if (hasDelegateExpression()) { - val variableDescriptor = bindingContext[DECLARATION_TO_DESCRIPTOR, this] as? VariableDescriptorWithAccessors - val accessors = variableDescriptor?.accessors ?: emptyList() - accessors.any { accessor -> - val delegatedFunctionDescriptor = bindingContext[DELEGATED_PROPERTY_RESOLVED_CALL, accessor]?.resultingDescriptor - delegatedFunctionDescriptor?.isSuspend == true - } - } else { - false - } - } - else -> { - val resolvedCall = getResolvedCall(bindingContext) - if ((resolvedCall?.resultingDescriptor as? FunctionDescriptor)?.isSuspend == true) true - else { - val propertyDescriptor = resolvedCall?.resultingDescriptor as? PropertyDescriptor - val s = propertyDescriptor?.fqNameSafe?.asString() - s?.startsWith("kotlin.coroutines.") == true && s.endsWith(".coroutineContext") - } - } - } -} diff --git a/idea/src/org/jetbrains/kotlin/idea/highlighter/markers/KotlinLineMarkerProvider.kt.172 b/idea/src/org/jetbrains/kotlin/idea/highlighter/markers/KotlinLineMarkerProvider.kt.172 deleted file mode 100644 index 63ccbcb6135..00000000000 --- a/idea/src/org/jetbrains/kotlin/idea/highlighter/markers/KotlinLineMarkerProvider.kt.172 +++ /dev/null @@ -1,434 +0,0 @@ -/* - * Copyright 2000-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.highlighter.markers - -import com.intellij.codeHighlighting.Pass -import com.intellij.codeInsight.daemon.* -import com.intellij.codeInsight.daemon.impl.LineMarkerNavigator -import com.intellij.codeInsight.daemon.impl.MarkerType -import com.intellij.codeInsight.daemon.impl.PsiElementListNavigator -import com.intellij.codeInsight.navigation.ListBackgroundUpdaterTask -import com.intellij.icons.AllIcons -import com.intellij.openapi.actionSystem.IdeActions -import com.intellij.openapi.editor.colors.CodeInsightColors -import com.intellij.openapi.editor.colors.EditorColorsManager -import com.intellij.openapi.editor.markup.GutterIconRenderer -import com.intellij.openapi.editor.markup.SeparatorPlacement -import com.intellij.openapi.progress.ProgressManager -import com.intellij.openapi.project.DumbService -import com.intellij.openapi.util.text.StringUtil -import com.intellij.psi.* -import com.intellij.psi.search.searches.ClassInheritorsSearch -import com.intellij.psi.util.PsiTreeUtil -import org.jetbrains.kotlin.asJava.LightClassUtil -import org.jetbrains.kotlin.asJava.toLightClass -import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor -import org.jetbrains.kotlin.descriptors.MemberDescriptor -import org.jetbrains.kotlin.descriptors.Modality -import org.jetbrains.kotlin.idea.KotlinIcons -import org.jetbrains.kotlin.idea.caches.lightClasses.KtFakeLightClass -import org.jetbrains.kotlin.idea.caches.lightClasses.KtFakeLightMethod -import org.jetbrains.kotlin.idea.caches.project.implementedDescriptors -import org.jetbrains.kotlin.idea.caches.project.implementingDescriptors -import org.jetbrains.kotlin.idea.caches.resolve.findModuleDescriptor -import org.jetbrains.kotlin.idea.core.isInheritable -import org.jetbrains.kotlin.idea.core.isOverridable -import org.jetbrains.kotlin.idea.core.toDescriptor -import org.jetbrains.kotlin.idea.presentation.DeclarationByModuleRenderer -import org.jetbrains.kotlin.idea.search.declarationsSearch.toPossiblyFakeLightMethods -import org.jetbrains.kotlin.idea.util.* -import org.jetbrains.kotlin.lexer.KtTokens -import org.jetbrains.kotlin.psi.* -import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespaceAndComments -import java.awt.event.MouseEvent -import java.util.* -import javax.swing.Icon -import javax.swing.ListCellRenderer - -class KotlinLineMarkerProvider : LineMarkerProvider { - override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo? { - if (DaemonCodeAnalyzerSettings.getInstance().SHOW_METHOD_SEPARATORS) { - if (element.canHaveSeparator()) { - val prevSibling = element.getPrevSiblingIgnoringWhitespaceAndComments() - if (prevSibling.canHaveSeparator() && - (element.wantsSeparator() || prevSibling?.wantsSeparator() == true) - ) { - return createLineSeparatorByElement(element) - } - } - } - - return null - } - - private fun PsiElement?.canHaveSeparator() = - this is KtFunction || this is KtClassInitializer || (this is KtProperty && !isLocal) - - private fun PsiElement.wantsSeparator() = StringUtil.getLineBreakCount(text) > 0 - - private fun createLineSeparatorByElement(element: PsiElement): LineMarkerInfo { - val anchor = PsiTreeUtil.getDeepestFirst(element) - - val info = LineMarkerInfo(anchor, anchor.textRange, null, Pass.LINE_MARKERS, null, null, GutterIconRenderer.Alignment.RIGHT) - info.separatorColor = EditorColorsManager.getInstance().globalScheme.getColor(CodeInsightColors.METHOD_SEPARATORS_COLOR) - info.separatorPlacement = SeparatorPlacement.TOP - return info - } - - override fun collectSlowLineMarkers(elements: List, result: MutableCollection>) { - if (elements.isEmpty()) return - - val first = elements.first() - if (DumbService.getInstance(first.project).isDumb || !ProjectRootsUtil.isInProjectOrLibSource(first)) return - - val functions = hashSetOf() - val properties = hashSetOf() - val declarations = hashSetOf() - - for (leaf in elements) { - ProgressManager.checkCanceled() - val element = leaf.parent as? KtNamedDeclaration ?: continue - if (!declarations.add(element)) continue - - when (element) { - is KtClass -> { - collectInheritedClassMarker(element, result) - collectHighlightingColorsMarkers(element, result) - } - is KtNamedFunction -> { - functions.add(element) - collectSuperDeclarationMarkers(element, result) - } - is KtProperty -> { - properties.add(element) - collectSuperDeclarationMarkers(element, result) - } - is KtParameter -> { - if (element.hasValOrVar()) { - properties.add(element) - collectSuperDeclarationMarkers(element, result) - } - } - } - collectMultiplatformMarkers(element, result) - } - - collectOverriddenFunctions(functions, result) - collectOverriddenPropertyAccessors(properties, result) - } -} - -private val OVERRIDING_MARK: Icon = AllIcons.Gutter.OverridingMethod -private val IMPLEMENTING_MARK: Icon = AllIcons.Gutter.ImplementingMethod -private val OVERRIDDEN_MARK: Icon = AllIcons.Gutter.OverridenMethod -private val IMPLEMENTED_MARK: Icon = AllIcons.Gutter.ImplementedMethod - -data class NavigationPopupDescriptor( - val targets: Collection, - val title: String, - val findUsagesTitle: String, - val renderer: ListCellRenderer<*>, - val updater: ListBackgroundUpdaterTask? = null -) { - fun showPopup(e: MouseEvent?) { - PsiElementListNavigator.openTargets(e, targets.toTypedArray(), title, findUsagesTitle, renderer, updater) - } -} - -interface TestableLineMarkerNavigator { - fun getTargetsPopupDescriptor(element: PsiElement?): NavigationPopupDescriptor? -} - -private val SUBCLASSED_CLASS = MarkerType( - "SUBCLASSED_CLASS", - { getPsiClass(it)?.let(::getSubclassedClassTooltip) }, - object : LineMarkerNavigator() { - override fun browse(e: MouseEvent?, element: PsiElement?) { - getPsiClass(element)?.let { MarkerType.navigateToSubclassedClass(e, it, DeclarationByModuleRenderer()) } - } - }) - -private val OVERRIDDEN_FUNCTION = object : MarkerType( - "OVERRIDDEN_FUNCTION", - { getPsiMethod(it)?.let(::getOverriddenMethodTooltip) }, - object : LineMarkerNavigator() { - override fun browse(e: MouseEvent?, element: PsiElement?) { - buildNavigateToOverriddenMethodPopup(e, element)?.showPopup(e) - } - }) { - - override fun getNavigationHandler(): GutterIconNavigationHandler { - val superHandler = super.getNavigationHandler() - return object : GutterIconNavigationHandler, TestableLineMarkerNavigator { - override fun navigate(e: MouseEvent?, elt: PsiElement?) { - superHandler.navigate(e, elt) - } - - override fun getTargetsPopupDescriptor(element: PsiElement?) = buildNavigateToOverriddenMethodPopup(null, element) - } - } -} - -private val OVERRIDDEN_PROPERTY = object : MarkerType( - "OVERRIDDEN_PROPERTY", - { it?.let { getOverriddenPropertyTooltip(it.parent as KtNamedDeclaration) } }, - object : LineMarkerNavigator() { - override fun browse(e: MouseEvent?, element: PsiElement?) { - buildNavigateToPropertyOverriddenDeclarationsPopup(e, element)?.showPopup(e) - } - }) { - - override fun getNavigationHandler(): GutterIconNavigationHandler { - val superHandler = super.getNavigationHandler() - return object : GutterIconNavigationHandler, TestableLineMarkerNavigator { - override fun navigate(e: MouseEvent?, elt: PsiElement?) { - superHandler.navigate(e, elt) - } - - override fun getTargetsPopupDescriptor(element: PsiElement?) = buildNavigateToPropertyOverriddenDeclarationsPopup(null, element) - } - } -} - -private val PsiElement.markerDeclaration - get() = (this as? KtDeclaration) ?: (parent as? KtDeclaration) - -private val PLATFORM_ACTUAL = MarkerType( - "PLATFORM_ACTUAL", - { it?.let { getPlatformActualTooltip(it.markerDeclaration) } }, - object : LineMarkerNavigator() { - override fun browse(e: MouseEvent?, element: PsiElement?) { - element?.let { navigateToPlatformActual(e, it.markerDeclaration) } - } - } -) - -private val EXPECTED_DECLARATION = MarkerType( - "EXPECTED_DECLARATION", - { it?.let { getExpectedDeclarationTooltip(it.markerDeclaration) } }, - object : LineMarkerNavigator() { - override fun browse(e: MouseEvent?, element: PsiElement?) { - element?.let { navigateToExpectedDeclaration(it.markerDeclaration) } - } - } -) - -private fun isImplementsAndNotOverrides( - descriptor: CallableMemberDescriptor, - overriddenMembers: Collection -): Boolean { - return descriptor.modality != Modality.ABSTRACT && overriddenMembers.all { it.modality == Modality.ABSTRACT } -} - -private fun collectSuperDeclarationMarkers(declaration: KtDeclaration, result: MutableCollection>) { - assert(declaration is KtNamedFunction || declaration is KtProperty || declaration is KtParameter) - - if (!declaration.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return - - val resolveWithParents = resolveDeclarationWithParents(declaration) - if (resolveWithParents.overriddenDescriptors.isEmpty()) return - - val implements = isImplementsAndNotOverrides(resolveWithParents.descriptor!!, resolveWithParents.overriddenDescriptors) - - val anchor = (declaration as? KtNamedDeclaration)?.nameIdentifier ?: declaration - - // NOTE: Don't store descriptors in line markers because line markers are not deleted while editing other files and this can prevent - // clearing the whole BindingTrace. - - val lineMarkerInfo = LineMarkerInfo( - anchor, - anchor.textRange, - if (implements) IMPLEMENTING_MARK else OVERRIDING_MARK, - Pass.LINE_MARKERS, - SuperDeclarationMarkerTooltip, - SuperDeclarationMarkerNavigationHandler(), - GutterIconRenderer.Alignment.RIGHT - ) - NavigateAction.setNavigateAction( - lineMarkerInfo, - if (declaration is KtNamedFunction) "Go to super method" else "Go to super property", - IdeActions.ACTION_GOTO_SUPER - ) - result.add(lineMarkerInfo) -} - -private fun collectInheritedClassMarker(element: KtClass, result: MutableCollection>) { - if (!element.isInheritable()) { - return - } - - val lightClass = element.toLightClass() ?: KtFakeLightClass(element) - - if (ClassInheritorsSearch.search(lightClass, false).findFirst() == null) return - - val anchor = element.nameIdentifier ?: element - - val lineMarkerInfo = LineMarkerInfo( - anchor, - anchor.textRange, - if (element.isInterface()) IMPLEMENTED_MARK else OVERRIDDEN_MARK, - Pass.LINE_MARKERS, - SUBCLASSED_CLASS.tooltip, - SUBCLASSED_CLASS.navigationHandler, - GutterIconRenderer.Alignment.RIGHT - ) - NavigateAction.setNavigateAction( - lineMarkerInfo, - if (element.isInterface()) "Go to implementations" else "Go to subclasses", - IdeActions.ACTION_GOTO_IMPLEMENTATION - ) - result.add(lineMarkerInfo) -} - -private fun collectOverriddenPropertyAccessors( - properties: Collection, - result: MutableCollection> -) { - val mappingToJava = HashMap() - for (property in properties) { - if (property.isOverridable()) { - property.toPossiblyFakeLightMethods().forEach { mappingToJava[it] = property } - mappingToJava[property] = property - } - } - - val classes = collectContainingClasses(mappingToJava.keys.filterIsInstance()) - - for (property in getOverriddenDeclarations(mappingToJava, classes)) { - ProgressManager.checkCanceled() - - val anchor = (property as? PsiNameIdentifierOwner)?.nameIdentifier ?: property - - val lineMarkerInfo = LineMarkerInfo( - anchor, - anchor.textRange, - if (isImplemented(property)) IMPLEMENTED_MARK else OVERRIDDEN_MARK, - Pass.LINE_MARKERS, - OVERRIDDEN_PROPERTY.tooltip, - OVERRIDDEN_PROPERTY.navigationHandler, - GutterIconRenderer.Alignment.RIGHT - ) - NavigateAction.setNavigateAction( - lineMarkerInfo, - "Go to overridden properties", - IdeActions.ACTION_GOTO_IMPLEMENTATION - ) - result.add(lineMarkerInfo) - } -} - -private val KtNamedDeclaration.expectOrActualAnchor - get() = - nameIdentifier ?: when (this) { - is KtConstructor<*> -> getConstructorKeyword() ?: getValueParameterList()?.leftParenthesis - is KtObjectDeclaration -> getObjectKeyword() - else -> null - } ?: this - -private fun collectMultiplatformMarkers( - declaration: KtNamedDeclaration, - result: MutableCollection> -) { - when { - declaration.isExpectDeclaration() -> collectActualMarkers(declaration, result) - declaration.isEffectivelyActual() -> collectExpectedMarkers(declaration, result) - } -} - -private fun collectActualMarkers( - declaration: KtNamedDeclaration, - result: MutableCollection> -) { - if (declaration is KtPrimaryConstructor) return - - val descriptor = declaration.toDescriptor() as? MemberDescriptor ?: return - val commonModuleDescriptor = declaration.containingKtFile.findModuleDescriptor() - - if (commonModuleDescriptor.implementingDescriptors.none { it.hasActualsFor(descriptor) }) return - - val anchor = declaration.expectOrActualAnchor - - val lineMarkerInfo = LineMarkerInfo( - anchor, - anchor.textRange, - KotlinIcons.ACTUAL, - Pass.LINE_MARKERS, - PLATFORM_ACTUAL.tooltip, - PLATFORM_ACTUAL.navigationHandler, - GutterIconRenderer.Alignment.RIGHT - ) - NavigateAction.setNavigateAction( - lineMarkerInfo, - "Go to actual declarations", - IdeActions.ACTION_GOTO_IMPLEMENTATION - ) - result.add(lineMarkerInfo) -} - -private fun collectExpectedMarkers( - declaration: KtNamedDeclaration, - result: MutableCollection> -) { - if (declaration is KtPrimaryConstructor) return - - val descriptor = declaration.toDescriptor() as? MemberDescriptor ?: return - val platformModuleDescriptor = declaration.containingKtFile.findModuleDescriptor() - if (!platformModuleDescriptor.implementedDescriptors.any { it.hasDeclarationOf(descriptor) }) return - - val anchor = declaration.expectOrActualAnchor - - val lineMarkerInfo = LineMarkerInfo( - anchor, - anchor.textRange, - KotlinIcons.EXPECT, - Pass.LINE_MARKERS, - EXPECTED_DECLARATION.tooltip, - EXPECTED_DECLARATION.navigationHandler, - GutterIconRenderer.Alignment.RIGHT - ) - NavigateAction.setNavigateAction( - lineMarkerInfo, - "Go to expected declaration", - null - ) - result.add(lineMarkerInfo) -} - -private fun collectOverriddenFunctions(functions: Collection, result: MutableCollection>) { - val mappingToJava = HashMap() - for (function in functions) { - if (function.isOverridable()) { - val method = LightClassUtil.getLightClassMethod(function) ?: KtFakeLightMethod.get(function) - if (method != null) { - mappingToJava[method] = function - } - mappingToJava[function] = function - } - } - - val classes = collectContainingClasses(mappingToJava.keys.filterIsInstance()) - - for (function in getOverriddenDeclarations(mappingToJava, classes)) { - ProgressManager.checkCanceled() - - val anchor = function.nameIdentifier ?: function - - val lineMarkerInfo = LineMarkerInfo( - anchor, - anchor.textRange, - if (isImplemented(function)) IMPLEMENTED_MARK else OVERRIDDEN_MARK, - Pass.LINE_MARKERS, OVERRIDDEN_FUNCTION.tooltip, - OVERRIDDEN_FUNCTION.navigationHandler, - GutterIconRenderer.Alignment.RIGHT - ) - NavigateAction.setNavigateAction( - lineMarkerInfo, - "Go to overridden methods", - IdeActions.ACTION_GOTO_IMPLEMENTATION - ) - result.add(lineMarkerInfo) - } -} diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/KotlinCommonIntentionActionsFactory.kt.172 b/idea/src/org/jetbrains/kotlin/idea/intentions/KotlinCommonIntentionActionsFactory.kt.172 deleted file mode 100644 index 43701d71e89..00000000000 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/KotlinCommonIntentionActionsFactory.kt.172 +++ /dev/null @@ -1,261 +0,0 @@ -/* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.kotlin.idea.intentions - -import com.intellij.codeInsight.intention.IntentionAction -import com.intellij.codeInsight.intention.JvmCommonIntentionActionsFactory -import com.intellij.codeInsight.intention.MethodInsertionInfo -import com.intellij.codeInsight.intention.QuickFixFactory -import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement -import com.intellij.openapi.editor.Editor -import com.intellij.openapi.project.Project -import com.intellij.psi.* -import com.intellij.psi.impl.source.tree.java.PsiReferenceExpressionImpl -import org.jetbrains.kotlin.asJava.LightClassUtil -import org.jetbrains.kotlin.asJava.elements.KtLightElement -import org.jetbrains.kotlin.builtins.DefaultBuiltIns -import org.jetbrains.kotlin.builtins.jvm.JavaToKotlinClassMap -import org.jetbrains.kotlin.descriptors.Visibilities -import org.jetbrains.kotlin.idea.core.ShortenReferences -import org.jetbrains.kotlin.idea.core.insertMembersAfter -import org.jetbrains.kotlin.idea.quickfix.AddModifierFix -import org.jetbrains.kotlin.idea.quickfix.RemoveModifierFix -import org.jetbrains.kotlin.lexer.KtTokens -import org.jetbrains.kotlin.name.FqName -import org.jetbrains.kotlin.psi.* -import org.jetbrains.kotlin.psi.KtPsiFactory.CallableBuilder -import org.jetbrains.kotlin.psi.KtPsiFactory.CallableBuilder.Target.CONSTRUCTOR -import org.jetbrains.kotlin.psi.KtPsiFactory.CallableBuilder.Target.FUNCTION -import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe -import org.jetbrains.uast.UClass -import org.jetbrains.uast.UDeclaration -import org.jetbrains.uast.UElement - -class KotlinCommonIntentionActionsFactory : JvmCommonIntentionActionsFactory() { - override fun createChangeModifierAction(declaration: UDeclaration, modifier: String, shouldPresent: Boolean): IntentionAction? { - val kModifierOwner = declaration.asKtElement() - ?: throw IllegalArgumentException("$declaration is expected to contain KtLightElement with KtModifierListOwner") - - val (kToken, shouldPresentMapped) = if (PsiModifier.FINAL == modifier) - KtTokens.OPEN_KEYWORD to !shouldPresent - else - javaPsiModifiersMapping[modifier] to shouldPresent - - if (kToken == null) return null - return if (shouldPresentMapped) - AddModifierFix.createIfApplicable(kModifierOwner, kToken) - else - RemoveModifierFix(kModifierOwner, kToken, false) - } - - override fun createAddBeanPropertyActions(uClass: UClass, - propertyName: String, - visibilityModifier: String, - propertyType: PsiType, - setterRequired: Boolean, - getterRequired: Boolean): List { - - fun addPropertyFix(lateinit: Boolean = false) = - Fix(uClass, - "Add property", - "Add '${if (lateinit) "lateinit " else ""}" + - "${if (setterRequired) "var" else "val"}' property '$propertyName' to '${uClass.name}'") - { uClass -> - val visibilityStr = javaVisibilityMapping.getValue(visibilityModifier) - val psiFactory = KtPsiFactory(uClass) - val modifiersString = if (lateinit) "lateinit $visibilityStr" else visibilityStr - val function = psiFactory.createProperty( - modifiersString, - propertyName, - typeString(propertyType), - setterRequired, - if (lateinit) null else "TODO(\"initialize me\")") - val ktClassOrObject = uClass.asKtElement()!! - insertMembersAfter(null, ktClassOrObject, listOf(function), null) - } - - if (setterRequired) - return listOf(addPropertyFix(), addPropertyFix(lateinit = true)) - else - return listOf(addPropertyFix()) - } - - override fun createAddCallableMemberActions(info: MethodInsertionInfo): List = - when (info) { - is MethodInsertionInfo.Method -> - createAddMethodAction(info)?.let { listOf(it) } ?: emptyList() - - is MethodInsertionInfo.Constructor -> - createAddConstructorActions(info) - } - - companion object { - val javaPsiModifiersMapping = mapOf( - PsiModifier.PRIVATE to KtTokens.PRIVATE_KEYWORD, - PsiModifier.PUBLIC to KtTokens.PUBLIC_KEYWORD, - PsiModifier.PROTECTED to KtTokens.PUBLIC_KEYWORD, - PsiModifier.ABSTRACT to KtTokens.ABSTRACT_KEYWORD - ) - - val javaVisibilityMapping: Map = mapOf( - PsiModifier.PRIVATE to Visibilities.PRIVATE.displayName, - PsiModifier.PUBLIC to "", - PsiModifier.PROTECTED to Visibilities.PROTECTED.displayName, - PsiModifier.PACKAGE_LOCAL to Visibilities.INTERNAL.displayName - ).withDefault { Visibilities.DEFAULT_VISIBILITY.displayName } - - fun typeString(str: PsiType): String { - var typeName: String? = when (str) { - PsiType.VOID -> "" - PsiType.INT -> "kotlin.Int" - PsiType.LONG -> "kotlin.Long" - PsiType.SHORT -> "kotlin.Short" - PsiType.BOOLEAN -> "kotlin.Boolean" - PsiType.BYTE -> "kotlin.Byte" - PsiType.CHAR -> "kotlin.Char" - PsiType.DOUBLE -> "kotlin.Double" - PsiType.FLOAT -> "kotlin.Float" - else -> null - } - if (typeName == null) - typeName = JavaToKotlinClassMap.mapJavaToKotlin(FqName(str.canonicalText), DefaultBuiltIns.Instance)?.fqNameSafe?.asString() - - return typeName ?: str.canonicalText - } - } - - private inline fun UElement.asKtElement(): T? = - (psi as? KtLightElement<*, *>?)?.kotlinOrigin as? T - - private fun CallableBuilder.paramsFromInfo(info: MethodInsertionInfo) { - for ((index, param) in info.parameters.withIndex()) { - param(param.name ?: "arg${index + 1}", typeString(param.type)) - } - } - - private fun createAddMethodAction(info: MethodInsertionInfo.Method): IntentionAction? { - val visibilityStr = info.modifiers.map { javaVisibilityMapping.get(it) ?: it }.joinToString(" ") - val functionString = CallableBuilder(FUNCTION).apply { - modifier(visibilityStr) - typeParams() - name(info.name) - paramsFromInfo(info) - info.returnType.let { - when (it) { - PsiType.VOID -> noReturnType() - else -> returnType(typeString(it)) - } - } - blockBody("") - } - - return Fix(info.containingClass, "Add method", "Add method '${info.name}' to '${info.containingClass.name}'") { - uClass -> - val psiFactory = KtPsiFactory(uClass) - val function = psiFactory.createFunction(functionString.asString()) - val ktClassOrObject = uClass.asKtElement()!! - insertMembersAfter(null, ktClassOrObject, listOf(function), ktClassOrObject.declarations.lastOrNull()) - } - - } - - private fun createAddConstructorActions(info: MethodInsertionInfo.Constructor): List { - val constructorString = CallableBuilder(CONSTRUCTOR).apply { - modifier("") - typeParams() - name() - paramsFromInfo(info) - noReturnType() - blockBody("") - }.asString() - val primaryConstructor = info.containingClass.asKtElement()!!.primaryConstructor - - val addConstructorAction = if (primaryConstructor == null) - Fix(info.containingClass, - "Add method", - "Add primary constructor to '${info.containingClass.name}'", - { uClass -> - val psiFactory = KtPsiFactory(uClass) - val constructor = psiFactory.createSecondaryConstructor(constructorString) - val ktClass = uClass.asKtElement()!! - val newPrimaryConstructor = ktClass.createPrimaryConstructorIfAbsent() - newPrimaryConstructor.valueParameterList!!.replace(constructor.valueParameterList!!) - ShortenReferences.DEFAULT.process(newPrimaryConstructor) - }) - else Fix(info.containingClass, - "Add method", - "Add secondary constructor to '${info.containingClass.name}'", - { uClass -> - val psiFactory = KtPsiFactory(uClass) - val constructor = psiFactory.createSecondaryConstructor(constructorString) - val ktClassOrObject = uClass.asKtElement()!! - insertMembersAfter(null, ktClassOrObject, listOf(constructor), null) - }) - - val changePrimaryConstructorAction = run { - if (primaryConstructor == null) return@run null - QuickFixFactory.getInstance() - .createChangeMethodSignatureFromUsageFix( - LightClassUtil.getLightClassMethod(primaryConstructor)!!, - fakeParametersExpressions(info.parameters), - PsiSubstitutor.EMPTY, info.containingClass, false, 2 - ).takeIf { it.isAvailable(info.containingClass.project, null, info.containingClass.containingFile) } - } - - return listOf(changePrimaryConstructorAction, addConstructorAction).filterNotNull() - } - - private fun fakeParametersExpressions(parameters: List): Array = - when { - parameters.isEmpty() -> emptyArray() - else -> JavaPsiFacade.getElementFactory(parameters.first().project) - .createParameterList( - parameters.map { it.name }.toTypedArray(), - parameters.map { it.type }.toTypedArray() - ).parameters.map { FakeExpressionFromParameter(it) }.toTypedArray() - } - - private class FakeExpressionFromParameter(private val psiParam: PsiParameter) : PsiReferenceExpressionImpl() { - - override fun getText(): String = psiParam.name!! - - override fun getProject(): Project = psiParam.project - - override fun getParent(): PsiElement = psiParam.parent - - override fun getType(): PsiType? = psiParam.type - - override fun isValid(): Boolean = true - - override fun getContainingFile(): PsiFile = psiParam.containingFile - - override fun getReferenceName(): String? = psiParam.name - - override fun resolve(): PsiElement? = psiParam - } - - private class Fix(uClass: UClass, private val familyName: String, private val text: String, private val action: (uClass: UClass) -> Unit) : LocalQuickFixAndIntentionActionOnPsiElement(uClass) { - override fun getFamilyName(): String = familyName - - override fun getText(): String = text - - override fun invoke(project: Project, file: PsiFile, editor: Editor?, startElement: PsiElement, endElement: PsiElement) = - action(startElement as UClass) - } - -} - diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/KotlinCrossLanguageQuickFixAction.kt.172 b/idea/src/org/jetbrains/kotlin/idea/quickfix/KotlinCrossLanguageQuickFixAction.kt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/KotlinQuickFixAction.kt.172 b/idea/src/org/jetbrains/kotlin/idea/quickfix/KotlinQuickFixAction.kt.172 deleted file mode 100644 index 8c2adc970dc..00000000000 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/KotlinQuickFixAction.kt.172 +++ /dev/null @@ -1,68 +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.idea.quickfix - -import com.intellij.codeInsight.FileModificationService -import com.intellij.codeInsight.intention.IntentionAction -import com.intellij.openapi.application.ApplicationManager -import com.intellij.openapi.editor.Editor -import com.intellij.openapi.project.Project -import com.intellij.psi.PsiElement -import com.intellij.psi.PsiFile -import org.jetbrains.kotlin.psi.CREATEBYPATTERN_MAY_NOT_REFORMAT -import org.jetbrains.kotlin.psi.KtCodeFragment -import org.jetbrains.kotlin.psi.KtFile -import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer - -abstract class KotlinQuickFixAction(element: T) : IntentionAction { - private val elementPointer = element.createSmartPointer() - - protected val element: T? - get() = elementPointer.element - - final override fun isAvailable(project: Project, editor: Editor?, file: PsiFile): Boolean { - if (ApplicationManager.getApplication().isUnitTestMode) { - CREATEBYPATTERN_MAY_NOT_REFORMAT = true - } - try { - val element = element ?: return false - return element.isValid && - !element.project.isDisposed && - (file.manager.isInProject(file) || file is KtCodeFragment) && - (file is KtFile) && - isAvailable(project, editor, file) - } - finally { - CREATEBYPATTERN_MAY_NOT_REFORMAT = false - } - } - - protected open fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean { - return true - } - - final override fun invoke(project: Project, editor: Editor?, file: PsiFile) { - val element = element ?: return - if (file is KtFile && FileModificationService.getInstance().prepareFileForWrite(element.containingFile)) { - invoke(project, editor, file) - } - } - - protected abstract fun invoke(project: Project, editor: Editor?, file: KtFile) - - override fun startInWriteAction() = true -} diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/QuickFixActionBase.kt.172 b/idea/src/org/jetbrains/kotlin/idea/quickfix/QuickFixActionBase.kt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/CallableBuilder.kt.172 b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/CallableBuilder.kt.172 deleted file mode 100644 index 2598706bb0e..00000000000 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/CallableBuilder.kt.172 +++ /dev/null @@ -1,1135 +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.idea.quickfix.createFromUsage.callableBuilder - -import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageUtils -import com.intellij.codeInsight.navigation.NavigationUtil -import com.intellij.codeInsight.template.* -import com.intellij.codeInsight.template.impl.TemplateImpl -import com.intellij.codeInsight.template.impl.TemplateManagerImpl -import com.intellij.openapi.application.ApplicationManager -import com.intellij.openapi.editor.Editor -import com.intellij.openapi.editor.ScrollType -import com.intellij.openapi.fileEditor.FileEditorManager -import com.intellij.openapi.fileEditor.OpenFileDescriptor -import com.intellij.openapi.ui.DialogWrapper -import com.intellij.openapi.util.UnfairTextRange -import com.intellij.psi.* -import com.intellij.psi.codeStyle.CodeStyleManager -import com.intellij.psi.codeStyle.JavaCodeStyleManager -import com.intellij.psi.util.PsiTreeUtil -import org.jetbrains.kotlin.builtins.KotlinBuiltIns -import org.jetbrains.kotlin.builtins.functions.FunctionClassDescriptor -import org.jetbrains.kotlin.cfg.pseudocode.Pseudocode -import org.jetbrains.kotlin.cfg.pseudocode.getContainingPseudocode -import org.jetbrains.kotlin.descriptors.* -import org.jetbrains.kotlin.descriptors.annotations.Annotations -import org.jetbrains.kotlin.descriptors.impl.MutablePackageFragmentDescriptor -import org.jetbrains.kotlin.descriptors.impl.SimpleFunctionDescriptorImpl -import org.jetbrains.kotlin.descriptors.impl.TypeParameterDescriptorImpl -import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithAllCompilerChecks -import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent -import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny -import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaClassDescriptor -import org.jetbrains.kotlin.idea.codeInsight.CodeInsightUtils -import org.jetbrains.kotlin.idea.core.* -import org.jetbrains.kotlin.idea.imports.importableFqName -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.createClass.ClassKind -import org.jetbrains.kotlin.idea.refactoring.* -import org.jetbrains.kotlin.idea.util.DialogWithEditor -import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers -import org.jetbrains.kotlin.idea.util.application.executeWriteCommand -import org.jetbrains.kotlin.idea.util.application.runWriteAction -import org.jetbrains.kotlin.incremental.components.NoLookupLocation -import org.jetbrains.kotlin.lexer.KtTokens -import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor -import org.jetbrains.kotlin.name.FqName -import org.jetbrains.kotlin.name.Name -import org.jetbrains.kotlin.psi.* -import org.jetbrains.kotlin.psi.psiUtil.* -import org.jetbrains.kotlin.psi.typeRefHelpers.setReceiverTypeReference -import org.jetbrains.kotlin.resolve.BindingContext -import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils -import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassOrAny -import org.jetbrains.kotlin.resolve.scopes.HierarchicalScope -import org.jetbrains.kotlin.resolve.scopes.LexicalScopeImpl -import org.jetbrains.kotlin.resolve.scopes.LexicalScopeKind -import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier -import org.jetbrains.kotlin.resolve.scopes.utils.memberScopeAsImportingScope -import org.jetbrains.kotlin.types.KotlinType -import org.jetbrains.kotlin.types.TypeProjectionImpl -import org.jetbrains.kotlin.types.TypeUtils -import org.jetbrains.kotlin.types.Variance -import org.jetbrains.kotlin.types.checker.KotlinTypeChecker -import org.jetbrains.kotlin.types.typeUtil.isAnyOrNullableAny -import org.jetbrains.kotlin.types.typeUtil.isUnit -import org.jetbrains.kotlin.types.typeUtil.makeNullable -import java.lang.AssertionError -import java.lang.IllegalArgumentException -import java.lang.IllegalStateException -import java.util.* - -/** - * Represents a single choice for a type (e.g. parameter type or return type). - */ -class TypeCandidate(val theType: KotlinType, scope: HierarchicalScope? = null) { - val typeParameters: Array - var renderedTypes: List = emptyList() - private set - var renderedTypeParameters: List? = null - private set - - fun render(typeParameterNameMap: Map, fakeFunction: FunctionDescriptor?) { - renderedTypes = theType.renderShort(typeParameterNameMap) - renderedTypeParameters = typeParameters.map { - RenderedTypeParameter(it, it.containingDeclaration == fakeFunction, typeParameterNameMap[it]!!) - } - } - - init { - val typeParametersInType = theType.getTypeParameters() - if (scope == null) { - typeParameters = typeParametersInType.toTypedArray() - renderedTypes = theType.renderShort(Collections.emptyMap()) - } - else { - typeParameters = getTypeParameterNamesNotInScope(typeParametersInType, scope).toTypedArray() - } - } - - override fun toString() = theType.toString() -} - -data class RenderedTypeParameter( - val typeParameter: TypeParameterDescriptor, - val fake: Boolean, - val text: String -) - -fun List.getTypeByRenderedType(renderedTypes: List): KotlinType? = - firstOrNull { it.renderedTypes == renderedTypes }?.theType - -class CallableBuilderConfiguration( - val callableInfos: List, - val originalElement: KtElement, - val currentFile: KtFile = originalElement.containingKtFile, - val currentEditor: Editor? = null, - val isExtension: Boolean = false, - val enableSubstitutions: Boolean = true -) - -sealed class CallablePlacement { - class WithReceiver(val receiverTypeCandidate: TypeCandidate): CallablePlacement() - class NoReceiver(val containingElement: PsiElement): CallablePlacement() -} - -class CallableBuilder(val config: CallableBuilderConfiguration) { - private var finished: Boolean = false - - val currentFileContext = config.currentFile.analyzeWithContent() - - private lateinit var _currentFileModule: ModuleDescriptor - val currentFileModule: ModuleDescriptor - get() { - if (!_currentFileModule.isValid) { - updateCurrentModule() - } - return _currentFileModule - } - - init { - updateCurrentModule() - } - - val pseudocode: Pseudocode? by lazy { config.originalElement.getContainingPseudocode(currentFileContext) } - - private val typeCandidates = HashMap>() - - var placement: CallablePlacement? = null - - private val elementsToShorten = ArrayList() - - private fun updateCurrentModule() { - _currentFileModule = config.currentFile.analyzeWithAllCompilerChecks().moduleDescriptor - } - - fun computeTypeCandidates(typeInfo: TypeInfo): List = - typeCandidates.getOrPut(typeInfo) { typeInfo.getPossibleTypes(this).map { TypeCandidate(it) } } - - private fun computeTypeCandidates( - typeInfo: TypeInfo, - substitutions: List, - scope: HierarchicalScope): List { - if (!typeInfo.substitutionsAllowed) return computeTypeCandidates(typeInfo) - return typeCandidates.getOrPut(typeInfo) { - val types = typeInfo.getPossibleTypes(this).asReversed() - - // We have to use semantic equality here - data class EqWrapper(val _type: KotlinType) { - override fun equals(other: Any?) = this === other - || other is EqWrapper && KotlinTypeChecker.DEFAULT.equalTypes(_type, other._type) - override fun hashCode() = 0 // no good way to compute hashCode() that would agree with our equals() - } - - val newTypes = LinkedHashSet(types.map(::EqWrapper)) - for (substitution in substitutions) { - // each substitution can be applied or not, so we offer all options - val toAdd = newTypes.map { it._type.substitute(substitution, typeInfo.variance) } - // substitution.byType are type arguments, but they cannot already occur in the type before substitution - val toRemove = newTypes.filter { substitution.byType in it._type } - - newTypes.addAll(toAdd.map(::EqWrapper)) - newTypes.removeAll(toRemove) - } - - if (newTypes.isEmpty()) { - newTypes.add(EqWrapper(currentFileModule.builtIns.anyType)) - } - - newTypes.map { TypeCandidate(it._type, scope) }.asReversed() - } - } - - private fun buildNext(iterator: Iterator) { - if (iterator.hasNext()) { - val context = Context(iterator.next()) - runWriteAction { context.buildAndRunTemplate { buildNext(iterator) } } - ApplicationManager.getApplication().invokeLater { context.showDialogIfNeeded() } - } - else { - runWriteAction { ShortenReferences.DEFAULT.process(elementsToShorten) } - } - } - - fun build(onFinish: () -> Unit = {}) { - try { - assert(config.currentEditor != null) { "Can't run build() without editor" } - if (finished) throw IllegalStateException("Current builder has already finished") - buildNext(config.callableInfos.iterator()) - } - finally { - finished = true - onFinish() - } - } - - private inner class Context(val callableInfo: CallableInfo) { - val skipReturnType: Boolean - val jetFileToEdit: KtFile - val containingFileEditor: Editor - val containingElement: PsiElement - val dialogWithEditor: DialogWithEditor? - val receiverClassDescriptor: ClassifierDescriptor? - val typeParameterNameMap: Map - val receiverTypeCandidate: TypeCandidate? - val mandatoryTypeParametersAsCandidates: List - val substitutions: List - var finished: Boolean = false - - init { - // gather relevant information - - val placement = placement - var nullableReceiver = false - when (placement) { - is CallablePlacement.NoReceiver -> { - containingElement = placement.containingElement - receiverClassDescriptor = with (placement.containingElement) { - when (this) { - is KtClassOrObject -> currentFileContext[BindingContext.CLASS, this] - is PsiClass -> getJavaClassDescriptor() - else -> null - } - } - } - is CallablePlacement.WithReceiver -> { - val theType = placement.receiverTypeCandidate.theType - nullableReceiver = theType.isMarkedNullable - receiverClassDescriptor = theType.constructor.declarationDescriptor - val classDeclaration = receiverClassDescriptor?.let { DescriptorToSourceUtils.getSourceFromDescriptor(it) } - containingElement = if (!config.isExtension && classDeclaration != null) classDeclaration else config.currentFile - } - else -> throw IllegalArgumentException("Placement wan't initialized") - } - val receiverType = receiverClassDescriptor?.defaultType?.let { - if (nullableReceiver) it.makeNullable() else it - } - - val project = config.currentFile.project - - if (containingElement.containingFile != config.currentFile) { - NavigationUtil.activateFileWithPsiElement(containingElement) - } - - dialogWithEditor = if (containingElement is KtElement) { - jetFileToEdit = containingElement.containingKtFile - containingFileEditor = if (jetFileToEdit != config.currentFile) { - FileEditorManager.getInstance(project).selectedTextEditor!! - } - else { - config.currentEditor!! - } - null - } else { - val dialog = object: DialogWithEditor(project, "Create from usage", "") { - override fun doOKAction() { - project.executeWriteCommand("Premature end of template") { - TemplateManagerImpl.getTemplateState(editor)?.gotoEnd(false) - } - super.doOKAction() - } - } - containingFileEditor = dialog.editor - with(containingFileEditor.settings) { - additionalColumnsCount = config.currentEditor!!.settings.getRightMargin(project) - additionalLinesCount = 5 - } - jetFileToEdit = PsiDocumentManager.getInstance(project).getPsiFile(containingFileEditor.document) as KtFile - jetFileToEdit.analysisContext = config.currentFile - dialog - } - - val scope = getDeclarationScope() - - receiverTypeCandidate = receiverType?.let { TypeCandidate(it, scope) } - - val fakeFunction: FunctionDescriptor? - // figure out type substitutions for type parameters - val substitutionMap = LinkedHashMap() - if (config.enableSubstitutions) { - collectSubstitutionsForReceiverTypeParameters(receiverType, substitutionMap) - val typeArgumentsForFakeFunction = callableInfo.typeParameterInfos - .map { - val typeCandidates = computeTypeCandidates(it) - assert (typeCandidates.size == 1) { "Ambiguous type candidates for type parameter $it: $typeCandidates" } - typeCandidates.first().theType - } - .subtract(substitutionMap.keys) - fakeFunction = createFakeFunctionDescriptor(scope, typeArgumentsForFakeFunction.size) - collectSubstitutionsForCallableTypeParameters(fakeFunction, typeArgumentsForFakeFunction, substitutionMap) - mandatoryTypeParametersAsCandidates = listOfNotNull(receiverTypeCandidate) + typeArgumentsForFakeFunction.map { TypeCandidate(substitutionMap[it]!!, scope) } - } - else { - fakeFunction = null - mandatoryTypeParametersAsCandidates = Collections.emptyList() - } - substitutions = substitutionMap.map { KotlinTypeSubstitution(it.key, it.value) } - - callableInfo.parameterInfos.forEach { - computeTypeCandidates(it.typeInfo, substitutions, scope) - } - - val returnTypeCandidate = computeTypeCandidates(callableInfo.returnTypeInfo, substitutions, scope).singleOrNull() - skipReturnType = when (callableInfo.kind) { - CallableKind.FUNCTION -> - returnTypeCandidate?.theType?.isUnit() ?: false - CallableKind.CLASS_WITH_PRIMARY_CONSTRUCTOR -> - callableInfo.returnTypeInfo == TypeInfo.Empty || returnTypeCandidate?.theType?.isAnyOrNullableAny() ?: false - CallableKind.CONSTRUCTOR -> true - CallableKind.PROPERTY -> containingElement is KtBlockExpression - } - - // figure out type parameter renames to avoid conflicts - typeParameterNameMap = getTypeParameterRenames(scope) - callableInfo.parameterInfos.forEach { renderTypeCandidates(it.typeInfo, typeParameterNameMap, fakeFunction) } - if (!skipReturnType) { - renderTypeCandidates(callableInfo.returnTypeInfo, typeParameterNameMap, fakeFunction) - } - receiverTypeCandidate?.render(typeParameterNameMap, fakeFunction) - mandatoryTypeParametersAsCandidates.forEach { it.render(typeParameterNameMap, fakeFunction) } - } - - private fun getDeclarationScope(): HierarchicalScope { - if (config.isExtension || receiverClassDescriptor == null) { - return currentFileModule.getPackage(config.currentFile.packageFqName).memberScope.memberScopeAsImportingScope() - } - - if (receiverClassDescriptor is ClassDescriptorWithResolutionScopes) { - return receiverClassDescriptor.scopeForMemberDeclarationResolution - } - - assert (receiverClassDescriptor is JavaClassDescriptor) { "Unexpected receiver class: $receiverClassDescriptor" } - - val projections = ((receiverClassDescriptor as JavaClassDescriptor).declaredTypeParameters) - .map { TypeProjectionImpl(it.defaultType) } - val memberScope = receiverClassDescriptor.getMemberScope(projections) - - return LexicalScopeImpl(memberScope.memberScopeAsImportingScope(), receiverClassDescriptor, false, null, - LexicalScopeKind.SYNTHETIC) { - receiverClassDescriptor.typeConstructor.parameters.forEach { addClassifierDescriptor(it) } - } - } - - private fun collectSubstitutionsForReceiverTypeParameters( - receiverType: KotlinType?, - result: MutableMap - ) { - if (placement is CallablePlacement.NoReceiver) return - - val classTypeParameters = receiverType?.arguments ?: Collections.emptyList() - val ownerTypeArguments = (placement as? CallablePlacement.WithReceiver)?.receiverTypeCandidate?.theType?.arguments - ?: Collections.emptyList() - assert(ownerTypeArguments.size == classTypeParameters.size) - ownerTypeArguments.zip(classTypeParameters).forEach { result[it.first.type] = it.second.type } - } - - private fun collectSubstitutionsForCallableTypeParameters( - fakeFunction: FunctionDescriptor, - typeArguments: Set, - result: MutableMap) { - for ((typeArgument, typeParameter) in typeArguments.zip(fakeFunction.typeParameters)) { - result[typeArgument] = typeParameter.defaultType - } - } - - private fun createFakeFunctionDescriptor(scope: HierarchicalScope, typeParameterCount: Int): FunctionDescriptor { - val fakeFunction = SimpleFunctionDescriptorImpl.create( - MutablePackageFragmentDescriptor(currentFileModule, FqName("fake")), - Annotations.EMPTY, - Name.identifier("fake"), - CallableMemberDescriptor.Kind.SYNTHESIZED, - SourceElement.NO_SOURCE - ) - - val validator = CollectingNameValidator { scope.findClassifier(Name.identifier(it), NoLookupLocation.FROM_IDE) == null } - val parameterNames = KotlinNameSuggester.suggestNamesForTypeParameters(typeParameterCount, validator) - val typeParameters = (0..typeParameterCount - 1).map { - TypeParameterDescriptorImpl.createWithDefaultBound( - fakeFunction, - Annotations.EMPTY, - false, - Variance.INVARIANT, - Name.identifier(parameterNames[it]), - it - ) - } - - return fakeFunction.initialize(null, null, typeParameters, Collections.emptyList(), null, - null, Visibilities.INTERNAL) - } - - private fun renderTypeCandidates( - typeInfo: TypeInfo, - typeParameterNameMap: Map, - fakeFunction: FunctionDescriptor? - ) { - typeCandidates[typeInfo]?.forEach { it.render(typeParameterNameMap, fakeFunction) } - } - - private fun isInsideInnerOrLocalClass(): Boolean { - val classOrObject = containingElement.getNonStrictParentOfType() - return classOrObject is KtClass && (classOrObject.isInner() || classOrObject.isLocal) - } - - private fun createDeclarationSkeleton(): KtNamedDeclaration { - with (config) { - val assignmentToReplace = - if (containingElement is KtBlockExpression && (callableInfo as? PropertyInfo)?.writable ?: false) { - originalElement as KtBinaryExpression - } - else null - - val ownerTypeString = if (isExtension) { - val renderedType = receiverTypeCandidate!!.renderedTypes.first() - val isFunctionType = receiverTypeCandidate.theType.constructor.declarationDescriptor is FunctionClassDescriptor - if (isFunctionType) "($renderedType)." else "$renderedType." - } else "" - - val classKind = (callableInfo as? ClassWithPrimaryConstructorInfo)?.classInfo?.kind - - fun renderParamList(): String { - val prefix = if (classKind == ClassKind.ANNOTATION_CLASS) "val " else "" - val list = callableInfo.parameterInfos.indices.joinToString(", ") { i -> "${prefix}p$i: Any" } - return if (callableInfo.parameterInfos.isNotEmpty() - || callableInfo.kind == CallableKind.FUNCTION - || callableInfo.kind == CallableKind.CONSTRUCTOR) "($list)" else list - } - - val paramList = when (callableInfo.kind) { - CallableKind.FUNCTION, CallableKind.CLASS_WITH_PRIMARY_CONSTRUCTOR, CallableKind.CONSTRUCTOR -> - renderParamList() - CallableKind.PROPERTY -> "" - } - val returnTypeString = if (skipReturnType || assignmentToReplace != null) "" else ": Any" - val header = "$ownerTypeString${callableInfo.name.quoteIfNeeded()}$paramList$returnTypeString" - - val psiFactory = KtPsiFactory(currentFile) - - val modifiers = - if (callableInfo.isAbstract) { - if (containingElement is KtClass && containingElement.isInterface()) "" else "abstract " - } - else if (containingElement is KtClassOrObject - && !(containingElement is KtClass && containingElement.isInterface()) - && containingElement.isAncestor(config.originalElement) - && callableInfo.kind != CallableKind.CONSTRUCTOR) "private " - else if (isExtension) "private " - else "" - - val isExpectClassMember by lazy { - containingElement is KtClassOrObject && containingElement.resolveToDescriptorIfAny()?.isExpect ?: false - } - - val declaration: KtNamedDeclaration = when (callableInfo.kind) { - CallableKind.FUNCTION, CallableKind.CONSTRUCTOR -> { - val body = when { - callableInfo.kind == CallableKind.CONSTRUCTOR -> "" - callableInfo.isAbstract -> "" - containingElement is KtClass && containingElement.hasModifier(KtTokens.EXTERNAL_KEYWORD) -> "" - containingElement is KtObjectDeclaration && containingElement.hasModifier(KtTokens.EXTERNAL_KEYWORD) -> "" - containingElement is KtObjectDeclaration && containingElement.isCompanion() - && containingElement.parent.parent is KtClass - && (containingElement.parent.parent as KtClass).hasModifier(KtTokens.EXTERNAL_KEYWORD) -> "" - isExpectClassMember -> "" - else -> "{}" - - } - @Suppress("USELESS_CAST") // KT-10755 - if (callableInfo is FunctionInfo) { - val operatorModifier = if (callableInfo.isOperator) "operator " else "" - val infixModifier = if (callableInfo.isInfix) "infix " else "" - psiFactory.createFunction("$modifiers$infixModifier${operatorModifier}fun<> $header $body") as KtNamedDeclaration - } - else if ((callableInfo as ConstructorInfo).isPrimary) { - val constructorText = if (modifiers.isNotEmpty()) "${modifiers}constructor$paramList" else paramList - psiFactory.createPrimaryConstructor(constructorText) as KtNamedDeclaration - } - else { - psiFactory.createSecondaryConstructor("${modifiers}constructor$paramList $body") as KtNamedDeclaration - } - } - CallableKind.CLASS_WITH_PRIMARY_CONSTRUCTOR -> { - with((callableInfo as ClassWithPrimaryConstructorInfo).classInfo) { - val classBody = when (kind) { - ClassKind.ANNOTATION_CLASS, ClassKind.ENUM_ENTRY -> "" - else -> "{\n\n}" - } - val safeName = name.quoteIfNeeded() - when (kind) { - ClassKind.ENUM_ENTRY -> { - val targetParent = applicableParents.singleOrNull() - if (!(targetParent is KtClass && targetParent.isEnum())) throw AssertionError("Enum class expected: ${targetParent?.text}") - val hasParameters = targetParent.primaryConstructorParameters.isNotEmpty() - psiFactory.createEnumEntry("$safeName${if (hasParameters) "()" else " "}") - } - else -> { - val openMod = if (open) "open " else "" - val innerMod = if (inner || isInsideInnerOrLocalClass()) "inner " else "" - val typeParamList = when (kind) { - ClassKind.PLAIN_CLASS, ClassKind.INTERFACE -> "<>" - else -> "" - } - psiFactory.createDeclaration( - "$openMod$innerMod${kind.keyword} $safeName$typeParamList$paramList$returnTypeString $classBody" - ) - } - } - } - } - CallableKind.PROPERTY -> { - val isVar = (callableInfo as PropertyInfo).writable - val valVar = if (isVar) "var" else "val" - val accessors = if (isExtension && !isExpectClassMember) { - buildString { - append("\nget() {}") - if (isVar) { - append("\nset() {}") - } - } - } - else "" - psiFactory.createProperty("$modifiers$valVar<> $header$accessors") - } - } - - if (assignmentToReplace != null) { - (declaration as KtProperty).initializer = assignmentToReplace.right - return assignmentToReplace.replace(declaration) as KtCallableDeclaration - } - - val declarationInPlace = placeDeclarationInContainer(declaration, containingElement, config.originalElement, jetFileToEdit) - - if (declarationInPlace is KtSecondaryConstructor) { - val containingClass = declarationInPlace.containingClassOrObject!! - if (containingClass.primaryConstructorParameters.isNotEmpty()) { - declarationInPlace.replaceImplicitDelegationCallWithExplicit(true) - } - else if ((receiverClassDescriptor as ClassDescriptor).getSuperClassOrAny().constructors.all { it.valueParameters.isNotEmpty() }) { - declarationInPlace.replaceImplicitDelegationCallWithExplicit(false) - } - } - - return declarationInPlace - } - } - - private fun getTypeParameterRenames(scope: HierarchicalScope): Map { - val allTypeParametersNotInScope = LinkedHashSet() - - mandatoryTypeParametersAsCandidates.asSequence() - .plus(callableInfo.parameterInfos.asSequence().flatMap { typeCandidates[it.typeInfo]!!.asSequence() }) - .flatMap { it.typeParameters.asSequence() } - .toCollection(allTypeParametersNotInScope) - - if (!skipReturnType) { - computeTypeCandidates(callableInfo.returnTypeInfo).asSequence().flatMapTo(allTypeParametersNotInScope) { - it.typeParameters.asSequence() - } - } - - val validator = CollectingNameValidator { scope.findClassifier(Name.identifier(it), NoLookupLocation.FROM_IDE) == null } - val typeParameterNames = allTypeParametersNotInScope.map { KotlinNameSuggester.suggestNameByName(it.name.asString(), validator) } - - return allTypeParametersNotInScope.zip(typeParameterNames).toMap() - } - - private fun setupTypeReferencesForShortening(declaration: KtNamedDeclaration, - parameterTypeExpressions: List): List { - val typeRefsToShorten = ArrayList() - - if (config.isExtension) { - val receiverTypeText = receiverTypeCandidate!!.theType.renderLong(typeParameterNameMap).first() - val replacingTypeRef = KtPsiFactory(declaration).createType(receiverTypeText) - val newTypeRef = (declaration as KtCallableDeclaration).setReceiverTypeReference(replacingTypeRef)!! - typeRefsToShorten.add(newTypeRef) - } - - val returnTypeRefs = declaration.getReturnTypeReferences() - if (returnTypeRefs.isNotEmpty()) { - val returnType = typeCandidates[callableInfo.returnTypeInfo]!!.getTypeByRenderedType( - returnTypeRefs.map { it.text } - ) - if (returnType != null) { - // user selected a given type - replaceWithLongerName(returnTypeRefs, returnType) - typeRefsToShorten.addAll(declaration.getReturnTypeReferences()) - } - } - - val valueParameters = declaration.getValueParameters() - val parameterIndicesToShorten = ArrayList() - assert(valueParameters.size == parameterTypeExpressions.size) - for ((i, parameter) in valueParameters.asSequence().withIndex()) { - val parameterTypeRef = parameter.typeReference - if (parameterTypeRef != null) { - val parameterType = parameterTypeExpressions[i].typeCandidates.getTypeByRenderedType( - listOf(parameterTypeRef.text) - ) - if (parameterType != null) { - replaceWithLongerName(listOf(parameterTypeRef), parameterType) - parameterIndicesToShorten.add(i) - } - } - } - - val expandedValueParameters = declaration.getValueParameters() - parameterIndicesToShorten.mapNotNullTo(typeRefsToShorten) { expandedValueParameters[it].typeReference } - - return typeRefsToShorten - } - - private fun postprocessDeclaration(declaration: KtNamedDeclaration) { - if (callableInfo is PropertyInfo && callableInfo.isLateinitPreferred) { - if (declaration.containingClassOrObject == null) return - val propertyDescriptor = declaration.resolveToDescriptorIfAny() as? PropertyDescriptor ?: return - val returnType = propertyDescriptor.returnType ?: return - if (TypeUtils.isNullableType(returnType) || KotlinBuiltIns.isPrimitiveType(returnType)) return - declaration.addModifier(KtTokens.LATEINIT_KEYWORD) - } - } - - private fun setupDeclarationBody(func: KtDeclarationWithBody) { - val oldBody = func.bodyExpression ?: return - val templateKind = when (func) { - is KtSecondaryConstructor -> TemplateKind.SECONDARY_CONSTRUCTOR - is KtNamedFunction, is KtPropertyAccessor -> TemplateKind.FUNCTION - else -> throw AssertionError("Unexpected declaration: " + func.getElementTextWithContext()) - } - val bodyText = getFunctionBodyTextFromTemplate( - func.project, - templateKind, - if (callableInfo.name.isNotEmpty()) callableInfo.name else null, - if (skipReturnType) "Unit" else (func as? KtFunction)?.typeReference?.text ?: "", - receiverClassDescriptor?.importableFqName ?: receiverClassDescriptor?.name?.let { FqName.topLevel(it) } - ) - oldBody.replace(KtPsiFactory(func).createBlock(bodyText)) - } - - private fun setupCallTypeArguments(callElement: KtCallElement, typeParameters: List) { - val oldTypeArgumentList = callElement.typeArgumentList ?: return - val renderedTypeArgs = typeParameters.map { typeParameter -> - val type = substitutions.first { it.byType.constructor.declarationDescriptor == typeParameter }.forType - IdeDescriptorRenderers.SOURCE_CODE.renderType(type) - } - if (renderedTypeArgs.isEmpty()) { - oldTypeArgumentList.delete() - } - else { - oldTypeArgumentList.replace(KtPsiFactory(callElement).createTypeArguments(renderedTypeArgs.joinToString(", ", "<", ">"))) - elementsToShorten.add(callElement.typeArgumentList!!) - } - } - - private fun setupReturnTypeTemplate(builder: TemplateBuilder, declaration: KtNamedDeclaration): TypeExpression? { - val candidates = typeCandidates[callableInfo.returnTypeInfo]!! - if (candidates.isEmpty()) return null - - val elementToReplace: KtElement? - val expression: TypeExpression = when (declaration) { - is KtCallableDeclaration -> { - elementToReplace = declaration.typeReference - TypeExpression.ForTypeReference(candidates) - } - is KtClassOrObject -> { - elementToReplace = declaration.superTypeListEntries.firstOrNull() - TypeExpression.ForDelegationSpecifier(candidates) - } - else -> throw AssertionError("Unexpected declaration kind: ${declaration.text}") - } - if (elementToReplace == null) return null - - if (candidates.size == 1) { - builder.replaceElement(elementToReplace, (expression.calculateResult(null) as TextResult).text) - return null - } - - builder.replaceElement(elementToReplace, expression) - return expression - } - - private fun setupValVarTemplate(builder: TemplateBuilder, property: KtProperty) { - if (!(callableInfo as PropertyInfo).writable) { - builder.replaceElement(property.valOrVarKeyword, ValVarExpression) - } - } - - private fun setupTypeParameterListTemplate( - builder: TemplateBuilderImpl, - declaration: KtNamedDeclaration - ): TypeParameterListExpression? { - when (declaration) { - is KtObjectDeclaration -> return null - !is KtTypeParameterListOwner -> throw AssertionError("Unexpected declaration kind: ${declaration.text}") - } - - val typeParameterList = (declaration as KtTypeParameterListOwner).typeParameterList ?: return null - - val typeParameterMap = HashMap>() - - val mandatoryTypeParameters = ArrayList() - //receiverTypeCandidate?.let { mandatoryTypeParameters.addAll(it.renderedTypeParameters!!) } - mandatoryTypeParametersAsCandidates.asSequence().flatMapTo(mandatoryTypeParameters) { it.renderedTypeParameters!!.asSequence() } - - callableInfo.parameterInfos.asSequence() - .flatMap { typeCandidates[it.typeInfo]!!.asSequence() } - .forEach { typeParameterMap[it.renderedTypes.first()] = it.renderedTypeParameters!! } - - if (declaration.getReturnTypeReference() != null) { - typeCandidates[callableInfo.returnTypeInfo]!!.forEach { - typeParameterMap[it.renderedTypes.first()] = it.renderedTypeParameters!! - } - } - - val expression = TypeParameterListExpression( - mandatoryTypeParameters, - typeParameterMap, - callableInfo.kind != CallableKind.CLASS_WITH_PRIMARY_CONSTRUCTOR - ) - val leftSpace = typeParameterList.prevSibling as? PsiWhiteSpace - val rangeStart = if (leftSpace != null) leftSpace.startOffset else typeParameterList.startOffset - val offset = typeParameterList.startOffset - val range = UnfairTextRange(rangeStart - offset, typeParameterList.endOffset - offset) - builder.replaceElement(typeParameterList, range, "TYPE_PARAMETER_LIST", expression, false) - return expression - } - - private fun setupParameterTypeTemplates(builder: TemplateBuilder, parameterList: List): List { - assert(parameterList.size == callableInfo.parameterInfos.size) - - val typeParameters = ArrayList() - for ((parameter, jetParameter) in callableInfo.parameterInfos.zip(parameterList)) { - val parameterTypeExpression = TypeExpression.ForTypeReference(typeCandidates[parameter.typeInfo]!!) - val parameterTypeRef = jetParameter.typeReference!! - builder.replaceElement(parameterTypeRef, parameterTypeExpression) - - // add parameter name to the template - val possibleNamesFromExpression = parameter.typeInfo.getPossibleNamesFromExpression(currentFileContext) - val preferredName = parameter.preferredName - val possibleNames = if (preferredName != null) { - arrayOf(preferredName, *possibleNamesFromExpression) - } - else { - possibleNamesFromExpression - } - - // figure out suggested names for each type option - val parameterTypeToNamesMap = HashMap>() - typeCandidates[parameter.typeInfo]!!.forEach { typeCandidate -> - val suggestedNames = KotlinNameSuggester.suggestNamesByType(typeCandidate.theType, { true }) - parameterTypeToNamesMap[typeCandidate.renderedTypes.first()] = suggestedNames.toTypedArray() - } - - // add expression to builder - val parameterNameExpression = ParameterNameExpression(possibleNames, parameterTypeToNamesMap) - val parameterNameIdentifier = jetParameter.nameIdentifier!! - builder.replaceElement(parameterNameIdentifier, parameterNameExpression) - - typeParameters.add(parameterTypeExpression) - } - return typeParameters - } - - private fun replaceWithLongerName(typeRefs: List, theType: KotlinType) { - val psiFactory = KtPsiFactory(jetFileToEdit.project) - val fullyQualifiedReceiverTypeRefs = theType.renderLong(typeParameterNameMap).map { psiFactory.createType(it) } - (typeRefs zip fullyQualifiedReceiverTypeRefs).forEach { (shortRef, longRef) -> shortRef.replace(longRef) } - } - - private fun transformToJavaMemberIfApplicable(declaration: KtNamedDeclaration): Boolean { - fun convertToJava(targetClass: PsiClass): PsiMember? { - val psiFactory = KtPsiFactory(declaration) - - psiFactory.createPackageDirectiveIfNeeded(config.currentFile.packageFqName)?.let { - declaration.containingFile.addBefore(it, null) - } - - val adjustedDeclaration = when (declaration) { - is KtNamedFunction, is KtProperty -> { - val klass = psiFactory.createClass("class Foo {}") - klass.getBody()!!.add(declaration) - (declaration.replace(klass) as KtClass).getBody()!!.declarations.first() - } - else -> declaration - } - - return when (adjustedDeclaration) { - is KtNamedFunction, is KtSecondaryConstructor -> { - createJavaMethod(adjustedDeclaration as KtFunction, targetClass) - } - is KtProperty -> { - createJavaField(adjustedDeclaration, targetClass) - } - is KtClass -> { - createJavaClass(adjustedDeclaration, targetClass) - } - else -> null - } - } - - if (config.isExtension || receiverClassDescriptor !is JavaClassDescriptor) return false - - val targetClass = DescriptorToSourceUtils.getSourceFromDescriptor(receiverClassDescriptor) as? PsiClass - if (targetClass == null || !targetClass.canRefactor()) return false - - val project = declaration.project - - val newJavaMember = convertToJava(targetClass) ?: return false - - val modifierList = newJavaMember.modifierList!! - if (newJavaMember is PsiMethod || newJavaMember is PsiClass) { - modifierList.setModifierProperty(PsiModifier.FINAL, false) - } - - val needStatic = when (callableInfo) { - is ClassWithPrimaryConstructorInfo -> with(callableInfo.classInfo) { - !inner && kind != ClassKind.ENUM_ENTRY && kind != ClassKind.ENUM_CLASS - } - else -> callableInfo.receiverTypeInfo.staticContextRequired - } - modifierList.setModifierProperty(PsiModifier.STATIC, needStatic) - - JavaCodeStyleManager.getInstance(project).shortenClassReferences(newJavaMember) - - val descriptor = OpenFileDescriptor(project, targetClass.containingFile.virtualFile) - val targetEditor = FileEditorManager.getInstance(project).openTextEditor(descriptor, true)!! - - when (newJavaMember) { - is PsiMethod -> CreateFromUsageUtils.setupEditor(newJavaMember, targetEditor) - is PsiField -> targetEditor.caretModel.moveToOffset(newJavaMember.endOffset - 1) - is PsiClass -> { - val constructor = newJavaMember.constructors.firstOrNull() - val superStatement = constructor?.body?.statements?.firstOrNull() as? PsiExpressionStatement - val superCall = superStatement?.expression as? PsiMethodCallExpression - if (superCall != null) { - val lParen = superCall.argumentList.firstChild - targetEditor.caretModel.moveToOffset(lParen.endOffset) - } - else { - targetEditor.caretModel.moveToOffset(newJavaMember.startOffset) - } - } - } - targetEditor.scrollingModel.scrollToCaret(ScrollType.RELATIVE) - - return true - } - - private fun setupEditor(declaration: KtNamedDeclaration) { - if (declaration is KtProperty && !declaration.hasInitializer() && containingElement is KtBlockExpression) { - val defaultValueType = typeCandidates[callableInfo.returnTypeInfo]!!.firstOrNull()?.theType - val defaultValue = defaultValueType?.let { CodeInsightUtils.defaultInitializer(it) } ?: "null" - val initializer = declaration.setInitializer(KtPsiFactory(declaration).createExpression(defaultValue))!! - val range = initializer.textRange - containingFileEditor.selectionModel.setSelection(range.startOffset, range.endOffset) - containingFileEditor.caretModel.moveToOffset(range.endOffset) - return - } - if (declaration is KtSecondaryConstructor && !declaration.hasImplicitDelegationCall()) { - containingFileEditor.caretModel.moveToOffset(declaration.getDelegationCall().valueArgumentList!!.startOffset + 1) - return - } - setupEditorSelection(containingFileEditor, declaration) - } - - // build templates - fun buildAndRunTemplate(onFinish: () -> Unit) { - val declarationSkeleton = createDeclarationSkeleton() - val project = declarationSkeleton.project - val declarationPointer = SmartPointerManager.getInstance(project).createSmartPsiElementPointer(declarationSkeleton) - - // build templates - PsiDocumentManager.getInstance(project).commitAllDocuments() - PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(containingFileEditor.document) - - val caretModel = containingFileEditor.caretModel - caretModel.moveToOffset(jetFileToEdit.node.startOffset) - - val declaration = declarationPointer.element!! - - val declarationMarker = containingFileEditor.document.createRangeMarker(declaration.textRange) - - val builder = TemplateBuilderImpl(jetFileToEdit) - if (declaration is KtProperty) { - setupValVarTemplate(builder, declaration) - } - if (!skipReturnType) { - setupReturnTypeTemplate(builder, declaration) - } - - val parameterTypeExpressions = setupParameterTypeTemplates(builder, declaration.getValueParameters()) - - // add a segment for the parameter list - // Note: because TemplateBuilderImpl does not have a replaceElement overload that takes in both a TextRange and alwaysStopAt, we - // need to create the segment first and then hack the Expression into the template later. We use this template to update the type - // parameter list as the user makes selections in the parameter types, and we need alwaysStopAt to be false so the user can't tab to - // it. - val expression = setupTypeParameterListTemplate(builder, declaration) - - // the template built by TemplateBuilderImpl is ordered by element position, but we want types to be first, so hack it - val templateImpl = builder.buildInlineTemplate() as TemplateImpl - val variables = templateImpl.variables!! - if (variables.isNotEmpty()) { - val typeParametersVar = if (expression != null) variables.removeAt(0) else null - for (i in 0..(callableInfo.parameterInfos.size - 1)) { - Collections.swap(variables, i * 2, i * 2 + 1) - } - typeParametersVar?.let { variables.add(it) } - } - - // TODO: Disabled shortening names because it causes some tests fail. Refactor code to use automatic reference shortening - templateImpl.isToShortenLongNames = false - - // run the template - TemplateManager.getInstance(project).startTemplate(containingFileEditor, templateImpl, object : TemplateEditingAdapter() { - private fun finishTemplate(brokenOff: Boolean) { - try { - PsiDocumentManager.getInstance(project).commitDocument(containingFileEditor.document) - - dialogWithEditor?.close(DialogWrapper.OK_EXIT_CODE) - if (brokenOff && !ApplicationManager.getApplication().isUnitTestMode) return - - // file templates - val newDeclaration = PsiTreeUtil.findElementOfClassAtOffset(jetFileToEdit, - declarationMarker.startOffset, - declaration::class.java, - false) ?: return - - runWriteAction { - postprocessDeclaration(newDeclaration) - - // file templates - if (newDeclaration is KtNamedFunction || newDeclaration is KtSecondaryConstructor) { - setupDeclarationBody(newDeclaration as KtFunction) - } - - if (newDeclaration is KtProperty) { - newDeclaration.getter?.let { setupDeclarationBody(it) } - } - - val callElement = config.originalElement as? KtCallElement - if (callElement != null) { - setupCallTypeArguments(callElement, expression?.currentTypeParameters ?: Collections.emptyList()) - } - - CodeStyleManager.getInstance(project).reformat(newDeclaration) - - // change short type names to fully qualified ones (to be shortened below) - val typeRefsToShorten = setupTypeReferencesForShortening(newDeclaration, parameterTypeExpressions) - if (!transformToJavaMemberIfApplicable(newDeclaration)) { - elementsToShorten.addAll(typeRefsToShorten) - setupEditor(newDeclaration) - } - } - } - finally { - declarationMarker.dispose() - finished = true - onFinish() - } - } - - override fun templateCancelled(template: Template?) { - finishTemplate(true) - } - - override fun templateFinished(template: Template?, brokenOff: Boolean) { - finishTemplate(brokenOff) - } - }) - } - - fun showDialogIfNeeded() { - if (!ApplicationManager.getApplication().isUnitTestMode && dialogWithEditor != null && !finished) { - dialogWithEditor.show() - } - } - } -} - -// TODO: Simplify and use formatter as much as possible -@Suppress("UNCHECKED_CAST") -internal fun placeDeclarationInContainer( - declaration: D, - container: PsiElement, - anchor: PsiElement, - fileToEdit: KtFile = container.containingFile as KtFile -): D { - val psiFactory = KtPsiFactory(container) - val newLine = psiFactory.createNewLine() - - fun calcNecessaryEmptyLines(decl: KtDeclaration, after: Boolean): Int { - var lineBreaksPresent = 0 - var neighbor: PsiElement? = null - - siblingsLoop@ - for (sibling in decl.siblings(forward = after, withItself = false)) { - when (sibling) { - is PsiWhiteSpace -> lineBreaksPresent += (sibling.text ?: "").count { it == '\n' } - else -> { - neighbor = sibling - break@siblingsLoop - } - } - } - - val neighborType = neighbor?.node?.elementType - val lineBreaksNeeded = when { - neighborType == KtTokens.LBRACE || neighborType == KtTokens.RBRACE -> 1 - neighbor is KtDeclaration && (neighbor !is KtProperty || decl !is KtProperty) -> 2 - else -> 1 - } - - return Math.max(lineBreaksNeeded - lineBreaksPresent, 0) - } - - val actualContainer = (container as? KtClassOrObject)?.getOrCreateBody() ?: container - - fun addDeclarationToClassOrObject(classOrObject: KtClassOrObject, - declaration: KtNamedDeclaration): KtNamedDeclaration { - val classBody = classOrObject.getOrCreateBody() - return if (declaration is KtNamedFunction) { - val neighbor = PsiTreeUtil.skipSiblingsBackward( - classBody.rBrace ?: classBody.lastChild!!, - PsiWhiteSpace::class.java - ) - classBody.addAfter(declaration, neighbor) as KtNamedDeclaration - } - else classBody.addAfter(declaration, classBody.lBrace!!) as KtNamedDeclaration - } - - - fun addNextToOriginalElementContainer(addBefore: Boolean): D { - val sibling = anchor.parentsWithSelf.first { it.parent == actualContainer } - return if (addBefore) { - actualContainer.addBefore(declaration, sibling) - } - else { - actualContainer.addAfter(declaration, sibling) - } as D - } - - val declarationInPlace = when { - declaration is KtPrimaryConstructor -> { - (container as KtClass).createPrimaryConstructorIfAbsent().replaced(declaration) as D - } - - actualContainer.isAncestor(anchor, true) -> { - val insertToBlock = container is KtBlockExpression - if (insertToBlock) { - val parent = container.parent - if (parent is KtFunctionLiteral) { - if (!parent.isMultiLine()) { - parent.addBefore(newLine, container) - parent.addAfter(newLine, container) - } - } - } - addNextToOriginalElementContainer(insertToBlock - || (declaration is KtProperty && actualContainer !is KtFile) - || declaration is KtTypeAlias) - } - - container is KtFile -> container.add(declaration) as D - - container is PsiClass -> { - if (declaration is KtSecondaryConstructor) { - val wrappingClass = psiFactory.createClass("class ${container.name} {\n}") - addDeclarationToClassOrObject(wrappingClass, declaration) - (fileToEdit.add(wrappingClass) as KtClass).declarations.first() as D - } - else { - fileToEdit.add(declaration) as D - } - } - - container is KtClassOrObject -> { - insertMember(null, container, declaration, container.declarations.lastOrNull()) - } - else -> throw AssertionError("Invalid containing element: ${container.text}") - } - - val parent = declarationInPlace.parent - calcNecessaryEmptyLines(declarationInPlace, false).let { - if (it > 0) parent.addBefore(psiFactory.createNewLine(it), declarationInPlace) - } - calcNecessaryEmptyLines(declarationInPlace, true).let { - if (it > 0) parent.addAfter(psiFactory.createNewLine(it), declarationInPlace) - } - return declarationInPlace -} - -internal fun KtNamedDeclaration.getReturnTypeReference() = getReturnTypeReferences().singleOrNull() - -internal fun KtNamedDeclaration.getReturnTypeReferences(): List { - return when (this) { - is KtCallableDeclaration -> listOfNotNull(typeReference) - is KtClassOrObject -> superTypeListEntries.mapNotNull { it.typeReference } - else -> throw AssertionError("Unexpected declaration kind: $text") - } -} - -fun CallableBuilderConfiguration.createBuilder(): CallableBuilder = CallableBuilder(this) diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/CallableInfo.kt.172 b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/CallableInfo.kt.172 deleted file mode 100644 index aaaf48b106e..00000000000 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/CallableInfo.kt.172 +++ /dev/null @@ -1,250 +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.idea.quickfix.createFromUsage.callableBuilder - -import com.intellij.psi.PsiElement -import com.intellij.util.ArrayUtil -import org.jetbrains.kotlin.descriptors.ClassDescriptorWithResolutionScopes -import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny -import org.jetbrains.kotlin.idea.core.KotlinNameSuggester -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.createClass.ClassInfo -import org.jetbrains.kotlin.idea.util.getResolutionScope -import org.jetbrains.kotlin.idea.util.getResolvableApproximations -import org.jetbrains.kotlin.psi.* -import org.jetbrains.kotlin.resolve.BindingContext -import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils -import org.jetbrains.kotlin.resolve.scopes.LexicalScope -import org.jetbrains.kotlin.types.ErrorUtils -import org.jetbrains.kotlin.types.KotlinType -import org.jetbrains.kotlin.types.Variance -import org.jetbrains.kotlin.types.typeUtil.makeNotNullable -import java.util.* - -/** - * Represents a concrete type or a set of types yet to be inferred from an expression. - */ -abstract class TypeInfo(val variance: Variance) { - object Empty: TypeInfo(Variance.INVARIANT) { - override fun getPossibleTypes(builder: CallableBuilder): List = Collections.emptyList() - } - - class ByExpression(val expression: KtExpression, variance: Variance): TypeInfo(variance) { - override fun getPossibleNamesFromExpression(bindingContext: BindingContext): Array { - return KotlinNameSuggester.suggestNamesByExpressionOnly(expression, bindingContext, { true }).toTypedArray() - } - - override fun getPossibleTypes(builder: CallableBuilder): List = - expression.guessTypes( - context = builder.currentFileContext, - module = builder.currentFileModule, - pseudocode = builder.pseudocode - ).flatMap { it.getPossibleSupertypes(variance, builder) } - } - - class ByTypeReference(val typeReference: KtTypeReference, variance: Variance): TypeInfo(variance) { - override fun getPossibleTypes(builder: CallableBuilder): List = - builder.currentFileContext[BindingContext.TYPE, typeReference].getPossibleSupertypes(variance, builder) - } - - class ByType(val theType: KotlinType, variance: Variance): TypeInfo(variance) { - override fun getPossibleTypes(builder: CallableBuilder): List = - theType.getPossibleSupertypes(variance, builder) - } - - class ByReceiverType(variance: Variance): TypeInfo(variance) { - override fun getPossibleTypes(builder: CallableBuilder): List = - (builder.placement as CallablePlacement.WithReceiver).receiverTypeCandidate.theType.getPossibleSupertypes(variance, builder) - } - - abstract class DelegatingTypeInfo(val delegate: TypeInfo): TypeInfo(delegate.variance) { - override val substitutionsAllowed: Boolean = delegate.substitutionsAllowed - override fun getPossibleNamesFromExpression(bindingContext: BindingContext) = delegate.getPossibleNamesFromExpression(bindingContext) - override fun getPossibleTypes(builder: CallableBuilder): List = delegate.getPossibleTypes(builder) - } - - class NoSubstitutions(delegate: TypeInfo): DelegatingTypeInfo(delegate) { - override val substitutionsAllowed: Boolean = false - } - - class StaticContextRequired(delegate: TypeInfo): DelegatingTypeInfo(delegate) { - override val staticContextRequired: Boolean = true - } - - class OfThis(delegate: TypeInfo) : DelegatingTypeInfo(delegate) - - val isOfThis: Boolean - get() = when (this) { - is OfThis -> true - is DelegatingTypeInfo -> delegate.isOfThis - else -> false - } - - open val substitutionsAllowed: Boolean = true - open val staticContextRequired: Boolean = false - open fun getPossibleNamesFromExpression(bindingContext: BindingContext): Array = ArrayUtil.EMPTY_STRING_ARRAY - abstract fun getPossibleTypes(builder: CallableBuilder): List - - private fun getScopeForTypeApproximation(config: CallableBuilderConfiguration, placement: CallablePlacement?): LexicalScope? { - if (placement == null) return config.originalElement.getResolutionScope() - - val containingElement = when (placement) { - is CallablePlacement.NoReceiver -> { - placement.containingElement - } - is CallablePlacement.WithReceiver -> { - val receiverClassDescriptor = - placement.receiverTypeCandidate.theType.constructor.declarationDescriptor - val classDeclaration = receiverClassDescriptor?.let { DescriptorToSourceUtils.getSourceFromDescriptor(it) } - if (!config.isExtension && classDeclaration != null) classDeclaration else config.currentFile - } - } - return when (containingElement) { - is KtClassOrObject -> (containingElement.resolveToDescriptorIfAny() as? ClassDescriptorWithResolutionScopes)?.scopeForMemberDeclarationResolution - is KtBlockExpression -> (containingElement.statements.firstOrNull() ?: containingElement).getResolutionScope() - is KtElement -> containingElement.containingKtFile.getResolutionScope() - else -> null - } - } - - protected fun KotlinType?.getPossibleSupertypes(variance: Variance, callableBuilder: CallableBuilder): List { - if (this == null || ErrorUtils.containsErrorType(this)) { - return Collections.singletonList(callableBuilder.currentFileModule.builtIns.anyType) - } - val scope = getScopeForTypeApproximation(callableBuilder.config, callableBuilder.placement) - val approximations = getResolvableApproximations(scope, false, true) - return when (variance) { - Variance.IN_VARIANCE -> approximations.toList() - else -> listOf(approximations.firstOrNull() ?: this) - } - } -} - -fun TypeInfo(expressionOfType: KtExpression, variance: Variance): TypeInfo = TypeInfo.ByExpression(expressionOfType, variance) -fun TypeInfo(typeReference: KtTypeReference, variance: Variance): TypeInfo = TypeInfo.ByTypeReference(typeReference, variance) -fun TypeInfo(theType: KotlinType, variance: Variance): TypeInfo = TypeInfo.ByType(theType, variance) - -fun TypeInfo.noSubstitutions(): TypeInfo = (this as? TypeInfo.NoSubstitutions) ?: TypeInfo.NoSubstitutions(this) - -fun TypeInfo.forceNotNull(): TypeInfo { - class ForcedNotNull(delegate: TypeInfo): TypeInfo.DelegatingTypeInfo(delegate) { - override fun getPossibleTypes(builder: CallableBuilder): List = - super.getPossibleTypes(builder).map { it.makeNotNullable() } - } - - return (this as? ForcedNotNull) ?: ForcedNotNull(this) -} - -fun TypeInfo.ofThis() = TypeInfo.OfThis(this) - -/** - * Encapsulates information about a function parameter that is going to be created. - */ -class ParameterInfo( - val typeInfo: TypeInfo, - val preferredName: String? = null -) - -enum class CallableKind { - FUNCTION, - CLASS_WITH_PRIMARY_CONSTRUCTOR, - CONSTRUCTOR, - PROPERTY -} - -abstract class CallableInfo ( - val name: String, - val receiverTypeInfo: TypeInfo, - val returnTypeInfo: TypeInfo, - val possibleContainers: List, - val typeParameterInfos: List, - val isAbstract: Boolean = false -) { - abstract val kind: CallableKind - abstract val parameterInfos: List - - abstract fun copy(receiverTypeInfo: TypeInfo = this.receiverTypeInfo, - possibleContainers: List = this.possibleContainers, - isAbstract: Boolean = this.isAbstract): CallableInfo -} - -class FunctionInfo(name: String, - receiverTypeInfo: TypeInfo, - returnTypeInfo: TypeInfo, - possibleContainers: List = Collections.emptyList(), - override val parameterInfos: List = Collections.emptyList(), - typeParameterInfos: List = Collections.emptyList(), - val isOperator: Boolean = false, - val isInfix: Boolean = false, - isAbstract: Boolean = false -) : CallableInfo(name, receiverTypeInfo, returnTypeInfo, possibleContainers, typeParameterInfos, isAbstract) { - override val kind: CallableKind get() = CallableKind.FUNCTION - - override fun copy(receiverTypeInfo: TypeInfo, possibleContainers: List, isAbstract: Boolean) = FunctionInfo( - name, - receiverTypeInfo, - returnTypeInfo, - possibleContainers, - parameterInfos, - typeParameterInfos, - isOperator, - isInfix, - isAbstract - ) -} - -class ClassWithPrimaryConstructorInfo(val classInfo: ClassInfo, expectedTypeInfo: TypeInfo): CallableInfo( - classInfo.name, TypeInfo.Empty, expectedTypeInfo.forceNotNull(), Collections.emptyList(), classInfo.typeArguments, false -) { - override val kind: CallableKind get() = CallableKind.CLASS_WITH_PRIMARY_CONSTRUCTOR - override val parameterInfos: List get() = classInfo.parameterInfos - - override fun copy(receiverTypeInfo: TypeInfo, possibleContainers: List, isAbstract: Boolean) = throw UnsupportedOperationException() -} - -class ConstructorInfo( - override val parameterInfos: List, - val targetClass: PsiElement, - val isPrimary: Boolean = false -): CallableInfo("", TypeInfo.Empty, TypeInfo.Empty, Collections.emptyList(), Collections.emptyList(), false) { - override val kind: CallableKind get() = CallableKind.CONSTRUCTOR - - override fun copy(receiverTypeInfo: TypeInfo, possibleContainers: List, isAbstract: Boolean) = throw UnsupportedOperationException() -} - -class PropertyInfo(name: String, - receiverTypeInfo: TypeInfo, - returnTypeInfo: TypeInfo, - val writable: Boolean, - possibleContainers: List = Collections.emptyList(), - typeParameterInfos: List = Collections.emptyList(), - isAbstract: Boolean = false, - val isLateinitPreferred: Boolean = false -) : CallableInfo(name, receiverTypeInfo, returnTypeInfo, possibleContainers, typeParameterInfos, isAbstract) { - override val kind: CallableKind get() = CallableKind.PROPERTY - override val parameterInfos: List get() = Collections.emptyList() - - override fun copy(receiverTypeInfo: TypeInfo, possibleContainers: List, isAbstract: Boolean) = PropertyInfo( - name, - receiverTypeInfo, - returnTypeInfo, - writable, - possibleContainers, - typeParameterInfos, - isAbstract, - isLateinitPreferred - ) -} diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/generationUtils.kt.172 b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/generationUtils.kt.172 deleted file mode 100644 index d708c8b2cc3..00000000000 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/generationUtils.kt.172 +++ /dev/null @@ -1,62 +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.idea.quickfix.createFromUsage.callableBuilder - -import com.intellij.openapi.editor.Editor -import com.intellij.openapi.editor.ScrollType -import com.intellij.psi.PsiElement -import com.intellij.psi.PsiWhiteSpace -import org.jetbrains.kotlin.psi.* -import org.jetbrains.kotlin.psi.psiUtil.endOffset -import org.jetbrains.kotlin.psi.psiUtil.siblings -import org.jetbrains.kotlin.psi.psiUtil.startOffset - -fun setupEditorSelection(editor: Editor, declaration: KtNamedDeclaration) { - val caretModel = editor.caretModel - val selectionModel = editor.selectionModel - - if (declaration is KtSecondaryConstructor) { - caretModel.moveToOffset(declaration.getConstructorKeyword().endOffset) - } - else { - caretModel.moveToOffset(declaration.nameIdentifier!!.endOffset) - } - - fun positionBetween(left: PsiElement, right: PsiElement) { - val from = left.siblings(withItself = false, forward = true).firstOrNull { it !is PsiWhiteSpace } ?: return - val to = right.siblings(withItself = false, forward = false).firstOrNull { it !is PsiWhiteSpace } ?: return - val startOffset = from.startOffset - val endOffset = to.endOffset - caretModel.moveToOffset(endOffset) - selectionModel.setSelection(startOffset, endOffset) - } - - when (declaration) { - is KtNamedFunction, is KtSecondaryConstructor -> { - ((declaration as KtFunction).bodyExpression as? KtBlockExpression)?.let { - positionBetween(it.lBrace!!, it.rBrace!!) - } - } - is KtClassOrObject -> { - caretModel.moveToOffset(declaration.startOffset) - } - is KtProperty -> { - caretModel.moveToOffset(declaration.endOffset) - } - } - editor.scrollingModel.scrollToCaret(ScrollType.CENTER) -} diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateBinaryOperationActionFactory.kt.172 b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateBinaryOperationActionFactory.kt.172 deleted file mode 100644 index 56353834c67..00000000000 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateBinaryOperationActionFactory.kt.172 +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createCallable - -import org.jetbrains.kotlin.diagnostics.Diagnostic -import org.jetbrains.kotlin.idea.project.builtIns -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.* -import org.jetbrains.kotlin.lexer.KtToken -import org.jetbrains.kotlin.lexer.KtTokens -import org.jetbrains.kotlin.psi.KtBinaryExpression -import org.jetbrains.kotlin.types.Variance -import org.jetbrains.kotlin.types.expressions.OperatorConventions -import java.util.* - -object CreateBinaryOperationActionFactory : CreateCallableMemberFromUsageFactory() { - override fun getElementOfInterest(diagnostic: Diagnostic): KtBinaryExpression? { - return diagnostic.psiElement.parent as? KtBinaryExpression - } - - override fun createCallableInfo(element: KtBinaryExpression, diagnostic: Diagnostic): CallableInfo? { - val token = element.operationToken as KtToken - val operationName = when (token) { - KtTokens.IDENTIFIER -> element.operationReference.getReferencedName() - else -> OperatorConventions.getNameForOperationSymbol(token, false, true)?.asString() - } ?: return null - val inOperation = token in OperatorConventions.IN_OPERATIONS - val comparisonOperation = token in OperatorConventions.COMPARISON_OPERATIONS - - val leftExpr = element.left ?: return null - val rightExpr = element.right ?: return null - - val receiverExpr = if (inOperation) rightExpr else leftExpr - val argumentExpr = if (inOperation) leftExpr else rightExpr - - val builtIns = element.builtIns - val receiverType = TypeInfo(receiverExpr, Variance.IN_VARIANCE) - val returnType = when { - inOperation -> TypeInfo.ByType(builtIns.booleanType, Variance.INVARIANT).noSubstitutions() - comparisonOperation -> TypeInfo.ByType(builtIns.intType, Variance.INVARIANT).noSubstitutions() - else -> TypeInfo(element, Variance.OUT_VARIANCE) - } - val parameters = Collections.singletonList(ParameterInfo(TypeInfo(argumentExpr, Variance.IN_VARIANCE))) - val isOperator = token != KtTokens.IDENTIFIER - return FunctionInfo(operationName, receiverType, returnType, parameterInfos = parameters, - isOperator = isOperator, - isInfix = !isOperator) - } -} diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateCallableFromCallActionFactory.kt.172 b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateCallableFromCallActionFactory.kt.172 deleted file mode 100644 index f625a241e96..00000000000 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateCallableFromCallActionFactory.kt.172 +++ /dev/null @@ -1,348 +0,0 @@ -/* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createCallable - -import com.intellij.openapi.project.Project -import com.intellij.psi.PsiClass -import com.intellij.psi.util.PsiTreeUtil -import org.jetbrains.kotlin.analyzer.AnalysisResult -import org.jetbrains.kotlin.builtins.KotlinBuiltIns -import org.jetbrains.kotlin.descriptors.CallableDescriptor -import org.jetbrains.kotlin.descriptors.ClassDescriptor -import org.jetbrains.kotlin.descriptors.ConstructorDescriptor -import org.jetbrains.kotlin.diagnostics.Diagnostic -import org.jetbrains.kotlin.diagnostics.Errors -import org.jetbrains.kotlin.idea.caches.resolve.analyzeAndGetResult -import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor -import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.* -import org.jetbrains.kotlin.idea.refactoring.canRefactor -import org.jetbrains.kotlin.idea.refactoring.getExtractionContainers -import org.jetbrains.kotlin.idea.refactoring.isInterfaceClass -import org.jetbrains.kotlin.idea.util.isAbstract -import org.jetbrains.kotlin.lexer.KtTokens -import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor -import org.jetbrains.kotlin.psi.* -import org.jetbrains.kotlin.psi.psiUtil.* -import org.jetbrains.kotlin.resolve.BindingContext -import org.jetbrains.kotlin.resolve.bindingContextUtil.getReferenceTargets -import org.jetbrains.kotlin.resolve.calls.callUtil.getCall -import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns -import org.jetbrains.kotlin.resolve.descriptorUtil.classValueType -import org.jetbrains.kotlin.resolve.scopes.receivers.* -import org.jetbrains.kotlin.resolve.source.getPsi -import org.jetbrains.kotlin.types.KotlinType -import org.jetbrains.kotlin.types.TypeUtils -import org.jetbrains.kotlin.types.Variance -import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf -import java.lang.AssertionError -import java.util.* - -sealed class CreateCallableFromCallActionFactory( - extensionsEnabled: Boolean = true -) : CreateCallableMemberFromUsageFactory(extensionsEnabled) { - protected abstract fun doCreateCallableInfo( - expression: E, - analysisResult: AnalysisResult, - name: String, - receiverType: TypeInfo, - possibleContainers: List - ): CallableInfo? - - protected fun getExpressionOfInterest(diagnostic: Diagnostic): KtExpression? { - val diagElement = diagnostic.psiElement - if (PsiTreeUtil.getParentOfType( - diagElement, - KtTypeReference::class.java, KtAnnotationEntry::class.java, KtImportDirective::class.java - ) != null) return null - - return when (diagnostic.factory) { - in Errors.UNRESOLVED_REFERENCE_DIAGNOSTICS, Errors.EXPRESSION_EXPECTED_PACKAGE_FOUND -> { - val parent = diagElement.parent - if (parent is KtCallExpression && parent.calleeExpression == diagElement) parent else diagElement - } - - Errors.NO_VALUE_FOR_PARAMETER, - Errors.TOO_MANY_ARGUMENTS, - Errors.NONE_APPLICABLE -> diagElement.getNonStrictParentOfType() - - Errors.TYPE_MISMATCH -> (diagElement.parent as? KtValueArgument)?.getStrictParentOfType() - - else -> throw AssertionError("Unexpected diagnostic: ${diagnostic.factory}") - } as? KtExpression - } - - override fun createCallableInfo(element: E, diagnostic: Diagnostic): CallableInfo? { - val project = element.project - - val calleeExpr = when (element) { - is KtCallExpression -> element.calleeExpression - is KtSimpleNameExpression -> element - else -> null - } as? KtSimpleNameExpression ?: return null - - if (calleeExpr.getReferencedNameElementType() != KtTokens.IDENTIFIER) return null - - val analysisResult = calleeExpr.analyzeAndGetResult() - val receiver = element.getCall(analysisResult.bindingContext)?.explicitReceiver - val receiverType = getReceiverTypeInfo(analysisResult.bindingContext, project, receiver) ?: return null - - val possibleContainers = - if (receiverType is TypeInfo.Empty) { - val containers = with(element.getQualifiedExpressionForSelectorOrThis().getExtractionContainers()) { - if (element is KtCallExpression) this else filter { it is KtClassBody || it is KtFile } - } - if (containers.isNotEmpty()) containers else return null - } - else Collections.emptyList() - - return doCreateCallableInfo(element, analysisResult, calleeExpr.getReferencedName(), receiverType, possibleContainers) - } - - private fun getReceiverTypeInfo(context: BindingContext, project: Project, receiver: Receiver?): TypeInfo? { - return when (receiver) { - null -> TypeInfo.Empty - is Qualifier -> { - val qualifierType = context.getType(receiver.expression) - if (qualifierType != null) return TypeInfo(qualifierType, Variance.IN_VARIANCE) - - if (receiver !is ClassQualifier) return null - val classifierType = receiver.descriptor.classValueType - if (classifierType != null) return TypeInfo(classifierType, Variance.IN_VARIANCE) - - val javaClassifier = receiver.descriptor as? JavaClassDescriptor ?: return null - val javaClass = DescriptorToSourceUtilsIde.getAnyDeclaration(project, javaClassifier) as? PsiClass - if (javaClass == null || !javaClass.canRefactor()) return null - TypeInfo.StaticContextRequired(TypeInfo(javaClassifier.defaultType, Variance.IN_VARIANCE)) - } - is ReceiverValue -> { - val originalType = receiver.type - val finalType = if (receiver is ExpressionReceiver) { - getDataFlowAwareTypes(receiver.expression, context, originalType).firstOrNull() ?: originalType - } else originalType - TypeInfo(finalType, Variance.IN_VARIANCE) - } - else -> throw AssertionError("Unexpected receiver: $receiver") - } - } - - protected fun getAbstractCallableInfo(mainCallable: CallableInfo, originalExpression: KtExpression): CallableInfo? { - val receiverTypeInfo: TypeInfo - val receiverType: KotlinType - - val originalReceiverTypeInfo = mainCallable.receiverTypeInfo - if (originalReceiverTypeInfo != TypeInfo.Empty) { - if (originalReceiverTypeInfo !is TypeInfo.ByType) return null - receiverTypeInfo = originalReceiverTypeInfo - receiverType = receiverTypeInfo.theType - } - else { - val containingClass = originalExpression.getStrictParentOfType() as? KtClass ?: return null - if (containingClass is KtEnumEntry) return null - receiverType = (containingClass.unsafeResolveToDescriptor() as ClassDescriptor).defaultType - receiverTypeInfo = TypeInfo(receiverType, Variance.IN_VARIANCE).ofThis() - } - - if (!receiverType.isAbstract() && TypeUtils.getAllSupertypes(receiverType).all { !it.isAbstract() }) return null - - return mainCallable.copy(receiverTypeInfo = receiverTypeInfo, possibleContainers = emptyList(), isAbstract = true) - } - - protected fun getCallableWithReceiverInsideExtension( - mainCallable: CallableInfo, - originalExpression: KtExpression, - context: BindingContext, - receiverType: TypeInfo - ): CallableInfo? { - if (receiverType != TypeInfo.Empty) return null - val callable = (originalExpression.getParentOfTypeAndBranch { bodyExpression } - ?: originalExpression.getParentOfTypeAndBranches { listOf(getter, setter) }) - ?: return null - if (callable !is KtFunctionLiteral && callable.receiverTypeReference == null) return null - val callableDescriptor = context[BindingContext.DECLARATION_TO_DESCRIPTOR, callable] as? CallableDescriptor ?: return null - val extensionReceiverType = callableDescriptor.extensionReceiverParameter?.type ?: return null - val newReceiverTypeInfo = TypeInfo(extensionReceiverType, Variance.IN_VARIANCE) - return mainCallable.copy(receiverTypeInfo = newReceiverTypeInfo, possibleContainers = emptyList()) - } - - sealed class Property: CreateCallableFromCallActionFactory() { - override fun getElementOfInterest(diagnostic: Diagnostic): KtSimpleNameExpression? { - val refExpr = getExpressionOfInterest(diagnostic) as? KtNameReferenceExpression ?: return null - if (refExpr.getParentOfTypeAndBranch { callableReference } != null) return null - return refExpr - } - - override fun doCreateCallableInfo( - expression: KtSimpleNameExpression, - analysisResult: AnalysisResult, - name: String, - receiverType: TypeInfo, - possibleContainers: List - ): CallableInfo? { - val fullCallExpr = expression.getQualifiedExpressionForSelectorOrThis() - val varExpected = fullCallExpr.getAssignmentByLHS() != null - val expressionForTypeGuess = fullCallExpr.getExpressionForTypeGuess() - val returnTypes = expressionForTypeGuess.guessTypes(analysisResult.bindingContext, analysisResult.moduleDescriptor) - val returnTypeInfo = TypeInfo(expressionForTypeGuess, if (varExpected) Variance.INVARIANT else Variance.OUT_VARIANCE) - val canBeLateinit = - varExpected - && returnTypes.any { !it.isMarkedNullable && !KotlinBuiltIns.isPrimitiveType(it) } - && fullCallExpr.parents.firstOrNull { it is KtDeclarationWithBody || it is KtClassInitializer } is KtDeclarationWithBody - return PropertyInfo(name, receiverType, returnTypeInfo, varExpected, possibleContainers, isLateinitPreferred = canBeLateinit) - } - - object Default : Property() { - override fun doCreateCallableInfo( - expression: KtSimpleNameExpression, - analysisResult: AnalysisResult, - name: String, - receiverType: TypeInfo, - possibleContainers: List - ): CallableInfo? { - return super.doCreateCallableInfo( - expression, - analysisResult, - name, - receiverType, - possibleContainers.filterNot { it is KtClassBody && (it.parent as KtClassOrObject).isInterfaceClass() } - ) - } - } - - object Abstract : Property() { - override fun doCreateCallableInfo( - expression: KtSimpleNameExpression, - analysisResult: AnalysisResult, - name: String, - receiverType: TypeInfo, - possibleContainers: List - ) = super.doCreateCallableInfo(expression, analysisResult, name, receiverType, possibleContainers)?.let { - getAbstractCallableInfo(it, expression) - } - } - - object ByImplicitExtensionReceiver : Property() { - override fun doCreateCallableInfo( - expression: KtSimpleNameExpression, - analysisResult: AnalysisResult, - name: String, - receiverType: TypeInfo, - possibleContainers: List - ) = super.doCreateCallableInfo(expression, analysisResult, name, receiverType, possibleContainers)?.let { - ByImplicitExtensionReceiver.getCallableWithReceiverInsideExtension(it, expression, analysisResult.bindingContext, receiverType) - } - } - } - - sealed class Function: CreateCallableFromCallActionFactory() { - override fun getElementOfInterest(diagnostic: Diagnostic): KtCallExpression? { - return getExpressionOfInterest(diagnostic) as? KtCallExpression - } - - override fun doCreateCallableInfo( - expression: KtCallExpression, - analysisResult: AnalysisResult, - name: String, - receiverType: TypeInfo, - possibleContainers: List - ): CallableInfo? { - val parameters = expression.getParameterInfos() - val typeParameters = expression.getTypeInfoForTypeArguments() - val fullCallExpression = expression.getQualifiedExpressionForSelectorOrThis() - val expectedType = fullCallExpression.guessTypes(analysisResult.bindingContext, analysisResult.moduleDescriptor).singleOrNull() - val returnType = if (expectedType != null) { - TypeInfo(expectedType, Variance.OUT_VARIANCE) - } else { - TypeInfo(fullCallExpression, Variance.OUT_VARIANCE) - } - return FunctionInfo(name, receiverType, returnType, possibleContainers, parameters, typeParameters) - } - - object Default : Function() - - object Abstract : Function() { - override fun doCreateCallableInfo( - expression: KtCallExpression, - analysisResult: AnalysisResult, - name: String, - receiverType: TypeInfo, - possibleContainers: List - ) = super.doCreateCallableInfo(expression, analysisResult, name, receiverType, possibleContainers)?.let { - getAbstractCallableInfo(it, expression) - } - } - - object ByImplicitExtensionReceiver : Function() { - override fun doCreateCallableInfo( - expression: KtCallExpression, - analysisResult: AnalysisResult, - name: String, - receiverType: TypeInfo, - possibleContainers: List - ) = super.doCreateCallableInfo(expression, analysisResult, name, receiverType, possibleContainers)?.let { - getCallableWithReceiverInsideExtension(it, expression, analysisResult.bindingContext, receiverType) - } - } - } - - object Constructor: CreateCallableFromCallActionFactory() { - override fun getElementOfInterest(diagnostic: Diagnostic): KtCallExpression? { - return getExpressionOfInterest(diagnostic) as? KtCallExpression - } - - override fun doCreateCallableInfo( - expression: KtCallExpression, - analysisResult: AnalysisResult, - name: String, - receiverType: TypeInfo, - possibleContainers: List - ): CallableInfo? { - if (expression.typeArguments.isNotEmpty()) return null - - val classDescriptor = expression - .calleeExpression - ?.getReferenceTargets(analysisResult.bindingContext) - ?.mapNotNull { (it as? ConstructorDescriptor)?.containingDeclaration } - ?.distinct() - ?.singleOrNull() as? ClassDescriptor - val klass = classDescriptor?.source?.getPsi() - if ((klass !is KtClass && klass !is PsiClass) || !klass.canRefactor()) return null - - val expectedType = analysisResult.bindingContext[BindingContext.EXPECTED_EXPRESSION_TYPE, expression.getQualifiedExpressionForSelectorOrThis()] - ?: classDescriptor.builtIns.nullableAnyType - if (!classDescriptor.defaultType.isSubtypeOf(expectedType)) return null - - val parameters = expression.getParameterInfos() - - return ConstructorInfo(parameters, klass) - } - } - - companion object { - val FUNCTIONS = arrayOf(Function.Default, - Function.Abstract, - Function.ByImplicitExtensionReceiver, - Constructor) - val INSTANCES = arrayOf(Function.Default, - Function.Abstract, - Function.ByImplicitExtensionReceiver, - Constructor, - Property.Default, - Property.Abstract, - Property.ByImplicitExtensionReceiver) - } -} diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateCallableFromUsageFix.kt.172 b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateCallableFromUsageFix.kt.172 deleted file mode 100644 index a5bd55711d7..00000000000 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateCallableFromUsageFix.kt.172 +++ /dev/null @@ -1,216 +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.idea.quickfix.createFromUsage.createCallable - -import com.intellij.codeInsight.intention.LowPriorityAction -import com.intellij.openapi.editor.Editor -import com.intellij.openapi.project.Project -import com.intellij.psi.PsiClass -import com.intellij.psi.PsiElement -import org.jetbrains.kotlin.builtins.functions.FunctionClassDescriptor -import org.jetbrains.kotlin.descriptors.ClassifierDescriptor -import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.CreateFromUsageFixBase -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.* -import org.jetbrains.kotlin.idea.refactoring.canRefactor -import org.jetbrains.kotlin.idea.refactoring.chooseContainerElementIfNecessary -import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers -import org.jetbrains.kotlin.idea.util.application.executeCommand -import org.jetbrains.kotlin.idea.util.isAbstract -import org.jetbrains.kotlin.psi.* -import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext -import java.util.* - -class CreateCallableFromUsageFix( - originalExpression: E, - callableInfos: List -) : CreateCallableFromUsageFixBase(originalExpression, callableInfos, false) - -class CreateExtensionCallableFromUsageFix( - originalExpression: E, - callableInfos: List -) : CreateCallableFromUsageFixBase(originalExpression, callableInfos, true), LowPriorityAction - -abstract class CreateCallableFromUsageFixBase( - originalExpression: E, - private val callableInfos: List, - val isExtension: Boolean -) : CreateFromUsageFixBase(originalExpression) { - init { - assert (callableInfos.isNotEmpty()) { "No CallableInfos: ${originalExpression.getElementTextWithContext()}" } - if (callableInfos.size > 1) { - val receiverSet = callableInfos.mapTo(HashSet()) { it.receiverTypeInfo } - if (receiverSet.size > 1) throw AssertionError("All functions must have common receiver: $receiverSet") - - val possibleContainerSet = callableInfos.mapTo(HashSet>()) { it.possibleContainers } - if (possibleContainerSet.size > 1) throw AssertionError("All functions must have common containers: $possibleContainerSet") - } - } - - private fun getDeclaration(descriptor: ClassifierDescriptor, project: Project): PsiElement? { - if (descriptor is FunctionClassDescriptor) { - val psiFactory = KtPsiFactory(project) - val syntheticClass = psiFactory.createClass(IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.render(descriptor)) - return psiFactory.createAnalyzableFile("${descriptor.name.asString()}.kt", "", element!!).add(syntheticClass) - } - return DescriptorToSourceUtilsIde.getAnyDeclaration(project, descriptor) - } - - private fun getDeclarationIfApplicable(project: Project, candidate: TypeCandidate): PsiElement? { - val descriptor = candidate.theType.constructor.declarationDescriptor ?: return null - val declaration = getDeclaration(descriptor, project) ?: return null - if (declaration !is KtClassOrObject && declaration !is KtTypeParameter && declaration !is PsiClass) return null - return if (isExtension || declaration.canRefactor()) declaration else null - } - - override fun getText(): String { - val element = element ?: return "" - val receiverTypeInfo = callableInfos.first().receiverTypeInfo - val renderedCallables = callableInfos.map { - buildString { - if (it.isAbstract) { - append("abstract ") - } - - val kind = when (it.kind) { - CallableKind.FUNCTION -> "function" - CallableKind.PROPERTY -> "property" - CallableKind.CONSTRUCTOR -> "secondary constructor" - else -> throw AssertionError("Unexpected callable info: $it") - } - append(kind) - - if (it.name.isNotEmpty()) { - append(" '") - - val receiverType = if (!receiverTypeInfo.isOfThis) { - CallableBuilderConfiguration(callableInfos, element, isExtension = isExtension) - .createBuilder() - .computeTypeCandidates(receiverTypeInfo) - .firstOrNull() - ?.theType - } - else null - - if (receiverType != null) { - if (isExtension) { - val receiverTypeText = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(receiverType) - val isFunctionType = receiverType.constructor.declarationDescriptor is FunctionClassDescriptor - append(if (isFunctionType) "($receiverTypeText)" else receiverTypeText).append('.') - } - else { - receiverType.constructor.declarationDescriptor?.let { - append(IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderClassifierName(it)).append('.') - } - } - } - - append("${it.name}'") - } - } - } - - return StringBuilder().apply { - append("Create ") - - val receiverInfo = receiverTypeInfo - if (!callableInfos.any { it.isAbstract }) { - if (isExtension) { - append("extension ") - } - else if (receiverInfo !is TypeInfo.Empty) { - append("member ") - } - } - - renderedCallables.joinTo(this) - }.toString() - } - - override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean { - val element = element ?: return false - - val receiverInfo = callableInfos.first().receiverTypeInfo - - if (receiverInfo is TypeInfo.Empty) { - if (callableInfos.any { it is PropertyInfo && it.possibleContainers.isEmpty() }) return false - return !isExtension - } - // TODO: Remove after companion object extensions are supported - if (isExtension && receiverInfo.staticContextRequired) return false - - val callableBuilder = CallableBuilderConfiguration(callableInfos, element, isExtension = isExtension).createBuilder() - val receiverTypeCandidates = callableBuilder.computeTypeCandidates(callableInfos.first().receiverTypeInfo) - val propertyInfo = callableInfos.firstOrNull { it is PropertyInfo } as PropertyInfo? - val isFunction = callableInfos.any { it.kind == CallableKind.FUNCTION } - return receiverTypeCandidates.any { - val declaration = getDeclarationIfApplicable(project, it) - val insertToJavaInterface = declaration is PsiClass && declaration.isInterface - when { - !isExtension && propertyInfo != null && insertToJavaInterface && (!receiverInfo.staticContextRequired || propertyInfo.writable) -> - false - isFunction && insertToJavaInterface && receiverInfo.staticContextRequired -> - false - !isExtension && declaration is KtTypeParameter -> false - propertyInfo != null && !propertyInfo.isAbstract && declaration is KtClass && declaration.isInterface() -> false - else -> - declaration != null - } - } - } - - override fun invoke(project: Project, editor: Editor?, file: KtFile) { - val element = element ?: return - val callableInfo = callableInfos.first() - - val callableBuilder = - CallableBuilderConfiguration(callableInfos, element as KtElement, file, editor!!, isExtension).createBuilder() - - fun runBuilder(placement: CallablePlacement) { - callableBuilder.placement = placement - project.executeCommand(text) { callableBuilder.build() } - } - - if (callableInfo is ConstructorInfo) { - runBuilder(CallablePlacement.NoReceiver(callableInfo.targetClass)) - return - } - - val popupTitle = "Choose target class or interface" - val receiverTypeCandidates = callableBuilder.computeTypeCandidates(callableInfo.receiverTypeInfo).let { - if (callableInfo.isAbstract) it.filter { it.theType.isAbstract() } else it - } - if (receiverTypeCandidates.isNotEmpty()) { - val containers = receiverTypeCandidates - .mapNotNull { candidate -> getDeclarationIfApplicable(project, candidate)?.let { candidate to it } } - - chooseContainerElementIfNecessary(containers, editor, popupTitle, false, { it.second }) { - runBuilder(CallablePlacement.WithReceiver(it.first)) - } - } - else { - assert(callableInfo.receiverTypeInfo is TypeInfo.Empty) { - "No receiver type candidates: ${element.text} in ${file.text}" - } - - chooseContainerElementIfNecessary(callableInfo.possibleContainers, editor, popupTitle, true, { it }) { - val container = if (it is KtClassBody) it.parent as KtClassOrObject else it - runBuilder(CallablePlacement.NoReceiver(container)) - } - } - } -} diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateCallableMemberFromUsageFactory.kt.172 b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateCallableMemberFromUsageFactory.kt.172 deleted file mode 100644 index 173fbad81eb..00000000000 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateCallableMemberFromUsageFactory.kt.172 +++ /dev/null @@ -1,78 +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.idea.quickfix.createFromUsage.createCallable - -import com.intellij.psi.SmartPsiElementPointer -import org.jetbrains.kotlin.diagnostics.Diagnostic -import org.jetbrains.kotlin.idea.quickfix.IntentionActionPriority -import org.jetbrains.kotlin.idea.quickfix.KotlinIntentionActionFactoryWithDelegate -import org.jetbrains.kotlin.idea.quickfix.QuickFixWithDelegateFactory -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.CreateFromUsageFixBase -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.CallableInfo -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.PropertyInfo -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.createVariable.CreateParameterFromUsageFix -import org.jetbrains.kotlin.psi.KtElement -import java.util.* - -abstract class CreateCallableMemberFromUsageFactory( - private val extensionsSupported: Boolean = true -) : KotlinIntentionActionFactoryWithDelegate>() { - private fun newCallableQuickFix( - originalElementPointer: SmartPsiElementPointer, - priority: IntentionActionPriority, - quickFixDataFactory: () -> List?, - quickFixFactory: (E, List) -> CreateFromUsageFixBase? - ): QuickFixWithDelegateFactory { - return QuickFixWithDelegateFactory(priority) { - val data = quickFixDataFactory().orEmpty() - val originalElement = originalElementPointer.element - if (data.isNotEmpty() && originalElement != null) quickFixFactory(originalElement, data) else null - } - } - - protected open fun createCallableInfo(element: E, diagnostic: Diagnostic): CallableInfo? = null - - override fun extractFixData(element: E, diagnostic: Diagnostic): List - = listOfNotNull(createCallableInfo(element, diagnostic)) - - override fun createFixes( - originalElementPointer: SmartPsiElementPointer, - diagnostic: Diagnostic, - quickFixDataFactory: () -> List? - ): List { - val fixes = ArrayList(3) - - newCallableQuickFix(originalElementPointer, IntentionActionPriority.NORMAL, quickFixDataFactory) { element, data -> - CreateCallableFromUsageFix(element, data) - }.let { fixes.add(it) } - - newCallableQuickFix(originalElementPointer, IntentionActionPriority.NORMAL, quickFixDataFactory) f@ { element, data -> - (data.singleOrNull() as? PropertyInfo)?.let { - CreateParameterFromUsageFix.createFixForPrimaryConstructorPropertyParameter(element, it) - } - }.let { fixes.add(it) } - - if (extensionsSupported) { - newCallableQuickFix(originalElementPointer, IntentionActionPriority.LOW, quickFixDataFactory) { element, data -> - if (data.any { it.isAbstract }) return@newCallableQuickFix null - CreateExtensionCallableFromUsageFix(element, data) - }.let { fixes.add(it) } - } - - return fixes - } -} \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateComponentFunctionActionFactory.kt.172 b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateComponentFunctionActionFactory.kt.172 deleted file mode 100644 index a70222f7991..00000000000 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateComponentFunctionActionFactory.kt.172 +++ /dev/null @@ -1,57 +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.idea.quickfix.createFromUsage.createCallable - -import org.jetbrains.kotlin.descriptors.ClassDescriptor -import org.jetbrains.kotlin.diagnostics.Diagnostic -import org.jetbrains.kotlin.diagnostics.Errors -import org.jetbrains.kotlin.idea.core.quickfix.QuickFixUtil -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.CallableInfo -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.FunctionInfo -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo -import org.jetbrains.kotlin.psi.KtDestructuringDeclaration -import org.jetbrains.kotlin.psi.KtForExpression -import org.jetbrains.kotlin.resolve.DataClassDescriptorResolver -import org.jetbrains.kotlin.types.Variance - -object CreateComponentFunctionActionFactory : CreateCallableMemberFromUsageFactory() { - override fun getElementOfInterest(diagnostic: Diagnostic): KtDestructuringDeclaration? { - QuickFixUtil.getParentElementOfType(diagnostic, KtDestructuringDeclaration::class.java)?.let { return it } - return QuickFixUtil.getParentElementOfType(diagnostic, KtForExpression::class.java)?.destructuringDeclaration - } - - override fun createCallableInfo(element: KtDestructuringDeclaration, diagnostic: Diagnostic): CallableInfo? { - val diagnosticWithParameters = Errors.COMPONENT_FUNCTION_MISSING.cast(diagnostic) - - val name = diagnosticWithParameters.a - if (!DataClassDescriptorResolver.isComponentLike(name)) return null - - val componentNumber = DataClassDescriptorResolver.getComponentIndex(name.asString()) - 1 - - val targetType = diagnosticWithParameters.b - val targetClassDescriptor = targetType.constructor.declarationDescriptor as? ClassDescriptor - if (targetClassDescriptor != null && targetClassDescriptor.isData) return null - - val ownerTypeInfo = TypeInfo(targetType, Variance.IN_VARIANCE) - val entries = element.entries - - val entry = entries[componentNumber] - val returnTypeInfo = TypeInfo(entry, Variance.OUT_VARIANCE) - - return FunctionInfo(name.identifier, ownerTypeInfo, returnTypeInfo, isOperator = true) - } -} diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateGetFunctionActionFactory.kt.172 b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateGetFunctionActionFactory.kt.172 deleted file mode 100644 index e3d66dd7d1b..00000000000 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateGetFunctionActionFactory.kt.172 +++ /dev/null @@ -1,40 +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.idea.quickfix.createFromUsage.createCallable - -import org.jetbrains.kotlin.diagnostics.Diagnostic -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.CallableInfo -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.FunctionInfo -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.ParameterInfo -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo -import org.jetbrains.kotlin.psi.KtArrayAccessExpression -import org.jetbrains.kotlin.types.Variance -import org.jetbrains.kotlin.util.OperatorNameConventions -import java.util.* - -object CreateGetFunctionActionFactory : CreateGetSetFunctionActionFactory(isGet = true) { - override fun createCallableInfo(element: KtArrayAccessExpression, diagnostic: Diagnostic): CallableInfo? { - val arrayExpr = element.arrayExpression ?: return null - - val arrayType = TypeInfo(arrayExpr, Variance.IN_VARIANCE) - val parameters = element.indexExpressions.map { ParameterInfo(TypeInfo(it, Variance.IN_VARIANCE)) } - val returnType = TypeInfo(element, Variance.OUT_VARIANCE) - return FunctionInfo( - OperatorNameConventions.GET.asString(), arrayType, returnType, Collections.emptyList(), parameters, isOperator = true - ) - } -} diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateHasNextFunctionActionFactory.kt.172 b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateHasNextFunctionActionFactory.kt.172 deleted file mode 100644 index 29b7392bb7a..00000000000 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateHasNextFunctionActionFactory.kt.172 +++ /dev/null @@ -1,43 +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.idea.quickfix.createFromUsage.createCallable - -import org.jetbrains.kotlin.diagnostics.Diagnostic -import org.jetbrains.kotlin.diagnostics.DiagnosticFactory -import org.jetbrains.kotlin.diagnostics.Errors -import org.jetbrains.kotlin.idea.core.quickfix.QuickFixUtil -import org.jetbrains.kotlin.idea.project.builtIns -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.CallableInfo -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.FunctionInfo -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo -import org.jetbrains.kotlin.psi.KtForExpression -import org.jetbrains.kotlin.types.Variance -import org.jetbrains.kotlin.util.OperatorNameConventions - -object CreateHasNextFunctionActionFactory : CreateCallableMemberFromUsageFactory() { - override fun getElementOfInterest(diagnostic: Diagnostic): KtForExpression? { - return QuickFixUtil.getParentElementOfType(diagnostic, KtForExpression::class.java) - } - - override fun createCallableInfo(element: KtForExpression, diagnostic: Diagnostic): CallableInfo? { - val diagnosticWithParameters = - DiagnosticFactory.cast(diagnostic, Errors.HAS_NEXT_MISSING, Errors.HAS_NEXT_FUNCTION_NONE_APPLICABLE) - val ownerType = TypeInfo(diagnosticWithParameters.a, Variance.IN_VARIANCE) - val returnType = TypeInfo(element.builtIns.booleanType, Variance.OUT_VARIANCE) - return FunctionInfo(OperatorNameConventions.HAS_NEXT.asString(), ownerType, returnType, isOperator = true) - } -} diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateInvokeFunctionActionFactory.kt.172 b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateInvokeFunctionActionFactory.kt.172 deleted file mode 100644 index 561534f2e19..00000000000 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateInvokeFunctionActionFactory.kt.172 +++ /dev/null @@ -1,53 +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.idea.quickfix.createFromUsage.createCallable - -import org.jetbrains.kotlin.diagnostics.Diagnostic -import org.jetbrains.kotlin.diagnostics.Errors -import org.jetbrains.kotlin.idea.project.builtIns -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.CallableInfo -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.FunctionInfo -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.ParameterInfo -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo -import org.jetbrains.kotlin.psi.KtCallExpression -import org.jetbrains.kotlin.types.Variance -import org.jetbrains.kotlin.types.isError -import org.jetbrains.kotlin.util.OperatorNameConventions - -object CreateInvokeFunctionActionFactory : CreateCallableMemberFromUsageFactory() { - override fun getElementOfInterest(diagnostic: Diagnostic): KtCallExpression? { - return diagnostic.psiElement.parent as? KtCallExpression - } - - override fun createCallableInfo(element: KtCallExpression, diagnostic: Diagnostic): CallableInfo? { - val expectedType = Errors.FUNCTION_EXPECTED.cast(diagnostic).b - if (expectedType.isError) return null - - val receiverType = TypeInfo(expectedType, Variance.IN_VARIANCE) - - val anyType = element.builtIns.nullableAnyType - val parameters = element.valueArguments.map { - ParameterInfo( - it.getArgumentExpression()?.let { TypeInfo(it, Variance.IN_VARIANCE) } ?: TypeInfo(anyType, Variance.IN_VARIANCE), - it.getArgumentName()?.referenceExpression?.getReferencedName() - ) - } - - val returnType = TypeInfo(element, Variance.OUT_VARIANCE) - return FunctionInfo(OperatorNameConventions.INVOKE.asString(), receiverType, returnType, parameterInfos = parameters, isOperator = true) - } -} diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateIteratorFunctionActionFactory.kt.172 b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateIteratorFunctionActionFactory.kt.172 deleted file mode 100644 index 63ef070a873..00000000000 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateIteratorFunctionActionFactory.kt.172 +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createCallable - -import org.jetbrains.kotlin.diagnostics.Diagnostic -import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithAllCompilerChecks -import org.jetbrains.kotlin.idea.core.quickfix.QuickFixUtil -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.CallableInfo -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.FunctionInfo -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.guessTypes -import org.jetbrains.kotlin.psi.KtExpression -import org.jetbrains.kotlin.psi.KtFile -import org.jetbrains.kotlin.psi.KtForExpression -import org.jetbrains.kotlin.types.KotlinTypeFactory -import org.jetbrains.kotlin.types.TypeProjectionImpl -import org.jetbrains.kotlin.types.Variance -import org.jetbrains.kotlin.util.OperatorNameConventions -import java.util.* - -object CreateIteratorFunctionActionFactory : CreateCallableMemberFromUsageFactory() { - override fun getElementOfInterest(diagnostic: Diagnostic): KtForExpression? { - return QuickFixUtil.getParentElementOfType(diagnostic, KtForExpression::class.java) - } - - override fun createCallableInfo(element: KtForExpression, diagnostic: Diagnostic): CallableInfo? { - val file = diagnostic.psiFile as? KtFile ?: return null - val iterableExpr = element.loopRange ?: return null - val variableExpr: KtExpression = ((element.loopParameter ?: element.destructuringDeclaration) ?: return null) as KtExpression - val iterableType = TypeInfo(iterableExpr, Variance.IN_VARIANCE) - - val (bindingContext, moduleDescriptor) = file.analyzeWithAllCompilerChecks() - - val returnJetType = moduleDescriptor.builtIns.iterator.defaultType - val returnJetTypeParameterTypes = variableExpr.guessTypes(bindingContext, moduleDescriptor) - if (returnJetTypeParameterTypes.size != 1) return null - - val returnJetTypeParameterType = TypeProjectionImpl(returnJetTypeParameterTypes[0]) - val returnJetTypeArguments = Collections.singletonList(returnJetTypeParameterType) - val newReturnJetType = KotlinTypeFactory.simpleTypeWithNonTrivialMemberScope(returnJetType.annotations, - returnJetType.constructor, - returnJetTypeArguments, - returnJetType.isMarkedNullable, - returnJetType.memberScope) - val returnType = TypeInfo(newReturnJetType, Variance.OUT_VARIANCE) - return FunctionInfo(OperatorNameConventions.ITERATOR.asString(), iterableType, returnType, isOperator = true) - } -} diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateNextFunctionActionFactory.kt.172 b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateNextFunctionActionFactory.kt.172 deleted file mode 100644 index 25f8ad6447a..00000000000 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateNextFunctionActionFactory.kt.172 +++ /dev/null @@ -1,44 +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.idea.quickfix.createFromUsage.createCallable - -import org.jetbrains.kotlin.diagnostics.Diagnostic -import org.jetbrains.kotlin.diagnostics.DiagnosticFactory -import org.jetbrains.kotlin.diagnostics.Errors -import org.jetbrains.kotlin.idea.core.quickfix.QuickFixUtil -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.CallableInfo -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.FunctionInfo -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo -import org.jetbrains.kotlin.psi.KtExpression -import org.jetbrains.kotlin.psi.KtForExpression -import org.jetbrains.kotlin.types.Variance -import org.jetbrains.kotlin.util.OperatorNameConventions - -object CreateNextFunctionActionFactory : CreateCallableMemberFromUsageFactory() { - override fun getElementOfInterest(diagnostic: Diagnostic): KtForExpression? { - return QuickFixUtil.getParentElementOfType(diagnostic, KtForExpression::class.java) - } - - override fun createCallableInfo(element: KtForExpression, diagnostic: Diagnostic): CallableInfo? { - val diagnosticWithParameters = DiagnosticFactory.cast(diagnostic, Errors.NEXT_MISSING, Errors.NEXT_NONE_APPLICABLE) - val ownerType = TypeInfo(diagnosticWithParameters.a, Variance.IN_VARIANCE) - - val variableExpr = element.loopParameter ?: element.destructuringDeclaration ?: return null - val returnType = TypeInfo(variableExpr as KtExpression, Variance.OUT_VARIANCE) - return FunctionInfo(OperatorNameConventions.NEXT.asString(), ownerType, returnType, isOperator = true) - } -} diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreatePropertyDelegateAccessorsActionFactory.kt.172 b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreatePropertyDelegateAccessorsActionFactory.kt.172 deleted file mode 100644 index 9107e5ba371..00000000000 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreatePropertyDelegateAccessorsActionFactory.kt.172 +++ /dev/null @@ -1,97 +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.idea.quickfix.createFromUsage.createCallable - -import com.intellij.util.SmartList -import org.jetbrains.kotlin.builtins.ReflectionTypes -import org.jetbrains.kotlin.config.LanguageFeature -import org.jetbrains.kotlin.descriptors.VariableAccessorDescriptor -import org.jetbrains.kotlin.descriptors.VariableDescriptorWithAccessors -import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor -import org.jetbrains.kotlin.diagnostics.Diagnostic -import org.jetbrains.kotlin.idea.caches.resolve.analyze -import org.jetbrains.kotlin.idea.project.languageVersionSettings -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.CallableInfo -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.FunctionInfo -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.ParameterInfo -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo -import org.jetbrains.kotlin.psi.KtExpression -import org.jetbrains.kotlin.psi.KtProperty -import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType -import org.jetbrains.kotlin.resolve.BindingContext -import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns -import org.jetbrains.kotlin.resolve.descriptorUtil.module -import org.jetbrains.kotlin.types.Variance -import org.jetbrains.kotlin.util.OperatorNameConventions - -object CreatePropertyDelegateAccessorsActionFactory : CreateCallableMemberFromUsageFactory() { - override fun getElementOfInterest(diagnostic: Diagnostic): KtExpression? { - return diagnostic.psiElement as? KtExpression - } - - override fun extractFixData(element: KtExpression, diagnostic: Diagnostic): List { - val context = element.analyze() - - fun isApplicableForAccessor(accessor: VariableAccessorDescriptor?): Boolean = - accessor != null && context[BindingContext.DELEGATED_PROPERTY_RESOLVED_CALL, accessor] == null - - val property = element.getNonStrictParentOfType() ?: return emptyList() - val propertyDescriptor = context[BindingContext.DECLARATION_TO_DESCRIPTOR, property] as? VariableDescriptorWithAccessors - ?: return emptyList() - - if (propertyDescriptor is LocalVariableDescriptor - && !element.languageVersionSettings.supportsFeature(LanguageFeature.LocalDelegatedProperties)) { - return emptyList() - } - - val propertyReceiver = propertyDescriptor.extensionReceiverParameter ?: propertyDescriptor.dispatchReceiverParameter - val propertyType = propertyDescriptor.type - - val accessorReceiverType = TypeInfo(element, Variance.IN_VARIANCE) - val builtIns = propertyDescriptor.builtIns - val thisRefParam = ParameterInfo(TypeInfo(propertyReceiver?.type ?: builtIns.nullableNothingType, Variance.IN_VARIANCE)) - val kPropertyStarType = ReflectionTypes.createKPropertyStarType(propertyDescriptor.module) ?: return emptyList() - val metadataParam = ParameterInfo(TypeInfo(kPropertyStarType, Variance.IN_VARIANCE), "property") - - val callableInfos = SmartList() - - if (isApplicableForAccessor(propertyDescriptor.getter)) { - val getterInfo = FunctionInfo( - name = OperatorNameConventions.GET_VALUE.asString(), - receiverTypeInfo = accessorReceiverType, - returnTypeInfo = TypeInfo(propertyType, Variance.OUT_VARIANCE), - parameterInfos = listOf(thisRefParam, metadataParam), - isOperator = true - ) - callableInfos.add(getterInfo) - } - - if (propertyDescriptor.isVar && isApplicableForAccessor(propertyDescriptor.setter)) { - val newValueParam = ParameterInfo(TypeInfo(propertyType, Variance.IN_VARIANCE)) - val setterInfo = FunctionInfo( - name = OperatorNameConventions.SET_VALUE.asString(), - receiverTypeInfo = accessorReceiverType, - returnTypeInfo = TypeInfo(builtIns.unitType, Variance.OUT_VARIANCE), - parameterInfos = listOf(thisRefParam, metadataParam, newValueParam), - isOperator = true - ) - callableInfos.add(setterInfo) - } - - return callableInfos - } -} diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateSetFunctionActionFactory.kt.172 b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateSetFunctionActionFactory.kt.172 deleted file mode 100644 index fdb05288c50..00000000000 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateSetFunctionActionFactory.kt.172 +++ /dev/null @@ -1,64 +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.idea.quickfix.createFromUsage.createCallable - -import org.jetbrains.kotlin.diagnostics.Diagnostic -import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall -import org.jetbrains.kotlin.idea.core.quickfix.QuickFixUtil -import org.jetbrains.kotlin.idea.project.builtIns -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.CallableInfo -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.FunctionInfo -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.ParameterInfo -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo -import org.jetbrains.kotlin.psi.* -import org.jetbrains.kotlin.types.ErrorUtils -import org.jetbrains.kotlin.types.Variance -import org.jetbrains.kotlin.types.expressions.OperatorConventions -import org.jetbrains.kotlin.util.OperatorNameConventions -import java.util.* - -object CreateSetFunctionActionFactory : CreateGetSetFunctionActionFactory(isGet = false) { - override fun createCallableInfo(element: KtArrayAccessExpression, diagnostic: Diagnostic): CallableInfo? { - val arrayExpr = element.arrayExpression ?: return null - val arrayType = TypeInfo(arrayExpr, Variance.IN_VARIANCE) - - val builtIns = element.builtIns - - val parameters = element.indexExpressions.mapTo(ArrayList()) { - ParameterInfo(TypeInfo(it, Variance.IN_VARIANCE)) - } - val assignmentExpr = QuickFixUtil.getParentElementOfType(diagnostic, KtOperationExpression::class.java) ?: return null - val valType = when (assignmentExpr) { - is KtBinaryExpression -> { - TypeInfo(assignmentExpr.right ?: return null, Variance.IN_VARIANCE) - } - is KtUnaryExpression -> { - if (assignmentExpr.operationToken !in OperatorConventions.INCREMENT_OPERATIONS) return null - - val rhsType = assignmentExpr.resolveToCall()?.resultingDescriptor?.returnType - TypeInfo(if (rhsType == null || ErrorUtils.containsErrorType(rhsType)) builtIns.anyType else rhsType, Variance.IN_VARIANCE) - } - else -> return null - } - parameters.add(ParameterInfo(valType, "value")) - - val returnType = TypeInfo(builtIns.unitType, Variance.OUT_VARIANCE) - return FunctionInfo( - OperatorNameConventions.SET.asString(), arrayType, returnType, Collections.emptyList(), parameters, isOperator = true - ) - } -} diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateUnaryOperationActionFactory.kt.172 b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateUnaryOperationActionFactory.kt.172 deleted file mode 100644 index cdee9f26e66..00000000000 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateUnaryOperationActionFactory.kt.172 +++ /dev/null @@ -1,44 +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.idea.quickfix.createFromUsage.createCallable - -import org.jetbrains.kotlin.diagnostics.Diagnostic -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.CallableInfo -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.FunctionInfo -import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo -import org.jetbrains.kotlin.lexer.KtToken -import org.jetbrains.kotlin.psi.KtUnaryExpression -import org.jetbrains.kotlin.types.Variance -import org.jetbrains.kotlin.types.expressions.OperatorConventions - -object CreateUnaryOperationActionFactory: CreateCallableMemberFromUsageFactory() { - override fun getElementOfInterest(diagnostic: Diagnostic): KtUnaryExpression? { - return diagnostic.psiElement.parent as? KtUnaryExpression - } - - override fun createCallableInfo(element: KtUnaryExpression, diagnostic: Diagnostic): CallableInfo? { - val token = element.operationToken as KtToken - val operationName = OperatorConventions.getNameForOperationSymbol(token, true, false) ?: return null - val incDec = token in OperatorConventions.INCREMENT_OPERATIONS - - val receiverExpr = element.baseExpression ?: return null - - val receiverType = TypeInfo(receiverExpr, Variance.IN_VARIANCE) - val returnType = if (incDec) TypeInfo.ByReceiverType(Variance.OUT_VARIANCE) else TypeInfo(element, Variance.OUT_VARIANCE) - return FunctionInfo(operationName.asString(), receiverType, returnType, isOperator = true) - } -} diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/crossLanguage/KotlinElementActionsFactory.kt.172 b/idea/src/org/jetbrains/kotlin/idea/quickfix/crossLanguage/KotlinElementActionsFactory.kt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/MoveKotlinDeclarationsHandler.kt.172 b/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/MoveKotlinDeclarationsHandler.kt.172 deleted file mode 100644 index 032ec4b8414..00000000000 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/MoveKotlinDeclarationsHandler.kt.172 +++ /dev/null @@ -1,212 +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.idea.refactoring.move.moveDeclarations - -import com.intellij.openapi.actionSystem.DataContext -import com.intellij.openapi.actionSystem.LangDataKeys -import com.intellij.openapi.editor.Editor -import com.intellij.openapi.project.Project -import com.intellij.psi.PsiDirectory -import com.intellij.psi.PsiElement -import com.intellij.psi.PsiPackage -import com.intellij.psi.PsiReference -import com.intellij.refactoring.JavaRefactoringSettings -import com.intellij.refactoring.RefactoringBundle -import com.intellij.refactoring.move.MoveCallback -import com.intellij.refactoring.move.MoveHandlerDelegate -import com.intellij.refactoring.move.moveClassesOrPackages.MoveClassesOrPackagesImpl -import com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesUtil -import com.intellij.refactoring.util.CommonRefactoringUtil -import org.jetbrains.kotlin.asJava.unwrapped -import org.jetbrains.kotlin.idea.core.getPackage -import org.jetbrains.kotlin.idea.refactoring.canRefactor -import org.jetbrains.kotlin.idea.refactoring.move.invokeMoveFilesOrDirectoriesRefactoring -import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.ui.KotlinAwareMoveFilesOrDirectoriesDialog -import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.ui.KotlinSelectNestedClassRefactoringDialog -import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.ui.MoveKotlinNestedClassesDialog -import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.ui.MoveKotlinTopLevelDeclarationsDialog -import org.jetbrains.kotlin.lexer.KtTokens -import org.jetbrains.kotlin.psi.* -import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject -import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext -import org.jetbrains.kotlin.psi.psiUtil.isTopLevelInFileOrScript -import java.util.* - -class MoveKotlinDeclarationsHandler : MoveHandlerDelegate() { - private fun getUniqueContainer(elements: Array): PsiElement? { - val getContainer: (PsiElement) -> PsiElement? = - if (elements.any { !isTopLevelInFileOrScript(it) }) { e -> - when (e) { - is KtNamedDeclaration -> e.containingClassOrObject ?: e.parent - is KtFile -> e.parent - else -> null - } - } - else { e -> - e.containingFile?.parent - } - return elements.mapNotNullTo(LinkedHashSet(), getContainer).singleOrNull() - } - - private fun KtNamedDeclaration.canMove() = if (this is KtClassOrObject) !isLocal else parent is KtFile - - private fun doMoveWithCheck( - project: Project, elements: Array, targetContainer: PsiElement?, callback: MoveCallback?, editor: Editor? - ): Boolean { - if (!CommonRefactoringUtil.checkReadOnlyStatusRecursively(project, elements.toList(), true)) return false - - val container = getUniqueContainer(elements) - if (container == null) { - CommonRefactoringUtil.showErrorHint( - project, editor, "All declarations must belong to the same directory or class", MOVE_DECLARATIONS, null - ) - return false - } - - val elementsToSearch = elements.flatMapTo(LinkedHashSet()) { - when (it) { - is KtNamedDeclaration -> listOf(it) - is KtFile -> it.declarations.filterIsInstance() - else -> emptyList() - } - } - - // todo: allow moving companion object - if (elementsToSearch.any { it is KtObjectDeclaration && it.isCompanion() }) { - val message = RefactoringBundle.getCannotRefactorMessage("Move declaration is not supported for companion objects") - CommonRefactoringUtil.showErrorHint(project, editor, message, MOVE_DECLARATIONS, null) - return true - } - - if (elementsToSearch.any { !it.canMove() }) { - val message = RefactoringBundle.getCannotRefactorMessage("Move declaration is only supported for top-level declarations and nested classes") - CommonRefactoringUtil.showErrorHint(project, editor, message, MOVE_DECLARATIONS, null) - return true - } - - if (elementsToSearch.any { it is KtEnumEntry }) { - val message = RefactoringBundle.getCannotRefactorMessage("Move declaration is not supported for enum entries") - CommonRefactoringUtil.showErrorHint(project, editor, message, MOVE_DECLARATIONS, null) - return true - } - - if (elements.all { it is KtFile }) { - val initialTargetElement = when { - targetContainer is PsiPackage || targetContainer is PsiDirectory -> targetContainer - container is PsiPackage || container is PsiDirectory -> container - else -> null - } - val initialTargetDirectory = MoveFilesOrDirectoriesUtil.resolveToDirectory(project, initialTargetElement) - val dialog = KotlinAwareMoveFilesOrDirectoriesDialog(project) { - invokeMoveFilesOrDirectoriesRefactoring(it, project, elements, initialTargetDirectory, callback) - } - dialog.setData(elements, initialTargetDirectory, "refactoring.moveFile") - dialog.show() - - return true - } - - when (container) { - is PsiDirectory, is PsiPackage, is KtFile -> { - val targetPackageName = MoveClassesOrPackagesImpl.getInitialTargetPackageName(targetContainer, elements) - val targetDirectory = if (targetContainer != null) { - MoveClassesOrPackagesImpl.getInitialTargetDirectory(targetContainer, elements) - } - else null - val searchInComments = JavaRefactoringSettings.getInstance()!!.MOVE_SEARCH_IN_COMMENTS - val searchInText = JavaRefactoringSettings.getInstance()!!.MOVE_SEARCH_FOR_TEXT - val targetFile = targetContainer as? KtFile - val moveToPackage = targetContainer !is KtFile - - MoveKotlinTopLevelDeclarationsDialog( - project, elementsToSearch, targetPackageName, targetDirectory, targetFile, moveToPackage, searchInComments, searchInText, callback - ).show() - } - - is KtClassOrObject -> { - if (elementsToSearch.size > 1) { - // todo: allow moving multiple classes to upper level - if (targetContainer !is KtClassOrObject) { - val message = RefactoringBundle.getCannotRefactorMessage("Moving multiple nested classes to top-level is not supported") - CommonRefactoringUtil.showErrorHint(project, editor, message, MOVE_DECLARATIONS, null) - return true - } - @Suppress("UNCHECKED_CAST") - MoveKotlinNestedClassesDialog(project, - elementsToSearch.filterIsInstance(), - container, - targetContainer, - callback).show() - return true - } - KotlinSelectNestedClassRefactoringDialog.chooseNestedClassRefactoring(elementsToSearch.first() as KtClassOrObject, - targetContainer) - } - - else -> throw AssertionError("Unexpected container: ${container.getElementTextWithContext()}") - } - - return true - } - - private fun canMove(elements: Array, targetContainer: PsiElement?, editorMode: Boolean): Boolean { - if (!super.canMove(elements, targetContainer)) return false - val container = getUniqueContainer(elements) ?: return false - - if (container is KtClassOrObject && targetContainer != null && targetContainer !is KtClassOrObject && elements.size > 1) { - return false - } - - return elements.all { e -> - when { - e is KtClass || e is KtObjectDeclaration && !e.isObjectLiteral() || e is KtNamedFunction || e is KtProperty || e is KtTypeAlias -> - (editorMode || (e as KtNamedDeclaration).canMove()) && e.canRefactor() - e is KtFile -> - e.declarations.any { it is KtNamedDeclaration } && e.canRefactor() - else -> - false - } - } - } - - override fun canMove(elements: Array, targetContainer: PsiElement?): Boolean { - return canMove(elements, targetContainer, false) - } - - override fun isValidTarget(psiElement: PsiElement?, sources: Array): Boolean { - return psiElement is PsiPackage - || (psiElement is PsiDirectory && psiElement.getPackage() != null) - || psiElement is KtFile - || (psiElement is KtClassOrObject - && !(psiElement.hasModifier(KtTokens.ANNOTATION_KEYWORD)) - && !sources.any { it.parent is KtFile }) - } - - override fun doMove(project: Project, elements: Array, targetContainer: PsiElement?, callback: MoveCallback?) { - doMoveWithCheck(project, elements, targetContainer, callback, null) - } - - override fun tryToMove( - element: PsiElement, project: Project, dataContext: DataContext?, reference: PsiReference?, editor: Editor? - ): Boolean { - val elementsToMove = element.unwrapped?.let { arrayOf(it) } ?: PsiElement.EMPTY_ARRAY - val targetContainer = dataContext?.let { dataContext -> LangDataKeys.TARGET_PSI_ELEMENT.getData(dataContext) } - return canMove(elementsToMove, targetContainer, true) && doMoveWithCheck(project, elementsToMove, targetContainer, null, editor) - } -} - -private val MOVE_DECLARATIONS = "Move Declarations" \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/KotlinAwareJavaGetterRenameProcessor.kt.172 b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/KotlinAwareJavaGetterRenameProcessor.kt.172 deleted file mode 100644 index 07df6e840a8..00000000000 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/KotlinAwareJavaGetterRenameProcessor.kt.172 +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2000-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.refactoring.rename - -import com.intellij.psi.PsiElement -import com.intellij.psi.PsiMethod -import com.intellij.psi.PsiReference -import com.intellij.psi.PsiType -import com.intellij.refactoring.rename.RenameJavaMethodProcessor -import org.jetbrains.kotlin.asJava.elements.KtLightMethod -import org.jetbrains.kotlin.idea.references.SyntheticPropertyAccessorReference -import org.jetbrains.kotlin.load.java.JvmAbi -import org.jetbrains.kotlin.name.Name -import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor -import org.jetbrains.kotlin.utils.ifEmpty - -class KotlinAwareJavaGetterRenameProcessor : RenameJavaMethodProcessor() { - override fun canProcessElement(element: PsiElement) = element is PsiMethod && element !is KtLightMethod && JvmAbi.isGetterName(element.name) - - override fun findReferences(element: PsiElement): MutableCollection { - val getterReferences = super.findReferences(element) - val getter = element as? PsiMethod ?: return getterReferences - val propertyName = SyntheticJavaPropertyDescriptor.propertyNameByGetMethodName(Name.identifier(getter.name)) ?: return getterReferences - val setterName = JvmAbi.setterName(propertyName.asString()) - val containingClass = getter.containingClass ?: return getterReferences - val setterReferences = containingClass - .findMethodsByName(setterName, true) - .filter { it.parameterList.parameters.size == 1 && it.returnType == PsiType.VOID } - .flatMap { super.findReferences(it).filterIsInstance() } - .ifEmpty { return getterReferences } - return ArrayList(getterReferences.size + setterReferences.size).apply { - addAll(getterReferences) - setterReferences.mapTo(this) { SyntheticPropertyAccessorReference.Getter(it.expression) } - } - } -} \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/KotlinSafeDeleteProcessor.kt.172 b/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/KotlinSafeDeleteProcessor.kt.172 deleted file mode 100644 index 93531ba2732..00000000000 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/KotlinSafeDeleteProcessor.kt.172 +++ /dev/null @@ -1,486 +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.idea.refactoring.safeDelete - -import com.intellij.openapi.application.ApplicationManager -import com.intellij.openapi.module.Module -import com.intellij.openapi.project.Project -import com.intellij.openapi.ui.Messages -import com.intellij.openapi.util.Condition -import com.intellij.openapi.util.Conditions -import com.intellij.openapi.util.Key -import com.intellij.psi.* -import com.intellij.psi.search.searches.ReferencesSearch -import com.intellij.refactoring.RefactoringBundle -import com.intellij.refactoring.safeDelete.JavaSafeDeleteProcessor -import com.intellij.refactoring.safeDelete.NonCodeUsageSearchInfo -import com.intellij.refactoring.safeDelete.usageInfo.SafeDeleteOverrideAnnotation -import com.intellij.refactoring.safeDelete.usageInfo.SafeDeleteOverridingMethodUsageInfo -import com.intellij.refactoring.safeDelete.usageInfo.SafeDeleteReferenceJavaDeleteUsageInfo -import com.intellij.refactoring.safeDelete.usageInfo.SafeDeleteReferenceSimpleDeleteUsageInfo -import com.intellij.usageView.UsageInfo -import org.jetbrains.annotations.TestOnly -import org.jetbrains.kotlin.asJava.* -import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor -import org.jetbrains.kotlin.descriptors.Modality -import org.jetbrains.kotlin.idea.KotlinBundle -import org.jetbrains.kotlin.idea.caches.resolve.analyze -import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall -import org.jetbrains.kotlin.idea.core.deleteElementAndCleanParent -import org.jetbrains.kotlin.idea.refactoring.checkSuperMethods -import org.jetbrains.kotlin.idea.refactoring.formatClass -import org.jetbrains.kotlin.idea.refactoring.formatFunction -import org.jetbrains.kotlin.idea.refactoring.withExpectedActuals -import org.jetbrains.kotlin.idea.refactoring.isTrueJavaMethod -import org.jetbrains.kotlin.idea.references.KtReference -import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchOptions -import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchParameters -import org.jetbrains.kotlin.idea.search.projectScope -import org.jetbrains.kotlin.idea.search.usagesSearch.processDelegationCallConstructorUsages -import org.jetbrains.kotlin.idea.util.isExpectDeclaration -import org.jetbrains.kotlin.idea.util.liftToExpected -import org.jetbrains.kotlin.idea.util.runOnExpectAndAllActuals -import org.jetbrains.kotlin.lexer.KtTokens -import org.jetbrains.kotlin.psi.* -import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType -import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypeAndBranch -import org.jetbrains.kotlin.psi.psiUtil.hasActualModifier -import org.jetbrains.kotlin.psi.psiUtil.parameterIndex -import org.jetbrains.kotlin.resolve.BindingContext -import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode -import org.jetbrains.kotlin.utils.SmartSet -import org.jetbrains.kotlin.utils.ifEmpty -import java.util.* - -class KotlinSafeDeleteProcessor : JavaSafeDeleteProcessor() { - companion object { - @set:TestOnly - internal var Project.ALLOW_LIFTING_ACTUAL_PARAMETER_TO_EXPECTED - by NotNullableUserDataProperty(Key.create("ALLOW_LIFTING_ACTUAL_PARAMETER_TO_EXPECTED"), true) - - private var KtDeclaration.dropActualModifier: Boolean? by UserDataProperty(Key.create("DROP_ACTUAL_MODIFIER")) - } - - override fun handlesElement(element: PsiElement): Boolean = element.canDeleteElement() - - override fun findUsages( - element: PsiElement, allElementsToDelete: Array, usages: MutableList - ): NonCodeUsageSearchInfo { - val deleteSet = SmartSet.create() - deleteSet.addAll(allElementsToDelete) - - fun getIgnoranceCondition() = Condition { - if (it is KtFile) return@Condition false - deleteSet.any { element -> JavaSafeDeleteProcessor.isInside(it, element.unwrapped) } - } - - fun getSearchInfo(element: PsiElement) = NonCodeUsageSearchInfo(getIgnoranceCondition(), element) - - fun searchKotlinDeclarationReferences(declaration: KtDeclaration): Sequence { - val elementsToSearch = if (declaration is KtParameter) declaration.withExpectedActuals() else listOf(declaration) - return elementsToSearch.asSequence().flatMap { - val searchParameters = KotlinReferencesSearchParameters( - it, - if (it.hasActualModifier()) it.project.projectScope() else it.useScope, - kotlinOptions = KotlinReferencesSearchOptions(acceptCallableOverrides = true) - ) - ReferencesSearch.search(searchParameters) - .asSequence() - .filterNot { reference -> getIgnoranceCondition().value(reference.element) } - } - } - - fun findKotlinParameterUsages(parameter: KtParameter) { - val ownerFunction = parameter.ownerFunction as? KtFunction ?: return - val index = parameter.parameterIndex() - for (reference in searchKotlinDeclarationReferences(ownerFunction)) { - val callee = reference.element as? KtExpression ?: continue - val resolvedCall = callee.resolveToCall(BodyResolveMode.FULL) ?: continue - val parameterDescriptor = resolvedCall.candidateDescriptor.valueParameters.getOrNull(index) ?: continue - val resolvedArgument = resolvedCall.valueArguments[parameterDescriptor] ?: continue - val arguments = resolvedArgument.arguments.filterIsInstance() - if (arguments.isEmpty()) continue - - usages.add(SafeDeleteValueArgumentListUsageInfo(parameter, *arguments.toTypedArray())) - } - } - - fun findKotlinDeclarationUsages(declaration: KtDeclaration): NonCodeUsageSearchInfo { - searchKotlinDeclarationReferences(declaration).mapNotNullTo(usages) { reference -> - val refElement = reference.element ?: return@mapNotNullTo null - refElement.getNonStrictParentOfType()?.let { importDirective -> - SafeDeleteImportDirectiveUsageInfo(importDirective, element) - } ?: SafeDeleteReferenceSimpleDeleteUsageInfo(refElement, declaration, false) - } - - if (declaration is KtParameter) { - findKotlinParameterUsages(declaration) - } - - return getSearchInfo(declaration) - } - - fun asLightElements(ktElements: Array) = - ktElements.flatMap { (it as? KtElement)?.toLightElements() ?: listOf(it) }.toTypedArray() - - fun findUsagesByJavaProcessor(element: PsiElement, forceReferencedElementUnwrapping: Boolean): NonCodeUsageSearchInfo? { - val javaUsages = ArrayList() - val searchInfo = super.findUsages(element, asLightElements(allElementsToDelete), javaUsages) - - javaUsages.filterIsInstance().mapNotNullTo(deleteSet) { it.element } - - val ignoranceCondition = getIgnoranceCondition() - - javaUsages.mapNotNullTo(usages) { usageInfo -> - when (usageInfo) { - is SafeDeleteOverridingMethodUsageInfo -> - usageInfo.smartPointer.element?.let { usageElement -> - KotlinSafeDeleteOverridingUsageInfo(usageElement, usageInfo.referencedElement) - } - - is SafeDeleteOverrideAnnotation -> - usageInfo.smartPointer.element?.let { usageElement -> - when { - usageElement.isTrueJavaMethod() -> usageInfo - usageElement.toLightMethods().all { method -> method.findSuperMethods().isEmpty() } -> { - KotlinSafeDeleteOverrideAnnotation(usageElement, usageInfo.referencedElement) as UsageInfo - } - else -> null - } - } - - is SafeDeleteReferenceJavaDeleteUsageInfo -> - usageInfo.element?.let { usageElement -> - when { - usageElement.getNonStrictParentOfType() != null -> null - ignoranceCondition.value(usageElement) -> null - else -> { - usageElement.getNonStrictParentOfType()?.let { importDirective -> - SafeDeleteImportDirectiveUsageInfo(importDirective, element) - } ?: usageElement.getParentOfTypeAndBranch { typeReference }?.let { - if (element is PsiClass && element.isInterface) SafeDeleteSuperTypeUsageInfo(it, element) else usageInfo - } ?: if (forceReferencedElementUnwrapping) { - SafeDeleteReferenceJavaDeleteUsageInfo(usageElement, element.unwrapped, usageInfo.isSafeDelete) - } else usageInfo - } - } - } - - else -> usageInfo - } - } - - return searchInfo - } - - fun findUsagesByJavaProcessor(elements: Sequence, insideDeleted: Condition): Condition = - elements - .mapNotNull { element -> findUsagesByJavaProcessor(element, true)?.insideDeletedCondition } - .fold(insideDeleted) { condition1, condition2 -> Conditions.or(condition1, condition2) } - - fun findUsagesByJavaProcessor(ktDeclaration: KtDeclaration): NonCodeUsageSearchInfo { - val lightElements = ktDeclaration.toLightElements() - if (lightElements.isEmpty()) { - return findKotlinDeclarationUsages(ktDeclaration) - } - return NonCodeUsageSearchInfo( - findUsagesByJavaProcessor( - lightElements.asSequence(), - getIgnoranceCondition() - ), - ktDeclaration - ) - } - - fun findTypeParameterUsages(parameter: KtTypeParameter) { - val owner = parameter.getNonStrictParentOfType() ?: return - - val parameterList = owner.typeParameters - val parameterIndex = parameterList.indexOf(parameter) - - for (reference in ReferencesSearch.search(owner)) { - if (reference !is KtReference) continue - - val referencedElement = reference.element - - val argList = referencedElement.getNonStrictParentOfType()?.typeArgumentList - ?: referencedElement.getNonStrictParentOfType()?.typeArgumentList - - if (argList != null) { - val projections = argList.arguments - if (parameterIndex < projections.size) { - usages.add(SafeDeleteTypeArgumentListUsageInfo(projections[parameterIndex], parameter)) - } - } - } - } - - fun findDelegationCallUsages(element: PsiElement) { - val constructors = when (element) { - is PsiClass -> element.constructors - is PsiMethod -> arrayOf(element) - else -> return - } - for (constructor in constructors) { - constructor.processDelegationCallConstructorUsages(constructor.useScope) { - if (!getIgnoranceCondition().value(it)) { - usages.add(SafeDeleteReferenceSimpleDeleteUsageInfo(it, element, false)) - } - true - } - } - } - - return when (element) { - is KtClassOrObject -> { - element.toLightClass()?.let { klass -> - findDelegationCallUsages(klass) - findUsagesByJavaProcessor(klass, false) - } ?: findKotlinDeclarationUsages(element) - } - - is KtSecondaryConstructor -> { - if (element.hasActualModifier()) { - findKotlinDeclarationUsages(element) - } else { - element.getRepresentativeLightMethod()?.let { method -> - findDelegationCallUsages(method) - findUsagesByJavaProcessor(method, false) - } ?: findKotlinDeclarationUsages(element) - } - } - - is KtNamedFunction -> { - if (element.isLocal || element.hasActualModifier()) { - findKotlinDeclarationUsages(element) - } - else { - val lightMethods = element.toLightMethods() - if (lightMethods.isNotEmpty()) { - lightMethods.map { method -> findUsagesByJavaProcessor(method, false) }.firstOrNull() - } - else { - findKotlinDeclarationUsages(element) - } - } - } - - is PsiMethod -> { - findUsagesByJavaProcessor(element, false) - } - - is PsiClass -> { - findUsagesByJavaProcessor(element, false) - } - - is KtProperty -> { - if (element.isLocal || element.hasActualModifier()) { - findKotlinDeclarationUsages(element) - } - else { - findUsagesByJavaProcessor(element) - } - } - - is KtTypeParameter -> { - findTypeParameterUsages(element) - findUsagesByJavaProcessor(element) - } - - is KtParameter -> - findUsagesByJavaProcessor(element) - - is KtTypeAlias -> { - findKotlinDeclarationUsages(element) - } - - else -> null - } ?: getSearchInfo(element) - } - - override fun findConflicts(element: PsiElement, allElementsToDelete: Array): MutableCollection? { - if (element is KtNamedFunction || element is KtProperty) { - val jetClass = element.getNonStrictParentOfType() - if (jetClass == null || jetClass.getBody() != element.parent) return null - - val modifierList = jetClass.modifierList - if (modifierList != null && modifierList.hasModifier(KtTokens.ABSTRACT_KEYWORD)) return null - - val bindingContext = (element as KtElement).analyze() - - val declarationDescriptor = - bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, element] as? CallableMemberDescriptor ?: return null - - return declarationDescriptor.overriddenDescriptors - .asSequence() - .filter { overridenDescriptor -> overridenDescriptor.modality == Modality.ABSTRACT } - .mapTo(ArrayList()) { overridenDescriptor -> - KotlinBundle.message( - "x.implements.y", - formatFunction(declarationDescriptor, true), - formatClass(declarationDescriptor.containingDeclaration, true), - formatFunction(overridenDescriptor, true), - formatClass(overridenDescriptor.containingDeclaration, true) - ) - } - } - - return super.findConflicts(element, allElementsToDelete) - } - - /* - * Mostly copied from JavaSafeDeleteProcessor.preprocessUsages - * Revision: d4fc033 - * (replaced original dialog) - */ - override fun preprocessUsages(project: Project, usages: Array): Array? { - val result = ArrayList() - val overridingMethodUsages = ArrayList() - - for (usage in usages) { - if (usage is KotlinSafeDeleteOverridingUsageInfo) { - overridingMethodUsages.add(usage) - } else { - result.add(usage) - } - } - - if (!overridingMethodUsages.isEmpty()) { - if (ApplicationManager.getApplication()!!.isUnitTestMode) { - result.addAll(overridingMethodUsages) - } else { - val dialog = KotlinOverridingDialog(project, overridingMethodUsages) - dialog.show() - - if (!dialog.isOK) return null - - result.addAll(dialog.selected) - } - } - - return result.toTypedArray() - } - - private fun KtDeclaration.removeOrClean() { - when (this) { - is KtParameter -> { - (parent as? KtParameterList)?.removeParameter(this) - } - is KtCallableDeclaration, is KtClassOrObject, is KtTypeAlias -> { - delete() - } - else -> { - removeModifier(KtTokens.IMPL_KEYWORD) - removeModifier(KtTokens.ACTUAL_KEYWORD) - } - } - } - - override fun prepareForDeletion(element: PsiElement) { - if (element is KtDeclaration) { - element.runOnExpectAndAllActuals(checkExpect = false) { it.removeOrClean() } - } - - when (element) { - is PsiMethod -> element.cleanUpOverrides() - - is KtNamedFunction -> - if (!element.isLocal) { - element.getRepresentativeLightMethod()?.cleanUpOverrides() - } - - is KtProperty -> - if (!element.isLocal) { - element.toLightMethods().forEach(PsiMethod::cleanUpOverrides) - } - - is KtTypeParameter -> - element.deleteElementAndCleanParent() - - is KtParameter -> { - element.ownerFunction?.let { - if (it.dropActualModifier == true) { - it.removeModifier(KtTokens.IMPL_KEYWORD) - it.removeModifier(KtTokens.ACTUAL_KEYWORD) - it.dropActualModifier = null - } - } - (element.parent as KtParameterList).removeParameter(element) - } - } - } - - private fun shouldAllowPropagationToExpected(parameter: KtParameter): Boolean { - if (ApplicationManager.getApplication().isUnitTestMode) return parameter.project.ALLOW_LIFTING_ACTUAL_PARAMETER_TO_EXPECTED - - return Messages.showYesNoDialog( - "Do you want to delete this parameter in expected declaration and all related actual ones?", - RefactoringBundle.message("safe.delete.title"), - Messages.getQuestionIcon() - ) == Messages.YES - } - - private fun shouldAllowPropagationToExpected(): Boolean { - if (ApplicationManager.getApplication().isUnitTestMode) return true - - return Messages.showYesNoDialog( - "Do you want to delete expected declaration together with all related actual ones?", - RefactoringBundle.message("safe.delete.title"), - Messages.getQuestionIcon() - ) == Messages.YES - } - - override fun getElementsToSearch( - element: PsiElement, module: Module?, allElementsToDelete: Collection - ): Collection? { - when (element) { - is KtParameter -> { - val expectParameter = element.liftToExpected() - if (expectParameter != null && expectParameter != element) { - if (shouldAllowPropagationToExpected(element)) { - return listOf(expectParameter) - } else { - element.ownerFunction?.dropActualModifier = true - return listOf(element) - } - } - - return element.toPsiParameters().flatMap { psiParameter -> - checkParametersInMethodHierarchy(psiParameter) ?: emptyList() - }.ifEmpty { listOf(element) } - } - - is KtDeclaration -> { - if (element.hasActualModifier() || element.isExpectDeclaration()) { - if (!shouldAllowPropagationToExpected()) { - return null - } - } - } - - is PsiParameter -> - return checkParametersInMethodHierarchy(element) - } - - if (ApplicationManager.getApplication()!!.isUnitTestMode) return Collections.singletonList(element) - - return when (element) { - is KtNamedFunction, is KtProperty -> checkSuperMethods(element as KtDeclaration, allElementsToDelete, "delete (with usage search)") - else -> super.getElementsToSearch(element, module, allElementsToDelete) - } - } -} diff --git a/idea/src/org/jetbrains/kotlin/idea/slicer/KotlinSliceProvider.kt.172 b/idea/src/org/jetbrains/kotlin/idea/slicer/KotlinSliceProvider.kt.172 deleted file mode 100644 index 62289d187ed..00000000000 --- a/idea/src/org/jetbrains/kotlin/idea/slicer/KotlinSliceProvider.kt.172 +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.kotlin.idea.slicer - -import com.intellij.ide.util.treeView.AbstractTreeStructure -import com.intellij.openapi.actionSystem.DefaultActionGroup -import com.intellij.psi.PsiElement -import com.intellij.slicer.* -import org.jetbrains.kotlin.idea.references.mainReference -import org.jetbrains.kotlin.psi.* -import org.jetbrains.kotlin.psi.psiUtil.isPlainWithEscapes -import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf - -class KotlinSliceProvider : SliceLanguageSupportProvider { - override fun createRootUsage(element: PsiElement, params: SliceAnalysisParams) = KotlinSliceUsage(element, params) - - override fun getExpressionAtCaret(atCaret: PsiElement?, dataFlowToThis: Boolean): KtExpression? { - val element = - atCaret?.parentsWithSelf - ?.firstOrNull { - it is KtProperty || - it is KtParameter || - it is KtDeclarationWithBody || - (it is KtClass && !it.hasExplicitPrimaryConstructor()) || - (it is KtExpression && it !is KtDeclaration) - } - ?.let { KtPsiUtil.safeDeparenthesize(it as KtExpression) } ?: return null - if (dataFlowToThis) { - if (element is KtConstantExpression) return null - if (element is KtStringTemplateExpression && element.isPlainWithEscapes()) return null - if (element is KtClassLiteralExpression) return null - if (element is KtCallableReferenceExpression) return null - } - return element - } - - override fun getElementForDescription(element: PsiElement): PsiElement { - return (element as? KtSimpleNameExpression)?.mainReference?.resolve() ?: element - } - - override fun getRenderer() = KotlinSliceUsageCellRenderer - - override fun startAnalyzeLeafValues(structure: AbstractTreeStructure, finalRunnable: Runnable) { - - } - - override fun startAnalyzeNullness(structure: AbstractTreeStructure, finalRunnable: Runnable) { - - } - - override fun registerExtraPanelActions(group: DefaultActionGroup, builder: SliceTreeBuilder) { - - } -} \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/slicer/KotlinSliceUsage.kt.172 b/idea/src/org/jetbrains/kotlin/idea/slicer/KotlinSliceUsage.kt.172 deleted file mode 100644 index 5dc7fd131c5..00000000000 --- a/idea/src/org/jetbrains/kotlin/idea/slicer/KotlinSliceUsage.kt.172 +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.kotlin.idea.slicer - -import com.intellij.psi.PsiElement -import com.intellij.slicer.SliceAnalysisParams -import com.intellij.slicer.SliceUsage -import com.intellij.util.Processor -import org.jetbrains.kotlin.psi.KtExpression - -open class KotlinSliceUsage : SliceUsage { - val lambdaLevel: Int - val forcedExpressionMode: Boolean - - constructor(element: PsiElement, parent: SliceUsage, lambdaLevel: Int, forcedExpressionMode: Boolean) : super(element, parent) { - this.lambdaLevel = lambdaLevel - this.forcedExpressionMode = forcedExpressionMode - } - - constructor(element: PsiElement, params: SliceAnalysisParams) : super(element, params) { - this.lambdaLevel = 0 - this.forcedExpressionMode = false - } - - override fun copy(): KotlinSliceUsage { - val element = usageInfo.element!! - if (parent == null) return KotlinSliceUsage(element, params) - return KotlinSliceUsage(element, parent, lambdaLevel, forcedExpressionMode) - } - - public override fun processUsagesFlownDownTo(element: PsiElement, uniqueProcessor: Processor) { - InflowSlicer(element as? KtExpression ?: return, uniqueProcessor, this).processChildren() - } - - public override fun processUsagesFlownFromThe(element: PsiElement, uniqueProcessor: Processor) { - OutflowSlicer(element as? KtExpression ?: return, uniqueProcessor, this).processChildren() - } -} \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/util/compat/statistic/statistic.kt.172 b/idea/src/org/jetbrains/kotlin/idea/util/compat/statistic/statistic.kt.172 deleted file mode 100644 index 590eee622dc..00000000000 --- a/idea/src/org/jetbrains/kotlin/idea/util/compat/statistic/statistic.kt.172 +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright 2000-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. - */ - -@file:Suppress("IncompatibleAPI") - -package org.jetbrains.kotlin.idea.util.compat.statistic - -/** - * Should be dropped after abandoning 172. - * BUNCH: 173 - */ -typealias AbstractProjectsUsagesCollector = com.intellij.internal.statistic.AbstractApplicationUsagesCollector - -/** - * Should be dropped after abandoning 172. - * BUNCH: 173 - */ -fun getEnumUsage(key: String, value: Enum<*>?) = com.intellij.internal.statistic.getEnumUsage(key, value) - -/** - * Should be dropped after abandoning 172. - * BUNCH: 173 - */ -fun getBooleanUsage(key: String, value: Boolean) = com.intellij.internal.statistic.getBooleanUsage(key, value) diff --git a/idea/src/org/jetbrains/kotlin/idea/versions/KotlinRuntimeLibraryUtil.kt.172 b/idea/src/org/jetbrains/kotlin/idea/versions/KotlinRuntimeLibraryUtil.kt.172 deleted file mode 100644 index f23a1612d54..00000000000 --- a/idea/src/org/jetbrains/kotlin/idea/versions/KotlinRuntimeLibraryUtil.kt.172 +++ /dev/null @@ -1,324 +0,0 @@ -/* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.kotlin.idea.versions - -import com.intellij.openapi.diagnostic.Logger -import com.intellij.openapi.module.Module -import com.intellij.openapi.module.ModuleManager -import com.intellij.openapi.module.ModuleUtil -import com.intellij.openapi.project.Project -import com.intellij.openapi.projectRoots.JavaSdkVersion -import com.intellij.openapi.projectRoots.Sdk -import com.intellij.openapi.roots.LibraryOrderEntry -import com.intellij.openapi.roots.ModuleRootManager -import com.intellij.openapi.roots.OrderRootType -import com.intellij.openapi.roots.ProjectFileIndex -import com.intellij.openapi.roots.libraries.Library -import com.intellij.openapi.ui.Messages -import com.intellij.openapi.vfs.JarFileSystem -import com.intellij.openapi.vfs.VfsUtil -import com.intellij.openapi.vfs.VirtualFile -import com.intellij.psi.JavaPsiFacade -import com.intellij.psi.PsiClass -import com.intellij.psi.search.GlobalSearchScope -import com.intellij.util.containers.MultiMap -import com.intellij.util.indexing.FileBasedIndex -import com.intellij.util.indexing.ScalarIndexExtension -import com.intellij.util.text.VersionComparatorUtil -import org.jetbrains.kotlin.builtins.KotlinBuiltIns -import org.jetbrains.kotlin.config.JvmTarget -import org.jetbrains.kotlin.config.KotlinCompilerVersion -import org.jetbrains.kotlin.idea.framework.JavaRuntimeDetectionUtil -import org.jetbrains.kotlin.idea.framework.isExternalLibrary -import org.jetbrains.kotlin.idea.util.application.runReadAction -import org.jetbrains.kotlin.idea.util.projectStructure.version -import org.jetbrains.kotlin.idea.util.runWithAlternativeResolveEnabled -import org.jetbrains.kotlin.idea.vfilefinder.KotlinJavaScriptMetaFileIndex -import org.jetbrains.kotlin.idea.vfilefinder.hasSomethingInPackage -import org.jetbrains.kotlin.metadata.deserialization.BinaryVersion -import org.jetbrains.kotlin.metadata.jvm.deserialization.JvmMetadataVersion -import org.jetbrains.kotlin.name.FqName -import org.jetbrains.kotlin.utils.JsMetadataVersion -import org.jetbrains.kotlin.utils.KotlinPaths -import org.jetbrains.kotlin.utils.LibraryUtils -import org.jetbrains.kotlin.utils.PathUtil -import java.io.File -import java.util.* - -fun getLibraryRootsWithAbiIncompatibleKotlinClasses(module: Module): Collection> { - return getLibraryRootsWithAbiIncompatibleVersion(module, JvmMetadataVersion.INSTANCE, KotlinJvmMetadataVersionIndex) -} - -fun getLibraryRootsWithAbiIncompatibleForKotlinJs(module: Module): Collection> { - return getLibraryRootsWithAbiIncompatibleVersion(module, JsMetadataVersion.INSTANCE, KotlinJsMetadataVersionIndex) -} - -fun findAllUsedLibraries(project: Project): MultiMap { - val libraries = MultiMap() - - for (module in ModuleManager.getInstance(project).modules) { - val moduleRootManager = ModuleRootManager.getInstance(module) - - for (entry in moduleRootManager.orderEntries.filterIsInstance()) { - val library = entry.library ?: continue - - libraries.putValue(library, module) - } - } - - return libraries -} - -enum class LibraryJarDescriptor( - val jarName: String, - val orderRootType: OrderRootType, - val shouldExist: Boolean, - val getPath: (KotlinPaths) -> File = { paths -> File(paths.libPath, jarName) } -) { - RUNTIME_JAR(PathUtil.KOTLIN_JAVA_STDLIB_JAR, OrderRootType.CLASSES, true, KotlinPaths::getStdlibPath) { - override fun findExistingJar(library: Library): VirtualFile? { - if (isExternalLibrary(library)) return null - return JavaRuntimeDetectionUtil.getRuntimeJar(Arrays.asList(*library.getFiles(OrderRootType.CLASSES))) - } - }, - - REFLECT_JAR(PathUtil.KOTLIN_JAVA_REFLECT_JAR, OrderRootType.CLASSES, false, KotlinPaths::getReflectPath), - SCRIPT_RUNTIME_JAR(PathUtil.KOTLIN_JAVA_SCRIPT_RUNTIME_JAR, OrderRootType.CLASSES, true, KotlinPaths::getScriptRuntimePath), - TEST_JAR(PathUtil.KOTLIN_TEST_JAR, OrderRootType.CLASSES, false, KotlinPaths::getKotlinTestPath), - - @Deprecated("RUNTIME_JDK7_JAR should be used since 1.2") - RUNTIME_JRE7_JAR(PathUtil.KOTLIN_JAVA_RUNTIME_JRE7_JAR, OrderRootType.CLASSES, false), - RUNTIME_JDK7_JAR(PathUtil.KOTLIN_JAVA_RUNTIME_JDK7_JAR, OrderRootType.CLASSES, false), - - @Deprecated("RUNTIME_JDK8_JAR should be used since 1.2") - RUNTIME_JRE8_JAR(PathUtil.KOTLIN_JAVA_RUNTIME_JRE8_JAR, OrderRootType.CLASSES, false), - RUNTIME_JDK8_JAR(PathUtil.KOTLIN_JAVA_RUNTIME_JDK8_JAR, OrderRootType.CLASSES, false), - - @Deprecated("RUNTIME_JDK7_SOURCES_JAR should be used since 1.2") - RUNTIME_JRE7_SOURCES_JAR(PathUtil.KOTLIN_JAVA_RUNTIME_JRE7_SRC_JAR, OrderRootType.SOURCES, false), - RUNTIME_JDK7_SOURCES_JAR(PathUtil.KOTLIN_JAVA_RUNTIME_JDK7_SRC_JAR, OrderRootType.SOURCES, false), - - @Deprecated("RUNTIME_JDK8_SOURCES_JAR should be used since 1.2") - RUNTIME_JRE8_SOURCES_JAR(PathUtil.KOTLIN_JAVA_RUNTIME_JRE8_SRC_JAR, OrderRootType.SOURCES, false), - RUNTIME_JDK8_SOURCES_JAR(PathUtil.KOTLIN_JAVA_RUNTIME_JDK8_SRC_JAR, OrderRootType.SOURCES, false), - - RUNTIME_SRC_JAR(PathUtil.KOTLIN_JAVA_STDLIB_SRC_JAR, OrderRootType.SOURCES, false, KotlinPaths::getStdlibSourcesPath) { - override fun findExistingJar(library: Library): VirtualFile? { - return super.findExistingJar(library) ?: LibraryUtils.getJarFile( - library.getFiles(orderRootType).toList(), - PathUtil.KOTLIN_JAVA_STDLIB_SRC_JAR_OLD - ) - } - }, - REFLECT_SRC_JAR(PathUtil.KOTLIN_REFLECT_SRC_JAR, OrderRootType.SOURCES, false), - TEST_SRC_JAR(PathUtil.KOTLIN_TEST_SRC_JAR, OrderRootType.SOURCES, false), - - JS_STDLIB_JAR(PathUtil.JS_LIB_JAR_NAME, OrderRootType.CLASSES, true, KotlinPaths::getJsStdLibJarPath), - JS_STDLIB_SRC_JAR(PathUtil.JS_LIB_SRC_JAR_NAME, OrderRootType.SOURCES, false, KotlinPaths::getJsStdLibSrcJarPath); - - open fun findExistingJar(library: Library): VirtualFile? { - if (isExternalLibrary(library)) return null - return LibraryUtils.getJarFile(Arrays.asList(*library.getFiles(orderRootType)), jarName) - } - - fun getPathInPlugin() = getPath(PathUtil.kotlinPathsForIdeaPlugin) -} - -fun bundledRuntimeVersion(): String = KotlinCompilerVersion.VERSION - - -fun getLocalJar(kotlinRuntimeJar: VirtualFile?): VirtualFile? { - if (kotlinRuntimeJar == null) return null - - val localJarFile = JarFileSystem.getInstance().getVirtualFileForJar(kotlinRuntimeJar) - if (localJarFile != null) { - return localJarFile - } - return kotlinRuntimeJar -} - -data class BinaryVersionedFile(val file: VirtualFile, val version: T, val supportedVersion: T) - -private fun getLibraryRootsWithAbiIncompatibleVersion( - module: Module, - supportedVersion: T, - index: ScalarIndexExtension -): Collection> { - val id = index.name - - val moduleWithAllDependencies = setOf(module) + ModuleUtil.getAllDependentModules(module) - val moduleWithAllDependentLibraries = GlobalSearchScope.union( - moduleWithAllDependencies.map { it.moduleWithLibrariesScope }.toTypedArray() - ) - - val allVersions = FileBasedIndex.getInstance().getAllKeys(id, module.project) - val badVersions = allVersions.filterNot(BinaryVersion::isCompatible).toHashSet() - val badRoots = hashSetOf>() - val fileIndex = ProjectFileIndex.SERVICE.getInstance(module.project) - - for (version in badVersions) { - val indexedFiles = FileBasedIndex.getInstance().getContainingFiles(id, version, moduleWithAllDependentLibraries) - for (indexedFile in indexedFiles) { - val libraryRoot = fileIndex.getClassRootForFile(indexedFile) ?: error( - "Only library roots were requested, and only class files should be indexed with the $id key. " + - "File: ${indexedFile.path}" - ) - badRoots.add(BinaryVersionedFile(com.intellij.util.PathUtil.getLocalFile(libraryRoot), version, supportedVersion)) - } - } - - return badRoots -} - -fun showRuntimeJarNotFoundDialog(project: Project, jarName: String) { - Messages.showErrorDialog( - project, - jarName + " is not found. Make sure plugin is properly installed.", - "No Runtime Found" - ) -} - -fun getKotlinJvmRuntimeMarkerClass(project: Project, scope: GlobalSearchScope): PsiClass? { - return runReadAction { - project.runWithAlternativeResolveEnabled { - JavaPsiFacade.getInstance(project).findClass(KotlinBuiltIns.FQ_NAMES.unit.asString(), scope) - } - } -} - -private val KOTLIN_JS_FQ_NAME = FqName("kotlin.js") - -fun hasKotlinJsKjsmFile(project: Project, scope: GlobalSearchScope): Boolean { - return runReadAction { - project.runWithAlternativeResolveEnabled { - KotlinJavaScriptMetaFileIndex.hasSomethingInPackage(KOTLIN_JS_FQ_NAME, scope) - } - } -} - -fun getStdlibArtifactId(sdk: Sdk?, version: String): String { - if (!hasJreSpecificRuntime(version)) { - return MAVEN_STDLIB_ID - } - - val sdkVersion = sdk?.version - if (hasJdkLikeUpdatedRuntime(version)) { - return when { - sdkVersion != null && sdkVersion.isAtLeast(JavaSdkVersion.JDK_1_8) -> MAVEN_STDLIB_ID_JDK8 - sdkVersion == JavaSdkVersion.JDK_1_7 -> MAVEN_STDLIB_ID_JDK7 - else -> MAVEN_STDLIB_ID - } - } - - return when { - sdkVersion != null && sdkVersion.isAtLeast(JavaSdkVersion.JDK_1_8) -> MAVEN_STDLIB_ID_JRE8 - sdkVersion == JavaSdkVersion.JDK_1_7 -> MAVEN_STDLIB_ID_JRE7 - else -> MAVEN_STDLIB_ID - } -} - -fun getDefaultJvmTarget(sdk: Sdk?, version: String): JvmTarget? { - if (!hasJreSpecificRuntime(version)) { - return null - } - val sdkVersion = sdk?.version - return when { - sdkVersion == null -> null - sdkVersion.isAtLeast(JavaSdkVersion.JDK_1_8) -> JvmTarget.JVM_1_8 - sdkVersion.isAtLeast(JavaSdkVersion.JDK_1_6) -> JvmTarget.JVM_1_6 - else -> null - } -} - -fun isSnapshot(version: String): Boolean { - return version.contains("SNAPSHOT", ignoreCase = true) -} - -fun hasJdkLikeUpdatedRuntime(version: String): Boolean = - VersionComparatorUtil.compare(version, "1.2.0-rc-39") >= 0 || - isSnapshot(version) || - version == "default_version" /* for tests */ - -fun hasJreSpecificRuntime(version: String): Boolean = - VersionComparatorUtil.compare(version, "1.1.0") >= 0 || - isSnapshot(version) || - version == "default_version" /* for tests */ - -const val MAVEN_STDLIB_ID = PathUtil.KOTLIN_JAVA_STDLIB_NAME - -const val MAVEN_STDLIB_ID_JRE7 = PathUtil.KOTLIN_JAVA_RUNTIME_JRE7_NAME -const val MAVEN_STDLIB_ID_JDK7 = PathUtil.KOTLIN_JAVA_RUNTIME_JDK7_NAME - -const val MAVEN_STDLIB_ID_JRE8 = PathUtil.KOTLIN_JAVA_RUNTIME_JRE8_NAME -const val MAVEN_STDLIB_ID_JDK8 = PathUtil.KOTLIN_JAVA_RUNTIME_JDK8_NAME - -const val MAVEN_JS_STDLIB_ID = PathUtil.JS_LIB_NAME -const val MAVEN_JS_TEST_ID = PathUtil.KOTLIN_TEST_JS_NAME - -const val MAVEN_OLD_JS_STDLIB_ID = "kotlin-js-library" -const val MAVEN_COMMON_STDLIB_ID = "kotlin-stdlib-common" // TODO: KotlinCommonMavenConfigurator -const val MAVEN_TEST_ID = PathUtil.KOTLIN_TEST_NAME -const val MAVEN_TEST_JUNIT_ID = "kotlin-test-junit" -const val MAVEN_COMMON_TEST_ID = "kotlin-test-common" -const val MAVEN_COMMON_TEST_ANNOTATIONS_ID = "kotlin-test-annotations-common" - -val LOG = Logger.getInstance("org.jetbrains.kotlin.idea.versions.KotlinRuntimeLibraryUtilKt") - -data class LibInfo( - val groupId: String, - val name: String, - val version: String = "0.0.0" -) - -data class DeprecatedLibInfo( - val old: LibInfo, - val new: LibInfo, - val outdatedAfterVersion: String, - val message: String -) - -private fun deprecatedLib( - oldGroupId: String, - oldName: String, - newGroupId: String = oldGroupId, - newName: String = oldName, - outdatedAfterVersion: String, - message: String -): DeprecatedLibInfo { - return DeprecatedLibInfo( - old = LibInfo(groupId = oldGroupId, name = oldName), - new = LibInfo(groupId = newGroupId, name = newName), - outdatedAfterVersion = outdatedAfterVersion, - message = message - ) -} - -val DEPRECATED_LIBRARIES_INFORMATION = listOf( - deprecatedLib( - oldGroupId = "org.jetbrains.kotlin", - oldName = PathUtil.KOTLIN_JAVA_RUNTIME_JRE7_NAME, newName = PathUtil.KOTLIN_JAVA_RUNTIME_JDK7_NAME, - outdatedAfterVersion = "1.2.0-rc-39", - message = "${PathUtil.KOTLIN_JAVA_RUNTIME_JRE7_NAME} is deprecated since 1.2.0 and should be replaced with ${PathUtil.KOTLIN_JAVA_RUNTIME_JDK7_NAME}" - ), - - deprecatedLib( - oldGroupId = "org.jetbrains.kotlin", - oldName = PathUtil.KOTLIN_JAVA_RUNTIME_JRE8_NAME, newName = PathUtil.KOTLIN_JAVA_RUNTIME_JDK8_NAME, - outdatedAfterVersion = "1.2.0-rc-39", - message = "${PathUtil.KOTLIN_JAVA_RUNTIME_JRE8_NAME} is deprecated since 1.2.0 and should be replaced with ${PathUtil.KOTLIN_JAVA_RUNTIME_JDK8_NAME}" - ) -) \ No newline at end of file diff --git a/idea/testData/codeInsight/lineMarker/recursiveCall/conventionCall.kt.172 b/idea/testData/codeInsight/lineMarker/recursiveCall/conventionCall.kt.172 deleted file mode 100644 index 573b62766e8..00000000000 --- a/idea/testData/codeInsight/lineMarker/recursiveCall/conventionCall.kt.172 +++ /dev/null @@ -1,52 +0,0 @@ -operator fun Any.get(a: Int) { - if (a > 0) { - this[a - 1] - } -} - -class A { - override fun equals(other: Any?): Boolean { - this == other - return true - } - - operator fun inc(): A { - this++ - ++this - return this - } - - operator fun component1(): Int { - // TODO: should be recursion marker too - val (a) = this - return 1 - } - - operator fun unaryPlus() { - +this - } - - operator fun unaryMinus() { - -this - } - - operator fun plus(a: Int) { - this + 1 - this += 1 - } - - operator fun invoke() { - val a = A() - a() - a.invoke() - - this.invoke() - this() - } -} - -class B -operator fun B.invoke() { - this() - invoke() -} \ No newline at end of file diff --git a/idea/testData/quickfix/createFromUsage/createFunction/fromJava/classMember.after.Dependency.kt.172 b/idea/testData/quickfix/createFromUsage/createFunction/fromJava/classMember.after.Dependency.kt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/quickfix/createFromUsage/createFunction/fromJava/classMember.after.java.172 b/idea/testData/quickfix/createFromUsage/createFunction/fromJava/classMember.after.java.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/quickfix/createFromUsage/createFunction/fromJava/classMember.before.Dependency.kt.172 b/idea/testData/quickfix/createFromUsage/createFunction/fromJava/classMember.before.Dependency.kt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/quickfix/createFromUsage/createFunction/fromJava/classMember.before.Main.java.172 b/idea/testData/quickfix/createFromUsage/createFunction/fromJava/classMember.before.Main.java.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/quickfix/createFromUsage/createFunction/fromJava/companionMember.after.Dependency.kt.172 b/idea/testData/quickfix/createFromUsage/createFunction/fromJava/companionMember.after.Dependency.kt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/quickfix/createFromUsage/createFunction/fromJava/companionMember.after.java.172 b/idea/testData/quickfix/createFromUsage/createFunction/fromJava/companionMember.after.java.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/quickfix/createFromUsage/createFunction/fromJava/companionMember.before.Dependency.kt.172 b/idea/testData/quickfix/createFromUsage/createFunction/fromJava/companionMember.before.Dependency.kt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/quickfix/createFromUsage/createFunction/fromJava/companionMember.before.Main.java.172 b/idea/testData/quickfix/createFromUsage/createFunction/fromJava/companionMember.before.Main.java.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/quickfix/createFromUsage/createFunction/fromJava/topLevel.after.Dependency.kt.172 b/idea/testData/quickfix/createFromUsage/createFunction/fromJava/topLevel.after.Dependency.kt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/quickfix/createFromUsage/createFunction/fromJava/topLevel.after.java.172 b/idea/testData/quickfix/createFromUsage/createFunction/fromJava/topLevel.after.java.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/quickfix/createFromUsage/createFunction/fromJava/topLevel.before.Dependency.kt.172 b/idea/testData/quickfix/createFromUsage/createFunction/fromJava/topLevel.before.Dependency.kt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/quickfix/createFromUsage/createFunction/fromJava/topLevel.before.Main.java.172 b/idea/testData/quickfix/createFromUsage/createFunction/fromJava/topLevel.before.Main.java.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/quickfix/createFromUsage/createTypeParameter/inContainingDeclaration/inAnnotation.kt.172 b/idea/testData/quickfix/createFromUsage/createTypeParameter/inContainingDeclaration/inAnnotation.kt.172 deleted file mode 100644 index 11ba0f18a31..00000000000 --- a/idea/testData/quickfix/createFromUsage/createTypeParameter/inContainingDeclaration/inAnnotation.kt.172 +++ /dev/null @@ -1,12 +0,0 @@ -// "Create type parameter 'Test' in class 'C'" "false" -// ACTION: Add 'testng' to classpath -// ACTION: Create annotation 'Test' -// ACTION: Make internal -// ACTION: Make private -// ACTION: Make protected -// ERROR: Unresolved reference: Test -class C { - @Test fun foo() { - - } -} \ No newline at end of file diff --git a/idea/testData/quickfix/createFromUsage/createVariable/property/fieldFromJava/classMemberLateinitVar.after.Dependency.kt.172 b/idea/testData/quickfix/createFromUsage/createVariable/property/fieldFromJava/classMemberLateinitVar.after.Dependency.kt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/quickfix/createFromUsage/createVariable/property/fieldFromJava/classMemberLateinitVar.after.java.172 b/idea/testData/quickfix/createFromUsage/createVariable/property/fieldFromJava/classMemberLateinitVar.after.java.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/quickfix/createFromUsage/createVariable/property/fieldFromJava/classMemberLateinitVar.before.Dependency.kt.172 b/idea/testData/quickfix/createFromUsage/createVariable/property/fieldFromJava/classMemberLateinitVar.before.Dependency.kt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/quickfix/createFromUsage/createVariable/property/fieldFromJava/classMemberLateinitVar.before.Main.java.172 b/idea/testData/quickfix/createFromUsage/createVariable/property/fieldFromJava/classMemberLateinitVar.before.Main.java.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/quickfix/createFromUsage/createVariable/property/fieldFromJava/classMemberVar.after.Dependency.kt.172 b/idea/testData/quickfix/createFromUsage/createVariable/property/fieldFromJava/classMemberVar.after.Dependency.kt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/quickfix/createFromUsage/createVariable/property/fieldFromJava/classMemberVar.after.java.172 b/idea/testData/quickfix/createFromUsage/createVariable/property/fieldFromJava/classMemberVar.after.java.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/quickfix/createFromUsage/createVariable/property/fieldFromJava/classMemberVar.before.Dependency.kt.172 b/idea/testData/quickfix/createFromUsage/createVariable/property/fieldFromJava/classMemberVar.before.Dependency.kt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/quickfix/createFromUsage/createVariable/property/fieldFromJava/classMemberVar.before.Main.java.172 b/idea/testData/quickfix/createFromUsage/createVariable/property/fieldFromJava/classMemberVar.before.Main.java.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/quickfix/createFromUsage/createVariable/property/fieldFromJava/companionMemberVar.after.Dependency.kt.172 b/idea/testData/quickfix/createFromUsage/createVariable/property/fieldFromJava/companionMemberVar.after.Dependency.kt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/quickfix/createFromUsage/createVariable/property/fieldFromJava/companionMemberVar.after.java.172 b/idea/testData/quickfix/createFromUsage/createVariable/property/fieldFromJava/companionMemberVar.after.java.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/quickfix/createFromUsage/createVariable/property/fieldFromJava/companionMemberVar.before.Dependency.kt.172 b/idea/testData/quickfix/createFromUsage/createVariable/property/fieldFromJava/companionMemberVar.before.Dependency.kt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/quickfix/createFromUsage/createVariable/property/fieldFromJava/companionMemberVar.before.Main.java.172 b/idea/testData/quickfix/createFromUsage/createVariable/property/fieldFromJava/companionMemberVar.before.Main.java.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/quickfix/createFromUsage/createVariable/property/fieldFromJava/topLevelVar.after.Dependency.kt.172 b/idea/testData/quickfix/createFromUsage/createVariable/property/fieldFromJava/topLevelVar.after.Dependency.kt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/quickfix/createFromUsage/createVariable/property/fieldFromJava/topLevelVar.after.java.172 b/idea/testData/quickfix/createFromUsage/createVariable/property/fieldFromJava/topLevelVar.after.java.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/quickfix/createFromUsage/createVariable/property/fieldFromJava/topLevelVar.before.Dependency.kt.172 b/idea/testData/quickfix/createFromUsage/createVariable/property/fieldFromJava/topLevelVar.before.Dependency.kt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/quickfix/createFromUsage/createVariable/property/fieldFromJava/topLevelVar.before.Main.java.172 b/idea/testData/quickfix/createFromUsage/createVariable/property/fieldFromJava/topLevelVar.before.Main.java.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/anonymousFunBodyExpression.leafGroups.txt.172 b/idea/testData/slicer/inflow/anonymousFunBodyExpression.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/anonymousFunBodyExpression.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/anonymousFunBodyExpression.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/anonymousFunReturnExpression.leafGroups.txt.172 b/idea/testData/slicer/inflow/anonymousFunReturnExpression.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/anonymousFunReturnExpression.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/anonymousFunReturnExpression.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/cast.leafGroups.txt.172 b/idea/testData/slicer/inflow/cast.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/cast.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/cast.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/compositeAssignments.leafGroups.txt.172 b/idea/testData/slicer/inflow/compositeAssignments.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/compositeAssignments.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/compositeAssignments.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/defaultGetterFieldInSetter.leafGroups.txt.172 b/idea/testData/slicer/inflow/defaultGetterFieldInSetter.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/defaultGetterFieldInSetter.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/defaultGetterFieldInSetter.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/delegateGetter.leafGroups.txt.172 b/idea/testData/slicer/inflow/delegateGetter.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/delegateGetter.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/delegateGetter.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/diamondHierarchyMiddleClassFun.leafGroups.txt.172 b/idea/testData/slicer/inflow/diamondHierarchyMiddleClassFun.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/diamondHierarchyMiddleClassFun.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/diamondHierarchyMiddleClassFun.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/diamondHierarchyMiddleInterfaceFun.leafGroups.txt.172 b/idea/testData/slicer/inflow/diamondHierarchyMiddleInterfaceFun.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/diamondHierarchyMiddleInterfaceFun.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/diamondHierarchyMiddleInterfaceFun.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/diamondHierarchyRootInterfaceFun.leafGroups.txt.172 b/idea/testData/slicer/inflow/diamondHierarchyRootInterfaceFun.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/diamondHierarchyRootInterfaceFun.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/diamondHierarchyRootInterfaceFun.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/doubleLambdaResult.leafGroups.txt.172 b/idea/testData/slicer/inflow/doubleLambdaResult.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/doubleLambdaResult.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/doubleLambdaResult.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/funParamerer.leafGroups.txt.172 b/idea/testData/slicer/inflow/funParamerer.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/funParamerer.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/funParamerer.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/funParamererWithDefault.leafGroups.txt.172 b/idea/testData/slicer/inflow/funParamererWithDefault.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/funParamererWithDefault.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/funParamererWithDefault.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/funResultViaCallableRef.leafGroups.txt.172 b/idea/testData/slicer/inflow/funResultViaCallableRef.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/funResultViaCallableRef.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/funResultViaCallableRef.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/funResultViaCallableRefWithAssignment.leafGroups.txt.172 b/idea/testData/slicer/inflow/funResultViaCallableRefWithAssignment.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/funResultViaCallableRefWithAssignment.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/funResultViaCallableRefWithAssignment.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/funResultViaCallableRefWithDirectCall.leafGroups.txt.172 b/idea/testData/slicer/inflow/funResultViaCallableRefWithDirectCall.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/funResultViaCallableRefWithDirectCall.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/funResultViaCallableRefWithDirectCall.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/funWithExpressionBody.leafGroups.txt.172 b/idea/testData/slicer/inflow/funWithExpressionBody.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/funWithExpressionBody.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/funWithExpressionBody.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/funWithReturnExpressions.leafGroups.txt.172 b/idea/testData/slicer/inflow/funWithReturnExpressions.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/funWithReturnExpressions.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/funWithReturnExpressions.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/getterAndSetterUsingField.leafGroups.txt.172 b/idea/testData/slicer/inflow/getterAndSetterUsingField.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/getterAndSetterUsingField.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/getterAndSetterUsingField.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/getterExpressionBody.leafGroups.txt.172 b/idea/testData/slicer/inflow/getterExpressionBody.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/getterExpressionBody.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/getterExpressionBody.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/getterReturnExpression.leafGroups.txt.172 b/idea/testData/slicer/inflow/getterReturnExpression.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/getterReturnExpression.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/getterReturnExpression.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/ifExpression.leafGroups.txt.172 b/idea/testData/slicer/inflow/ifExpression.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/ifExpression.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/ifExpression.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/lambdaResult.leafGroups.txt.172 b/idea/testData/slicer/inflow/lambdaResult.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/lambdaResult.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/lambdaResult.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/lambdaResultWithAssignments.leafGroups.txt.172 b/idea/testData/slicer/inflow/lambdaResultWithAssignments.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/lambdaResultWithAssignments.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/lambdaResultWithAssignments.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/lambdaResultWithDirectCall.leafGroups.txt.172 b/idea/testData/slicer/inflow/lambdaResultWithDirectCall.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/lambdaResultWithDirectCall.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/lambdaResultWithDirectCall.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/lambdaResultWithDirectCallViaAssignment.leafGroups.txt.172 b/idea/testData/slicer/inflow/lambdaResultWithDirectCallViaAssignment.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/lambdaResultWithDirectCallViaAssignment.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/lambdaResultWithDirectCallViaAssignment.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/localVal.leafGroups.txt.172 b/idea/testData/slicer/inflow/localVal.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/localVal.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/localVal.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/localVar.leafGroups.txt.172 b/idea/testData/slicer/inflow/localVar.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/localVar.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/localVar.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/memberValWithInitializer.leafGroups.txt.172 b/idea/testData/slicer/inflow/memberValWithInitializer.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/memberValWithInitializer.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/memberValWithInitializer.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/memberValWithSplitInitializer.leafGroups.txt.172 b/idea/testData/slicer/inflow/memberValWithSplitInitializer.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/memberValWithSplitInitializer.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/memberValWithSplitInitializer.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/memberVarWithInitializer.leafGroups.txt.172 b/idea/testData/slicer/inflow/memberVarWithInitializer.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/memberVarWithInitializer.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/memberVarWithInitializer.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/memberVarWithSplitInitializer.leafGroups.txt.172 b/idea/testData/slicer/inflow/memberVarWithSplitInitializer.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/memberVarWithSplitInitializer.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/memberVarWithSplitInitializer.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/noFieldInGetter.leafGroups.txt.172 b/idea/testData/slicer/inflow/noFieldInGetter.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/noFieldInGetter.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/noFieldInGetter.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/nonLocalReturn.leafGroups.txt.172 b/idea/testData/slicer/inflow/nonLocalReturn.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/nonLocalReturn.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/nonLocalReturn.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/notNullAssertion.leafGroups.txt.172 b/idea/testData/slicer/inflow/notNullAssertion.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/notNullAssertion.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/notNullAssertion.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/nullsAndNotNulls.kt.172 b/idea/testData/slicer/inflow/nullsAndNotNulls.kt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/nullsAndNotNulls.leafGroups.txt.172 b/idea/testData/slicer/inflow/nullsAndNotNulls.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/nullsAndNotNulls.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/nullsAndNotNulls.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/nullsAndNotNulls.results.txt.172 b/idea/testData/slicer/inflow/nullsAndNotNulls.results.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/overridingFunctionResult.leafGroups.txt.172 b/idea/testData/slicer/inflow/overridingFunctionResult.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/overridingFunctionResult.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/overridingFunctionResult.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/overridingParameter.leafGroups.txt.172 b/idea/testData/slicer/inflow/overridingParameter.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/overridingParameter.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/overridingParameter.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/overridingPropertyGetterResult.leafGroups.txt.172 b/idea/testData/slicer/inflow/overridingPropertyGetterResult.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/overridingPropertyGetterResult.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/overridingPropertyGetterResult.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/overridingPropertyResult.leafGroups.txt.172 b/idea/testData/slicer/inflow/overridingPropertyResult.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/overridingPropertyResult.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/overridingPropertyResult.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/primaryConstructorParameter.leafGroups.txt.172 b/idea/testData/slicer/inflow/primaryConstructorParameter.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/primaryConstructorParameter.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/primaryConstructorParameter.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/primaryConstructorParameterWithDefault.leafGroups.txt.172 b/idea/testData/slicer/inflow/primaryConstructorParameterWithDefault.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/primaryConstructorParameterWithDefault.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/primaryConstructorParameterWithDefault.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/qualifiedAssignmentsForQualifiedRef.leafGroups.txt.172 b/idea/testData/slicer/inflow/qualifiedAssignmentsForQualifiedRef.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/qualifiedAssignmentsForQualifiedRef.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/qualifiedAssignmentsForQualifiedRef.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/qualifiedAssignmentsForSimpleRef.leafGroups.txt.172 b/idea/testData/slicer/inflow/qualifiedAssignmentsForSimpleRef.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/qualifiedAssignmentsForSimpleRef.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/qualifiedAssignmentsForSimpleRef.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/safeCast.leafGroups.txt.172 b/idea/testData/slicer/inflow/safeCast.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/safeCast.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/safeCast.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/secondaryConstructorParameter.leafGroups.txt.172 b/idea/testData/slicer/inflow/secondaryConstructorParameter.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/secondaryConstructorParameter.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/secondaryConstructorParameter.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/secondaryConstructorParameterWithDefault.leafGroups.txt.172 b/idea/testData/slicer/inflow/secondaryConstructorParameterWithDefault.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/secondaryConstructorParameterWithDefault.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/secondaryConstructorParameterWithDefault.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/settersViaDelegateForQualifiedRef.leafGroups.txt.172 b/idea/testData/slicer/inflow/settersViaDelegateForQualifiedRef.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/settersViaDelegateForQualifiedRef.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/settersViaDelegateForQualifiedRef.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/settersViaDelegateForSimpleRef.leafGroups.txt.172 b/idea/testData/slicer/inflow/settersViaDelegateForSimpleRef.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/settersViaDelegateForSimpleRef.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/settersViaDelegateForSimpleRef.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/topLevelVal.leafGroups.txt.172 b/idea/testData/slicer/inflow/topLevelVal.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/topLevelVal.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/topLevelVal.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/topLevelVar.leafGroups.txt.172 b/idea/testData/slicer/inflow/topLevelVar.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/topLevelVar.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/topLevelVar.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/valParameter.leafGroups.txt.172 b/idea/testData/slicer/inflow/valParameter.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/valParameter.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/valParameter.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/varParameter.leafGroups.txt.172 b/idea/testData/slicer/inflow/varParameter.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/varParameter.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/varParameter.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/whenExpression.leafGroups.txt.172 b/idea/testData/slicer/inflow/whenExpression.leafGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/slicer/inflow/whenExpression.nullnessGroups.txt.172 b/idea/testData/slicer/inflow/whenExpression.nullnessGroups.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/testData/structureView/fileStructure/EmptyFile.after.172 b/idea/testData/structureView/fileStructure/EmptyFile.after.172 deleted file mode 100644 index 8480c6ec600..00000000000 --- a/idea/testData/structureView/fileStructure/EmptyFile.after.172 +++ /dev/null @@ -1 +0,0 @@ -+EmptyFile.kt diff --git a/idea/tests/org/jetbrains/kotlin/idea/parameterInfo/MockParameterInfoUIContext.java.172 b/idea/tests/org/jetbrains/kotlin/idea/parameterInfo/MockParameterInfoUIContext.java.172 deleted file mode 100644 index 0fe69d29d45..00000000000 --- a/idea/tests/org/jetbrains/kotlin/idea/parameterInfo/MockParameterInfoUIContext.java.172 +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright 2000-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.parameterInfo; - -import com.intellij.lang.parameterInfo.ParameterInfoUIContext; -import com.intellij.psi.PsiElement; - -import java.awt.*; -import java.util.ArrayList; -import java.util.Collections; - -public class MockParameterInfoUIContext implements ParameterInfoUIContext { - private final PsiElement myParameterOwner; - private final int myCurrentParameterIndex; - - private final ArrayList result = new ArrayList(); - - MockParameterInfoUIContext(PsiElement parameterOwner, int currentParameterIndex) { - myParameterOwner = parameterOwner; - myCurrentParameterIndex = currentParameterIndex; - } - - @Override - public String setupUIComponentPresentation(String text, int highlightStartOffset, int highlightEndOffset, - boolean isDisabled, boolean strikeout, - boolean isDisabledBeforeHighlight, Color background) { - String highlightedText; - if (highlightStartOffset != -1 && highlightEndOffset != -1) { - highlightedText = text.substring(0, highlightStartOffset) - + "" - + text.substring(highlightStartOffset, highlightEndOffset) - + "" - + text.substring(highlightEndOffset); - } - else { - highlightedText = text; - } - - String resultText = "Text: (" + highlightedText + "), " + - "Disabled: " + isDisabled + ", " + - "Strikeout: " + strikeout + ", " + - "Green: " + KotlinParameterInfoWithCallHandlerBase.GREEN_BACKGROUND.equals(background); - result.add(resultText); - - // return value not used, just return something - return resultText; - } - - @Override - public boolean isUIComponentEnabled() { - return false; - } - - @Override - public void setUIComponentEnabled(boolean enabled) { - } - - @Override - public int getCurrentParameterIndex() { - return myCurrentParameterIndex; - } - - @Override - public PsiElement getParameterOwner() { - return myParameterOwner; - } - - @Override - public Color getDefaultParameterColor() { - return null; - } - - public String getResultText() { - StringBuilder stringBuilder = new StringBuilder(); - Collections.sort(result); - for (String s : result) { - stringBuilder.append(s).append("\n"); - } - return stringBuilder.toString().trim(); - } -} diff --git a/idea/tests/org/jetbrains/kotlin/idea/parameterInfo/MockUpdateParameterInfoContext.java.172 b/idea/tests/org/jetbrains/kotlin/idea/parameterInfo/MockUpdateParameterInfoContext.java.172 deleted file mode 100644 index fdee5439b1c..00000000000 --- a/idea/tests/org/jetbrains/kotlin/idea/parameterInfo/MockUpdateParameterInfoContext.java.172 +++ /dev/null @@ -1,109 +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.idea.parameterInfo; - -import com.intellij.lang.parameterInfo.UpdateParameterInfoContext; -import com.intellij.openapi.editor.Editor; -import com.intellij.openapi.project.Project; -import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiFile; -import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture; -import com.intellij.util.ArrayUtil; -import org.jetbrains.annotations.NotNull; - -public class MockUpdateParameterInfoContext implements UpdateParameterInfoContext { - private int myCurrentParameter = -1; - private PsiFile myFile; - private JavaCodeInsightTestFixture myFixture; - - MockUpdateParameterInfoContext(PsiFile file, JavaCodeInsightTestFixture fixture) { - myFile = file; - myFixture = fixture; - } - - - @Override - public void removeHint() { - } - - @Override - public void setParameterOwner(PsiElement o) { - } - - @Override - public PsiElement getParameterOwner() { - return null; - } - - @Override - public void setHighlightedParameter(Object parameter) { - } - - @Override - public Object getHighlightedParameter() { - return null; - } - - @Override - public void setCurrentParameter(int index) { - myCurrentParameter = index; - } - - public int getCurrentParameter() { - return myCurrentParameter; - } - - @Override - public boolean isUIComponentEnabled(int index) { - return false; - } - - @Override - public void setUIComponentEnabled(int index, boolean b) { - } - - @Override - public int getParameterListStart() { - return 0; - } - - @Override - public Object[] getObjectsToView() { - return ArrayUtil.EMPTY_OBJECT_ARRAY; - } - - @Override - public Project getProject() { - return null; - } - - @Override - public PsiFile getFile() { - return myFile; - } - - @Override - public int getOffset() { - return myFixture.getCaretOffset(); - } - - @NotNull - @Override - public Editor getEditor() { - return myFixture.getEditor(); - } -} diff --git a/idea/tests/org/jetbrains/kotlin/idea/quickfix/AbstractQuickFixTest.kt.172 b/idea/tests/org/jetbrains/kotlin/idea/quickfix/AbstractQuickFixTest.kt.172 deleted file mode 100644 index b01504cce5e..00000000000 --- a/idea/tests/org/jetbrains/kotlin/idea/quickfix/AbstractQuickFixTest.kt.172 +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.kotlin.idea.quickfix - -import com.intellij.codeInsight.daemon.quickFix.ActionHint -import com.intellij.codeInsight.intention.IntentionAction -import com.intellij.codeInspection.SuppressableProblemGroup -import com.intellij.openapi.command.CommandProcessor -import com.intellij.openapi.util.io.FileUtil -import com.intellij.openapi.util.text.StringUtil -import com.intellij.openapi.vfs.CharsetToolkit -import com.intellij.rt.execution.junit.FileComparisonFailure -import com.intellij.testFramework.* -import com.intellij.util.ui.UIUtil -import junit.framework.TestCase -import org.jetbrains.kotlin.idea.facet.KotlinFacet -import org.jetbrains.kotlin.idea.test.* -import org.jetbrains.kotlin.psi.KtFile -import org.jetbrains.kotlin.test.InTextDirectivesUtils -import org.junit.Assert -import java.io.File -import java.io.IOException - -abstract class AbstractQuickFixTest : KotlinLightCodeInsightFixtureTestCase(), QuickFixTest { - @Throws(Exception::class) - protected fun doTest(beforeFileName: String) { - val beforeFileText = FileUtil.loadFile(File(beforeFileName)) - configureCompilerOptions(beforeFileText, project, module) - - val inspections = parseInspectionsToEnable(beforeFileName, beforeFileText).toTypedArray() - - try { - myFixture.enableInspections(*inspections) - - doKotlinQuickFixTest(beforeFileName) - checkForUnexpectedErrors() - } finally { - myFixture.disableInspections(*inspections) - } - } - - override fun getProjectDescriptor(): LightProjectDescriptor { - if ("createfromusage" in testDataPath.toLowerCase()) { - return KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE - } - return super.getProjectDescriptor() - } - - override val captureExceptions: Boolean - get() = false - - fun shouldBeAvailableAfterExecution(): Boolean { - return InTextDirectivesUtils.isDirectiveDefined(myFixture.file.text, "// SHOULD_BE_AVAILABLE_AFTER_EXECUTION") - } - - protected open fun configExtra(options: String) { - - } - - private fun doKotlinQuickFixTest(beforeFileName: String) { - val testFile = File(beforeFileName) - CommandProcessor.getInstance().executeCommand(project, { - var fileText = "" - var expectedErrorMessage: String? = "" - var fixtureClasses = emptyList() - try { - fileText = FileUtil.loadFile(testFile, CharsetToolkit.UTF8_CHARSET) - TestCase.assertTrue("\"\" is missing in file \"${testFile.path}\"", fileText.contains("")) - - fixtureClasses = InTextDirectivesUtils.findListWithPrefixes(fileText, "// FIXTURE_CLASS: ") - for (fixtureClass in fixtureClasses) { - TestFixtureExtension.loadFixture(fixtureClass, LightPlatformTestCase.getModule()) - } - - expectedErrorMessage = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// SHOULD_FAIL_WITH: ") - val contents = StringUtil.convertLineSeparators(fileText) - myFixture.configureByText(testFile.canonicalFile.name, contents) - - checkForUnexpectedActions() - - configExtra(fileText) - - applyAction(contents, testFile.canonicalPath) - - val compilerArgumentsAfter = InTextDirectivesUtils.findStringWithPrefixes(fileText, "COMPILER_ARGUMENTS_AFTER: ") - if (compilerArgumentsAfter != null) { - val facetSettings = KotlinFacet.get(module)!!.configuration.settings - val compilerSettings = facetSettings.compilerSettings - TestCase.assertEquals(compilerArgumentsAfter, compilerSettings?.additionalArguments) - } - - UsefulTestCase.assertEmpty(expectedErrorMessage) - } - catch (e: FileComparisonFailure) { - throw e - } - catch (e: AssertionError) { - throw e - } - catch (e: Throwable) { - if (expectedErrorMessage == null) { - throw e - } - else { - Assert.assertEquals("Wrong exception message", expectedErrorMessage, e.message) - } - } - finally { - for (fixtureClass in fixtureClasses) { - TestFixtureExtension.unloadFixture(fixtureClass) - } - ConfigLibraryUtil.unconfigureLibrariesByDirective(myFixture.module, fileText) - } - }, "", "") - } - - private fun applyAction(contents: String, testFullPath: String) { - val fileName = testFullPath.substringAfterLast(File.separatorChar, "") - val actionHint = ActionHint.parse(myFixture.file, contents.replace("\${file}", fileName, ignoreCase = true)) - val intention = findActionWithText(actionHint.expectedText) - if (actionHint.shouldPresent()) { - if (intention == null) { - fail("Action with text '" + actionHint.expectedText + "' not found\nAvailable actions: " + - myFixture.availableIntentions.joinToString(prefix = "[", postfix = "]") { it.text }) - } - myFixture.launchAction(intention!!) - UIUtil.dispatchAllInvocationEvents() - UIUtil.dispatchAllInvocationEvents() - - if (!shouldBeAvailableAfterExecution()) { - assertNull("Action '${actionHint.expectedText}' is still available after its invocation in test " + testFullPath, - findActionWithText(actionHint.expectedText)) - } - - myFixture.checkResultByFile(File(testFullPath).name + ".after") - } - else { - assertNull("Action with text ${actionHint.expectedText} is present, but should not", intention) - } - } - - @Throws(ClassNotFoundException::class) - private fun checkForUnexpectedActions() { - val text = myFixture.editor.document.text - val actionHint = ActionHint.parse(myFixture.file, text) - if (!actionHint.shouldPresent()) { - val actions = myFixture.availableIntentions - - val prefix = "class " - if (actionHint.expectedText.startsWith(prefix)) { - val className = actionHint.expectedText.substring(prefix.length) - val aClass = Class.forName(className) - assert(IntentionAction::class.java.isAssignableFrom(aClass)) { className + " should be inheritor of IntentionAction" } - - val validActions = HashSet(InTextDirectivesUtils.findLinesWithPrefixesRemoved(text, "// ACTION:")) - - actions.removeAll { action -> !aClass.isAssignableFrom(action.javaClass) || validActions.contains(action.text) } - - if (!actions.isEmpty()) { - Assert.fail("Unexpected intention actions present\n " + actions.map { action -> action.javaClass.toString() + " " + action.toString() + "\n" } - ) - } - - for (action in actions) { - if (aClass.isAssignableFrom(action.javaClass) && !validActions.contains(action.text)) { - Assert.fail("Unexpected intention action " + action.javaClass + " found") - } - } - } - else { - // Action shouldn't be found. Check that other actions are expected and thus tested action isn't there under another name. - DirectiveBasedActionUtils.checkAvailableActionsAreExpected(myFixture.file, actions) - } - } - } - - fun findActionWithText(text: String): IntentionAction? { - val intentions = myFixture.availableIntentions.filter { it.text == text } - if (intentions.isNotEmpty()) return intentions.first() - - // Support warning suppression - val caretOffset = myFixture.caretOffset - for (highlight in myFixture.doHighlighting()) { - if (highlight.startOffset <= caretOffset && caretOffset <= highlight.endOffset) { - val group = highlight.problemGroup - if (group is SuppressableProblemGroup) { - val at = myFixture.file.findElementAt(highlight.actualStartOffset) - val actions = group.getSuppressActions(at) - for (action in actions) { - if (action.text == text) { - return action - } - } - } - } - } - return null - } - - fun checkForUnexpectedErrors() { - DirectiveBasedActionUtils.checkForUnexpectedErrors(myFixture.file as KtFile) - } - - override fun getTestDataPath(): String { - // Ensure full path is returned. Otherwise FileComparisonFailureException does not provide link to file diff - val testDataPath = super.getTestDataPath() - try { - return File(testDataPath).getCanonicalPath() - } - catch (e: IOException) { - e.printStackTrace() - return testDataPath - } - - } -} diff --git a/idea/tests/org/jetbrains/kotlin/idea/quickfix/CommonIntentionActionsTest.kt.172 b/idea/tests/org/jetbrains/kotlin/idea/quickfix/CommonIntentionActionsTest.kt.172 deleted file mode 100644 index b4e2b043f63..00000000000 --- a/idea/tests/org/jetbrains/kotlin/idea/quickfix/CommonIntentionActionsTest.kt.172 +++ /dev/null @@ -1,307 +0,0 @@ -/* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.kotlin.idea.quickfix - -import com.intellij.codeInsight.intention.IntentionAction -import com.intellij.codeInsight.intention.JvmCommonIntentionActionsFactory -import com.intellij.codeInsight.intention.MethodInsertionInfo -import com.intellij.lang.Language -import com.intellij.psi.JavaPsiFacade -import com.intellij.psi.PsiModifier -import com.intellij.psi.PsiType -import com.intellij.psi.search.GlobalSearchScope -import com.intellij.testFramework.fixtures.CodeInsightTestFixture -import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase -import org.jetbrains.uast.* -import org.junit.Assert - -class CommonIntentionActionsTest : LightPlatformCodeInsightFixtureTestCase() { - fun testMakeNotFinal() { - myFixture.configureByText("foo.kt", """ - class Foo { - fun bar(){} - } - """) - - myFixture.launchAction( - codeModifications - .createChangeModifierAction(atCaret(myFixture), PsiModifier.FINAL, false)!! - .ensureHasText("Make 'bar' open") - ) - myFixture.checkResult(""" - class Foo { - open fun bar(){} - } - """) - } - - fun testMakePrivate() { - myFixture.configureByText("foo.kt", """ - class Foo { - fun bar(){} - } - """) - - myFixture.launchAction( - codeModifications - .createChangeModifierAction(atCaret(myFixture), PsiModifier.PRIVATE, true)!! - .ensureHasText("Make 'Foo' private") - ) - myFixture.checkResult(""" - private class Foo { - fun bar(){} - } - """) - } - - fun testMakeNotPrivate() { - myFixture.configureByText("foo.kt", """ - private class Foo { - fun bar(){} - } - """.trim()) - - myFixture.launchAction( - codeModifications - .createChangeModifierAction(atCaret(myFixture), PsiModifier.PRIVATE, false)!! - .ensureHasText("Remove 'private' modifier") - ) - myFixture.checkResult(""" - class Foo { - fun bar(){} - } - """.trim(), true) - } - - fun testDontMakeFunInObjectsOpen() { - myFixture.configureByText("foo.kt", """ - object Foo { - fun bar(){} - } - """.trim()) - Assert.assertNull(codeModifications.createChangeModifierAction(atCaret(myFixture), PsiModifier.FINAL, false)) - } - - fun testAddVoidVoidMethod() { - myFixture.configureByText("foo.kt", """ - |class Foo { - | fun bar() {} - |} - """.trim().trimMargin()) - - myFixture.launchAction( - codeModifications.createAddCallableMemberActions( - MethodInsertionInfo.simpleMethodInfo(atCaret(myFixture), "baz", PsiModifier.PRIVATE, PsiType.VOID, emptyList()) - ).findWithText("Add method 'baz' to 'Foo'") - ) - myFixture.checkResult(""" - |class Foo { - | fun bar() {} - | private fun baz() { - | - | } - |} - """.trim().trimMargin(), true) - } - - fun testAddIntIntMethod() { - myFixture.configureByText("foo.kt", """ - |class Foo { - | fun bar() {} - |} - """.trim().trimMargin()) - - myFixture.launchAction( - codeModifications.createAddCallableMemberActions( - MethodInsertionInfo.simpleMethodInfo(atCaret(myFixture), "baz", PsiModifier.PUBLIC, PsiType.INT, makeParams(PsiType.INT)) - ).findWithText("Add method 'baz' to 'Foo'") - ) - myFixture.checkResult(""" - |class Foo { - | fun bar() {} - | fun baz(param0: Int): Int { - | - | } - |} - """.trim().trimMargin(), true) - } - - fun testAddIntPrimaryConstructor() { - myFixture.configureByText("foo.kt", """ - |class Foo { - |} - """.trim().trimMargin()) - - myFixture.launchAction( - codeModifications.createAddCallableMemberActions( - MethodInsertionInfo.constructorInfo(atCaret(myFixture), makeParams(PsiType.INT)) - ).findWithText("Add primary constructor to 'Foo'") - ) - myFixture.checkResult(""" - |class Foo(param0: Int) { - |} - """.trim().trimMargin(), true) - } - - fun testAddIntSecondaryConstructor() { - myFixture.configureByText("foo.kt", """ - |class Foo() { - |} - """.trim().trimMargin()) - - myFixture.launchAction( - codeModifications.createAddCallableMemberActions( - MethodInsertionInfo.constructorInfo(atCaret(myFixture), makeParams(PsiType.INT)) - ).findWithText("Add secondary constructor to 'Foo'") - ) - myFixture.checkResult(""" - |class Foo() { - | constructor(param0: Int) { - | - | } - |} - """.trim().trimMargin(), true) - } - - fun testChangePrimaryConstructorInt() { - myFixture.configureByText("foo.kt", """ - |class Foo() { - |} - """.trim().trimMargin()) - - myFixture.launchAction( - codeModifications.createAddCallableMemberActions( - MethodInsertionInfo.constructorInfo(atCaret(myFixture), makeParams(PsiType.INT)) - ).findWithText("Add 'int' as 1st parameter to method 'Foo'") - ) - myFixture.checkResult(""" - |class Foo(param0: Int) { - |} - """.trim().trimMargin(), true) - } - - fun testRemoveConstructorParameters() { - myFixture.configureByText("foo.kt", """ - |class Foo(i: Int) { - |} - """.trim().trimMargin()) - - myFixture.launchAction( - codeModifications.createAddCallableMemberActions( - MethodInsertionInfo.constructorInfo(atCaret(myFixture), makeParams()) - ).findWithText("Remove 1st parameter from method 'Foo'") - ) - myFixture.checkResult(""" - |class Foo() { - |} - """.trim().trimMargin(), true) - } - - fun testAddStringVarProperty() { - myFixture.configureByText("foo.kt", """ - |class Foo { - | fun bar() {} - |} - """.trim().trimMargin()) - - myFixture.launchAction( - codeModifications.createAddBeanPropertyActions( - atCaret(myFixture), - "baz", - PsiModifier.PUBLIC, - PsiType.getTypeByName("java.lang.String", project, GlobalSearchScope.allScope(project)), - true, - true - ).findWithText("Add 'var' property 'baz' to 'Foo'") - ) - myFixture.checkResult(""" - |class Foo { - | var baz: String = TODO("initialize me") - | fun bar() {} - |} - """.trim().trimMargin(), true) - } - - fun testAddLateInitStringVarProperty() { - myFixture.configureByText("foo.kt", """ - |class Foo { - | fun bar() {} - |} - """.trim().trimMargin()) - - myFixture.launchAction(codeModifications.createAddBeanPropertyActions( - atCaret(myFixture), "baz", PsiModifier.PUBLIC, PsiType.getTypeByName("java.lang.String", project, GlobalSearchScope.allScope(project)), true, true) - .findWithText("Add 'lateinit var' property 'baz' to 'Foo'")) - myFixture.checkResult(""" - |class Foo { - | lateinit var baz: String - | fun bar() {} - |} - """.trim().trimMargin(), true) - } - - fun testAddStringValProperty() { - myFixture.configureByText("foo.kt", """ - |class Foo { - | fun bar() {} - |} - """.trim().trimMargin()) - - myFixture.launchAction( - codeModifications.createAddBeanPropertyActions( - atCaret(myFixture), - "baz", - PsiModifier.PUBLIC, - PsiType.getTypeByName("java.lang.String", project, GlobalSearchScope.allScope(project)), - false, - true - ).findWithText("Add 'val' property 'baz' to 'Foo'") - ) - myFixture.checkResult(""" - |class Foo { - | val baz: String = TODO("initialize me") - | fun bar() {} - |} - """.trim().trimMargin(), true) - } - - private fun makeParams(vararg psyTypes: PsiType): List { - val uastContext = UastContext(myFixture.project) - val factory = JavaPsiFacade.getElementFactory(myFixture.project) - val parameters = psyTypes.mapIndexed { index, psiType -> factory.createParameter("param$index", psiType) } - return parameters.map { uastContext.convertElement(it, null, UParameter::class.java) as UParameter } - } - - @Suppress("UNCHECKED_CAST") - private fun atCaret(myFixture: CodeInsightTestFixture): T { - return myFixture.elementAtCaret.toUElement() as T - } - - @Suppress("CAST_NEVER_SUCCEEDS") - private fun List.findWithText(text: String): IntentionAction = - this.firstOrNull { it.text == text } ?: - Assert.fail("intention with text '$text' was not found, only ${this.joinToString { "\"${it.text}\"" }} available") as Nothing - - @Suppress("CAST_NEVER_SUCCEEDS") - private fun IntentionAction.ensureHasText(text: String): IntentionAction = - if (this.text == text) this else Assert.fail("intention with text '$text' was not found, only \"${this.text}\" available") as Nothing - - private val codeModifications: JvmCommonIntentionActionsFactory - get() = JvmCommonIntentionActionsFactory.forLanguage(Language.findLanguageByID("kotlin")!!)!! - -} - diff --git a/idea/tests/org/jetbrains/kotlin/idea/quickfix/QuickFixMultiFileTestGenerated.java.172 b/idea/tests/org/jetbrains/kotlin/idea/quickfix/QuickFixMultiFileTestGenerated.java.172 deleted file mode 100644 index f1a3cd005ff..00000000000 --- a/idea/tests/org/jetbrains/kotlin/idea/quickfix/QuickFixMultiFileTestGenerated.java.172 +++ /dev/null @@ -1,2180 +0,0 @@ -/* - * 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; - -import com.intellij.testFramework.TestDataPath; -import org.jetbrains.kotlin.test.JUnit3RunnerWithInners; -import org.jetbrains.kotlin.test.KotlinTestUtils; -import org.jetbrains.kotlin.test.TargetBackend; -import org.jetbrains.kotlin.test.TestMetadata; -import org.junit.runner.RunWith; - -import java.io.File; -import java.util.regex.Pattern; - -// TODO -/** This class is generated by {@link org.jetbrains.kotlin.generators.tests.TestsPackage}. DO NOT MODIFY MANUALLY */ -@SuppressWarnings("all") -@TestMetadata("idea/testData/quickfix") -@TestDataPath("$PROJECT_ROOT") -@RunWith(JUnit3RunnerWithInners.class) -public class QuickFixMultiFileTestGenerated extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInQuickfix() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("idea/testData/quickfix/addAnnotationTarget") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class AddAnnotationTarget extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInAddAnnotationTarget() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/addAnnotationTarget"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("withJava.before.Main.kt") - public void testWithJava() throws Exception { - runTest("idea/testData/quickfix/addAnnotationTarget/withJava.before.Main.kt"); - } - } - - @TestMetadata("idea/testData/quickfix/addJvmDefault") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class AddJvmDefault extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInAddJvmDefault() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/addJvmDefault"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("javaDefaultOverride.before.Main.kt") - public void testJavaDefaultOverride() throws Exception { - runTest("idea/testData/quickfix/addJvmDefault/javaDefaultOverride.before.Main.kt"); - } - } - - @TestMetadata("idea/testData/quickfix/addStarProjections") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class AddStarProjections extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInAddStarProjections() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/addStarProjections"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - } - - @TestMetadata("idea/testData/quickfix/autoImports") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class AutoImports extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInAutoImports() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/autoImports"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("ambiguousNamePreferFromJdk.before.Main.kt") - public void testAmbiguousNamePreferFromJdk() throws Exception { - runTest("idea/testData/quickfix/autoImports/ambiguousNamePreferFromJdk.before.Main.kt"); - } - - @TestMetadata("ambiguousNamePreferWithImportsFromPackage.before.Main.kt") - public void testAmbiguousNamePreferWithImportsFromPackage() throws Exception { - runTest("idea/testData/quickfix/autoImports/ambiguousNamePreferWithImportsFromPackage.before.Main.kt"); - } - - @TestMetadata("callableReferenceExtension.before.Main.kt") - public void testCallableReferenceExtension() throws Exception { - runTest("idea/testData/quickfix/autoImports/callableReferenceExtension.before.Main.kt"); - } - - @TestMetadata("callableReferenceExtension2.before.Main.kt") - public void testCallableReferenceExtension2() throws Exception { - runTest("idea/testData/quickfix/autoImports/callableReferenceExtension2.before.Main.kt"); - } - - @TestMetadata("callableReferenceTopLevel.before.Main.kt") - public void testCallableReferenceTopLevel() throws Exception { - runTest("idea/testData/quickfix/autoImports/callableReferenceTopLevel.before.Main.kt"); - } - - @TestMetadata("classImport.before.Main.kt") - public void testClassImport() throws Exception { - runTest("idea/testData/quickfix/autoImports/classImport.before.Main.kt"); - } - - @TestMetadata("constructorParameterAnnotation.test") - public void testConstructorParameterAnnotation() throws Exception { - runTest("idea/testData/quickfix/autoImports/constructorParameterAnnotation.test"); - } - - @TestMetadata("constructorReference.before.Main.kt") - public void testConstructorReference() throws Exception { - runTest("idea/testData/quickfix/autoImports/constructorReference.before.Main.kt"); - } - - @TestMetadata("delegateExtensionBoth.test") - public void testDelegateExtensionBoth() throws Exception { - runTest("idea/testData/quickfix/autoImports/delegateExtensionBoth.test"); - } - - @TestMetadata("delegateExtensionGet.test") - public void testDelegateExtensionGet() throws Exception { - runTest("idea/testData/quickfix/autoImports/delegateExtensionGet.test"); - } - - @TestMetadata("delegateExtensionSet.test") - public void testDelegateExtensionSet() throws Exception { - runTest("idea/testData/quickfix/autoImports/delegateExtensionSet.test"); - } - - @TestMetadata("delegateNoOperator.test") - public void testDelegateNoOperator() throws Exception { - runTest("idea/testData/quickfix/autoImports/delegateNoOperator.test"); - } - - @TestMetadata("divOperator.before.Main.kt") - public void testDivOperator() throws Exception { - runTest("idea/testData/quickfix/autoImports/divOperator.before.Main.kt"); - } - - @TestMetadata("dslMarkers.before.Main.kt") - public void testDslMarkers() throws Exception { - runTest("idea/testData/quickfix/autoImports/dslMarkers.before.Main.kt"); - } - - @TestMetadata("extensionFunctionImport.before.Main.kt") - public void testExtensionFunctionImport() throws Exception { - runTest("idea/testData/quickfix/autoImports/extensionFunctionImport.before.Main.kt"); - } - - @TestMetadata("extensionFunctionImportImplicitReceiver.before.Main.kt") - public void testExtensionFunctionImportImplicitReceiver() throws Exception { - runTest("idea/testData/quickfix/autoImports/extensionFunctionImportImplicitReceiver.before.Main.kt"); - } - - @TestMetadata("extensionPropertyImport.before.Main.kt") - public void testExtensionPropertyImport() throws Exception { - runTest("idea/testData/quickfix/autoImports/extensionPropertyImport.before.Main.kt"); - } - - @TestMetadata("extensionPropertyOnTypeAliasFromExpansion.before.Main.kt") - public void testExtensionPropertyOnTypeAliasFromExpansion() throws Exception { - runTest("idea/testData/quickfix/autoImports/extensionPropertyOnTypeAliasFromExpansion.before.Main.kt"); - } - - @TestMetadata("extensionPropertyOnTypeAliasFromOtherTypeAlias.before.Main.kt") - public void testExtensionPropertyOnTypeAliasFromOtherTypeAlias() throws Exception { - runTest("idea/testData/quickfix/autoImports/extensionPropertyOnTypeAliasFromOtherTypeAlias.before.Main.kt"); - } - - @TestMetadata("factoryFunctionFromLambda.before.Main.kt") - public void testFactoryFunctionFromLambda() throws Exception { - runTest("idea/testData/quickfix/autoImports/factoryFunctionFromLambda.before.Main.kt"); - } - - @TestMetadata("falsePostfixOperator.before.Main.kt") - public void testFalsePostfixOperator() throws Exception { - runTest("idea/testData/quickfix/autoImports/falsePostfixOperator.before.Main.kt"); - } - - @TestMetadata("functionImport.before.Main.kt") - public void testFunctionImport() throws Exception { - runTest("idea/testData/quickfix/autoImports/functionImport.before.Main.kt"); - } - - @TestMetadata("importInFirstPartInQualifiedExpression.before.Main.kt") - public void testImportInFirstPartInQualifiedExpression() throws Exception { - runTest("idea/testData/quickfix/autoImports/importInFirstPartInQualifiedExpression.before.Main.kt"); - } - - @TestMetadata("importInFirstPartInUserType.test") - public void testImportInFirstPartInUserType() throws Exception { - runTest("idea/testData/quickfix/autoImports/importInFirstPartInUserType.test"); - } - - @TestMetadata("importKotlinCompanionPropertyAsFieldFromJava.test") - public void testImportKotlinCompanionPropertyAsFieldFromJava() throws Exception { - runTest("idea/testData/quickfix/autoImports/importKotlinCompanionPropertyAsFieldFromJava.test"); - } - - @TestMetadata("importKotlinCompanionStaticFunctionFromJava.test") - public void testImportKotlinCompanionStaticFunctionFromJava() throws Exception { - runTest("idea/testData/quickfix/autoImports/importKotlinCompanionStaticFunctionFromJava.test"); - } - - @TestMetadata("importKotlinCompanionStaticPropertyDefaultGetterFromJava.test") - public void testImportKotlinCompanionStaticPropertyDefaultGetterFromJava() throws Exception { - runTest("idea/testData/quickfix/autoImports/importKotlinCompanionStaticPropertyDefaultGetterFromJava.test"); - } - - @TestMetadata("importKotlinCompanionStaticPropertyDefaultSetterFromJava.test") - public void testImportKotlinCompanionStaticPropertyDefaultSetterFromJava() throws Exception { - runTest("idea/testData/quickfix/autoImports/importKotlinCompanionStaticPropertyDefaultSetterFromJava.test"); - } - - @TestMetadata("importKotlinCompanionStaticPropertyOverloadedGetterFromJava.test") - public void testImportKotlinCompanionStaticPropertyOverloadedGetterFromJava() throws Exception { - runTest("idea/testData/quickfix/autoImports/importKotlinCompanionStaticPropertyOverloadedGetterFromJava.test"); - } - - @TestMetadata("importKotlinCompanionStaticPropertyOverloadedSetterFromJava.test") - public void testImportKotlinCompanionStaticPropertyOverloadedSetterFromJava() throws Exception { - runTest("idea/testData/quickfix/autoImports/importKotlinCompanionStaticPropertyOverloadedSetterFromJava.test"); - } - - @TestMetadata("importKotlinPropertyAsFieldFromJava.test") - public void testImportKotlinPropertyAsFieldFromJava() throws Exception { - runTest("idea/testData/quickfix/autoImports/importKotlinPropertyAsFieldFromJava.test"); - } - - @TestMetadata("importKotlinStaticFunctionFromJava.test") - public void testImportKotlinStaticFunctionFromJava() throws Exception { - runTest("idea/testData/quickfix/autoImports/importKotlinStaticFunctionFromJava.test"); - } - - @TestMetadata("importKotlinStaticPropertyDefaultGetterFromJava.test") - public void testImportKotlinStaticPropertyDefaultGetterFromJava() throws Exception { - runTest("idea/testData/quickfix/autoImports/importKotlinStaticPropertyDefaultGetterFromJava.test"); - } - - @TestMetadata("importKotlinStaticPropertyDefaultSetterFromJava.test") - public void testImportKotlinStaticPropertyDefaultSetterFromJava() throws Exception { - runTest("idea/testData/quickfix/autoImports/importKotlinStaticPropertyDefaultSetterFromJava.test"); - } - - @TestMetadata("importKotlinStaticPropertyOverloadedGetterFromJava.test") - public void testImportKotlinStaticPropertyOverloadedGetterFromJava() throws Exception { - runTest("idea/testData/quickfix/autoImports/importKotlinStaticPropertyOverloadedGetterFromJava.test"); - } - - @TestMetadata("importKotlinStaticPropertyOverloadedSetterFromJava.test") - public void testImportKotlinStaticPropertyOverloadedSetterFromJava() throws Exception { - runTest("idea/testData/quickfix/autoImports/importKotlinStaticPropertyOverloadedSetterFromJava.test"); - } - - @TestMetadata("importTrait.before.Main.kt") - public void testImportTrait() throws Exception { - runTest("idea/testData/quickfix/autoImports/importTrait.before.Main.kt"); - } - - @TestMetadata("indexCallExtensionGet.test") - public void testIndexCallExtensionGet() throws Exception { - runTest("idea/testData/quickfix/autoImports/indexCallExtensionGet.test"); - } - - @TestMetadata("indexCallExtensionGetNoOperator.test") - public void testIndexCallExtensionGetNoOperator() throws Exception { - runTest("idea/testData/quickfix/autoImports/indexCallExtensionGetNoOperator.test"); - } - - @TestMetadata("indexCallExtensionImportGetOnNoOperatorWarning.test") - public void testIndexCallExtensionImportGetOnNoOperatorWarning() throws Exception { - runTest("idea/testData/quickfix/autoImports/indexCallExtensionImportGetOnNoOperatorWarning.test"); - } - - @TestMetadata("indexCallExtensionImportSetOnNoOperatorWarning.test") - public void testIndexCallExtensionImportSetOnNoOperatorWarning() throws Exception { - runTest("idea/testData/quickfix/autoImports/indexCallExtensionImportSetOnNoOperatorWarning.test"); - } - - @TestMetadata("indexCallExtensionSet.test") - public void testIndexCallExtensionSet() throws Exception { - runTest("idea/testData/quickfix/autoImports/indexCallExtensionSet.test"); - } - - @TestMetadata("indexCallNoImportWhenGetNeededButSetAvailable.test") - public void testIndexCallNoImportWhenGetNeededButSetAvailable() throws Exception { - runTest("idea/testData/quickfix/autoImports/indexCallNoImportWhenGetNeededButSetAvailable.test"); - } - - @TestMetadata("indexCallNoImportWhenSetNeededButGetAvailable.test") - public void testIndexCallNoImportWhenSetNeededButGetAvailable() throws Exception { - runTest("idea/testData/quickfix/autoImports/indexCallNoImportWhenSetNeededButGetAvailable.test"); - } - - @TestMetadata("infixCall.before.Main.kt") - public void testInfixCall() throws Exception { - runTest("idea/testData/quickfix/autoImports/infixCall.before.Main.kt"); - } - - @TestMetadata("infixCall2.before.Main.kt") - public void testInfixCall2() throws Exception { - runTest("idea/testData/quickfix/autoImports/infixCall2.before.Main.kt"); - } - - @TestMetadata("invokeExtension.test") - public void testInvokeExtension() throws Exception { - runTest("idea/testData/quickfix/autoImports/invokeExtension.test"); - } - - @TestMetadata("invokeExtensionNoOperator.test") - public void testInvokeExtensionNoOperator() throws Exception { - runTest("idea/testData/quickfix/autoImports/invokeExtensionNoOperator.test"); - } - - @TestMetadata("memberImportFunction.test") - public void testMemberImportFunction() throws Exception { - runTest("idea/testData/quickfix/autoImports/memberImportFunction.test"); - } - - @TestMetadata("memberImportJavaField.test") - public void testMemberImportJavaField() throws Exception { - runTest("idea/testData/quickfix/autoImports/memberImportJavaField.test"); - } - - @TestMetadata("memberImportJavaMethod.test") - public void testMemberImportJavaMethod() throws Exception { - runTest("idea/testData/quickfix/autoImports/memberImportJavaMethod.test"); - } - - @TestMetadata("memberImportNotForClassFunction.test") - public void testMemberImportNotForClassFunction() throws Exception { - runTest("idea/testData/quickfix/autoImports/memberImportNotForClassFunction.test"); - } - - @TestMetadata("memberImportNotForClassProperty.test") - public void testMemberImportNotForClassProperty() throws Exception { - runTest("idea/testData/quickfix/autoImports/memberImportNotForClassProperty.test"); - } - - @TestMetadata("memberImportNotForJavaNonStaticField.test") - public void testMemberImportNotForJavaNonStaticField() throws Exception { - runTest("idea/testData/quickfix/autoImports/memberImportNotForJavaNonStaticField.test"); - } - - @TestMetadata("memberImportNotForJavaNonStaticMethod.test") - public void testMemberImportNotForJavaNonStaticMethod() throws Exception { - runTest("idea/testData/quickfix/autoImports/memberImportNotForJavaNonStaticMethod.test"); - } - - @TestMetadata("memberImportNotForTopLevelFunction.test") - public void testMemberImportNotForTopLevelFunction() throws Exception { - runTest("idea/testData/quickfix/autoImports/memberImportNotForTopLevelFunction.test"); - } - - @TestMetadata("memberImportProperty.test") - public void testMemberImportProperty() throws Exception { - runTest("idea/testData/quickfix/autoImports/memberImportProperty.test"); - } - - @TestMetadata("memberWithTopLevelConflict.before.Main.kt") - public void testMemberWithTopLevelConflict() throws Exception { - runTest("idea/testData/quickfix/autoImports/memberWithTopLevelConflict.before.Main.kt"); - } - - @TestMetadata("minusOperator.before.Main.kt") - public void testMinusOperator() throws Exception { - runTest("idea/testData/quickfix/autoImports/minusOperator.before.Main.kt"); - } - - @TestMetadata("multiDeclarationExtensionAllComponents.test") - public void testMultiDeclarationExtensionAllComponents() throws Exception { - runTest("idea/testData/quickfix/autoImports/multiDeclarationExtensionAllComponents.test"); - } - - @TestMetadata("multiDeclarationExtensionAllComponentsMany.test") - public void testMultiDeclarationExtensionAllComponentsMany() throws Exception { - runTest("idea/testData/quickfix/autoImports/multiDeclarationExtensionAllComponentsMany.test"); - } - - @TestMetadata("multiDeclarationExtensionAllComponentsPrefereFull.test") - public void testMultiDeclarationExtensionAllComponentsPrefereFull() throws Exception { - runTest("idea/testData/quickfix/autoImports/multiDeclarationExtensionAllComponentsPrefereFull.test"); - } - - @TestMetadata("multiDeclarationExtensionAllComponentsPrefereNotDeprecated.test") - public void testMultiDeclarationExtensionAllComponentsPrefereNotDeprecated() throws Exception { - runTest("idea/testData/quickfix/autoImports/multiDeclarationExtensionAllComponentsPrefereNotDeprecated.test"); - } - - @TestMetadata("multiDeclarationExtensionComponent1.test") - public void testMultiDeclarationExtensionComponent1() throws Exception { - runTest("idea/testData/quickfix/autoImports/multiDeclarationExtensionComponent1.test"); - } - - @TestMetadata("multiDeclarationExtensionComponent2.test") - public void testMultiDeclarationExtensionComponent2() throws Exception { - runTest("idea/testData/quickfix/autoImports/multiDeclarationExtensionComponent2.test"); - } - - @TestMetadata("multiDeclarationExtensionComponentNoOperator.test") - public void testMultiDeclarationExtensionComponentNoOperator() throws Exception { - runTest("idea/testData/quickfix/autoImports/multiDeclarationExtensionComponentNoOperator.test"); - } - - @TestMetadata("nestedClass.before.Main.kt") - public void testNestedClass() throws Exception { - runTest("idea/testData/quickfix/autoImports/nestedClass.before.Main.kt"); - } - - @TestMetadata("noFunctionImportOnSimpleName.test") - public void testNoFunctionImportOnSimpleName() throws Exception { - runTest("idea/testData/quickfix/autoImports/noFunctionImportOnSimpleName.test"); - } - - @TestMetadata("noImportForFunInQualifiedNotFirst.before.Main.kt") - public void testNoImportForFunInQualifiedNotFirst() throws Exception { - runTest("idea/testData/quickfix/autoImports/noImportForFunInQualifiedNotFirst.before.Main.kt"); - } - - @TestMetadata("noImportForNestedInPrivate.before.Main.kt") - public void testNoImportForNestedInPrivate() throws Exception { - runTest("idea/testData/quickfix/autoImports/noImportForNestedInPrivate.before.Main.kt"); - } - - @TestMetadata("noImportForPrivateClass.before.Main.kt") - public void testNoImportForPrivateClass() throws Exception { - runTest("idea/testData/quickfix/autoImports/noImportForPrivateClass.before.Main.kt"); - } - - @TestMetadata("noImportInImports.before.Main.kt") - public void testNoImportInImports() throws Exception { - runTest("idea/testData/quickfix/autoImports/noImportInImports.before.Main.kt"); - } - - @TestMetadata("noImportInQualifiedExpressionNotFirst.before.Main.kt") - public void testNoImportInQualifiedExpressionNotFirst() throws Exception { - runTest("idea/testData/quickfix/autoImports/noImportInQualifiedExpressionNotFirst.before.Main.kt"); - } - - @TestMetadata("noImportInQualifiedUserTypeNotFirst.before.Main.kt") - public void testNoImportInQualifiedUserTypeNotFirst() throws Exception { - runTest("idea/testData/quickfix/autoImports/noImportInQualifiedUserTypeNotFirst.before.Main.kt"); - } - - @TestMetadata("noImportInSafeQualifiedExpressionNotFirst.before.Main.kt") - public void testNoImportInSafeQualifiedExpressionNotFirst() throws Exception { - runTest("idea/testData/quickfix/autoImports/noImportInSafeQualifiedExpressionNotFirst.before.Main.kt"); - } - - @TestMetadata("noImportInterfaceRefAsConstructor.before.Main.kt") - public void testNoImportInterfaceRefAsConstructor() throws Exception { - runTest("idea/testData/quickfix/autoImports/noImportInterfaceRefAsConstructor.before.Main.kt"); - } - - @TestMetadata("noImportsForClassInExcludedPackage.before.Main.kt") - public void testNoImportsForClassInExcludedPackage() throws Exception { - runTest("idea/testData/quickfix/autoImports/noImportsForClassInExcludedPackage.before.Main.kt"); - } - - @TestMetadata("noImportsForExcludedClass.before.Main.kt") - public void testNoImportsForExcludedClass() throws Exception { - runTest("idea/testData/quickfix/autoImports/noImportsForExcludedClass.before.Main.kt"); - } - - @TestMetadata("noImportsForFunctionInExcludedPackage.before.Main.kt") - public void testNoImportsForFunctionInExcludedPackage() throws Exception { - runTest("idea/testData/quickfix/autoImports/noImportsForFunctionInExcludedPackage.before.Main.kt"); - } - - @TestMetadata("noMemberFunctionImportOnSimpleName.test") - public void testNoMemberFunctionImportOnSimpleName() throws Exception { - runTest("idea/testData/quickfix/autoImports/noMemberFunctionImportOnSimpleName.test"); - } - - @TestMetadata("noneApplicableFromInstanceButExtension.before.Main.kt") - public void testNoneApplicableFromInstanceButExtension() throws Exception { - runTest("idea/testData/quickfix/autoImports/noneApplicableFromInstanceButExtension.before.Main.kt"); - } - - @TestMetadata("notExcludedClass.before.Main.kt") - public void testNotExcludedClass() throws Exception { - runTest("idea/testData/quickfix/autoImports/notExcludedClass.before.Main.kt"); - } - - @TestMetadata("objectImport.before.Main.kt") - public void testObjectImport() throws Exception { - runTest("idea/testData/quickfix/autoImports/objectImport.before.Main.kt"); - } - - @TestMetadata("objectMemberFunctionImportWhenReceiverPresent.before.Main.kt") - public void testObjectMemberFunctionImportWhenReceiverPresent() throws Exception { - runTest("idea/testData/quickfix/autoImports/objectMemberFunctionImportWhenReceiverPresent.before.Main.kt"); - } - - @TestMetadata("operatorAssignPlus.test") - public void testOperatorAssignPlus() throws Exception { - runTest("idea/testData/quickfix/autoImports/operatorAssignPlus.test"); - } - - @TestMetadata("operatorAssignPlusAssign.test") - public void testOperatorAssignPlusAssign() throws Exception { - runTest("idea/testData/quickfix/autoImports/operatorAssignPlusAssign.test"); - } - - @TestMetadata("operatorAssignPlusTwoVariantsDifferentPackages.test") - public void testOperatorAssignPlusTwoVariantsDifferentPackages() throws Exception { - runTest("idea/testData/quickfix/autoImports/operatorAssignPlusTwoVariantsDifferentPackages.test"); - } - - @TestMetadata("packageClass.before.Main.kt") - public void testPackageClass() throws Exception { - runTest("idea/testData/quickfix/autoImports/packageClass.before.Main.kt"); - } - - @TestMetadata("plusOperator.before.Main.kt") - public void testPlusOperator() throws Exception { - runTest("idea/testData/quickfix/autoImports/plusOperator.before.Main.kt"); - } - - @TestMetadata("plusOperatorWithTypeMismatch.before.Main.kt") - public void testPlusOperatorWithTypeMismatch() throws Exception { - runTest("idea/testData/quickfix/autoImports/plusOperatorWithTypeMismatch.before.Main.kt"); - } - - @TestMetadata("postfixOperator.before.Main.kt") - public void testPostfixOperator() throws Exception { - runTest("idea/testData/quickfix/autoImports/postfixOperator.before.Main.kt"); - } - - @TestMetadata("propertyImport.before.Main.kt") - public void testPropertyImport() throws Exception { - runTest("idea/testData/quickfix/autoImports/propertyImport.before.Main.kt"); - } - - @TestMetadata("sameModuleImportPriority.before.Main.kt") - public void testSameModuleImportPriority() throws Exception { - runTest("idea/testData/quickfix/autoImports/sameModuleImportPriority.before.Main.kt"); - } - - @TestMetadata("timesAssign.before.Main.kt") - public void testTimesAssign() throws Exception { - runTest("idea/testData/quickfix/autoImports/timesAssign.before.Main.kt"); - } - - @TestMetadata("typeAliasExtensionFunction.before.Main.kt") - public void testTypeAliasExtensionFunction() throws Exception { - runTest("idea/testData/quickfix/autoImports/typeAliasExtensionFunction.before.Main.kt"); - } - - @TestMetadata("typeAliasExtensionFunctionInTypeAliasChain.before.Main.kt") - public void testTypeAliasExtensionFunctionInTypeAliasChain() throws Exception { - runTest("idea/testData/quickfix/autoImports/typeAliasExtensionFunctionInTypeAliasChain.before.Main.kt"); - } - - @TestMetadata("typeAliasExtensionProperty.before.Main.kt") - public void testTypeAliasExtensionProperty() throws Exception { - runTest("idea/testData/quickfix/autoImports/typeAliasExtensionProperty.before.Main.kt"); - } - - @TestMetadata("typeAliasImport.before.Main.kt") - public void testTypeAliasImport() throws Exception { - runTest("idea/testData/quickfix/autoImports/typeAliasImport.before.Main.kt"); - } - - @TestMetadata("unaryMinusOperator.before.Main.kt") - public void testUnaryMinusOperator() throws Exception { - runTest("idea/testData/quickfix/autoImports/unaryMinusOperator.before.Main.kt"); - } - - @TestMetadata("unaryPlusOperator.before.Main.kt") - public void testUnaryPlusOperator() throws Exception { - runTest("idea/testData/quickfix/autoImports/unaryPlusOperator.before.Main.kt"); - } - - @TestMetadata("withSmartCastQualifier.before.Main.kt") - public void testWithSmartCastQualifier() throws Exception { - runTest("idea/testData/quickfix/autoImports/withSmartCastQualifier.before.Main.kt"); - } - - @TestMetadata("idea/testData/quickfix/autoImports/mismatchingArgs") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class MismatchingArgs extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInMismatchingArgs() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/autoImports/mismatchingArgs"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("checkArgumentTypes.test") - public void testCheckArgumentTypes() throws Exception { - runTest("idea/testData/quickfix/autoImports/mismatchingArgs/checkArgumentTypes.test"); - } - - @TestMetadata("constantExpectedTypeMismatch.test") - public void testConstantExpectedTypeMismatch() throws Exception { - runTest("idea/testData/quickfix/autoImports/mismatchingArgs/constantExpectedTypeMismatch.test"); - } - - @TestMetadata("expectedTypeRequired.test") - public void testExpectedTypeRequired() throws Exception { - runTest("idea/testData/quickfix/autoImports/mismatchingArgs/expectedTypeRequired.test"); - } - - @TestMetadata("extensionExplicitReceiver.test") - public void testExtensionExplicitReceiver() throws Exception { - runTest("idea/testData/quickfix/autoImports/mismatchingArgs/extensionExplicitReceiver.test"); - } - - @TestMetadata("extensionImplicitReceiver.test") - public void testExtensionImplicitReceiver() throws Exception { - runTest("idea/testData/quickfix/autoImports/mismatchingArgs/extensionImplicitReceiver.test"); - } - - @TestMetadata("extensionWrongReceiver.test") - public void testExtensionWrongReceiver() throws Exception { - runTest("idea/testData/quickfix/autoImports/mismatchingArgs/extensionWrongReceiver.test"); - } - - @TestMetadata("ignoreErrorsOutsideCall.test") - public void testIgnoreErrorsOutsideCall() throws Exception { - runTest("idea/testData/quickfix/autoImports/mismatchingArgs/ignoreErrorsOutsideCall.test"); - } - - @TestMetadata("lambdaArgument.test") - public void testLambdaArgument() throws Exception { - runTest("idea/testData/quickfix/autoImports/mismatchingArgs/lambdaArgument.test"); - } - - @TestMetadata("namedArgument.test") - public void testNamedArgument() throws Exception { - runTest("idea/testData/quickfix/autoImports/mismatchingArgs/namedArgument.test"); - } - - @TestMetadata("notForIncompleteCall.test") - public void testNotForIncompleteCall() throws Exception { - runTest("idea/testData/quickfix/autoImports/mismatchingArgs/notForIncompleteCall.test"); - } - - @TestMetadata("smartCast.test") - public void testSmartCast() throws Exception { - runTest("idea/testData/quickfix/autoImports/mismatchingArgs/smartCast.test"); - } - - @TestMetadata("topLevelFun.test") - public void testTopLevelFun() throws Exception { - runTest("idea/testData/quickfix/autoImports/mismatchingArgs/topLevelFun.test"); - } - - @TestMetadata("topLevelFun_notWithReceiver.test") - public void testTopLevelFun_notWithReceiver() throws Exception { - runTest("idea/testData/quickfix/autoImports/mismatchingArgs/topLevelFun_notWithReceiver.test"); - } - - @TestMetadata("typeMismatch.test") - public void testTypeMismatch() throws Exception { - runTest("idea/testData/quickfix/autoImports/mismatchingArgs/typeMismatch.test"); - } - } - } - - @TestMetadata("idea/testData/quickfix/changeSignature") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class ChangeSignature extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - @TestMetadata("addJavaMethodParameter.before.Main.kt") - public void testAddJavaMethodParameter() throws Exception { - runTest("idea/testData/quickfix/changeSignature/addJavaMethodParameter.before.Main.kt"); - } - - @TestMetadata("addParameterWithImport.before.Main.kt") - public void testAddParameterWithImport() throws Exception { - runTest("idea/testData/quickfix/changeSignature/addParameterWithImport.before.Main.kt"); - } - - public void testAllFilesPresentInChangeSignature() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/changeSignature"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("matchFunctionLiteralWithSAMType.before.Main.kt") - public void testMatchFunctionLiteralWithSAMType() throws Exception { - runTest("idea/testData/quickfix/changeSignature/matchFunctionLiteralWithSAMType.before.Main.kt"); - } - - @TestMetadata("removeJavaMethodParameter.before.Main.kt") - public void testRemoveJavaMethodParameter() throws Exception { - runTest("idea/testData/quickfix/changeSignature/removeJavaMethodParameter.before.Main.kt"); - } - - @TestMetadata("idea/testData/quickfix/changeSignature/jk") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class Jk extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInJk() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/changeSignature/jk"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("jkAddFunctionParameter.before.Main.java") - public void testJkAddFunctionParameter() throws Exception { - runTest("idea/testData/quickfix/changeSignature/jk/jkAddFunctionParameter.before.Main.java"); - } - - @TestMetadata("jkAddImplicitPrimaryConstructorParameter.before.Main.java") - public void testJkAddImplicitPrimaryConstructorParameter() throws Exception { - runTest("idea/testData/quickfix/changeSignature/jk/jkAddImplicitPrimaryConstructorParameter.before.Main.java"); - } - - @TestMetadata("jkAddPrimaryConstructorParameter.before.Main.java") - public void testJkAddPrimaryConstructorParameter() throws Exception { - runTest("idea/testData/quickfix/changeSignature/jk/jkAddPrimaryConstructorParameter.before.Main.java"); - } - - @TestMetadata("jkAddSecondaryConstructorParameter.before.Main.java") - public void testJkAddSecondaryConstructorParameter() throws Exception { - runTest("idea/testData/quickfix/changeSignature/jk/jkAddSecondaryConstructorParameter.before.Main.java"); - } - - @TestMetadata("jkChangeFunctionParameter.before.Main.java") - public void testJkChangeFunctionParameter() throws Exception { - runTest("idea/testData/quickfix/changeSignature/jk/jkChangeFunctionParameter.before.Main.java"); - } - - @TestMetadata("jkChangePrimaryConstructorParameter.before.Main.java") - public void testJkChangePrimaryConstructorParameter() throws Exception { - runTest("idea/testData/quickfix/changeSignature/jk/jkChangePrimaryConstructorParameter.before.Main.java"); - } - - @TestMetadata("jkChangeSecondaryConstructorParameter.before.Main.java") - public void testJkChangeSecondaryConstructorParameter() throws Exception { - runTest("idea/testData/quickfix/changeSignature/jk/jkChangeSecondaryConstructorParameter.before.Main.java"); - } - - @TestMetadata("jkKeepValOnAddingParameter1.before.Main.java") - public void testJkKeepValOnAddingParameter1() throws Exception { - runTest("idea/testData/quickfix/changeSignature/jk/jkKeepValOnAddingParameter1.before.Main.java"); - } - - @TestMetadata("jkKeepValOnAddingParameter2.before.Main.java") - public void testJkKeepValOnAddingParameter2() throws Exception { - runTest("idea/testData/quickfix/changeSignature/jk/jkKeepValOnAddingParameter2.before.Main.java"); - } - - @TestMetadata("jkKeepValOnParameterTypeChange.before.Main.java") - public void testJkKeepValOnParameterTypeChange() throws Exception { - runTest("idea/testData/quickfix/changeSignature/jk/jkKeepValOnParameterTypeChange.before.Main.java"); - } - - @TestMetadata("jkRemoveFunctionParameter.before.Main.java") - public void testJkRemoveFunctionParameter() throws Exception { - runTest("idea/testData/quickfix/changeSignature/jk/jkRemoveFunctionParameter.before.Main.java"); - } - - @TestMetadata("jkRemovePrimaryConstructorParameter.before.Main.java") - public void testJkRemovePrimaryConstructorParameter() throws Exception { - runTest("idea/testData/quickfix/changeSignature/jk/jkRemovePrimaryConstructorParameter.before.Main.java"); - } - - @TestMetadata("jkRemoveSecondaryConstructorParameter.before.Main.java") - public void testJkRemoveSecondaryConstructorParameter() throws Exception { - runTest("idea/testData/quickfix/changeSignature/jk/jkRemoveSecondaryConstructorParameter.before.Main.java"); - } - } - } - - @TestMetadata("idea/testData/quickfix/checkArguments") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class CheckArguments extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInCheckArguments() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/checkArguments"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - } - - @TestMetadata("idea/testData/quickfix/convertJavaInterfaceToClass") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class ConvertJavaInterfaceToClass extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInConvertJavaInterfaceToClass() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/convertJavaInterfaceToClass"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("kotlinInheritor.before.Main.java") - public void testKotlinInheritor() throws Exception { - runTest("idea/testData/quickfix/convertJavaInterfaceToClass/kotlinInheritor.before.Main.java"); - } - } - - @TestMetadata("idea/testData/quickfix/createFromUsage") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class CreateFromUsage extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInCreateFromUsage() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/createFromUsage"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("idea/testData/quickfix/createFromUsage/createClass") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class CreateClass extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInCreateClass() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/createFromUsage/createClass"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("idea/testData/quickfix/createFromUsage/createClass/annotationEntry") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class AnnotationEntry extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInAnnotationEntry() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/createFromUsage/createClass/annotationEntry"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("nestedGroovyAnnotation.before.Main.kt") - public void testNestedGroovyAnnotation() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/annotationEntry/nestedGroovyAnnotation.before.Main.kt"); - } - - @TestMetadata("nestedJavaAnnotation.before.Main.kt") - public void testNestedJavaAnnotation() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/annotationEntry/nestedJavaAnnotation.before.Main.kt"); - } - - @TestMetadata("nestedJavaAnnotationWithNamedArgs.before.Main.kt") - public void testNestedJavaAnnotationWithNamedArgs() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/annotationEntry/nestedJavaAnnotationWithNamedArgs.before.Main.kt"); - } - } - - @TestMetadata("idea/testData/quickfix/createFromUsage/createClass/callExpression") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class CallExpression extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInCallExpression() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/createFromUsage/createClass/callExpression"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("callInAnnotationEntryWithJavaQualifier.before.Main.kt") - public void testCallInAnnotationEntryWithJavaQualifier() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/callExpression/callInAnnotationEntryWithJavaQualifier.before.Main.kt"); - } - - @TestMetadata("callWithExplicitParamNamesAndJavaQualifier.before.Main.kt") - public void testCallWithExplicitParamNamesAndJavaQualifier() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/callExpression/callWithExplicitParamNamesAndJavaQualifier.before.Main.kt"); - } - - @TestMetadata("callWithFinalJavaSupertype.before.Main.kt") - public void testCallWithFinalJavaSupertype() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/callExpression/callWithFinalJavaSupertype.before.Main.kt"); - } - - @TestMetadata("callWithGenericJavaReceiver.before.Main.kt") - public void testCallWithGenericJavaReceiver() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/callExpression/callWithGenericJavaReceiver.before.Main.kt"); - } - - @TestMetadata("callWithGroovyClassQualifier.before.Main.kt") - public void testCallWithGroovyClassQualifier() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/callExpression/callWithGroovyClassQualifier.before.Main.kt"); - } - - @TestMetadata("callWithJavaClassQualifier.before.Main.kt") - public void testCallWithJavaClassQualifier() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/callExpression/callWithJavaClassQualifier.before.Main.kt"); - } - - @TestMetadata("callWithJavaClassReceiver.before.Main.kt") - public void testCallWithJavaClassReceiver() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/callExpression/callWithJavaClassReceiver.before.Main.kt"); - } - - @TestMetadata("callWithJavaQualifierInMemberValDelegate.before.Main.kt") - public void testCallWithJavaQualifierInMemberValDelegate() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/callExpression/callWithJavaQualifierInMemberValDelegate.before.Main.kt"); - } - - @TestMetadata("callWithSuperclassAndJavaReceiverNoConstructorParams.before.Main.kt") - public void testCallWithSuperclassAndJavaReceiverNoConstructorParams() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/callExpression/callWithSuperclassAndJavaReceiverNoConstructorParams.before.Main.kt"); - } - - @TestMetadata("callWithSuperclassConstructorParamsAndJavaReceiver.before.Main.kt") - public void testCallWithSuperclassConstructorParamsAndJavaReceiver() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/callExpression/callWithSuperclassConstructorParamsAndJavaReceiver.before.Main.kt"); - } - - @TestMetadata("callWithSupertraitAndJavaReceiver.before.Main.kt") - public void testCallWithSupertraitAndJavaReceiver() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/callExpression/callWithSupertraitAndJavaReceiver.before.Main.kt"); - } - - @TestMetadata("idea/testData/quickfix/createFromUsage/createClass/callExpression/typeArguments") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class TypeArguments extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInTypeArguments() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/createFromUsage/createClass/callExpression/typeArguments"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("javaClassMember.before.Main.kt") - public void testJavaClassMember() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/callExpression/typeArguments/javaClassMember.before.Main.kt"); - } - - @TestMetadata("javaClassMemberInner.before.Main.kt") - public void testJavaClassMemberInner() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/callExpression/typeArguments/javaClassMemberInner.before.Main.kt"); - } - - @TestMetadata("javaClassMemberInnerPartialSubstitution.before.Main.kt") - public void testJavaClassMemberInnerPartialSubstitution() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/callExpression/typeArguments/javaClassMemberInnerPartialSubstitution.before.Main.kt"); - } - - @TestMetadata("javaClassMemberInnerWithReceiverArg.before.Main.kt") - public void testJavaClassMemberInnerWithReceiverArg() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/callExpression/typeArguments/javaClassMemberInnerWithReceiverArg.before.Main.kt"); - } - - @TestMetadata("javaClassMemberPartialSubstitution.before.Main.kt") - public void testJavaClassMemberPartialSubstitution() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/callExpression/typeArguments/javaClassMemberPartialSubstitution.before.Main.kt"); - } - } - } - - @TestMetadata("idea/testData/quickfix/createFromUsage/createClass/delegationSpecifier") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class DelegationSpecifier extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInDelegationSpecifier() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/createFromUsage/createClass/delegationSpecifier"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("delegatorToNestedJavaSupercall.before.Main.kt") - public void testDelegatorToNestedJavaSupercall() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/delegationSpecifier/delegatorToNestedJavaSupercall.before.Main.kt"); - } - - @TestMetadata("delegatorToNestedJavaSupercallWithParamNames.before.Main.kt") - public void testDelegatorToNestedJavaSupercallWithParamNames() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/delegationSpecifier/delegatorToNestedJavaSupercallWithParamNames.before.Main.kt"); - } - - @TestMetadata("traitDelegatorToNestedGroovySuperclass.before.Main.kt") - public void testTraitDelegatorToNestedGroovySuperclass() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/delegationSpecifier/traitDelegatorToNestedGroovySuperclass.before.Main.kt"); - } - - @TestMetadata("traitDelegatorToNestedJavaSuperclass.before.Main.kt") - public void testTraitDelegatorToNestedJavaSuperclass() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/delegationSpecifier/traitDelegatorToNestedJavaSuperclass.before.Main.kt"); - } - } - - @TestMetadata("idea/testData/quickfix/createFromUsage/createClass/importDirective") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class ImportDirective extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInImportDirective() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/createFromUsage/createClass/importDirective"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("annotationWithJavaQualifier.before.Main.kt") - public void testAnnotationWithJavaQualifier() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/importDirective/annotationWithJavaQualifier.before.Main.kt"); - } - - @TestMetadata("classWithGroovyQualifier.before.Main.kt") - public void testClassWithGroovyQualifier() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/importDirective/classWithGroovyQualifier.before.Main.kt"); - } - - @TestMetadata("classWithJavaQualifier.before.Main.kt") - public void testClassWithJavaQualifier() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/importDirective/classWithJavaQualifier.before.Main.kt"); - } - - @TestMetadata("enumEntryInJavaEnum.before.Main.kt") - public void testEnumEntryInJavaEnum() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/importDirective/enumEntryInJavaEnum.before.Main.kt"); - } - - @TestMetadata("enumWithJavaQualifier.before.Main.kt") - public void testEnumWithJavaQualifier() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/importDirective/enumWithJavaQualifier.before.Main.kt"); - } - - @TestMetadata("objectWithJavaQualifier.before.Main.kt") - public void testObjectWithJavaQualifier() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/importDirective/objectWithJavaQualifier.before.Main.kt"); - } - - @TestMetadata("traitWithJavaQualifier.before.Main.kt") - public void testTraitWithJavaQualifier() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/importDirective/traitWithJavaQualifier.before.Main.kt"); - } - } - - @TestMetadata("idea/testData/quickfix/createFromUsage/createClass/referenceExpression") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class ReferenceExpression extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInReferenceExpression() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/createFromUsage/createClass/referenceExpression"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("classByNestedGroovyQualifier.before.Main.kt") - public void testClassByNestedGroovyQualifier() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/referenceExpression/classByNestedGroovyQualifier.before.Main.kt"); - } - - @TestMetadata("classByNestedJavaQualifier.before.Main.kt") - public void testClassByNestedJavaQualifier() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/referenceExpression/classByNestedJavaQualifier.before.Main.kt"); - } - - @TestMetadata("enumByNestedJavaQualifier.before.Main.kt") - public void testEnumByNestedJavaQualifier() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/referenceExpression/enumByNestedJavaQualifier.before.Main.kt"); - } - - @TestMetadata("enumEntryWithJavaEnumQualifier.before.Main.kt") - public void testEnumEntryWithJavaEnumQualifier() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/referenceExpression/enumEntryWithJavaEnumQualifier.before.Main.kt"); - } - - @TestMetadata("enumEntryWithJavaEnumSuperclass.before.Main.kt") - public void testEnumEntryWithJavaEnumSuperclass() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/referenceExpression/enumEntryWithJavaEnumSuperclass.before.Main.kt"); - } - - @TestMetadata("enumEntryWithJavaNonEnumQualifier.before.Main.kt") - public void testEnumEntryWithJavaNonEnumQualifier() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/referenceExpression/enumEntryWithJavaNonEnumQualifier.before.Main.kt"); - } - - @TestMetadata("enumEntryWithJavaNonEnumSuperclass.before.Main.kt") - public void testEnumEntryWithJavaNonEnumSuperclass() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/referenceExpression/enumEntryWithJavaNonEnumSuperclass.before.Main.kt"); - } - - @TestMetadata("objectWithJavaQualifier.before.Main.kt") - public void testObjectWithJavaQualifier() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/referenceExpression/objectWithJavaQualifier.before.Main.kt"); - } - - @TestMetadata("traitByNestedJavaQualifier.before.Main.kt") - public void testTraitByNestedJavaQualifier() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/referenceExpression/traitByNestedJavaQualifier.before.Main.kt"); - } - } - - @TestMetadata("idea/testData/quickfix/createFromUsage/createClass/typeReference") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class TypeReference extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInTypeReference() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/createFromUsage/createClass/typeReference"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("annotationJavaTypeReceiver.before.Main.kt") - public void testAnnotationJavaTypeReceiver() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/typeReference/annotationJavaTypeReceiver.before.Main.kt"); - } - - @TestMetadata("classGroovyTypeReceiver.before.Main.kt") - public void testClassGroovyTypeReceiver() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/typeReference/classGroovyTypeReceiver.before.Main.kt"); - } - - @TestMetadata("classJavaTypeReceiver.before.Main.kt") - public void testClassJavaTypeReceiver() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/typeReference/classJavaTypeReceiver.before.Main.kt"); - } - - @TestMetadata("enumEntryJavaEnumReceiver.before.Main.kt") - public void testEnumEntryJavaEnumReceiver() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/typeReference/enumEntryJavaEnumReceiver.before.Main.kt"); - } - - @TestMetadata("enumJavaTypeReceiver.before.Main.kt") - public void testEnumJavaTypeReceiver() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/typeReference/enumJavaTypeReceiver.before.Main.kt"); - } - - @TestMetadata("traitJavaTypeReceiver.before.Main.kt") - public void testTraitJavaTypeReceiver() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createClass/typeReference/traitJavaTypeReceiver.before.Main.kt"); - } - } - } - - @TestMetadata("idea/testData/quickfix/createFromUsage/createFunction") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class CreateFunction extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInCreateFunction() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/createFromUsage/createFunction"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("idea/testData/quickfix/createFromUsage/createFunction/call") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class Call extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInCall() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/createFromUsage/createFunction/call"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("extensionFunOnGroovyType.before.Main.kt") - public void testExtensionFunOnGroovyType() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createFunction/call/extensionFunOnGroovyType.before.Main.kt"); - } - - @TestMetadata("extensionFunOnJavaType.before.Main.kt") - public void testExtensionFunOnJavaType() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createFunction/call/extensionFunOnJavaType.before.Main.kt"); - } - - @TestMetadata("extensionFunOnTypeFromAnotherPackage.before.Main.kt") - public void testExtensionFunOnTypeFromAnotherPackage() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createFunction/call/extensionFunOnTypeFromAnotherPackage.before.Main.kt"); - } - - @TestMetadata("funOnGroovyType.before.Main.kt") - public void testFunOnGroovyType() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createFunction/call/funOnGroovyType.before.Main.kt"); - } - - @TestMetadata("funOnJavaInterface.before.Main.kt") - public void testFunOnJavaInterface() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createFunction/call/funOnJavaInterface.before.Main.kt"); - } - - @TestMetadata("funOnJavaType.before.Main.kt") - public void testFunOnJavaType() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createFunction/call/funOnJavaType.before.Main.kt"); - } - - @TestMetadata("genericFunOnJavaType.before.Main.kt") - public void testGenericFunOnJavaType() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createFunction/call/genericFunOnJavaType.before.Main.kt"); - } - - @TestMetadata("staticExtensionFunOnJavaClass.before.Main.kt") - public void testStaticExtensionFunOnJavaClass() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createFunction/call/staticExtensionFunOnJavaClass.before.Main.kt"); - } - - @TestMetadata("staticFunOnJavaClass.before.Main.kt") - public void testStaticFunOnJavaClass() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createFunction/call/staticFunOnJavaClass.before.Main.kt"); - } - - @TestMetadata("staticFunOnJavaInterface.before.Main.kt") - public void testStaticFunOnJavaInterface() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createFunction/call/staticFunOnJavaInterface.before.Main.kt"); - } - - @TestMetadata("idea/testData/quickfix/createFromUsage/createFunction/call/typeArguments") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class TypeArguments extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInTypeArguments() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/createFromUsage/createFunction/call/typeArguments"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("javaClassMember.before.Main.kt") - public void testJavaClassMember() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createFunction/call/typeArguments/javaClassMember.before.Main.kt"); - } - - @TestMetadata("javaClassMemberPartialSubstitution.before.Main.kt") - public void testJavaClassMemberPartialSubstitution() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createFunction/call/typeArguments/javaClassMemberPartialSubstitution.before.Main.kt"); - } - - @TestMetadata("javaClassMemberWithReceiverArg.before.Main.kt") - public void testJavaClassMemberWithReceiverArg() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createFunction/call/typeArguments/javaClassMemberWithReceiverArg.before.Main.kt"); - } - } - } - } - - @TestMetadata("idea/testData/quickfix/createFromUsage/createSecondaryConstructor") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class CreateSecondaryConstructor extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInCreateSecondaryConstructor() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/createFromUsage/createSecondaryConstructor"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("delegatorToSuperCallJavaClass.before.Main.kt") - public void testDelegatorToSuperCallJavaClass() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createSecondaryConstructor/delegatorToSuperCallJavaClass.before.Main.kt"); - } - - @TestMetadata("groovyConstructor.before.Main.kt") - public void testGroovyConstructor() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createSecondaryConstructor/groovyConstructor.before.Main.kt"); - } - - @TestMetadata("javaConstructor.before.Main.kt") - public void testJavaConstructor() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createSecondaryConstructor/javaConstructor.before.Main.kt"); - } - - @TestMetadata("superCallJavaClass.before.Main.kt") - public void testSuperCallJavaClass() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createSecondaryConstructor/superCallJavaClass.before.Main.kt"); - } - } - - @TestMetadata("idea/testData/quickfix/createFromUsage/createTypeAlias") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class CreateTypeAlias extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInCreateTypeAlias() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/createFromUsage/createTypeAlias"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("idea/testData/quickfix/createFromUsage/createTypeAlias/typeReference") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class TypeReference extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInTypeReference() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/createFromUsage/createTypeAlias/typeReference"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("javaUserTypeReceiver.test") - public void testJavaUserTypeReceiver() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createTypeAlias/typeReference/javaUserTypeReceiver.test"); - } - } - } - - @TestMetadata("idea/testData/quickfix/createFromUsage/createTypeParameter") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class CreateTypeParameter extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInCreateTypeParameter() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/createFromUsage/createTypeParameter"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - } - - @TestMetadata("idea/testData/quickfix/createFromUsage/createVariable") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class CreateVariable extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInCreateVariable() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/createFromUsage/createVariable"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("idea/testData/quickfix/createFromUsage/createVariable/parameter") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class Parameter extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInParameter() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/createFromUsage/createVariable/parameter"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("platformType.before.Main.kt") - public void testPlatformType() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createVariable/parameter/platformType.before.Main.kt"); - } - } - - @TestMetadata("idea/testData/quickfix/createFromUsage/createVariable/primaryParameter") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class PrimaryParameter extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInPrimaryParameter() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/createFromUsage/createVariable/primaryParameter"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("staticValOnJavaClass.before.Main.kt") - public void testStaticValOnJavaClass() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createVariable/primaryParameter/staticValOnJavaClass.before.Main.kt"); - } - - @TestMetadata("valOnJavaType.before.Main.kt") - public void testValOnJavaType() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createVariable/primaryParameter/valOnJavaType.before.Main.kt"); - } - } - - @TestMetadata("idea/testData/quickfix/createFromUsage/createVariable/property") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class Property extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInProperty() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/createFromUsage/createVariable/property"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("extensionPropertyOnTypeFromAnotherPackage.before.Main.kt") - public void testExtensionPropertyOnTypeFromAnotherPackage() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createVariable/property/extensionPropertyOnTypeFromAnotherPackage.before.Main.kt"); - } - - @TestMetadata("extensionValOnGroovyType.before.Main.kt") - public void testExtensionValOnGroovyType() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createVariable/property/extensionValOnGroovyType.before.Main.kt"); - } - - @TestMetadata("extensionValOnJavaType.before.Main.kt") - public void testExtensionValOnJavaType() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createVariable/property/extensionValOnJavaType.before.Main.kt"); - } - - @TestMetadata("staticExtensionValOnJavaType.before.Main.kt") - public void testStaticExtensionValOnJavaType() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createVariable/property/staticExtensionValOnJavaType.before.Main.kt"); - } - - @TestMetadata("staticValOnJavaClass.before.Main.kt") - public void testStaticValOnJavaClass() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createVariable/property/staticValOnJavaClass.before.Main.kt"); - } - - @TestMetadata("staticValOnJavaInterface.before.Main.kt") - public void testStaticValOnJavaInterface() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createVariable/property/staticValOnJavaInterface.before.Main.kt"); - } - - @TestMetadata("staticVarOnJavaInterface.before.Main.kt") - public void testStaticVarOnJavaInterface() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createVariable/property/staticVarOnJavaInterface.before.Main.kt"); - } - - @TestMetadata("valOnGroovyType.before.Main.kt") - public void testValOnGroovyType() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createVariable/property/valOnGroovyType.before.Main.kt"); - } - - @TestMetadata("valOnJavaInterface.before.Main.kt") - public void testValOnJavaInterface() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createVariable/property/valOnJavaInterface.before.Main.kt"); - } - - @TestMetadata("valOnJavaType.before.Main.kt") - public void testValOnJavaType() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createVariable/property/valOnJavaType.before.Main.kt"); - } - - @TestMetadata("varOnJavaType.before.Main.kt") - public void testVarOnJavaType() throws Exception { - runTest("idea/testData/quickfix/createFromUsage/createVariable/property/varOnJavaType.before.Main.kt"); - } - } - } - } - - @TestMetadata("idea/testData/quickfix/deprecatedSymbolUsage") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class DeprecatedSymbolUsage extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInDeprecatedSymbolUsage() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/deprecatedSymbolUsage"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("javaDeprecated.before.Main.kt") - public void testJavaDeprecated() throws Exception { - runTest("idea/testData/quickfix/deprecatedSymbolUsage/javaDeprecated.before.Main.kt"); - } - - @TestMetadata("toMethodFromCompanionObject.before.Main.kt") - public void testToMethodFromCompanionObject() throws Exception { - runTest("idea/testData/quickfix/deprecatedSymbolUsage/toMethodFromCompanionObject.before.Main.kt"); - } - - @TestMetadata("idea/testData/quickfix/deprecatedSymbolUsage/classUsages") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class ClassUsages extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - @TestMetadata("addImportFromSamePackage.before.Main.kt") - public void testAddImportFromSamePackage() throws Exception { - runTest("idea/testData/quickfix/deprecatedSymbolUsage/classUsages/addImportFromSamePackage.before.Main.kt"); - } - - public void testAllFilesPresentInClassUsages() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/deprecatedSymbolUsage/classUsages"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("idea/testData/quickfix/deprecatedSymbolUsage/classUsages/wholeProject") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class WholeProject extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInWholeProject() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/deprecatedSymbolUsage/classUsages/wholeProject"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("annotation.before.Main.kt") - public void testAnnotation() throws Exception { - runTest("idea/testData/quickfix/deprecatedSymbolUsage/classUsages/wholeProject/annotation.before.Main.kt"); - } - } - } - - @TestMetadata("idea/testData/quickfix/deprecatedSymbolUsage/imports") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class Imports extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - @TestMetadata("addImportForOperator.before.Main.kt") - public void testAddImportForOperator() throws Exception { - runTest("idea/testData/quickfix/deprecatedSymbolUsage/imports/addImportForOperator.before.Main.kt"); - } - - @TestMetadata("addImportFromSamePackage.before.Main.kt") - public void testAddImportFromSamePackage() throws Exception { - runTest("idea/testData/quickfix/deprecatedSymbolUsage/imports/addImportFromSamePackage.before.Main.kt"); - } - - @TestMetadata("addImportFromSamePackage2.before.Main.kt") - public void testAddImportFromSamePackage2() throws Exception { - runTest("idea/testData/quickfix/deprecatedSymbolUsage/imports/addImportFromSamePackage2.before.Main.kt"); - } - - @TestMetadata("addImportFromSamePackage3.before.Main.kt") - public void testAddImportFromSamePackage3() throws Exception { - runTest("idea/testData/quickfix/deprecatedSymbolUsage/imports/addImportFromSamePackage3.before.Main.kt"); - } - - @TestMetadata("addImports.before.Main.kt") - public void testAddImports() throws Exception { - runTest("idea/testData/quickfix/deprecatedSymbolUsage/imports/addImports.before.Main.kt"); - } - - @TestMetadata("addImportsSimple.before.Main.kt") - public void testAddImportsSimple() throws Exception { - runTest("idea/testData/quickfix/deprecatedSymbolUsage/imports/addImportsSimple.before.Main.kt"); - } - - @TestMetadata("addImportsWithSameName.before.Main.kt") - public void testAddImportsWithSameName() throws Exception { - runTest("idea/testData/quickfix/deprecatedSymbolUsage/imports/addImportsWithSameName.before.Main.kt"); - } - - public void testAllFilesPresentInImports() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/deprecatedSymbolUsage/imports"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("rootPackage.before.Main.kt") - public void testRootPackage() throws Exception { - runTest("idea/testData/quickfix/deprecatedSymbolUsage/imports/rootPackage.before.Main.kt"); - } - } - - @TestMetadata("idea/testData/quickfix/deprecatedSymbolUsage/keepComments") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class KeepComments extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInKeepComments() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/deprecatedSymbolUsage/keepComments"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - } - - @TestMetadata("idea/testData/quickfix/deprecatedSymbolUsage/keepLineBreaks") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class KeepLineBreaks extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInKeepLineBreaks() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/deprecatedSymbolUsage/keepLineBreaks"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - } - - @TestMetadata("idea/testData/quickfix/deprecatedSymbolUsage/operatorCalls") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class OperatorCalls extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInOperatorCalls() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/deprecatedSymbolUsage/operatorCalls"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - } - - @TestMetadata("idea/testData/quickfix/deprecatedSymbolUsage/optionalParameters") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class OptionalParameters extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInOptionalParameters() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/deprecatedSymbolUsage/optionalParameters"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - } - - @TestMetadata("idea/testData/quickfix/deprecatedSymbolUsage/properties") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class Properties extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInProperties() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/deprecatedSymbolUsage/properties"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - } - - @TestMetadata("idea/testData/quickfix/deprecatedSymbolUsage/publishedApi") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class PublishedApi extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInPublishedApi() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/deprecatedSymbolUsage/publishedApi"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - } - - @TestMetadata("idea/testData/quickfix/deprecatedSymbolUsage/safeCall") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class SafeCall extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInSafeCall() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/deprecatedSymbolUsage/safeCall"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - } - - @TestMetadata("idea/testData/quickfix/deprecatedSymbolUsage/typeAliases") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class TypeAliases extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInTypeAliases() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/deprecatedSymbolUsage/typeAliases"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("idea/testData/quickfix/deprecatedSymbolUsage/typeAliases/wholeProject") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class WholeProject extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInWholeProject() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/deprecatedSymbolUsage/typeAliases/wholeProject"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("typealias.before.Main.kt") - public void testTypealias() throws Exception { - runTest("idea/testData/quickfix/deprecatedSymbolUsage/typeAliases/wholeProject/typealias.before.Main.kt"); - } - } - } - - @TestMetadata("idea/testData/quickfix/deprecatedSymbolUsage/typeArguments") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class TypeArguments extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInTypeArguments() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/deprecatedSymbolUsage/typeArguments"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("platformType.before.Main.kt") - public void testPlatformType() throws Exception { - runTest("idea/testData/quickfix/deprecatedSymbolUsage/typeArguments/platformType.before.Main.kt"); - } - } - - @TestMetadata("idea/testData/quickfix/deprecatedSymbolUsage/wholeProject") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class WholeProject extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInWholeProject() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/deprecatedSymbolUsage/wholeProject"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("function.before.Main.kt") - public void testFunction() throws Exception { - runTest("idea/testData/quickfix/deprecatedSymbolUsage/wholeProject/function.before.Main.kt"); - } - - @TestMetadata("property.before.Main.kt") - public void testProperty() throws Exception { - runTest("idea/testData/quickfix/deprecatedSymbolUsage/wholeProject/property.before.Main.kt"); - } - } - } - - @TestMetadata("idea/testData/quickfix/increaseVisibility") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class IncreaseVisibility extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInIncreaseVisibility() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/increaseVisibility"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("privateMemberToInternalMultiFile.before.Main.kt") - public void testPrivateMemberToInternalMultiFile() throws Exception { - runTest("idea/testData/quickfix/increaseVisibility/privateMemberToInternalMultiFile.before.Main.kt"); - } - - @TestMetadata("privateTopLevelFunInFile.before.Main.kt") - public void testPrivateTopLevelFunInFile() throws Exception { - runTest("idea/testData/quickfix/increaseVisibility/privateTopLevelFunInFile.before.Main.kt"); - } - - @TestMetadata("privateTopLevelValInFile.before.Main.kt") - public void testPrivateTopLevelValInFile() throws Exception { - runTest("idea/testData/quickfix/increaseVisibility/privateTopLevelValInFile.before.Main.kt"); - } - - @TestMetadata("privateTopLevelVarInFile.before.Main.kt") - public void testPrivateTopLevelVarInFile() throws Exception { - runTest("idea/testData/quickfix/increaseVisibility/privateTopLevelVarInFile.before.Main.kt"); - } - - @TestMetadata("privateTopLevelVarWithSetterInFile.before.Main.kt") - public void testPrivateTopLevelVarWithSetterInFile() throws Exception { - runTest("idea/testData/quickfix/increaseVisibility/privateTopLevelVarWithSetterInFile.before.Main.kt"); - } - } - - @TestMetadata("idea/testData/quickfix/memberVisibilityCanBePrivate") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class MemberVisibilityCanBePrivate extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInMemberVisibilityCanBePrivate() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/memberVisibilityCanBePrivate"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("getter.before.Main.kt") - public void testGetter() throws Exception { - runTest("idea/testData/quickfix/memberVisibilityCanBePrivate/getter.before.Main.kt"); - } - } - - @TestMetadata("idea/testData/quickfix/migration") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class Migration extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInMigration() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/migration"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("idea/testData/quickfix/migration/conflictingExtension") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class ConflictingExtension extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInConflictingExtension() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/migration/conflictingExtension"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("removeImports.before.Main.kt") - public void testRemoveImports() throws Exception { - runTest("idea/testData/quickfix/migration/conflictingExtension/removeImports.before.Main.kt"); - } - - @TestMetadata("removeImportsOverloads.before.Main.kt") - public void testRemoveImportsOverloads() throws Exception { - runTest("idea/testData/quickfix/migration/conflictingExtension/removeImportsOverloads.before.Main.kt"); - } - } - - @TestMetadata("idea/testData/quickfix/migration/javaAnnotationPositionedArguments") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class JavaAnnotationPositionedArguments extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInJavaAnnotationPositionedArguments() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/migration/javaAnnotationPositionedArguments"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("basicMultiple.before.Main.kt") - public void testBasicMultiple() throws Exception { - runTest("idea/testData/quickfix/migration/javaAnnotationPositionedArguments/basicMultiple.before.Main.kt"); - } - - @TestMetadata("noValueForArgumentMultiple.before.Main.kt") - public void testNoValueForArgumentMultiple() throws Exception { - runTest("idea/testData/quickfix/migration/javaAnnotationPositionedArguments/noValueForArgumentMultiple.before.Main.kt"); - } - - @TestMetadata("wrongTypeMultiple.before.Main.kt") - public void testWrongTypeMultiple() throws Exception { - runTest("idea/testData/quickfix/migration/javaAnnotationPositionedArguments/wrongTypeMultiple.before.Main.kt"); - } - } - } - - @TestMetadata("idea/testData/quickfix/modifiers") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class Modifiers extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInModifiers() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/modifiers"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("constVal.before.Main.kt") - public void testConstVal() throws Exception { - runTest("idea/testData/quickfix/modifiers/constVal.before.Main.kt"); - } - - @TestMetadata("idea/testData/quickfix/modifiers/addOpenToClassDeclaration") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class AddOpenToClassDeclaration extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInAddOpenToClassDeclaration() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/modifiers/addOpenToClassDeclaration"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("finalJavaSupertype.before.Main.kt") - public void testFinalJavaSupertype() throws Exception { - runTest("idea/testData/quickfix/modifiers/addOpenToClassDeclaration/finalJavaSupertype.before.Main.kt"); - } - - @TestMetadata("finalJavaUpperBound.before.Main.kt") - public void testFinalJavaUpperBound() throws Exception { - runTest("idea/testData/quickfix/modifiers/addOpenToClassDeclaration/finalJavaUpperBound.before.Main.kt"); - } - } - } - - @TestMetadata("idea/testData/quickfix/nullables") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class Nullables extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInNullables() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/nullables"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - } - - @TestMetadata("idea/testData/quickfix/obsoleteCoroutines") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class ObsoleteCoroutines extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInObsoleteCoroutines() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/obsoleteCoroutines"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - } - - @TestMetadata("idea/testData/quickfix/optimizeImports") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class OptimizeImports extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInOptimizeImports() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/optimizeImports"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("notRemoveImportsForTypeAliases.before.Main.kt") - public void testNotRemoveImportsForTypeAliases() throws Exception { - runTest("idea/testData/quickfix/optimizeImports/notRemoveImportsForTypeAliases.before.Main.kt"); - } - } - - @TestMetadata("idea/testData/quickfix/override") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class Override extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInOverride() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/override"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("idea/testData/quickfix/override/nothingToOverride") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class NothingToOverride extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInNothingToOverride() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/override/nothingToOverride"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("import.before.Main.kt") - public void testImport() throws Exception { - runTest("idea/testData/quickfix/override/nothingToOverride/import.before.Main.kt"); - } - - @TestMetadata("overrideJavaMethodWithAnnotation.test") - public void testOverrideJavaMethodWithAnnotation() throws Exception { - runTest("idea/testData/quickfix/override/nothingToOverride/overrideJavaMethodWithAnnotation.test"); - } - - @TestMetadata("twoPackages.before.Main.kt") - public void testTwoPackages() throws Exception { - runTest("idea/testData/quickfix/override/nothingToOverride/twoPackages.before.Main.kt"); - } - } - } - - @TestMetadata("idea/testData/quickfix/properties") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class Properties extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInProperties() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/properties"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - } - - @TestMetadata("idea/testData/quickfix/removeUnused") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class RemoveUnused extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInRemoveUnused() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/removeUnused"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("javaTriangle.before.Main.kt") - public void testJavaTriangle() throws Exception { - runTest("idea/testData/quickfix/removeUnused/javaTriangle.before.Main.kt"); - } - - @TestMetadata("javaTriangle2.before.Main.kt") - public void testJavaTriangle2() throws Exception { - runTest("idea/testData/quickfix/removeUnused/javaTriangle2.before.Main.kt"); - } - - @TestMetadata("javaTriangle3.before.Main.kt") - public void testJavaTriangle3() throws Exception { - runTest("idea/testData/quickfix/removeUnused/javaTriangle3.before.Main.kt"); - } - - @TestMetadata("javaTriangleUnused.before.Main.kt") - public void testJavaTriangleUnused() throws Exception { - runTest("idea/testData/quickfix/removeUnused/javaTriangleUnused.before.Main.kt"); - } - - @TestMetadata("javaTriangleUnused2.before.Main.kt") - public void testJavaTriangleUnused2() throws Exception { - runTest("idea/testData/quickfix/removeUnused/javaTriangleUnused2.before.Main.kt"); - } - - @TestMetadata("secondaryConstructorFromJava.before.Main.kt") - public void testSecondaryConstructorFromJava() throws Exception { - runTest("idea/testData/quickfix/removeUnused/secondaryConstructorFromJava.before.Main.kt"); - } - - @TestMetadata("secondaryConstructorFromJavaDelegate.before.Main.kt") - public void testSecondaryConstructorFromJavaDelegate() throws Exception { - runTest("idea/testData/quickfix/removeUnused/secondaryConstructorFromJavaDelegate.before.Main.kt"); - } - - @TestMetadata("usedObjectAsAliasMulti.before.Main.kt") - public void testUsedObjectAsAliasMulti() throws Exception { - runTest("idea/testData/quickfix/removeUnused/usedObjectAsAliasMulti.before.Main.kt"); - } - } - - @TestMetadata("idea/testData/quickfix/suppress") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class Suppress extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInSuppress() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/suppress"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("idea/testData/quickfix/suppress/forStatement") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class ForStatement extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInForStatement() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/suppress/forStatement"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - } - } - - @TestMetadata("idea/testData/quickfix/typeImports") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class TypeImports extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInTypeImports() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/typeImports"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("importFromAnotherFile.before.Main.kt") - public void testImportFromAnotherFile() throws Exception { - runTest("idea/testData/quickfix/typeImports/importFromAnotherFile.before.Main.kt"); - } - } - - @TestMetadata("idea/testData/quickfix/typeMismatch") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class TypeMismatch extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - @TestMetadata("addArrayOfTypeForJavaAnnotation.before.Main.kt") - public void testAddArrayOfTypeForJavaAnnotation() throws Exception { - runTest("idea/testData/quickfix/typeMismatch/addArrayOfTypeForJavaAnnotation.before.Main.kt"); - } - - public void testAllFilesPresentInTypeMismatch() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/typeMismatch"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("paramTypeInOverrides.before.Main.kt") - public void testParamTypeInOverrides() throws Exception { - runTest("idea/testData/quickfix/typeMismatch/paramTypeInOverrides.before.Main.kt"); - } - - @TestMetadata("idea/testData/quickfix/typeMismatch/genericVarianceViolation") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class GenericVarianceViolation extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInGenericVarianceViolation() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/typeMismatch/genericVarianceViolation"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("basicMultiple.before.Main.kt") - public void testBasicMultiple() throws Exception { - runTest("idea/testData/quickfix/typeMismatch/genericVarianceViolation/basicMultiple.before.Main.kt"); - } - } - - @TestMetadata("idea/testData/quickfix/typeMismatch/wrapWithCollectionLiteral") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class WrapWithCollectionLiteral extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInWrapWithCollectionLiteral() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/typeMismatch/wrapWithCollectionLiteral"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - } - } - - @TestMetadata("idea/testData/quickfix/variables") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class Variables extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInVariables() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/variables"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - - @TestMetadata("idea/testData/quickfix/variables/changeMutability") - @TestDataPath("$PROJECT_ROOT") - @RunWith(JUnit3RunnerWithInners.class) - public static class ChangeMutability extends AbstractQuickFixMultiFileTest { - private void runTest(String testDataFilePath) throws Exception { - KotlinTestUtils.runTest(this::doTestWithExtraFile, TargetBackend.ANY, testDataFilePath); - } - - public void testAllFilesPresentInChangeMutability() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/quickfix/variables/changeMutability"), Pattern.compile("^(\\w+)\\.((before\\.Main\\.\\w+)|(test))$"), TargetBackend.ANY, true); - } - } - } -} diff --git a/idea/tests/org/jetbrains/kotlin/idea/slicer/AbstractSlicerLeafGroupingTest.kt.172 b/idea/tests/org/jetbrains/kotlin/idea/slicer/AbstractSlicerLeafGroupingTest.kt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/tests/org/jetbrains/kotlin/idea/slicer/AbstractSlicerNullnessGroupingTest.kt.172 b/idea/tests/org/jetbrains/kotlin/idea/slicer/AbstractSlicerNullnessGroupingTest.kt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/tests/org/jetbrains/kotlin/idea/slicer/AbstractSlicerTest.kt.172 b/idea/tests/org/jetbrains/kotlin/idea/slicer/AbstractSlicerTest.kt.172 deleted file mode 100644 index 123291b81a1..00000000000 --- a/idea/tests/org/jetbrains/kotlin/idea/slicer/AbstractSlicerTest.kt.172 +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.kotlin.idea.slicer - -import com.intellij.analysis.AnalysisScope -import com.intellij.openapi.util.io.FileUtil -import com.intellij.slicer.SliceAnalysisParams -import com.intellij.slicer.SliceUsage -import com.intellij.usages.TextChunk -import com.intellij.util.CommonProcessors -import com.intellij.util.Processor -import gnu.trove.THashSet -import gnu.trove.TObjectHashingStrategy -import com.intellij.util.PathUtil -import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase -import org.jetbrains.kotlin.idea.util.application.runReadAction -import org.jetbrains.kotlin.psi.KtFile -import org.jetbrains.kotlin.test.InTextDirectivesUtils -import org.jetbrains.kotlin.test.KotlinTestUtils -import java.awt.Font -import java.io.File - -abstract class AbstractSlicerTest : KotlinLightCodeInsightFixtureTestCase() { - object SliceUsageHashingStrategy : TObjectHashingStrategy { - override fun computeHashCode(`object`: KotlinSliceUsage): Int { - return `object`.usageInfo.hashCode() * 31 + `object`.forcedExpressionMode.hashCode() - } - - override fun equals(o1: KotlinSliceUsage, o2: KotlinSliceUsage): Boolean { - return o1.usageInfo == o2.usageInfo && o1.forcedExpressionMode == o2.forcedExpressionMode - } - } - - // Based on SliceUsage.processChildren - private fun KotlinSliceUsage.processChildrenWithoutProgress(processor: (KotlinSliceUsage) -> Unit) { - if (this is KotlinSliceDereferenceUsage) return - - val element = runReadAction { element } - - @Suppress("UNCHECKED_CAST") - val uniqueProcessor = CommonProcessors.UniqueProcessor( - { - processor(it as KotlinSliceUsage) - true - }, - SliceUsageHashingStrategy - ) as Processor - - runReadAction { - if (params.dataFlowToThis) { - processUsagesFlownDownTo(element, uniqueProcessor) - } - else { - processUsagesFlownFromThe(element, uniqueProcessor) - } - } - } - - private fun buildTreeRepresentation(rootUsage: KotlinSliceUsage): String { - val visitedUsages = THashSet(SliceUsageHashingStrategy) - - fun TextChunk.render(): String { - var text = text - if (attributes.fontType == Font.BOLD) { - text = "$text" - } - return text - } - - fun process(usage: KotlinSliceUsage, indent: Int): String { - val isDuplicated = !visitedUsages.add(usage) - - return buildString { - val chunks = usage.text - append(chunks.first().render() + " ") - append("\t".repeat(indent)) - if (usage is KotlinSliceDereferenceUsage) { - append("DEREFERENCE: ") - } - append("[LAMBDA] ".repeat(usage.lambdaLevel)) - chunks.slice(1..chunks.size - 1).joinTo( - this, - separator = "", - prefix = if (isDuplicated) "DUPLICATE: " else "", - postfix = "\n" - ) { it.render() } - if (!isDuplicated) { - usage.processChildrenWithoutProgress { - append(process(it, indent + 1)) - } - } - }.replace(Regex(""), "") - } - - return process(rootUsage, 0) - } - - protected fun doTest(path: String) { - val mainFile = File(path) - val rootDir = mainFile.parentFile - - val namePrefix = FileUtil.getNameWithoutExtension(mainFile) - val extraFiles = rootDir.listFiles { _, name -> - name.startsWith("$namePrefix.") && PathUtil.getFileExtension(name).let { it == "kt" || it == "java" } - } - - myFixture.testDataPath = "${KotlinTestUtils.getHomeDirectory()}/${rootDir.path}" - - val fileText = FileUtil.loadFile(mainFile, true) - val flowKind = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// FLOW: ") - val withDereferences = InTextDirectivesUtils.isDirectiveDefined(fileText, "// WITH_DEREFERENCES") - val analysisParams = SliceAnalysisParams().apply { - dataFlowToThis = when (flowKind) { - "IN" -> true - "OUT" -> false - else -> throw AssertionError("Invalid flow kind: $flowKind") - } - showInstanceDereferences = withDereferences - scope = AnalysisScope(project) - } - - extraFiles.forEach { myFixture.configureByFile(it.name) } - val file = myFixture.configureByFile(mainFile.name) as KtFile - val elementAtCaret = file.findElementAt(editor.caretModel.offset) - val sliceProvider = KotlinSliceProvider() - val expression = sliceProvider.getExpressionAtCaret(elementAtCaret, analysisParams.dataFlowToThis)!! - val rootUsage = sliceProvider.createRootUsage(expression, analysisParams) - KotlinTestUtils.assertEqualsToFile(File(path.replace(".kt", ".results.txt")), buildTreeRepresentation(rootUsage)) - } -} \ No newline at end of file diff --git a/idea/tests/org/jetbrains/kotlin/idea/slicer/AbstractSlicerTreeTest.kt.172 b/idea/tests/org/jetbrains/kotlin/idea/slicer/AbstractSlicerTreeTest.kt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/tests/org/jetbrains/kotlin/idea/slicer/SlicerLeafGroupingTestGenerated.java.172 b/idea/tests/org/jetbrains/kotlin/idea/slicer/SlicerLeafGroupingTestGenerated.java.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/tests/org/jetbrains/kotlin/idea/slicer/SlicerNullnessGroupingTestGenerated.java.172 b/idea/tests/org/jetbrains/kotlin/idea/slicer/SlicerNullnessGroupingTestGenerated.java.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/tests/org/jetbrains/kotlin/idea/slicer/SlicerTestGenerated.java.172 b/idea/tests/org/jetbrains/kotlin/idea/slicer/SlicerTestGenerated.java.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/tests/org/jetbrains/kotlin/idea/slicer/SlicerTreeTestGenerated.java.172 b/idea/tests/org/jetbrains/kotlin/idea/slicer/SlicerTreeTestGenerated.java.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/tests/org/jetbrains/kotlin/idea/structureView/AbstractKotlinFileStructureTest.kt.172 b/idea/tests/org/jetbrains/kotlin/idea/structureView/AbstractKotlinFileStructureTest.kt.172 deleted file mode 100644 index ed5dcf1f320..00000000000 --- a/idea/tests/org/jetbrains/kotlin/idea/structureView/AbstractKotlinFileStructureTest.kt.172 +++ /dev/null @@ -1,87 +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.idea.structureView - -import com.intellij.ide.actions.ViewStructureAction -import com.intellij.ide.util.FileStructurePopup -import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider -import com.intellij.openapi.ui.Queryable.PrintInfo -import com.intellij.openapi.util.io.FileUtil -import com.intellij.ui.treeStructure.filtered.FilteringTreeStructure -import com.intellij.util.ui.tree.TreeUtil -import org.jetbrains.kotlin.idea.completion.test.configureWithExtraFile -import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase -import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor -import org.jetbrains.kotlin.idea.test.PluginTestCaseBase -import org.jetbrains.kotlin.test.InTextDirectivesUtils -import org.jetbrains.kotlin.test.KotlinTestUtils -import java.io.File - -abstract class AbstractKotlinFileStructureTest : KotlinLightCodeInsightFixtureTestCase() { - override fun getTestDataPath() = PluginTestCaseBase.getTestDataPathBase() + "/structureView/fileStructure" - - override fun getProjectDescriptor() = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE - - fun doTest(path: String) { - myFixture.configureWithExtraFile(path) - - val textEditor = TextEditorProvider.getInstance()!!.getTextEditor(myFixture.editor) - val popup = ViewStructureAction.createPopup(myFixture.project, textEditor) - - if (popup == null) throw AssertionError("popup mustn't be null") - - popup.createCenterPanel() - popup.treeBuilder.ui!!.updater!!.setPassThroughMode(true) - popup.update() - - popup.setup() - - val printInfo = PrintInfo(arrayOf("text"), arrayOf("location")) - val popupText = StructureViewUtil.print(popup.tree, false, printInfo, null) - KotlinTestUtils.assertEqualsToFile(File("${FileUtil.getNameWithoutExtension(path)}.after"), popupText) - } - - protected fun FileStructurePopup.setup() { - val fileText = FileUtil.loadFile(File(testDataPath, fileName()), true) - - val withInherited = InTextDirectivesUtils.isDirectiveDefined(fileText, "WITH_INHERITED") - setTreeActionState(KotlinInheritedMembersNodeProvider::class.java, withInherited) - } - - fun FileStructurePopup.update() { - treeBuilder.refilter()!!.doWhenProcessed { - getStructure().rebuild() - updateRecursively(getRootNode()) - treeBuilder.updateFromRoot() - - TreeUtil.expandAll(tree) - } - } - - fun FileStructurePopup.getFileStructureSpeedSearch() = speedSearch as FileStructurePopup.MyTreeSpeedSearch - - fun FileStructurePopup.getStructure() = treeBuilder.treeStructure as FilteringTreeStructure - - fun FileStructurePopup.getRootNode() = treeBuilder.rootElement as FilteringTreeStructure.FilteringNode - - fun FileStructurePopup.updateRecursively(node: FilteringTreeStructure.FilteringNode) { - node.update() - for (child in node.children()!!) { - updateRecursively(child) - } - } -} diff --git a/idea/tests/org/jetbrains/kotlin/idea/structureView/KotlinFileStructureTestBase.kt.172 b/idea/tests/org/jetbrains/kotlin/idea/structureView/KotlinFileStructureTestBase.kt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/idea/tests/org/jetbrains/kotlin/psi/KotlinInjectionTest.kt.172 b/idea/tests/org/jetbrains/kotlin/psi/KotlinInjectionTest.kt.172 deleted file mode 100644 index 579c03a95dc..00000000000 --- a/idea/tests/org/jetbrains/kotlin/psi/KotlinInjectionTest.kt.172 +++ /dev/null @@ -1,566 +0,0 @@ -/* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.kotlin.psi - -import com.intellij.lang.html.HTMLLanguage -import com.intellij.openapi.fileTypes.PlainTextLanguage -import org.intellij.lang.regexp.RegExpLanguage -import org.intellij.plugins.intelliLang.Configuration -import org.intellij.plugins.intelliLang.inject.config.BaseInjection -import org.intellij.plugins.intelliLang.inject.config.InjectionPlace - -class KotlinInjectionTest : AbstractInjectionTest() { - fun testInjectionOnJavaPredefinedMethodWithAnnotation() = doInjectionPresentTest( - """ - val test1 = java.util.regex.Pattern.compile("pattern") - """, - RegExpLanguage.INSTANCE.id, - unInjectShouldBePresent = false - ) - - fun testInjectionOnJavaCustomInjectionWithAnnotation() { - val customInjection = BaseInjection("java") - customInjection.injectedLanguageId = HTMLLanguage.INSTANCE.id - val elementPattern = customInjection.compiler.createElementPattern( - """psiParameter().ofMethod(2, psiMethod().withName("replace").withParameters("int", "int", "java.lang.String").definedInClass("java.lang.StringBuilder"))""", - "HTML temp rule") - customInjection.setInjectionPlaces(InjectionPlace(elementPattern, true)) - - try { - Configuration.getInstance().replaceInjections(listOf(customInjection), listOf(), true) - - doInjectionPresentTest( - """ - val stringBuilder = StringBuilder().replace(0, 0, "") - """, - HTMLLanguage.INSTANCE.id, - unInjectShouldBePresent = false - ) - } - finally { - Configuration.getInstance().replaceInjections(listOf(), listOf(customInjection), true) - } - } - - fun testInjectionWithCommentOnProperty() = doInjectionPresentTest( - """ - //language=file-reference - val test = "simple" - """) - - fun testInjectionWithUsageOnReceiverWithRuntime() = doInjectionPresentTest( - """ - val test = "some" - fun foo() = test.toRegex() - """, - languageId = RegExpLanguage.INSTANCE.id, unInjectShouldBePresent = false) - - fun testInjectionWithUsageInParameterWithRuntime() = doInjectionPresentTest( - """ - val test = "some" - fun foo() = Regex(test) - """, - languageId = RegExpLanguage.INSTANCE.id, unInjectShouldBePresent = false) - - fun testNoInjectionThoughSeveralAssignmentsWithRuntime() = assertNoInjection( - """ - val first = "some" - val test = first - fun foo() = Regex(test) - """) - - fun testInjectionWithMultipleCommentsOnFun() = doInjectionPresentTest( - """ - // Some comment - // Other comment - //language=file-reference - fun test() = "simple" - """) - - fun testInjectionWithAnnotationOnPropertyWithAnnotation() = doInjectionPresentTest( - """ - @org.intellij.lang.annotations.Language("file-reference") - val test = "simple" - """) - - fun testInjectWithCommentOnProperty() = doFileReferenceInjectTest( - """ - val test = "simple" - """, - """ - //language=file-reference - val test = "simple" - """ - ) - - fun testInjectWithCommentOnCommentedProperty() = doFileReferenceInjectTest( - """ - // Hello - val test = "simple" - """, - """ - // Hello - //language=file-reference - val test = "simple" - """ - ) - - fun testInjectWithCommentOnPropertyWithKDoc() = doFileReferenceInjectTest( - """ - /** - * Hi - */ - val test = "simple" - """, - """ - /** - * Hi - */ - //language=file-reference - val test = "simple" - """ - ) - - fun testInjectWithCommentOnExpression() = doFileReferenceInjectTest( - """ - fun test() { - "" - } - """, - """ - fun test() { - //language=file-reference - "" - } - """ - ) - - fun testInjectWithCommentOnDeepExpression() = doFileReferenceInjectTest( - """ - fun test() { - "" + "" - } - """, - """ - fun test() { - "" + "" - } - """ - ) - - fun testInjectOnPropertyWithAnnotation() = doFileReferenceInjectTest( - """ - val test = "simple" - """, - """ - import org.intellij.lang.annotations.Language - - @Language("file-reference") - val test = "simple" - """ - ) - - fun testInjectWithOnExpressionWithAnnotation() = doFileReferenceInjectTest( - """ - fun test() { - "" - } - """, - """ - fun test() { - //language=file-reference - "" - } - """ - ) - - // TODO: add test for non-default language annotation - - fun testRemoveInjectionWithAnnotation() = doRemoveInjectionTest( - """ - import org.intellij.lang.annotations.Language - - @Language("file-reference") - val test = "simple" - """, - """ - import org.intellij.lang.annotations.Language - - val test = "simple" - """ - ) - - fun testRemoveInjectionWithComment() = doRemoveInjectionTest( - """ - //language=file-reference - val test = "simple" - """, - """ - val test = "simple" - """ - ) - - fun testRemoveInjectionWithCommentNotFirst() = doRemoveInjectionTest( - """ - // Some comment. To do a language injection, add a line comment language=some instruction. - // language=file-reference - val test = "simple" - """, - """ - // Some comment. To do a language injection, add a line comment language=some instruction. - val test = "simple" - """ - ) - - fun testRemoveInjectionWithCommentAfterKDoc() = doRemoveInjectionTest( - """ - /**Property*/ - // language=file-reference - val test = "simple" - """, - """ - /**Property*/ - val test = "simple" - """ - ) - - fun testRemoveInjectionWithCommentInExpression() = doRemoveInjectionTest( - """ - fun test() { - // This is my favorite part - // language=RegExp - "something" - } - """, - """ - fun test() { - // This is my favorite part - "something" - } - """ - ) - - fun testInjectionWithUsageInFunctionWithMarkedParameterWithAnnotation() = doInjectionPresentTest( - """ - import org.intellij.lang.annotations.Language - - val v = "some" - - fun foo(@Language("HTML") s: String) {} - - fun other() { foo(v) } - """, - languageId = HTMLLanguage.INSTANCE.id, unInjectShouldBePresent = false) - - fun testInjectionOfCustomParameterWithAnnotation() = doInjectionPresentTest( - """ - import org.intellij.lang.annotations.Language - - fun foo(@Language("HTML") s: String) {} - - fun other() { foo("some") } - """, - languageId = HTMLLanguage.INSTANCE.id, unInjectShouldBePresent = false) - - fun testInjectionOfCustomParameterInConstructorWithAnnotation() = doInjectionPresentTest( - """ - import org.intellij.lang.annotations.Language - - class Test(@Language("HTML") val s: String) - - fun other() { Test("some") } - """, - languageId = HTMLLanguage.INSTANCE.id, unInjectShouldBePresent = false) - - fun testInjectionOfCustomParameterDefaultCallWithAnnotation() = doInjectionPresentTest( - """ - import org.intellij.lang.annotations.Language - - fun foo(@Language("HTML") s: String) {} - - fun other() { foo(s = "some") } - """, - languageId = HTMLLanguage.INSTANCE.id, unInjectShouldBePresent = false) - - fun testInjectionOfCustomParameterInJavaConstructorWithAnnotationWithAnnotation() = doInjectionPresentTest( - """ - fun bar() { Test("some") } - """, - javaText = - """ - import org.intellij.lang.annotations.Language; - - public class Test { - public Test(@Language("HTML") String str) {} - } - """, - languageId = HTMLLanguage.INSTANCE.id, unInjectShouldBePresent = false - ) - - fun testInjectionOfCustomParameterJavaWithAnnotation() = doInjectionPresentTest( - """ - fun bar() { Test.foo("some") } - """, - javaText = - """ - import org.intellij.lang.annotations.Language; - - public class Test { - public static void foo(@Language("HTML") String str) {} - } - """, - languageId = HTMLLanguage.INSTANCE.id, unInjectShouldBePresent = false - ) - - fun testInjectionOnInterpolationWithAnnotation() = doInjectionPresentTest( - """ - val b = 2 - - @org.intellij.lang.annotations.Language("HTML") - val test = "simple${'$'}{b}.kt" - """, - unInjectShouldBePresent = false, - shreds = listOf( - ShredInfo(range(0, 6), hostRange=range(1, 7)), - ShredInfo(range(6, 21), hostRange=range(11, 14), prefix="missingValue") - ) - ) - - fun testInjectionOnInterpolatedStringWithComment() = doInjectionPresentTest( - """ - val some = 42 - // language=HTML - val test = "ml>${'$'}some" - """, - languageId = HTMLLanguage.INSTANCE.id, unInjectShouldBePresent = false, - shreds = listOf( - ShredInfo(range(0, 6), hostRange = range(1, 7)), - ShredInfo(range(6, 17), hostRange = range(12, 19), prefix="some")) - ) - - fun testEditorShortShreadsInInterpolatedInjection() = doInjectionPresentTest( - """ - val s = 42 - // language=TEXT - val test = "${'$'}s text ${'$'}s${'$'}{s}${'$'}s text ${'$'}s" - """, - languageId = PlainTextLanguage.INSTANCE.id, unInjectShouldBePresent = false, - shreds = listOf( - ShredInfo(range(0, 0), hostRange=range(1, 1)), - ShredInfo(range(0, 7), hostRange=range(3, 9), prefix="s"), - ShredInfo(range(7, 8), hostRange=range(11, 11), prefix="s"), - ShredInfo(range(8, 20), hostRange=range(15, 15), prefix="missingValue"), - ShredInfo(range(20, 27), hostRange=range(17, 23), prefix="s"), - ShredInfo(range(27, 28), hostRange=range(25, 25), prefix="s") - ) - ) - - fun testEditorLongShreadsInInterpolatedInjection() = doInjectionPresentTest( - """ - val s = 42 - // language=TEXT - val test = "${'$'}{s} text ${'$'}{s}${'$'}s${'$'}{s} text ${'$'}{s}" - """, - languageId = PlainTextLanguage.INSTANCE.id, unInjectShouldBePresent = false, - shreds = listOf( - ShredInfo(range(0, 0), hostRange=range(1, 1)), - ShredInfo(range(0, 18), hostRange=range(5, 11), prefix="missingValue"), - ShredInfo(range(18, 30), hostRange=range(15, 15), prefix="missingValue"), - ShredInfo(range(30, 31), hostRange=range(17, 17), prefix="s"), - ShredInfo(range(31, 49), hostRange=range(21, 27), prefix="missingValue"), - ShredInfo(range(49, 61), hostRange=range(31, 31), prefix="missingValue") - ) - ) - - fun testEditorShreadsWithEscapingInjection() = doInjectionPresentTest( - """ - // language=TEXT - val test = "\rtext\ttext\n\t" - """, - languageId = PlainTextLanguage.INSTANCE.id, unInjectShouldBePresent = false, - shreds = listOf( - ShredInfo(range(0, 12), hostRange=range(1, 17)) - ) - ) - - fun testEditorShreadsInInterpolatedWithEscapingInjection() = doInjectionPresentTest( - """ - val s = 1 - // language=TEXT - val test = "\r${'$'}s text${'$'}s\ttext\n\t" - """, - languageId = PlainTextLanguage.INSTANCE.id, unInjectShouldBePresent = false, - shreds = listOf( - ShredInfo(range(0, 1), hostRange=range(1, 3)), - ShredInfo(range(1, 7), hostRange=range(5, 10), prefix="s"), - ShredInfo(range(7, 15), hostRange=range(12, 22), prefix="s") - ) - ) - - fun testSuffixPrefixWithAnnotation() = doInjectionPresentTest( - """ - @org.intellij.lang.annotations.Language("TEXT", prefix = "abc", suffix = "ghi") - val test = "def" - """, - languageId = PlainTextLanguage.INSTANCE.id, unInjectShouldBePresent = false, - shreds = listOf(ShredInfo(range(0, 9), hostRange=range(1, 4), prefix = "abc", suffix = "ghi")) - ) - - fun testSuffixPrefixInComment() = doInjectionPresentTest( - """ - // language="TEXT" prefix="abc" suffix=ghi - val test = "def" - """, - languageId = PlainTextLanguage.INSTANCE.id, unInjectShouldBePresent = false, - shreds = listOf(ShredInfo(range(0, 9), hostRange=range(1, 4), prefix = "abc", suffix = "ghi")) - ) - - fun testJavaAnnotationsPattern() { - val customInjection = BaseInjection("java") - customInjection.injectedLanguageId = RegExpLanguage.INSTANCE.id - val elementPattern = customInjection.compiler.createElementPattern( - """psiMethod().withName("value").withParameters().definedInClass("Matches")""", - "temp rule") - customInjection.setInjectionPlaces(InjectionPlace(elementPattern, true)) - - try { - Configuration.getInstance().replaceInjections(listOf(customInjection), listOf(), true) - - doInjectionPresentTest( - javaText = """ - @interface Matches { String value(); } - """, - text = """ - @Matches("[A-Z][a-z]+") - val name = "John" - """, - languageId = RegExpLanguage.INSTANCE.id, - unInjectShouldBePresent = false - ) - - doInjectionPresentTest( - javaText = """ - @interface Matches { String value(); } - """, - text = """ - @Matches(value = "[A-Z][a-z]+") - val name = "John" - """, - languageId = RegExpLanguage.INSTANCE.id, - unInjectShouldBePresent = false - ) - } - finally { - Configuration.getInstance().replaceInjections(listOf(), listOf(customInjection), true) - } - } - - fun testKotlinAnnotationsPattern() { - val customInjection = BaseInjection("kotlin") - customInjection.injectedLanguageId = RegExpLanguage.INSTANCE.id - val elementPattern = customInjection.compiler.createElementPattern( - """kotlinParameter().ofFunction(0, kotlinFunction().withName("Matches").definedInClass("Matches"))""".trimIndent(), - "temp rule") - customInjection.setInjectionPlaces(InjectionPlace(elementPattern, true)) - - try { - Configuration.getInstance().replaceInjections(listOf(customInjection), listOf(), true) - - doInjectionPresentTest( - text = """ - annotation class Matches(val pattern: String) - - @Matches("[A-Z][a-z]+") - val name = "John" - """, - languageId = RegExpLanguage.INSTANCE.id, - unInjectShouldBePresent = false - ) - - doInjectionPresentTest( - text = """ - annotation class Matches(val pattern: String) - - @Matches(pattern = "[A-Z][a-z]+") - val name = "John" - """, - languageId = RegExpLanguage.INSTANCE.id, - unInjectShouldBePresent = false - ) - } - finally { - Configuration.getInstance().replaceInjections(listOf(), listOf(customInjection), true) - } - } - - fun testInjectionOnReturnResultWithAnnotation() = doInjectionPresentTest( - """ - import org.intellij.lang.annotations.Language - - @Language("HTML") - fun htmlProvider(): String { - return "ml>" - } - """, - languageId = HTMLLanguage.INSTANCE.id, unInjectShouldBePresent = false - ) - - fun testInjectionOnReturnResultWithElvisWithAnnotation() = doInjectionPresentTest( - """ - import org.intellij.lang.annotations.Language - - @Language("HTML") - fun htmlProvider(arg: String?): String { - return arg ?: "ml>" - } - """, - languageId = HTMLLanguage.INSTANCE.id, unInjectShouldBePresent = false - ) - - fun testInjectionOnReturnResultWithIfWithAnnotation() = doInjectionPresentTest( - """ - import org.intellij.lang.annotations.Language - - @Language("HTML") - fun htmlProvider(arg: String?): String { - return if (arg == null) "
" else "ml>" - } - """, - languageId = HTMLLanguage.INSTANCE.id, unInjectShouldBePresent = false - ) - - fun testInjectionExpressionBodyWithAnnotation() = doInjectionPresentTest( - """ - import org.intellij.lang.annotations.Language - - @Language("HTML") - fun htmlProvider() = "ml>" - """, - languageId = HTMLLanguage.INSTANCE.id, unInjectShouldBePresent = false - ) - - fun testInjectionExpressionBodyElvisWithAnnotation() = doInjectionPresentTest( - """ - import org.intellij.lang.annotations.Language - - @Language("HTML") - fun htmlProvider(arg: String?) = arg ?: "ml>" - """, - languageId = HTMLLanguage.INSTANCE.id, unInjectShouldBePresent = false - ) - -} diff --git a/j2k/tests/org/jetbrains/kotlin/j2k/AbstractJavaToKotlinConverterForWebDemoTest.kt.172 b/j2k/tests/org/jetbrains/kotlin/j2k/AbstractJavaToKotlinConverterForWebDemoTest.kt.172 deleted file mode 100644 index 84d0a7dc3ab..00000000000 --- a/j2k/tests/org/jetbrains/kotlin/j2k/AbstractJavaToKotlinConverterForWebDemoTest.kt.172 +++ /dev/null @@ -1,128 +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.j2k - -import com.intellij.codeInsight.ContainerProvider -import com.intellij.codeInsight.NullableNotNullManager -import com.intellij.codeInsight.runner.JavaMainMethodProvider -import com.intellij.core.CoreApplicationEnvironment -import com.intellij.core.JavaCoreApplicationEnvironment -import com.intellij.core.JavaCoreProjectEnvironment -import com.intellij.lang.MetaLanguage -import com.intellij.openapi.extensions.Extensions -import com.intellij.openapi.extensions.ExtensionsArea -import com.intellij.openapi.fileTypes.FileTypeExtensionPoint -import com.intellij.openapi.util.Disposer -import com.intellij.openapi.util.io.FileUtil -import com.intellij.psi.FileContextProvider -import com.intellij.psi.PsiElement -import com.intellij.psi.PsiElementFinder -import com.intellij.psi.PsiModifierListOwner -import com.intellij.psi.augment.PsiAugmentProvider -import com.intellij.psi.augment.TypeAnnotationModifier -import com.intellij.psi.compiled.ClassFileDecompilers -import com.intellij.psi.impl.JavaClassSupersImpl -import com.intellij.psi.impl.PsiTreeChangePreprocessor -import com.intellij.psi.impl.compiled.ClsCustomNavigationPolicy -import com.intellij.psi.meta.MetaDataContributor -import com.intellij.psi.stubs.BinaryFileStubBuilders -import com.intellij.psi.util.JavaClassSupers -import junit.framework.TestCase -import org.jetbrains.kotlin.utils.PathUtil -import java.io.File -import java.net.URLClassLoader - -abstract class AbstractJavaToKotlinConverterForWebDemoTest : TestCase() { - val DISPOSABLE = Disposer.newDisposable() - - fun doTest(javaPath: String) { - try { - val fileContents = FileUtil.loadFile(File(javaPath), true) - val javaCoreEnvironment: JavaCoreProjectEnvironment = setUpJavaCoreEnvironment() - translateToKotlin(fileContents, javaCoreEnvironment.project) - } - finally { - Disposer.dispose(DISPOSABLE) - } - } - - fun setUpJavaCoreEnvironment(): JavaCoreProjectEnvironment { - Extensions.cleanRootArea(DISPOSABLE) - val area = Extensions.getRootArea() - - registerExtensionPoints(area) - - val applicationEnvironment = JavaCoreApplicationEnvironment(DISPOSABLE) - val javaCoreEnvironment = object : JavaCoreProjectEnvironment(DISPOSABLE, applicationEnvironment) { - override fun preregisterServices() { - val projectArea = Extensions.getArea(project) - CoreApplicationEnvironment.registerExtensionPoint(projectArea, PsiTreeChangePreprocessor.EP_NAME, PsiTreeChangePreprocessor::class.java) - CoreApplicationEnvironment.registerExtensionPoint(projectArea, PsiElementFinder.EP_NAME, PsiElementFinder::class.java) - } - } - - javaCoreEnvironment.project.registerService(NullableNotNullManager::class.java, object : NullableNotNullManager(javaCoreEnvironment.project) { - override fun isNullable(owner: PsiModifierListOwner, checkBases: Boolean) = !isNotNull(owner, checkBases) - override fun isNotNull(owner: PsiModifierListOwner, checkBases: Boolean) = true - override fun hasHardcodedContracts(element: PsiElement): Boolean = false - override fun getPredefinedNotNulls() = emptyList() - }) - - applicationEnvironment.application.registerService(JavaClassSupers::class.java, JavaClassSupersImpl::class.java) - - for (root in PathUtil.getJdkClassesRootsFromCurrentJre()) { - javaCoreEnvironment.addJarToClassPath(root) - } - val annotations: File? = findAnnotations() - if (annotations != null && annotations.exists()) { - javaCoreEnvironment.addJarToClassPath(annotations) - } - return javaCoreEnvironment - } - - private fun registerExtensionPoints(area: ExtensionsArea) { - CoreApplicationEnvironment.registerExtensionPoint(area, BinaryFileStubBuilders.EP_NAME, FileTypeExtensionPoint::class.java) - CoreApplicationEnvironment.registerExtensionPoint(area, FileContextProvider.EP_NAME, FileContextProvider::class.java) - - CoreApplicationEnvironment.registerExtensionPoint(area, MetaDataContributor.EP_NAME, MetaDataContributor::class.java) - CoreApplicationEnvironment.registerExtensionPoint(area, PsiAugmentProvider.EP_NAME, PsiAugmentProvider::class.java) - CoreApplicationEnvironment.registerExtensionPoint(area, JavaMainMethodProvider.EP_NAME, JavaMainMethodProvider::class.java) - - CoreApplicationEnvironment.registerExtensionPoint(area, ContainerProvider.EP_NAME, ContainerProvider::class.java) - CoreApplicationEnvironment.registerExtensionPoint(area, ClsCustomNavigationPolicy.EP_NAME, ClsCustomNavigationPolicy::class.java) - CoreApplicationEnvironment.registerExtensionPoint(area, ClassFileDecompilers.EP_NAME, ClassFileDecompilers.Decompiler::class.java) - - CoreApplicationEnvironment.registerExtensionPoint(area, TypeAnnotationModifier.EP_NAME, TypeAnnotationModifier::class.java) - CoreApplicationEnvironment.registerExtensionPoint(area, MetaLanguage.EP_NAME, MetaLanguage::class.java) - } - - fun findAnnotations(): File? { - var classLoader = JavaToKotlinTranslator::class.java.classLoader - while (classLoader != null) { - val loader = classLoader - if (loader is URLClassLoader) { - for (url in loader.urLs) { - if ("file" == url.protocol && url.file!!.endsWith("/annotations.jar")) { - return File(url.file!!) - } - } - } - classLoader = classLoader.parent - } - return null - } -} diff --git a/jps-plugin/jps-tests/test/org/jetbrains/kotlin/jps/build/KotlinJpsBuildTest.kt.172 b/jps-plugin/jps-tests/test/org/jetbrains/kotlin/jps/build/KotlinJpsBuildTest.kt.172 deleted file mode 100644 index 6738778597a..00000000000 --- a/jps-plugin/jps-tests/test/org/jetbrains/kotlin/jps/build/KotlinJpsBuildTest.kt.172 +++ /dev/null @@ -1,1159 +0,0 @@ -/* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.kotlin.jps.build - -import com.google.common.collect.Lists -import com.intellij.openapi.util.io.FileUtil -import com.intellij.openapi.util.io.FileUtil.toSystemIndependentName -import com.intellij.openapi.util.io.FileUtilRt -import com.intellij.openapi.util.text.StringUtil -import com.intellij.openapi.vfs.StandardFileSystems -import com.intellij.testFramework.LightVirtualFile -import com.intellij.testFramework.UsefulTestCase -import com.intellij.util.io.URLUtil -import com.intellij.util.io.ZipUtil -import junit.framework.TestCase -import org.jetbrains.jps.ModuleChunk -import org.jetbrains.jps.api.CanceledStatus -import org.jetbrains.jps.builders.BuildResult -import org.jetbrains.jps.builders.CompileScopeTestBuilder -import org.jetbrains.jps.builders.JpsBuildTestCase -import org.jetbrains.jps.builders.TestProjectBuilderLogger -import org.jetbrains.jps.builders.impl.BuildDataPathsImpl -import org.jetbrains.jps.builders.logging.BuildLoggingManager -import org.jetbrains.jps.cmdline.ProjectDescriptor -import org.jetbrains.jps.devkit.model.JpsPluginModuleType -import org.jetbrains.jps.incremental.BuilderRegistry -import org.jetbrains.jps.incremental.CompileContext -import org.jetbrains.jps.incremental.IncProjectBuilder -import org.jetbrains.jps.incremental.ModuleLevelBuilder -import org.jetbrains.jps.incremental.messages.BuildMessage -import org.jetbrains.jps.incremental.messages.CompilerMessage -import org.jetbrains.jps.model.JpsModuleRootModificationUtil -import org.jetbrains.jps.model.JpsProject -import org.jetbrains.jps.model.java.JavaSourceRootType -import org.jetbrains.jps.model.java.JpsJavaDependencyScope -import org.jetbrains.jps.model.java.JpsJavaExtensionService -import org.jetbrains.jps.model.java.JpsJavaSdkType -import org.jetbrains.jps.model.library.JpsOrderRootType -import org.jetbrains.jps.model.module.JpsModule -import org.jetbrains.jps.util.JpsPathUtil -import org.jetbrains.kotlin.cli.common.Usage -import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments -import org.jetbrains.kotlin.cli.jvm.K2JVMCompiler -import org.jetbrains.kotlin.codegen.AsmUtil -import org.jetbrains.kotlin.codegen.JvmCodegenUtil -import org.jetbrains.kotlin.config.ApiVersion -import org.jetbrains.kotlin.config.IncrementalCompilation -import org.jetbrains.kotlin.config.KotlinCompilerVersion.TEST_IS_PRE_RELEASE_SYSTEM_PROPERTY -import org.jetbrains.kotlin.incremental.CacheVersion -import org.jetbrains.kotlin.incremental.components.LookupTracker -import org.jetbrains.kotlin.incremental.withIC -import org.jetbrains.kotlin.jps.model.JpsKotlinCompilerSettings -import org.jetbrains.kotlin.jps.build.KotlinJpsBuildTest.LibraryDependency.* -import org.jetbrains.kotlin.jps.model.kotlinCommonCompilerArguments -import org.jetbrains.kotlin.jps.model.kotlinCompilerArguments -import org.jetbrains.kotlin.jps.platforms.productionBuildTarget -import org.jetbrains.kotlin.load.kotlin.PackagePartClassUtils -import org.jetbrains.kotlin.name.FqName -import org.jetbrains.kotlin.test.KotlinTestUtils -import org.jetbrains.kotlin.test.MockLibraryUtil -import org.jetbrains.kotlin.utils.PathUtil -import org.jetbrains.kotlin.utils.Printer -import org.jetbrains.org.objectweb.asm.ClassReader -import org.jetbrains.org.objectweb.asm.ClassVisitor -import org.jetbrains.org.objectweb.asm.MethodVisitor -import org.jetbrains.org.objectweb.asm.Opcodes -import org.junit.Assert -import java.io.* -import java.net.URLClassLoader -import java.nio.file.Paths -import java.util.* -import java.util.zip.ZipOutputStream - -open class KotlinJpsBuildTest : AbstractKotlinJpsBuildTestCase() { - companion object { - private val PROJECT_NAME = "kotlinProject" - private val ADDITIONAL_MODULE_NAME = "module2" - private val JDK_NAME = "IDEA_JDK" - - private val EXCLUDE_FILES = arrayOf("Excluded.class", "YetAnotherExcluded.class") - private val NOTHING = arrayOf() - private val KOTLIN_JS_LIBRARY = "jslib-example" - private val PATH_TO_KOTLIN_JS_LIBRARY = AbstractKotlinJpsBuildTestCase.TEST_DATA_PATH + "general/KotlinJavaScriptProjectWithDirectoryAsLibrary/" + KOTLIN_JS_LIBRARY - private val KOTLIN_JS_LIBRARY_JAR = "$KOTLIN_JS_LIBRARY.jar" - - private fun getMethodsOfClass(classFile: File): Set { - val result = TreeSet() - ClassReader(FileUtil.loadFileBytes(classFile)).accept(object : ClassVisitor(Opcodes.ASM5) { - override fun visitMethod(access: Int, name: String, desc: String, signature: String?, exceptions: Array?): MethodVisitor? { - result.add(name) - return null - } - }, 0) - return result - } - - @JvmStatic - protected fun assertFilesExistInOutput(module: JpsModule, vararg relativePaths: String) { - for (path in relativePaths) { - val outputFile = findFileInOutputDir(module, path) - assertTrue("Output not written: " + outputFile.absolutePath + "\n Directory contents: \n" + dirContents(outputFile.parentFile), outputFile.exists()) - } - } - - @JvmStatic - protected fun findFileInOutputDir(module: JpsModule, relativePath: String): File { - val outputUrl = JpsJavaExtensionService.getInstance().getOutputUrl(module, false) - assertNotNull(outputUrl) - val outputDir = File(JpsPathUtil.urlToPath(outputUrl)) - return File(outputDir, relativePath) - } - - - @JvmStatic - protected fun assertFilesNotExistInOutput(module: JpsModule, vararg relativePaths: String) { - val outputUrl = JpsJavaExtensionService.getInstance().getOutputUrl(module, false) - assertNotNull(outputUrl) - val outputDir = File(JpsPathUtil.urlToPath(outputUrl)) - for (path in relativePaths) { - val outputFile = File(outputDir, path) - assertFalse("Output directory \"" + outputFile.absolutePath + "\" contains \"" + path + "\"", outputFile.exists()) - } - } - - private fun dirContents(dir: File): String { - val files = dir.listFiles() ?: return "" - val builder = StringBuilder() - for (file in files) { - builder.append(" * ").append(file.name).append("\n") - } - return builder.toString() - } - - @JvmStatic - protected fun klass(moduleName: String, classFqName: String): String { - val outputDirPrefix = "out/production/$moduleName/" - return outputDirPrefix + classFqName.replace('.', '/') + ".class" - } - - @JvmStatic - protected fun module(moduleName: String): String { - return "out/production/$moduleName/${JvmCodegenUtil.getMappingFileName(moduleName)}" - } - } - - annotation class WorkingDir(val name: String) - - enum class LibraryDependency { - NONE, - JVM_MOCK_RUNTIME, - JVM_FULL_RUNTIME, - JS_STDLIB, - } - - protected lateinit var originalProjectDir: File - private val expectedOutputFile: File - get() = File(originalProjectDir, "expected-output.txt") - - override fun setUp() { - super.setUp() - val currentTestMethod = this::class.members.firstOrNull { it.name == "test" + getTestName(false) } - val workingDirFromAnnotation = currentTestMethod?.annotations?.filterIsInstance()?.firstOrNull()?.name - val projDirPath = Paths.get(TEST_DATA_PATH, "general", workingDirFromAnnotation ?: getTestName(false)) - originalProjectDir = projDirPath.toFile() - workDir = AbstractKotlinJpsBuildTestCase.copyTestDataToTmpDir(originalProjectDir) - orCreateProjectDir - } - - override fun tearDown() { - FileUtil.delete(workDir) - super.tearDown() - } - - override fun doGetProjectDir(): File = workDir - - protected fun initProject(libraryDependency: LibraryDependency = NONE) { - addJdk(JDK_NAME) - loadProject(workDir.absolutePath + File.separator + PROJECT_NAME + ".ipr") - - when (libraryDependency) { - NONE -> {} - JVM_MOCK_RUNTIME -> addKotlinMockRuntimeDependency() - JVM_FULL_RUNTIME -> addKotlinStdlibDependency() - JS_STDLIB -> addKotlinJavaScriptStdlibDependency() - } - } - - fun doTest() { - initProject(JVM_MOCK_RUNTIME) - buildAllModules().assertSuccessful() - } - - fun doTestWithRuntime() { - initProject(JVM_FULL_RUNTIME) - buildAllModules().assertSuccessful() - } - - fun doTestWithKotlinJavaScriptLibrary() { - initProject(JS_STDLIB) - createKotlinJavaScriptLibraryArchive() - addDependency(KOTLIN_JS_LIBRARY, File(workDir, KOTLIN_JS_LIBRARY_JAR)) - buildAllModules().assertSuccessful() - } - - fun testKotlinProject() { - doTest() - - checkWhen(touch("src/test1.kt"), null, packageClasses("kotlinProject", "src/test1.kt", "Test1Kt")) - } - - fun testSourcePackagePrefix() { - doTest() - } - - fun testSourcePackageLongPrefix() { - initProject() - val buildResult = buildAllModules() - buildResult.assertSuccessful() - val warnings = buildResult.getMessages(BuildMessage.Kind.WARNING) - assertEquals("Warning about invalid package prefix in module 2 is expected: $warnings", 1, warnings.size) - assertEquals("Invalid package prefix name is ignored: invalid-prefix.test", warnings.first().messageText) - } - - fun testSourcePackagePrefixWithInnerClasses() { - initProject() - buildAllModules().assertSuccessful() - } - - fun testKotlinJavaScriptProject() { - initProject(JS_STDLIB) - buildAllModules().assertSuccessful() - - checkOutputFilesList() - checkWhen(touch("src/test1.kt"), null, pathsToDelete = k2jsOutput(PROJECT_NAME)) - } - - private fun k2jsOutput(vararg moduleNames: String): Array { - val moduleNamesSet = moduleNames.toSet() - val list = mutableListOf() - - myProject.modules.forEach { - if (it.name in moduleNamesSet) { - val outputDir = it.productionBuildTarget.outputDir!! - list.add(toSystemIndependentName(File("$outputDir/${it.name}.js").relativeTo(workDir).path)) - list.add(toSystemIndependentName(File("$outputDir/${it.name}.meta.js").relativeTo(workDir).path)) - - val kjsmFiles = outputDir.walk() - .filter { it.isFile && it.extension.equals("kjsm", ignoreCase = true) } - - list.addAll(kjsmFiles.map { toSystemIndependentName(it.relativeTo(workDir).path) }) - } - } - - return list.toTypedArray() - } - - fun testKotlinJavaScriptProjectWithCustomOutputPaths() { - initProject(JS_STDLIB) - buildAllModules().assertSuccessful() - - checkOutputFilesList(File(workDir, "target")) - } - - fun testKotlinJavaScriptProjectWithSourceMap() { - initProject(JS_STDLIB) - buildAllModules().assertSuccessful() - - val sourceMapContent = File(getOutputDir(PROJECT_NAME), "$PROJECT_NAME.js.map").readText() - val expectedPath = "prefix-dir/src/pkg/test1.kt" - assertTrue("Source map file should contain relative path ($expectedPath)", sourceMapContent.contains("\"$expectedPath\"")) - - val librarySourceMapFile = File(getOutputDir(PROJECT_NAME), "lib/kotlin.js.map") - assertTrue("Source map for stdlib should be copied to $librarySourceMapFile", librarySourceMapFile.exists()) - } - - fun testKotlinJavaScriptProjectWithSourceMapRelativePaths() { - initProject(JS_STDLIB) - buildAllModules().assertSuccessful() - - val sourceMapContent = File(getOutputDir(PROJECT_NAME), "$PROJECT_NAME.js.map").readText() - val expectedPath = "../../../src/pkg/test1.kt" - assertTrue("Source map file should contain relative path ($expectedPath)", sourceMapContent.contains("\"$expectedPath\"")) - - val librarySourceMapFile = File(getOutputDir(PROJECT_NAME), "lib/kotlin.js.map") - assertTrue("Source map for stdlib should be copied to $librarySourceMapFile", librarySourceMapFile.exists()) - } - - fun testKotlinJavaScriptProjectWithTwoModules() { - initProject(JS_STDLIB) - buildAllModules().assertSuccessful() - - checkOutputFilesList() - checkWhen(touch("src/test1.kt"), null, k2jsOutput(PROJECT_NAME)) - checkWhen(touch("module2/src/module2.kt"), null, k2jsOutput(ADDITIONAL_MODULE_NAME)) - checkWhen(arrayOf(touch("src/test1.kt"), touch("module2/src/module2.kt")), null, k2jsOutput(PROJECT_NAME, ADDITIONAL_MODULE_NAME)) - } - - @WorkingDir("KotlinJavaScriptProjectWithTwoModules") - fun testKotlinJavaScriptProjectWithTwoModulesAndWithLibrary() { - initProject() - createKotlinJavaScriptLibraryArchive() - addDependency(KOTLIN_JS_LIBRARY, File(workDir, KOTLIN_JS_LIBRARY_JAR)) - addKotlinJavaScriptStdlibDependency() - buildAllModules().assertSuccessful() - } - - fun testKotlinJavaScriptProjectWithDirectoryAsStdlib() { - initProject() - val jslibJar = PathUtil.kotlinPathsForDistDirectory.jsStdLibJarPath - val jslibDir = File(workDir, "KotlinJavaScript") - try { - ZipUtil.extract(jslibJar, jslibDir, null) - } - catch (ex: IOException) { - throw IllegalStateException(ex.message) - } - - addDependency("KotlinJavaScript", jslibDir) - buildAllModules().assertSuccessful() - - checkOutputFilesList() - checkWhen(touch("src/test1.kt"), null, k2jsOutput(PROJECT_NAME)) - } - - fun testKotlinJavaScriptProjectWithDirectoryAsLibrary() { - initProject(JS_STDLIB) - addDependency(KOTLIN_JS_LIBRARY, File(workDir, KOTLIN_JS_LIBRARY)) - buildAllModules().assertSuccessful() - - checkOutputFilesList() - checkWhen(touch("src/test1.kt"), null, k2jsOutput(PROJECT_NAME)) - } - - fun testKotlinJavaScriptProjectWithLibrary() { - doTestWithKotlinJavaScriptLibrary() - - checkOutputFilesList() - checkWhen(touch("src/test1.kt"), null, k2jsOutput(PROJECT_NAME)) - } - - fun testKotlinJavaScriptProjectWithLibraryCustomOutputDir() { - doTestWithKotlinJavaScriptLibrary() - - checkOutputFilesList() - checkWhen(touch("src/test1.kt"), null, k2jsOutput(PROJECT_NAME)) - } - - fun testKotlinJavaScriptProjectWithLibraryNoCopy() { - doTestWithKotlinJavaScriptLibrary() - - checkOutputFilesList() - checkWhen(touch("src/test1.kt"), null, k2jsOutput(PROJECT_NAME)) - } - - fun testKotlinJavaScriptProjectWithLibraryAndErrors() { - initProject(JS_STDLIB) - createKotlinJavaScriptLibraryArchive() - addDependency(KOTLIN_JS_LIBRARY, File(workDir, KOTLIN_JS_LIBRARY_JAR)) - buildAllModules().assertFailed() - - checkOutputFilesList() - } - - fun testKotlinJavaScriptProjectWithEmptyDependencies() { - initProject(JS_STDLIB) - buildAllModules().assertSuccessful() - } - - fun testKotlinJavaScriptInternalFromSpecialRelatedModule() { - initProject(JS_STDLIB) - buildAllModules().assertSuccessful() - } - - fun testKotlinJavaScriptProjectWithTests() { - initProject(JS_STDLIB) - buildAllModules().assertSuccessful() - } - - fun testKotlinJavaScriptProjectWithTestsAndSeparateTestAndSrcModuleDependencies() { - initProject(JS_STDLIB) - buildAllModules().assertSuccessful() - } - - fun testKotlinJavaScriptProjectWithTestsAndTestAndSrcModuleDependency() { - initProject(JS_STDLIB) - val buildResult = buildAllModules() - buildResult.assertSuccessful() - - val warnings = buildResult.getMessages(BuildMessage.Kind.WARNING) - assertEquals("Warning about duplicate module definition: $warnings", 0, warnings.size) - } - - fun testKotlinJavaScriptProjectWithTwoSrcModuleDependency() { - initProject(JS_STDLIB) - val buildResult = buildAllModules() - buildResult.assertSuccessful() - - val warnings = buildResult.getMessages(BuildMessage.Kind.WARNING) - assertEquals("Warning about duplicate module definition: $warnings", 0, warnings.size) - } - - fun testExcludeFolderInSourceRoot() { - doTest() - - val module = myProject.modules.get(0) - assertFilesExistInOutput(module, "Foo.class") - assertFilesNotExistInOutput(module, *EXCLUDE_FILES) - - checkWhen( - touch("src/foo.kt"), null, - arrayOf(klass("kotlinProject", "Foo"), module("kotlinProject")) - ) - } - - fun testExcludeModuleFolderInSourceRootOfAnotherModule() { - doTest() - - for (module in myProject.modules) { - assertFilesExistInOutput(module, "Foo.class") - } - - checkWhen( - touch("src/foo.kt"), null, - arrayOf(klass("kotlinProject", "Foo"), module("kotlinProject")) - ) - checkWhen( - touch("src/module2/src/foo.kt"), null, - arrayOf(klass("module2", "Foo"), module("module2")) - ) - } - - fun testExcludeFileUsingCompilerSettings() { - doTest() - - val module = myProject.modules.get(0) - assertFilesExistInOutput(module, "Foo.class", "Bar.class") - assertFilesNotExistInOutput(module, *EXCLUDE_FILES) - - if (IncrementalCompilation.isEnabledForJvm()) { - checkWhen(touch("src/foo.kt"), null, arrayOf(module("kotlinProject"), klass("kotlinProject", "Foo"))) - } - else { - val allClasses = myProject.outputPaths() - checkWhen(touch("src/foo.kt"), null, allClasses) - } - - checkWhen(touch("src/Excluded.kt"), null, NOTHING) - checkWhen(touch("src/dir/YetAnotherExcluded.kt"), null, NOTHING) - } - - fun testExcludeFolderNonRecursivelyUsingCompilerSettings() { - doTest() - - val module = myProject.modules.get(0) - assertFilesExistInOutput(module, "Foo.class", "Bar.class") - assertFilesNotExistInOutput(module, *EXCLUDE_FILES) - - if (IncrementalCompilation.isEnabledForJvm()) { - checkWhen(touch("src/foo.kt"), null, arrayOf(module("kotlinProject"), klass("kotlinProject", "Foo"))) - checkWhen(touch("src/dir/subdir/bar.kt"), null, arrayOf(module("kotlinProject"), klass("kotlinProject", "Bar"))) - } - else { - val allClasses = myProject.outputPaths() - checkWhen(touch("src/foo.kt"), null, allClasses) - checkWhen(touch("src/dir/subdir/bar.kt"), null, allClasses) - } - - checkWhen(touch("src/dir/Excluded.kt"), null, NOTHING) - checkWhen(touch("src/dir/subdir/YetAnotherExcluded.kt"), null, NOTHING) - } - - fun testExcludeFolderRecursivelyUsingCompilerSettings() { - doTest() - - val module = myProject.modules.get(0) - assertFilesExistInOutput(module, "Foo.class", "Bar.class") - assertFilesNotExistInOutput(module, *EXCLUDE_FILES) - - if (IncrementalCompilation.isEnabledForJvm()) { - checkWhen(touch("src/foo.kt"), null, arrayOf(module("kotlinProject"), klass("kotlinProject", "Foo"))) - } - else { - val allClasses = myProject.outputPaths() - checkWhen(touch("src/foo.kt"), null, allClasses) - } - - checkWhen(touch("src/exclude/Excluded.kt"), null, NOTHING) - checkWhen(touch("src/exclude/YetAnotherExcluded.kt"), null, NOTHING) - checkWhen(touch("src/exclude/subdir/Excluded.kt"), null, NOTHING) - checkWhen(touch("src/exclude/subdir/YetAnotherExcluded.kt"), null, NOTHING) - } - - fun testKotlinProjectTwoFilesInOnePackage() { - doTest() - - if (IncrementalCompilation.isEnabledForJvm()) { - checkWhen(touch("src/test1.kt"), null, packageClasses("kotlinProject", "src/test1.kt", "_DefaultPackage")) - checkWhen(touch("src/test2.kt"), null, packageClasses("kotlinProject", "src/test2.kt", "_DefaultPackage")) - } - else { - val allClasses = myProject.outputPaths() - checkWhen(touch("src/test1.kt"), null, allClasses) - checkWhen(touch("src/test2.kt"), null, allClasses) - } - - checkWhen(arrayOf(del("src/test1.kt"), del("src/test2.kt")), NOTHING, - arrayOf(packagePartClass("kotlinProject", "src/test1.kt", "_DefaultPackage"), - packagePartClass("kotlinProject", "src/test2.kt", "_DefaultPackage"), - module("kotlinProject"))) - - assertFilesNotExistInOutput(myProject.modules.get(0), "_DefaultPackage.class") - } - - fun testDefaultLanguageVersionCustomApiVersion() { - initProject(JVM_FULL_RUNTIME) - buildAllModules().assertFailed() - - assertEquals(1, myProject.modules.size) - val module = myProject.modules.first() - val args = module.kotlinCompilerArguments - args.apiVersion = "1.2" - myProject.kotlinCommonCompilerArguments = args - - buildAllModules().assertSuccessful() - } - - fun testKotlinJavaProject() { - doTestWithRuntime() - } - - fun testJKJProject() { - doTestWithRuntime() - } - - fun testKJKProject() { - doTestWithRuntime() - } - - fun testKJCircularProject() { - doTestWithRuntime() - } - - fun testJKJInheritanceProject() { - doTestWithRuntime() - } - - fun testKJKInheritanceProject() { - doTestWithRuntime() - } - - fun testCircularDependenciesNoKotlinFiles() { - doTest() - } - - fun testCircularDependenciesDifferentPackages() { - initProject(JVM_MOCK_RUNTIME) - val result = buildAllModules() - - // Check that outputs are located properly - assertFilesExistInOutput(findModule("module2"), "kt1/Kt1Kt.class") - assertFilesExistInOutput(findModule("kotlinProject"), "kt2/Kt2Kt.class") - - result.assertSuccessful() - - if (IncrementalCompilation.isEnabledForJvm()) { - checkWhen(touch("src/kt2.kt"), null, packageClasses("kotlinProject", "src/kt2.kt", "kt2.Kt2Kt")) - checkWhen(touch("module2/src/kt1.kt"), null, packageClasses("module2", "module2/src/kt1.kt", "kt1.Kt1Kt")) - } - else { - val allClasses = myProject.outputPaths() - checkWhen(touch("src/kt2.kt"), null, allClasses) - checkWhen(touch("module2/src/kt1.kt"), null, allClasses) - } - } - - fun testCircularDependenciesSamePackage() { - initProject(JVM_MOCK_RUNTIME) - val result = buildAllModules() - result.assertSuccessful() - - // Check that outputs are located properly - val facadeWithA = findFileInOutputDir(findModule("module1"), "test/AKt.class") - val facadeWithB = findFileInOutputDir(findModule("module2"), "test/BKt.class") - UsefulTestCase.assertSameElements(getMethodsOfClass(facadeWithA), "", "a", "getA") - UsefulTestCase.assertSameElements(getMethodsOfClass(facadeWithB), "", "b", "getB", "setB") - - - if (IncrementalCompilation.isEnabledForJvm()) { - checkWhen(touch("module1/src/a.kt"), null, packageClasses("module1", "module1/src/a.kt", "test.TestPackage")) - checkWhen(touch("module2/src/b.kt"), null, packageClasses("module2", "module2/src/b.kt", "test.TestPackage")) - } - else { - val allClasses = myProject.outputPaths() - checkWhen(touch("module1/src/a.kt"), null, allClasses) - checkWhen(touch("module2/src/b.kt"), null, allClasses) - } - } - - fun testCircularDependenciesSamePackageWithTests() { - initProject(JVM_MOCK_RUNTIME) - val result = buildAllModules() - result.assertSuccessful() - - // Check that outputs are located properly - val facadeWithA = findFileInOutputDir(findModule("module1"), "test/AKt.class") - val facadeWithB = findFileInOutputDir(findModule("module2"), "test/BKt.class") - UsefulTestCase.assertSameElements(getMethodsOfClass(facadeWithA), "", "a", "funA", "getA") - UsefulTestCase.assertSameElements(getMethodsOfClass(facadeWithB), "", "b", "funB", "getB", "setB") - - if (IncrementalCompilation.isEnabledForJvm()) { - checkWhen(touch("module1/src/a.kt"), null, packageClasses("module1", "module1/src/a.kt", "test.TestPackage")) - checkWhen(touch("module2/src/b.kt"), null, packageClasses("module2", "module2/src/b.kt", "test.TestPackage")) - } - else { - val allProductionClasses = myProject.outputPaths(tests = false) - checkWhen(touch("module1/src/a.kt"), null, allProductionClasses) - checkWhen(touch("module2/src/b.kt"), null, allProductionClasses) - } - } - - fun testInternalFromAnotherModule() { - initProject(JVM_MOCK_RUNTIME) - val result = buildAllModules() - result.assertFailed() - result.checkErrors() - } - - fun testInternalFromSpecialRelatedModule() { - initProject(JVM_MOCK_RUNTIME) - buildAllModules().assertSuccessful() - - val classpath = listOf("out/production/module1", "out/test/module2").map { File(workDir, it).toURI().toURL() }.toTypedArray() - val clazz = URLClassLoader(classpath).loadClass("test2.BarKt") - clazz.getMethod("box").invoke(null) - } - - fun testCircularDependenciesInternalFromAnotherModule() { - initProject(JVM_MOCK_RUNTIME) - val result = buildAllModules() - result.assertFailed() - result.checkErrors() - } - - fun testCircularDependenciesWrongInternalFromTests() { - initProject(JVM_MOCK_RUNTIME) - val result = buildAllModules() - result.assertFailed() - result.checkErrors() - } - - fun testCircularDependencyWithReferenceToOldVersionLib() { - initProject(JVM_MOCK_RUNTIME) - - val libraryJar = MockLibraryUtil.compileJvmLibraryToJar(workDir.absolutePath + File.separator + "oldModuleLib/src", "module-lib") - - AbstractKotlinJpsBuildTestCase.addDependency(JpsJavaDependencyScope.COMPILE, Lists.newArrayList(findModule("module1"), findModule("module2")), false, "module-lib", libraryJar) - - val result = buildAllModules() - result.assertSuccessful() - } - - fun testDependencyToOldKotlinLib() { - initProject() - - val libraryJar = MockLibraryUtil.compileJvmLibraryToJar(workDir.absolutePath + File.separator + "oldModuleLib/src", "module-lib") - - AbstractKotlinJpsBuildTestCase.addDependency(JpsJavaDependencyScope.COMPILE, Lists.newArrayList(findModule("module")), false, "module-lib", libraryJar) - - addKotlinStdlibDependency() - - val result = buildAllModules() - result.assertSuccessful() - } - - fun testDevKitProject() { - initProject(JVM_MOCK_RUNTIME) - assertEquals(myProject.modules.single().moduleType, JpsPluginModuleType.INSTANCE) - buildAllModules().assertSuccessful() - } - - fun testAccessToInternalInProductionFromTests() { - initProject(JVM_MOCK_RUNTIME) - val result = buildAllModules() - result.assertSuccessful() - } - - private fun createKotlinJavaScriptLibraryArchive() { - val jarFile = File(workDir, KOTLIN_JS_LIBRARY_JAR) - try { - val zip = ZipOutputStream(FileOutputStream(jarFile)) - ZipUtil.addDirToZipRecursively(zip, jarFile, File(PATH_TO_KOTLIN_JS_LIBRARY), "", null, null) - zip.close() - } - catch (ex: FileNotFoundException) { - throw IllegalStateException(ex.message) - } - catch (ex: IOException) { - throw IllegalStateException(ex.message) - } - - } - - private fun checkOutputFilesList(outputDir: File = productionOutputDir) { - if (!expectedOutputFile.exists()) { - expectedOutputFile.writeText("") - throw IllegalStateException("$expectedOutputFile did not exist. Created empty file.") - } - - val sb = StringBuilder() - val p = Printer(sb, " ") - outputDir.printFilesRecursively(p) - - UsefulTestCase.assertSameLinesWithFile(expectedOutputFile.canonicalPath, sb.toString(), true) - } - - private fun File.printFilesRecursively(p: Printer) { - val files = listFiles() ?: return - - for (file in files.sortedBy { it.name }) { - when { - file.isFile -> { - p.println(file.name) - } - file.isDirectory -> { - p.println(file.name + "/") - p.pushIndent() - file.printFilesRecursively(p) - p.popIndent() - } - } - } - } - - private val productionOutputDir - get() = File(workDir, "out/production") - - private fun getOutputDir(moduleName: String): File = File(productionOutputDir, moduleName) - - fun testReexportedDependency() { - initProject() - AbstractKotlinJpsBuildTestCase.addKotlinStdlibDependency(myProject.modules.filter { module -> module.name == "module2" }, true) - buildAllModules().assertSuccessful() - } - - fun testCheckIsCancelledIsCalledOftenEnough() { - val classCount = 30 - val methodCount = 30 - - fun generateFiles() { - val srcDir = File(workDir, "src") - srcDir.mkdirs() - - for (i in 0..classCount) { - val code = buildString { - appendln("package foo") - appendln("class Foo$i {") - for (j in 0..methodCount) { - appendln(" fun get${j*j}(): Int = square($j)") - } - appendln("}") - - } - File(srcDir, "Foo$i.kt").writeText(code) - } - } - - generateFiles() - initProject(JVM_MOCK_RUNTIME) - - var checkCancelledCalledCount = 0 - val countingCancelledStatus = CanceledStatus { - checkCancelledCalledCount++ - false - } - - val logger = TestProjectBuilderLogger() - val buildResult = BuildResult() - - buildCustom(countingCancelledStatus, logger, buildResult) - - buildResult.assertSuccessful() - assert(checkCancelledCalledCount > classCount) { - "isCancelled should be called at least once per class. Expected $classCount, but got $checkCancelledCalledCount" - } - } - - fun testCancelKotlinCompilation() { - initProject(JVM_MOCK_RUNTIME) - buildAllModules().assertSuccessful() - - val module = myProject.modules.get(0) - assertFilesExistInOutput(module, "foo/Bar.class") - - val buildResult = BuildResult() - val canceledStatus = object : CanceledStatus { - var checkFromIndex = 0 - - override fun isCanceled(): Boolean { - val messages = buildResult.getMessages(BuildMessage.Kind.INFO) - for (i in checkFromIndex..messages.size - 1) { - if (messages[i].messageText.matches("kotlinc-jvm .+ \\(JRE .+\\)".toRegex())) { - return true - } - } - - checkFromIndex = messages.size - return false - } - } - - touch("src/Bar.kt").apply() - buildCustom(canceledStatus, TestProjectBuilderLogger(), buildResult) - assertCanceled(buildResult) - } - - fun testFileDoesNotExistWarning() { - fun absoluteFiles(vararg paths: String): Array = - paths.map { File(it).absoluteFile }.toTypedArray() - - initProject(JVM_MOCK_RUNTIME) - - val filesToBeReported = absoluteFiles("badroot.jar", "some/test.class") - val otherFiles = absoluteFiles("test/other/file.xml", "some/other/baddir") - - AbstractKotlinJpsBuildTestCase.addDependency( - JpsJavaDependencyScope.COMPILE, - Lists.newArrayList(findModule("module")), - false, - "LibraryWithBadRoots", - *(filesToBeReported + otherFiles) - ) - - val result = buildAllModules() - result.assertSuccessful() - - val actualWarnings = result.getMessages(BuildMessage.Kind.WARNING).map { it.messageText } - val expectedWarnings = filesToBeReported.map { "Classpath entry points to a non-existent location: $it" } - - val expectedText = expectedWarnings.sorted().joinToString("\n") - val actualText = actualWarnings.sorted().joinToString("\n") - - Assert.assertEquals(expectedText, actualText) - } - - fun testHelp() { - initProject() - - val result = buildAllModules() - result.assertSuccessful() - val warning = result.getMessages(BuildMessage.Kind.WARNING).single() - - val expectedText = StringUtil.convertLineSeparators(Usage.render(K2JVMCompiler(), K2JVMCompilerArguments())) - Assert.assertEquals(expectedText, warning.messageText) - } - - fun testWrongArgument() { - initProject() - - val result = buildAllModules() - result.assertFailed() - val errors = result.getMessages(BuildMessage.Kind.ERROR).joinToString("\n\n") { it.messageText } - - Assert.assertEquals("Invalid argument: -abcdefghij-invalid-argument", errors) - } - - fun testCodeInKotlinPackage() { - initProject(JVM_MOCK_RUNTIME) - - val result = buildAllModules() - result.assertFailed() - val errors = result.getMessages(BuildMessage.Kind.ERROR) - - Assert.assertEquals("Only the Kotlin standard library is allowed to use the 'kotlin' package", errors.single().messageText) - } - - fun testDoNotCreateUselessKotlinIncrementalCaches() { - initProject(JVM_MOCK_RUNTIME) - buildAllModules().assertSuccessful() - - val storageRoot = BuildDataPathsImpl(myDataStorageRoot).dataStorageRoot - assertTrue(File(storageRoot, "targets/java-test/kotlinProject/kotlin").exists()) - assertFalse(File(storageRoot, "targets/java-production/kotlinProject/kotlin").exists()) - } - - fun testDoNotCreateUselessKotlinIncrementalCachesForDependentTargets() { - initProject(JVM_MOCK_RUNTIME) - buildAllModules().assertSuccessful() - - if (IncrementalCompilation.isEnabledForJvm()) { - checkWhen(touch("src/utils.kt"), null, packageClasses("kotlinProject", "src/utils.kt", "_DefaultPackage")) - } - else { - val allClasses = findModule("kotlinProject").outputFilesPaths() - checkWhen(touch("src/utils.kt"), null, allClasses.toTypedArray()) - } - - val storageRoot = BuildDataPathsImpl(myDataStorageRoot).dataStorageRoot - assertTrue(File(storageRoot, "targets/java-production/kotlinProject/kotlin").exists()) - assertFalse(File(storageRoot, "targets/java-production/module2/kotlin").exists()) - } - - fun testKotlinProjectWithEmptyProductionOutputDir() { - initProject(JVM_MOCK_RUNTIME) - val result = buildAllModules() - result.assertFailed() - result.checkErrors() - } - - fun testKotlinProjectWithEmptyTestOutputDir() { - doTest() - } - - fun testKotlinProjectWithEmptyProductionOutputDirWithoutSrcDir() { - doTest() - } - - fun testKotlinProjectWithEmptyOutputDirInSomeModules() { - doTest() - } - - fun testEAPToReleaseIC() { - fun setPreRelease(value: Boolean) { - System.setProperty(TEST_IS_PRE_RELEASE_SYSTEM_PROPERTY, value.toString()) - } - - try { - withIC { - initProject(JVM_MOCK_RUNTIME) - - setPreRelease(true) - buildAllModules().assertSuccessful() - assertCompiled(KotlinBuilder.KOTLIN_BUILDER_NAME, "src/Bar.kt", "src/Foo.kt") - - touch("src/Foo.kt").apply() - buildAllModules() - assertCompiled(KotlinBuilder.KOTLIN_BUILDER_NAME, "src/Foo.kt") - - setPreRelease(false) - touch("src/Foo.kt").apply() - buildAllModules().assertSuccessful() - assertCompiled(KotlinBuilder.KOTLIN_BUILDER_NAME, "src/Bar.kt", "src/Foo.kt") - } - } - finally { - System.clearProperty(TEST_IS_PRE_RELEASE_SYSTEM_PROPERTY) - } - } - - fun testGetDependentTargets() { - fun addModuleWithSourceAndTestRoot(name: String): JpsModule { - return addModule(name, "src/").apply { - contentRootsList.addUrl(JpsPathUtil.pathToUrl("test/")) - addSourceRoot(JpsPathUtil.pathToUrl("test/"), JavaSourceRootType.TEST_SOURCE) - } - } - - val a = addModuleWithSourceAndTestRoot("a") - val b = addModuleWithSourceAndTestRoot("b") - val c = addModuleWithSourceAndTestRoot("c") - val b2 = addModuleWithSourceAndTestRoot("b2") - val c2 = addModuleWithSourceAndTestRoot("c2") - - JpsModuleRootModificationUtil.addDependency(b, a, JpsJavaDependencyScope.COMPILE, /*exported =*/ true) - JpsModuleRootModificationUtil.addDependency(c, b, JpsJavaDependencyScope.COMPILE, /*exported =*/ false) - JpsModuleRootModificationUtil.addDependency(b2, a, JpsJavaDependencyScope.COMPILE, /*exported =*/ false) - JpsModuleRootModificationUtil.addDependency(c2, b2, JpsJavaDependencyScope.COMPILE, /*exported =*/ false) - - val actual = StringBuilder() - buildCustom(CanceledStatus.NULL, TestProjectBuilderLogger(), BuildResult()) { - project.setTestingContext(TestingContext(LookupTracker.DO_NOTHING, object : BuildLogger { - override fun buildStarted(context: CompileContext, chunk: ModuleChunk) { - actual.append("Targets dependent on ${chunk.targets.joinToString() }:\n") - actual.append(getDependentTargets(chunk.targets, context).map { it.toString() }.sorted().joinToString("\n")) - actual.append("\n---------\n") - } - - override fun afterBuildStarted(context: CompileContext, chunk: ModuleChunk) {} - override fun actionsOnCacheVersionChanged(actions: List) {} - override fun buildFinished(exitCode: ModuleLevelBuilder.ExitCode) {} - override fun markedAsDirtyBeforeRound(files: Iterable) {} - override fun markedAsDirtyAfterRound(files: Iterable) {} - })) - } - - val expectedFile = File(getCurrentTestDataRoot(), "expected.txt") - - KotlinTestUtils.assertEqualsToFile(expectedFile, actual.toString()) - } - - fun testJre9() { - val jdk9Path = KotlinTestUtils.getJdk9Home().absolutePath - - val jdk = myModel.global.addSdk(JDK_NAME, jdk9Path, "9", JpsJavaSdkType.INSTANCE) - jdk.addRoot(StandardFileSystems.JRT_PROTOCOL_PREFIX + jdk9Path + URLUtil.JAR_SEPARATOR + "java.base", JpsOrderRootType.COMPILED) - - loadProject(workDir.absolutePath + File.separator + PROJECT_NAME + ".ipr") - addKotlinStdlibDependency() - - buildAllModules().assertSuccessful() - } - - fun testCustomDestination() { - loadProject(workDir.absolutePath + File.separator + PROJECT_NAME + ".ipr") - addKotlinStdlibDependency() - buildAllModules().apply { - assertSuccessful() - - val aClass = File(workDir, "customOut/A.class") - assert(aClass.exists()) { "$aClass does not exist!" } - - val warnings = getMessages(BuildMessage.Kind.WARNING) - assert(warnings.isEmpty()) { "Unexpected warnings: \n${warnings.joinToString("\n")}" } - } - } - - private fun BuildResult.checkErrors() { - val actualErrors = getMessages(BuildMessage.Kind.ERROR) - .map { it as CompilerMessage } - .map { "${it.messageText} at line ${it.line}, column ${it.column}" }.sorted().joinToString("\n") - val expectedFile = File(getCurrentTestDataRoot(), "errors.txt") - KotlinTestUtils.assertEqualsToFile(expectedFile, actualErrors) - } - - private fun getCurrentTestDataRoot() = File(AbstractKotlinJpsBuildTestCase.TEST_DATA_PATH + "general/" + getTestName(false)) - - private fun buildCustom( - canceledStatus: CanceledStatus, - logger: TestProjectBuilderLogger, - buildResult: BuildResult, - setupProject: ProjectDescriptor.() -> Unit = {} - ) { - val scopeBuilder = CompileScopeTestBuilder.make().allModules() - val descriptor = this.createProjectDescriptor(BuildLoggingManager(logger)) - - descriptor.setupProject() - - try { - val builder = IncProjectBuilder(descriptor, BuilderRegistry.getInstance(), this.myBuildParams, canceledStatus, null, true) - builder.addMessageHandler(buildResult) - builder.build(scopeBuilder.build(), false) - } - finally { - descriptor.dataManager.flush(false) - descriptor.release() - } - } - - private fun assertCanceled(buildResult: BuildResult) { - val list = buildResult.getMessages(BuildMessage.Kind.INFO) - assertTrue("The build has been canceled" == list.last().messageText) - } - - private fun findModule(name: String): JpsModule { - for (module in myProject.modules) { - if (module.name == name) { - return module - } - } - throw IllegalStateException("Couldn't find module $name") - } - - protected fun checkWhen(action: Action, pathsToCompile: Array?, pathsToDelete: Array?) { - checkWhen(arrayOf(action), pathsToCompile, pathsToDelete) - } - - protected fun checkWhen(actions: Array, pathsToCompile: Array?, pathsToDelete: Array?) { - for (action in actions) { - action.apply() - } - - buildAllModules().assertSuccessful() - - if (pathsToCompile != null) { - assertCompiled(KotlinBuilder.KOTLIN_BUILDER_NAME, *pathsToCompile) - } - - if (pathsToDelete != null) { - assertDeleted(*pathsToDelete) - } - } - - protected fun packageClasses(moduleName: String, fileName: String, packageClassFqName: String): Array { - return arrayOf(module(moduleName), packagePartClass(moduleName, fileName, packageClassFqName)) - } - - protected fun packagePartClass(moduleName: String, fileName: String, packageClassFqName: String): String { - val path = FileUtilRt.toSystemIndependentName(File(workDir, fileName).absolutePath) - val fakeVirtualFile = object : LightVirtualFile(path.substringAfterLast('/')) { - override fun getPath(): String { - // strip extra "/" from the beginning - return path.substring(1) - } - } - - val packagePartFqName = PackagePartClassUtils.getDefaultPartFqName(FqName(packageClassFqName), fakeVirtualFile) - return klass(moduleName, AsmUtil.internalNameByFqNameWithoutInnerClasses(packagePartFqName)) - } - - private fun JpsProject.outputPaths(production: Boolean = true, tests: Boolean = true) = - modules.flatMap { it.outputFilesPaths(production = production, tests = tests) }.toTypedArray() - - private fun JpsModule.outputFilesPaths(production: Boolean = true, tests: Boolean = true): List { - val outputFiles = arrayListOf() - if (production) { - prodOut.walk().filterTo(outputFiles) { it.isFile } - } - if (tests) { - testsOut.walk().filterTo(outputFiles) { it.isFile } - } - return outputFiles.map { FileUtilRt.toSystemIndependentName(it.relativeTo(workDir).path) } - } - - private val JpsModule.prodOut: File - get() = outDir(forTests = false) - - private val JpsModule.testsOut: File - get() = outDir(forTests = true) - - private fun JpsModule.outDir(forTests: Boolean) = - JpsJavaExtensionService.getInstance().getOutputDirectory(this, forTests)!! - - protected enum class Operation { - CHANGE, - DELETE - } - - protected fun touch(path: String): Action = Action(Operation.CHANGE, path) - - protected fun del(path: String): Action = Action(Operation.DELETE, path) - - // TODO inline after KT-3974 will be fixed - protected fun touch(file: File): Unit = JpsBuildTestCase.change(file.absolutePath) - - protected inner class Action constructor(private val operation: Operation, private val path: String) { - fun apply() { - val file = File(workDir, path) - when (operation) { - Operation.CHANGE -> - touch(file) - Operation.DELETE -> - assertTrue("Can not delete file \"" + file.absolutePath + "\"", file.delete()) - } - } - } -} diff --git a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/JvmDeclarationUElementPlaceholder.kt.172 b/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/JvmDeclarationUElementPlaceholder.kt.172 deleted file mode 100644 index 49e8ed2038d..00000000000 --- a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/JvmDeclarationUElementPlaceholder.kt.172 +++ /dev/null @@ -1,13 +0,0 @@ -/* - * 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.uast.kotlin - -import org.jetbrains.uast.UElement - -/** - * Actual only for 173-bunch, please remove when 173 is over - */ -typealias JvmDeclarationUElementPlaceholder = UElement \ No newline at end of file diff --git a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/KotlinAbstractUElement.kt.172 b/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/KotlinAbstractUElement.kt.172 deleted file mode 100644 index 3a251d0b00d..00000000000 --- a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/KotlinAbstractUElement.kt.172 +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.uast.kotlin - -import com.intellij.psi.PsiElement -import org.jetbrains.kotlin.asJava.toLightGetter -import org.jetbrains.kotlin.asJava.toLightSetter -import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget -import org.jetbrains.kotlin.psi.* -import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject -import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType -import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf -import org.jetbrains.uast.* -import org.jetbrains.uast.kotlin.expressions.KotlinUElvisExpression -import org.jetbrains.uast.kotlin.internal.KotlinUElementWithComments -import org.jetbrains.uast.kotlin.psi.UastKotlinPsiVariable - -abstract class KotlinAbstractUElement(private val givenParent: UElement?) : KotlinUElementWithComments, - JvmDeclarationUElementPlaceholder { - - override val uastParent: UElement? by lz { - givenParent ?: convertParent() - } - - protected open fun convertParent(): UElement? { - val psi = psi - var parent = psi?.parent ?: psi?.containingFile - - if (psi is KtAnnotationEntry) { - val parentUnwrapped = KotlinConverter.unwrapElements(parent) ?: return null - val target = psi.useSiteTarget?.getAnnotationUseSiteTarget() - when (target) { - AnnotationUseSiteTarget.PROPERTY_GETTER -> - parent = (parentUnwrapped as? KtProperty)?.getter - ?: (parentUnwrapped as? KtParameter)?.toLightGetter() - ?: parent - - AnnotationUseSiteTarget.PROPERTY_SETTER -> - parent = (parentUnwrapped as? KtProperty)?.setter - ?: (parentUnwrapped as? KtParameter)?.toLightSetter() - ?: parent - } - } - if (psi is UastKotlinPsiVariable && parent != null) { - parent = parent.parent - } - - while (parent is KtStringTemplateEntryWithExpression || - parent is KtStringTemplateExpression && parent.entries.size == 1) { - parent = parent.parent - } - - if (parent is KtWhenConditionWithExpression) { - parent = parent.parent - } - - if (parent is KtImportList) { - parent = parent.parent - } - - if (psi is KtFunctionLiteral && parent is KtLambdaExpression) { - parent = parent.parent - } - - if (parent is KtLambdaArgument) { - parent = parent.parent - } - - if (psi is KtSuperTypeCallEntry) { - parent = parent?.parent - } - - val result = doConvertParent(this, parent) - if (result == this) { - throw IllegalStateException("Loop in parent structure when converting a $psi of type ${psi?.javaClass} with parent $parent of type ${parent?.javaClass} text: [${parent?.text}]") - } - - return result - } - - override fun equals(other: Any?): Boolean { - if (other !is UElement) { - return false - } - - return this.psi == other.psi - } - - override fun hashCode() = psi?.hashCode() ?: 0 -} - -fun doConvertParent(element: UElement, parent: PsiElement?): UElement? { - val parentUnwrapped = KotlinConverter.unwrapElements(parent) ?: return null - if (parent is KtValueArgument && parentUnwrapped is KtAnnotationEntry) { - return (KotlinUastLanguagePlugin().convertElementWithParent(parentUnwrapped, null) as? KotlinUAnnotation) - ?.findAttributeValueExpression(parent) - } - - if (parent is KtParameter) { - val annotationClass = findAnnotationClassFromConstructorParameter(parent) - if (annotationClass != null) { - return annotationClass.methods.find { it.name == parent.name } - } - } - - if (parent is KtClassInitializer) { - val containingClass = parent.containingClassOrObject - if (containingClass != null) { - val containingUClass = KotlinUastLanguagePlugin().convertElementWithParent(containingClass, null) as? KotlinUClass - containingUClass?.methods?.filterIsInstance()?.firstOrNull { it.isPrimary }?.let { - return it.uastBody - } - } - } - - val result = KotlinUastLanguagePlugin().convertElementWithParent(parentUnwrapped, null) - - if (result is UEnumConstant && element is UDeclaration) { - return result.initializingClass - } - - if (result is UCallExpression && result.uastParent is UEnumConstant) { - return result.uastParent - } - - if (result is USwitchClauseExpressionWithBody && !isInConditionBranch(element, result)) { - return result.body - } - - if (result is KotlinUDestructuringDeclarationExpression && - element.psi == (parent as KtDestructuringDeclaration).initializer) { - return result.tempVarAssignment - } - - if (result is KotlinUElvisExpression && parent is KtBinaryExpression) { - when (element.psi) { - parent.left -> return result.lhsDeclaration - parent.right -> return result.rhsIfExpression - } - } - - if (result is UMethod - && result !is KotlinConstructorUMethod // no sense to wrap super calls with `return` - && element is UExpression - && element !is UBlockExpression - && element !is UTypeReferenceExpression // when element is a type in extension methods - ) { - return KotlinUBlockExpression.KotlinLazyUBlockExpression(result, { block -> - listOf(KotlinUImplicitReturnExpression(block).apply { returnExpression = element }) - }).expressions.single() - } - - return result -} - -private fun isInConditionBranch(element: UElement, result: USwitchClauseExpressionWithBody) = - element.psi?.parentsWithSelf?.takeWhile { it !== result.psi }?.any { it is KtWhenCondition } ?: false - - -private fun findAnnotationClassFromConstructorParameter(parameter: KtParameter): UClass? { - val primaryConstructor = parameter.getStrictParentOfType() ?: return null - val containingClass = primaryConstructor.getContainingClassOrObject() - if (containingClass.isAnnotation()) { - return KotlinUastLanguagePlugin().convertElementWithParent(containingClass, null) as? UClass - } - return null -} - -abstract class KotlinAbstractUExpression(givenParent: UElement?) - : KotlinAbstractUElement(givenParent), UExpression { - - override val annotations: List - get() { - val annotatedExpression = psi?.parent as? KtAnnotatedExpression ?: return emptyList() - return annotatedExpression.annotationEntries.map { KotlinUAnnotation(it, this) } - } -} - diff --git a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/KotlinUastLanguagePlugin.kt.172 b/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/KotlinUastLanguagePlugin.kt.172 deleted file mode 100644 index 0591cee977c..00000000000 --- a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/KotlinUastLanguagePlugin.kt.172 +++ /dev/null @@ -1,541 +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.uast.kotlin - -import com.intellij.lang.Language -import com.intellij.openapi.components.ServiceManager -import com.intellij.openapi.util.Key -import com.intellij.psi.PsiElement -import com.intellij.psi.PsiFile -import com.intellij.psi.impl.source.tree.LeafPsiElement -import org.jetbrains.kotlin.asJava.LightClassUtil -import org.jetbrains.kotlin.asJava.classes.KtLightClass -import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade -import org.jetbrains.kotlin.asJava.elements.* -import org.jetbrains.kotlin.asJava.toLightClass -import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper -import org.jetbrains.kotlin.config.LanguageVersionSettings -import org.jetbrains.kotlin.descriptors.ConstructorDescriptor -import org.jetbrains.kotlin.descriptors.FunctionDescriptor -import org.jetbrains.kotlin.idea.KotlinLanguage -import org.jetbrains.kotlin.lexer.KtTokens -import org.jetbrains.kotlin.psi.* -import org.jetbrains.kotlin.psi.psiUtil.getParentOfType -import org.jetbrains.kotlin.resolve.BindingContext -import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall -import org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatform -import org.jetbrains.uast.* -import org.jetbrains.uast.java.JavaUastLanguagePlugin -import org.jetbrains.uast.kotlin.declarations.KotlinUMethod -import org.jetbrains.uast.kotlin.expressions.* -import org.jetbrains.uast.kotlin.psi.UastKotlinPsiParameter -import org.jetbrains.uast.kotlin.psi.UastKotlinPsiVariable - -interface KotlinUastResolveProviderService { - fun getBindingContext(element: KtElement): BindingContext - fun getTypeMapper(element: KtElement): KotlinTypeMapper? - fun getLanguageVersionSettings(element: KtElement): LanguageVersionSettings - fun isJvmElement(psiElement: PsiElement): Boolean -} - -var PsiElement.destructuringDeclarationInitializer: Boolean? by UserDataProperty(Key.create("kotlin.uast.destructuringDeclarationInitializer")) - -class KotlinUastLanguagePlugin : UastLanguagePlugin { - override val priority = 10 - - private val javaPlugin by lz { UastLanguagePlugin.getInstances().first { it is JavaUastLanguagePlugin } } - - override val language: Language - get() = KotlinLanguage.INSTANCE - - override fun isFileSupported(fileName: String): Boolean { - return fileName.endsWith(".kt", false) || fileName.endsWith(".kts", false) - } - - private val PsiElement.isJvmElement: Boolean - get() { - val resolveProvider = ServiceManager.getService(project, KotlinUastResolveProviderService::class.java) - return resolveProvider.isJvmElement(this) - } - - override fun convertElement(element: PsiElement, parent: UElement?, requiredType: Class?): UElement? { - if (!element.isJvmElement) return null - return convertDeclarationOrElement(element, parent, requiredType) - } - - override fun convertElementWithParent(element: PsiElement, requiredType: Class?): UElement? { - if (!element.isJvmElement) return null - if (element is PsiFile) return convertDeclaration(element, null, requiredType) - if (element is KtLightClassForFacade) return convertDeclaration(element, null, requiredType) - - return convertDeclarationOrElement(element, null, requiredType) - } - - private fun convertDeclarationOrElement(element: PsiElement, givenParent: UElement?, requiredType: Class?): UElement? { - if (element is UElement) return element - - if (element.isValid) { - element.getUserData(KOTLIN_CACHED_UELEMENT_KEY)?.get()?.let { cachedUElement -> - return if (requiredType == null || requiredType.isInstance(cachedUElement)) cachedUElement else null - } - } - - val uElement = convertDeclaration(element, givenParent, requiredType) - ?: KotlinConverter.convertPsiElement(element, givenParent, requiredType) - /* - if (uElement != null) { - element.putUserData(KOTLIN_CACHED_UELEMENT_KEY, WeakReference(uElement)) - } - */ - return uElement - } - - override fun getMethodCallExpression( - element: PsiElement, - containingClassFqName: String?, - methodName: String - ): UastLanguagePlugin.ResolvedMethod? { - if (element !is KtCallExpression) return null - val resolvedCall = element.getResolvedCall(element.analyze()) ?: return null - val resultingDescriptor = resolvedCall.resultingDescriptor - if (resultingDescriptor !is FunctionDescriptor || resultingDescriptor.name.asString() != methodName) return null - - val parent = element.parent - val parentUElement = convertElementWithParent(parent, null) ?: return null - - val uExpression = KotlinUFunctionCallExpression(element, parentUElement, resolvedCall) - val method = uExpression.resolve() ?: return null - if (method.name != methodName) return null - return UastLanguagePlugin.ResolvedMethod(uExpression, method) - } - - override fun getConstructorCallExpression( - element: PsiElement, - fqName: String - ): UastLanguagePlugin.ResolvedConstructor? { - if (element !is KtCallExpression) return null - val resolvedCall = element.getResolvedCall(element.analyze()) ?: return null - val resultingDescriptor = resolvedCall.resultingDescriptor - if (resultingDescriptor !is ConstructorDescriptor - || resultingDescriptor.returnType.constructor.declarationDescriptor?.name?.asString() != fqName) { - return null - } - - val parent = KotlinConverter.unwrapElements(element.parent) ?: return null - val parentUElement = convertElementWithParent(parent, null) ?: return null - - val uExpression = KotlinUFunctionCallExpression(element, parentUElement, resolvedCall) - val method = uExpression.resolve() ?: return null - val containingClass = method.containingClass ?: return null - return UastLanguagePlugin.ResolvedConstructor(uExpression, method, containingClass) - } - - internal fun convertDeclaration(element: PsiElement, - givenParent: UElement?, - requiredType: Class?): UElement? { - fun

build(ctor: (P, UElement?) -> UElement): () -> UElement? { - return { ctor(element as P, givenParent) } - } - - val original = element.originalElement - return with(requiredType) { - when (original) { - is KtLightMethod -> el(build(KotlinUMethod.Companion::create)) // .Companion is needed because of KT-13934 - is KtLightClass -> when (original.kotlinOrigin) { - is KtEnumEntry -> el { - convertEnumEntry(original.kotlinOrigin as KtEnumEntry, givenParent) - } - else -> el { KotlinUClass.create(original, givenParent) } - } - is KtLightFieldImpl.KtLightEnumConstant -> el(build(::KotlinUEnumConstant)) - is KtLightField -> el(build(::KotlinUField)) - is KtLightParameter, is UastKotlinPsiParameter -> el(build(::KotlinUParameter)) - is UastKotlinPsiVariable -> el(build(::KotlinUVariable)) - - is KtEnumEntry -> el { - convertEnumEntry(original, givenParent) - } - is KtClassOrObject -> el { - original.toLightClass()?.let { lightClass -> - KotlinUClass.create(lightClass, givenParent) - } - } - is KtFunction -> - if (original.isLocal) { - el { - val parent = original.parent - if (parent is KtLambdaExpression) { - KotlinULambdaExpression(parent, givenParent) // your parent is the ULambdaExpression - } else if (original.name.isNullOrEmpty()) { - createLocalFunctionLambdaExpression(original, givenParent) - } - else { - val uDeclarationsExpression = createLocalFunctionDeclaration(original, givenParent) - val localFunctionVar = uDeclarationsExpression.declarations.single() as KotlinLocalFunctionUVariable - localFunctionVar.uastInitializer - } - } - } - else { - el { - val lightMethod = LightClassUtil.getLightClassMethod(original) ?: return null - convertDeclaration(lightMethod, givenParent, requiredType) - } - } - - is KtPropertyAccessor -> el { - val lightMethod = LightClassUtil.getLightClassAccessorMethod(original) ?: return null - convertDeclaration(lightMethod, givenParent, requiredType) - } - - is KtProperty -> - if (original.isLocal) { - KotlinConverter.convertPsiElement(element, givenParent, requiredType) - } - else { - convertNonLocalProperty(original, givenParent, requiredType) - } - - is KtParameter -> el { - val ownerFunction = original.ownerFunction as? KtFunction ?: return null - val lightMethod = LightClassUtil.getLightClassMethod(ownerFunction) ?: return null - val lightParameter = lightMethod.parameterList.parameters.find { it.name == original.name } ?: return null - KotlinUParameter(lightParameter, givenParent) - } - - is KtFile -> el { KotlinUFile(original, this@KotlinUastLanguagePlugin) } - is FakeFileForLightClass -> el { KotlinUFile(original.navigationElement, this@KotlinUastLanguagePlugin) } - is KtAnnotationEntry -> el(build(::KotlinUAnnotation)) - is KtLightAnnotationForSourceEntry -> convertElement(original.kotlinOrigin, givenParent, requiredType) - else -> null - } - } - } - - private fun convertEnumEntry(original: KtEnumEntry, givenParent: UElement?): UElement? { - return LightClassUtil.getLightClassBackingField(original)?.let { psiField -> - if (psiField is KtLightFieldImpl.KtLightEnumConstant) { - KotlinUEnumConstant(psiField, givenParent) - } - else { - null - } - } - } - - override fun isExpressionValueUsed(element: UExpression): Boolean { - return when (element) { - is KotlinUSimpleReferenceExpression.KotlinAccessorCallExpression -> element.setterValue != null - is KotlinAbstractUExpression -> { - val ktElement = element.psi as? KtElement ?: return false - ktElement.analyze()[BindingContext.USED_AS_EXPRESSION, ktElement] ?: false - } - else -> false - } - } -} - -internal inline fun Class?.el(f: () -> UElement?): UElement? { - return if (this == null || isAssignableFrom(ActualT::class.java)) f() else null -} - -internal inline fun Class?.expr(f: () -> UExpression?): UExpression? { - return if (this == null || isAssignableFrom(ActualT::class.java)) f() else null -} - -private fun convertNonLocalProperty(property: KtProperty, - givenParent: UElement?, - requiredType: Class?): UElement? { - val methods = LightClassUtil.getLightClassPropertyMethods(property) - return methods.backingField?.let { backingField -> - with(requiredType) { - el { KotlinUField(backingField, givenParent) } - } - } ?: methods.getter?.let { getter -> - KotlinUastLanguagePlugin().convertDeclaration(getter, givenParent, requiredType) - } -} - -internal object KotlinConverter { - internal tailrec fun unwrapElements(element: PsiElement?): PsiElement? = when (element) { - is KtValueArgumentList -> unwrapElements(element.parent) - is KtValueArgument -> unwrapElements(element.parent) - is KtDeclarationModifierList -> unwrapElements(element.parent) - is KtContainerNode -> unwrapElements(element.parent) - is KtSimpleNameStringTemplateEntry -> unwrapElements(element.parent) - is KtLightParameterList -> unwrapElements(element.parent) - else -> element - } - - internal fun convertPsiElement(element: PsiElement?, - givenParent: UElement?, - requiredType: Class?): UElement? { - fun

build(ctor: (P, UElement?) -> UElement): () -> UElement? { - return { ctor(element as P, givenParent) } - } - - return with (requiredType) { when (element) { - is KtParameterList -> el { - val declarationsExpression = KotlinUDeclarationsExpression(givenParent) - declarationsExpression.apply { - declarations = element.parameters.mapIndexed { i, p -> - KotlinUParameter(UastKotlinPsiParameter.create(p, element, declarationsExpression, i), this) - } - } - } - is KtClassBody -> el(build(KotlinUExpressionList.Companion::createClassBody)) - is KtCatchClause -> el(build(::KotlinUCatchClause)) - is KtVariableDeclaration -> - if (element is KtProperty && !element.isLocal) { - el { - LightClassUtil.getLightClassBackingField(element)?.let { - KotlinUField(it, givenParent) - } - } - } - else { - el { - convertVariablesDeclaration(element, givenParent).declarations.singleOrNull() - } - } - - is KtExpression -> KotlinConverter.convertExpression(element, givenParent, requiredType) - is KtLambdaArgument -> element.getLambdaExpression()?.let { KotlinConverter.convertExpression(it, givenParent, requiredType) } - is KtLightElementBase -> { - val expression = element.kotlinOrigin - when (expression) { - is KtExpression -> KotlinConverter.convertExpression(expression, givenParent, requiredType) - else -> el { UastEmptyExpression } - } - } - is KtLiteralStringTemplateEntry, is KtEscapeStringTemplateEntry -> el(build(::KotlinStringULiteralExpression)) - is KtStringTemplateEntry -> element.expression?.let { convertExpression(it, givenParent, requiredType) } ?: expr { UastEmptyExpression } - is KtWhenEntry -> el(build(::KotlinUSwitchEntry)) - is KtWhenCondition -> convertWhenCondition(element, givenParent, requiredType) - is KtTypeReference -> el { LazyKotlinUTypeReferenceExpression(element, givenParent) } - is KtConstructorDelegationCall -> - el { KotlinUFunctionCallExpression(element, givenParent) } - is KtSuperTypeCallEntry -> - el { - (element.getParentOfType(true)?.parent as? KtObjectLiteralExpression) - ?.toUElementOfType() - ?: KotlinUFunctionCallExpression(element, givenParent) - } - is KtImportDirective -> el(build(::KotlinUImportStatement)) - else -> { - if (element is LeafPsiElement) { - if (element.elementType == KtTokens.IDENTIFIER) - el(build(::UIdentifier)) - else if (element.elementType == KtTokens.LBRACKET && element.parent is KtCollectionLiteralExpression) - el { - UIdentifier( - element, - KotlinUCollectionLiteralExpression( - element.parent as KtCollectionLiteralExpression, - null - ) - ) - } - else null - } else { - null - } - } - }} - } - - - internal fun convertEntry(entry: KtStringTemplateEntry, - givenParent: UElement?, - requiredType: Class? = null): UExpression? { - return with(requiredType) { - if (entry is KtStringTemplateEntryWithExpression) { - expr { - KotlinConverter.convertOrEmpty(entry.expression, givenParent) - } - } - else { - expr { - if (entry is KtEscapeStringTemplateEntry) - KotlinStringULiteralExpression(entry, givenParent, entry.unescapedValue) - else - KotlinStringULiteralExpression(entry, givenParent) - } - } - } - } - - internal fun convertExpression(expression: KtExpression, - givenParent: UElement?, - requiredType: Class? = null): UExpression? { - fun

build(ctor: (P, UElement?) -> UExpression): () -> UExpression? { - return { ctor(expression as P, givenParent) } - } - - return with (requiredType) { when (expression) { - is KtVariableDeclaration -> expr(build(::convertVariablesDeclaration)) - - is KtStringTemplateExpression -> { - when { - expression.entries.isEmpty() -> { - expr { KotlinStringULiteralExpression(expression, givenParent, "") } - } - expression.entries.size == 1 -> convertEntry(expression.entries[0], givenParent, requiredType) - else -> { - expr { KotlinStringTemplateUPolyadicExpression(expression, givenParent) } - } - } - } - is KtDestructuringDeclaration -> expr { - val declarationsExpression = KotlinUDestructuringDeclarationExpression(givenParent, expression) - declarationsExpression.apply { - val tempAssignment = KotlinULocalVariable(UastKotlinPsiVariable.create(expression, declarationsExpression), declarationsExpression) - val destructuringAssignments = expression.entries.mapIndexed { i, entry -> - val psiFactory = KtPsiFactory(expression.project) - val initializer = psiFactory.createAnalyzableExpression("${tempAssignment.name}.component${i + 1}()", - expression.containingFile) - initializer.destructuringDeclarationInitializer = true - KotlinULocalVariable(UastKotlinPsiVariable.create(entry, tempAssignment.psi, declarationsExpression, initializer), declarationsExpression) - } - declarations = listOf(tempAssignment) + destructuringAssignments - } - } - is KtLabeledExpression -> expr(build(::KotlinULabeledExpression)) - is KtClassLiteralExpression -> expr(build(::KotlinUClassLiteralExpression)) - is KtObjectLiteralExpression -> expr(build(::KotlinUObjectLiteralExpression)) - is KtDotQualifiedExpression -> expr(build(::KotlinUQualifiedReferenceExpression)) - is KtSafeQualifiedExpression -> expr(build(::KotlinUSafeQualifiedExpression)) - is KtSimpleNameExpression -> expr(build(::KotlinUSimpleReferenceExpression)) - is KtCallExpression -> expr(build(::KotlinUFunctionCallExpression)) - is KtCollectionLiteralExpression -> expr(build(::KotlinUCollectionLiteralExpression)) - is KtBinaryExpression -> { - if (expression.operationToken == KtTokens.ELVIS) { - expr(build(::createElvisExpression)) - } - else expr(build(::KotlinUBinaryExpression)) - } - is KtParenthesizedExpression -> expr(build(::KotlinUParenthesizedExpression)) - is KtPrefixExpression -> expr(build(::KotlinUPrefixExpression)) - is KtPostfixExpression -> expr(build(::KotlinUPostfixExpression)) - is KtThisExpression -> expr(build(::KotlinUThisExpression)) - is KtSuperExpression -> expr(build(::KotlinUSuperExpression)) - is KtCallableReferenceExpression -> expr(build(::KotlinUCallableReferenceExpression)) - is KtIsExpression -> expr(build(::KotlinUTypeCheckExpression)) - is KtIfExpression -> expr(build(::KotlinUIfExpression)) - is KtWhileExpression -> expr(build(::KotlinUWhileExpression)) - is KtDoWhileExpression -> expr(build(::KotlinUDoWhileExpression)) - is KtForExpression -> expr(build(::KotlinUForEachExpression)) - is KtWhenExpression -> expr(build(::KotlinUSwitchExpression)) - is KtBreakExpression -> expr(build(::KotlinUBreakExpression)) - is KtContinueExpression -> expr(build(::KotlinUContinueExpression)) - is KtReturnExpression -> expr(build(::KotlinUReturnExpression)) - is KtThrowExpression -> expr(build(::KotlinUThrowExpression)) - is KtBlockExpression -> expr(build(::KotlinUBlockExpression)) - is KtConstantExpression -> expr(build(::KotlinULiteralExpression)) - is KtTryExpression -> expr(build(::KotlinUTryExpression)) - is KtArrayAccessExpression -> expr(build(::KotlinUArrayAccessExpression)) - is KtLambdaExpression -> expr(build(::KotlinULambdaExpression)) - is KtBinaryExpressionWithTypeRHS -> expr(build(::KotlinUBinaryExpressionWithType)) - is KtClassOrObject -> expr { - expression.toLightClass()?.let { lightClass -> - KotlinUDeclarationsExpression(givenParent).apply { - declarations = listOf(KotlinUClass.create(lightClass, this)) - } - } ?: UastEmptyExpression - } - is KtFunction -> if (expression.name.isNullOrEmpty()) { - expr(build(::createLocalFunctionLambdaExpression)) - } - else { - expr(build(::createLocalFunctionDeclaration)) - } - - else -> expr(build(::UnknownKotlinExpression)) - }} - } - - internal fun convertWhenCondition(condition: KtWhenCondition, - givenParent: UElement?, - requiredType: Class? = null): UExpression? { - return with(requiredType) { - when (condition) { - is KtWhenConditionInRange -> expr { - KotlinCustomUBinaryExpression(condition, givenParent).apply { - leftOperand = KotlinStringUSimpleReferenceExpression("it", this) - operator = when { - condition.isNegated -> KotlinBinaryOperators.NOT_IN - else -> KotlinBinaryOperators.IN - } - rightOperand = KotlinConverter.convertOrEmpty(condition.rangeExpression, this) - } - } - is KtWhenConditionIsPattern -> expr { - KotlinCustomUBinaryExpressionWithType(condition, givenParent).apply { - operand = KotlinStringUSimpleReferenceExpression("it", this) - operationKind = when { - condition.isNegated -> KotlinBinaryExpressionWithTypeKinds.NEGATED_INSTANCE_CHECK - else -> UastBinaryExpressionWithTypeKind.INSTANCE_CHECK - } - val typeRef = condition.typeReference - typeReference = typeRef?.let { - LazyKotlinUTypeReferenceExpression(it, this) { typeRef.toPsiType(this, boxed = true) } - } - } - } - - is KtWhenConditionWithExpression -> - condition.expression?.let { KotlinConverter.convertExpression(it, givenParent, requiredType) } - - else -> expr { UastEmptyExpression } - } - } - } - - internal fun convertOrEmpty(expression: KtExpression?, parent: UElement?): UExpression { - return expression?.let { convertExpression(it, parent, null) } ?: UastEmptyExpression - } - - internal fun convertOrNull(expression: KtExpression?, parent: UElement?): UExpression? { - return if (expression != null) convertExpression(expression, parent, null) else null - } - - internal fun KtPsiFactory.createAnalyzableExpression(text: String, context: PsiElement): KtExpression = - createAnalyzableProperty("val x = $text", context).initializer ?: error("Failed to create expression from text: '$text'") - - internal fun KtPsiFactory.createAnalyzableProperty(text: String, context: PsiElement): KtProperty = - createAnalyzableDeclaration(text, context) - - internal fun KtPsiFactory.createAnalyzableDeclaration(text: String, context: PsiElement): TDeclaration { - val file = createAnalyzableFile("dummy.kt", text, context) - val declarations = file.declarations - assert(declarations.size == 1) { "${declarations.size} declarations in $text" } - return declarations.first() as TDeclaration - } -} - -private fun convertVariablesDeclaration( - psi: KtVariableDeclaration, - parent: UElement? -): UDeclarationsExpression { - val declarationsExpression = KotlinUDeclarationsExpression(null, parent, psi) - val parentPsiElement = parent?.psi - val variable = KotlinUAnnotatedLocalVariable( - UastKotlinPsiVariable.create(psi, parentPsiElement, declarationsExpression), declarationsExpression) { annotationParent -> - psi.annotationEntries.map { KotlinUAnnotation(it, annotationParent) } - } - return declarationsExpression.apply { declarations = listOf(variable) } -} diff --git a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/declarations/KotlinUAnnotation.kt.172 b/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/declarations/KotlinUAnnotation.kt.172 deleted file mode 100644 index 8e467ef6dea..00000000000 --- a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/declarations/KotlinUAnnotation.kt.172 +++ /dev/null @@ -1,76 +0,0 @@ -package org.jetbrains.uast.kotlin - -import com.intellij.psi.PsiClass -import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor -import org.jetbrains.kotlin.psi.KtAnnotationEntry -import org.jetbrains.kotlin.psi.KtParameter -import org.jetbrains.kotlin.psi.ValueArgument -import org.jetbrains.kotlin.resolve.BindingContext -import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall -import org.jetbrains.kotlin.resolve.calls.model.ArgumentMatch -import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall -import org.jetbrains.kotlin.resolve.descriptorUtil.annotationClass -import org.jetbrains.kotlin.resolve.source.getPsi -import org.jetbrains.uast.* - -class KotlinUAnnotation( - override val psi: KtAnnotationEntry, - givenParent: UElement? -) : KotlinAbstractUElement(givenParent), UAnnotation { - private val resolvedAnnotation: AnnotationDescriptor? by lz { psi.analyze()[BindingContext.ANNOTATION, psi] } - - private val resolvedCall: ResolvedCall<*>? by lz { psi.getResolvedCall(psi.analyze()) } - - override val qualifiedName: String? - get() = resolvedAnnotation?.fqName?.asString() - - override val attributeValues: List by lz { - resolvedCall?.valueArguments?.entries?.mapNotNull { - val arguments = it.value.arguments - val name = it.key.name.asString() - when { - arguments.size == 1 -> - KotlinUNamedExpression.create(name, arguments.first(), this) - arguments.size > 1 -> - KotlinUNamedExpression.create(name, arguments, this) - else -> null - } - } ?: emptyList() - } - - override fun resolve(): PsiClass? { - val descriptor = resolvedAnnotation?.annotationClass ?: return null - return descriptor.toSource()?.getMaybeLightElement(this) as? PsiClass - } - - override fun findAttributeValue(name: String?): UExpression? = - findDeclaredAttributeValue(name) ?: findAttributeDefaultValue(name ?: "value") - - fun findAttributeValueExpression(arg: ValueArgument): UExpression? { - val mapping = resolvedCall?.getArgumentMapping(arg) - return (mapping as? ArgumentMatch)?.let { match -> - val namedExpression = attributeValues.find { it.name == match.valueParameter.name.asString() } - namedExpression?.expression as? KotlinUVarargExpression ?: namedExpression - } - } - - override fun findDeclaredAttributeValue(name: String?): UExpression? { - return attributeValues.find { - it.name == name || - (name == null && it.name == "value") || - (name == "value" && it.name == null) - }?.expression - } - - private fun findAttributeDefaultValue(name: String): UExpression? { - val parameter = resolvedAnnotation - ?.annotationClass - ?.unsubstitutedPrimaryConstructor - ?.valueParameters - ?.find { it.name.asString() == name } ?: return null - - val defaultValue = (parameter.source.getPsi() as? KtParameter)?.defaultValue ?: return null - return getLanguagePlugin().convertWithParent(defaultValue) - } -} - diff --git a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/declarations/KotlinUClass.kt.172 b/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/declarations/KotlinUClass.kt.172 deleted file mode 100644 index 0d546f58dc4..00000000000 --- a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/declarations/KotlinUClass.kt.172 +++ /dev/null @@ -1,258 +0,0 @@ -/* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.uast.kotlin - -import com.intellij.psi.* -import org.jetbrains.kotlin.asJava.classes.KtLightClass -import org.jetbrains.kotlin.asJava.classes.KtLightClassForLocalDeclaration -import org.jetbrains.kotlin.asJava.classes.KtLightClassForScript -import org.jetbrains.kotlin.asJava.elements.KtLightMethod -import org.jetbrains.kotlin.load.java.JvmAbi -import org.jetbrains.kotlin.psi.* -import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments -import org.jetbrains.kotlin.utils.SmartList -import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull -import org.jetbrains.uast.* -import org.jetbrains.uast.java.AbstractJavaUClass -import org.jetbrains.uast.kotlin.declarations.KotlinUMethod -import org.jetbrains.uast.kotlin.declarations.UastLightIdentifier - -abstract class AbstractKotlinUClass(private val givenParent: UElement?) : AbstractJavaUClass() { - override val uastParent: UElement? by lz { givenParent ?: convertParent() } - - //TODO: should be merged with KotlinAbstractUElement.convertParent() after detaching from AbstractJavaUClass - open fun convertParent(): UElement? = - (this.psi as? KtLightClassForLocalDeclaration)?.kotlinOrigin?.parent?.let { - when (it) { - is KtClassBody -> it.parent.toUElement() // TODO: it seems that `class_body`-s are never created in kotlin uast in top-down walk, probably they should be completely skipped and always unwrapped - else -> it.toUElement() - } - } ?: (psi.parent ?: psi.containingFile).toUElement() - -} - -open class KotlinUClass private constructor( - psi: KtLightClass, - givenParent: UElement? -) : AbstractKotlinUClass(givenParent), PsiClass by psi { - - val ktClass = psi.kotlinOrigin - - override val psi = unwrap(psi) - - override fun getOriginalElement(): PsiElement? = super.getOriginalElement() - - override fun getNameIdentifier(): PsiIdentifier? = UastLightIdentifier(psi, ktClass) - - override fun getContainingFile(): PsiFile? = unwrapFakeFileForLightClass(psi.containingFile) - - override val annotations: List - get() = ktClass?.annotationEntries?.map { KotlinUAnnotation(it, this) } ?: emptyList() - - override val uastAnchor: UElement - get() = UIdentifier(nameIdentifier, this) - - override fun getInnerClasses(): Array { - // filter DefaultImpls to avoid processing same methods from original interface multiple times - // filter Enum entry classes to avoid duplication with PsiEnumConstant initializer class - return psi.innerClasses.filter { - it.name != JvmAbi.DEFAULT_IMPLS_CLASS_NAME && !it.isEnumEntryLightClass() - }.mapNotNull { - getLanguagePlugin().convertOpt(it, this) - }.toTypedArray() - } - - override fun getSuperClass(): UClass? = super.getSuperClass() - override fun getFields(): Array = super.getFields() - override fun getInitializers(): Array = super.getInitializers() - - override fun getMethods(): Array { - val hasPrimaryConstructor = ktClass?.hasPrimaryConstructor() ?: false - var secondaryConstructorsCount = 0 - - fun createUMethod(psiMethod: PsiMethod): UMethod { - return if (psiMethod is KtLightMethod && - psiMethod.isConstructor) { - if (!hasPrimaryConstructor && secondaryConstructorsCount++ == 0) - KotlinSecondaryConstructorWithInitializersUMethod(ktClass, psiMethod, this) - else - KotlinConstructorUMethod(ktClass, psiMethod, this) - } else { - getLanguagePlugin().convertOpt(psiMethod, this) ?: reportConvertFailure(psiMethod) - } - } - - fun isDelegatedMethod(psiMethod: PsiMethod) = psiMethod is KtLightMethod && psiMethod.isDelegated - - return psi.methods.asSequence() - .filterNot(::isDelegatedMethod) - .map(::createUMethod) - .toList() - .toTypedArray() - } - - private fun PsiClass.isEnumEntryLightClass() = (this as? KtLightClass)?.kotlinOrigin is KtEnumEntry - - companion object { - fun create(psi: KtLightClass, containingElement: UElement?): UClass = when (psi) { - is PsiAnonymousClass -> KotlinUAnonymousClass(psi, containingElement) - is KtLightClassForScript -> KotlinScriptUClass(psi, containingElement) - else -> KotlinUClass(psi, containingElement) - } - } -} - -open class KotlinConstructorUMethod( - private val ktClass: KtClassOrObject?, - override val psi: KtLightMethod, - givenParent: UElement? -) : KotlinUMethod(psi, givenParent) { - - val isPrimary: Boolean - get() = psi.kotlinOrigin.let { it is KtPrimaryConstructor || it is KtClassOrObject } - - override val uastBody: UExpression? by lz { - val delegationCall: KtCallElement? = psi.kotlinOrigin.let { - when { - isPrimary -> ktClass?.superTypeListEntries?.firstIsInstanceOrNull() - it is KtSecondaryConstructor -> it.getDelegationCall() - else -> null - } - } - val bodyExpressions = getBodyExpressions() - if (delegationCall == null && bodyExpressions.isEmpty()) return@lz null - KotlinUBlockExpression.KotlinLazyUBlockExpression(this) { uastParent -> - SmartList().apply { - delegationCall?.let { - add(KotlinUFunctionCallExpression(it, uastParent)) - } - bodyExpressions.forEach { - add(KotlinConverter.convertOrEmpty(it, uastParent)) - } - } - } - } - - open protected fun getBodyExpressions(): List { - if (isPrimary) return getInitializers() - val bodyExpression = (psi.kotlinOrigin as? KtFunction)?.bodyExpression ?: return emptyList() - if (bodyExpression is KtBlockExpression) return bodyExpression.statements - return listOf(bodyExpression) - } - - protected fun getInitializers() = ktClass?.getAnonymousInitializers()?.mapNotNull { it.body } ?: emptyList() - -} - -// This class was created as a workaround for KT-21617 to be the only constructor which includes `init` block -// when there is no primary constructors in the class. -// It is expected to have only one constructor of this type in a UClass. -class KotlinSecondaryConstructorWithInitializersUMethod( - ktClass: KtClassOrObject?, - psi: KtLightMethod, - givenParent: UElement? -) : KotlinConstructorUMethod(ktClass, psi, givenParent) { - override fun getBodyExpressions(): List = getInitializers() + super.getBodyExpressions() -} - -class KotlinUAnonymousClass( - psi: PsiAnonymousClass, - givenParent: UElement? -) : AbstractKotlinUClass(givenParent), UAnonymousClass, PsiAnonymousClass by psi { - - override val psi: PsiAnonymousClass = unwrap(psi) - - override fun getOriginalElement(): PsiElement? = super.getOriginalElement() - - override fun getSuperClass(): UClass? = super.getSuperClass() - override fun getFields(): Array = super.getFields() - override fun getMethods(): Array = super.getMethods() - override fun getInitializers(): Array = super.getInitializers() - override fun getInnerClasses(): Array = super.getInnerClasses() - - override fun getContainingFile(): PsiFile = unwrapFakeFileForLightClass(psi.containingFile) - - override val uastAnchor: UElement? - get() { - val ktClassOrObject = (psi.originalElement as? KtLightClass)?.kotlinOrigin as? KtObjectDeclaration ?: return null - return UIdentifier(ktClassOrObject.getObjectKeyword(), this) - } - -} - -class KotlinScriptUClass( - psi: KtLightClassForScript, - override val uastParent: UElement? -) : AbstractJavaUClass(), PsiClass by psi { - override fun getContainingFile(): PsiFile = unwrapFakeFileForLightClass(psi.containingFile) - - override fun getNameIdentifier(): PsiIdentifier? = UastLightIdentifier(psi, psi.kotlinOrigin) - - override val uastAnchor: UElement - get() = UIdentifier(nameIdentifier, this) - - override val psi = unwrap(psi) - - override fun getSuperClass(): UClass? = super.getSuperClass() - - override fun getFields(): Array = super.getFields() - - override fun getInitializers(): Array = super.getInitializers() - - override fun getInnerClasses(): Array = - psi.innerClasses.mapNotNull { getLanguagePlugin().convertOpt(it, this) }.toTypedArray() - - override fun getMethods(): Array = psi.methods.map(this::createUMethod).toTypedArray() - - private fun createUMethod(method: PsiMethod): UMethod { - return if (method.isConstructor) { - KotlinScriptConstructorUMethod(psi.script, method as KtLightMethod, this) - } - else { - getLanguagePlugin().convertOpt(method, this) ?: reportConvertFailure(method) - } - } - - override fun getOriginalElement(): PsiElement? = psi.originalElement - - class KotlinScriptConstructorUMethod( - script: KtScript, - override val psi: KtLightMethod, - override val uastParent: UElement? - ) : KotlinUMethod(psi, uastParent) { - override val uastBody: UExpression? by lz { - val initializers = script.declarations.filterIsInstance() - KotlinUBlockExpression.create(initializers, this) - } - } -} -private fun reportConvertFailure(psiMethod: PsiMethod): Nothing { - val isValid = psiMethod.isValid - val report = KotlinExceptionWithAttachments( - "cant convert $psiMethod of ${psiMethod.javaClass} to UMethod" - + if (!isValid) " (method is not valid)" else "" - ) - - if (isValid) { - report.withAttachment("method", psiMethod.text) - psiMethod.containingFile?.let { - report.withAttachment("file", it.text) - } - } - - throw report -} \ No newline at end of file diff --git a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/declarations/KotlinUFile.kt.172 b/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/declarations/KotlinUFile.kt.172 deleted file mode 100644 index 33dde2e91d4..00000000000 --- a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/declarations/KotlinUFile.kt.172 +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.uast.kotlin - -import com.intellij.psi.PsiClass -import com.intellij.psi.PsiComment -import com.intellij.psi.PsiRecursiveElementWalkingVisitor -import org.jetbrains.kotlin.asJava.findFacadeClass -import org.jetbrains.kotlin.asJava.toLightClass -import org.jetbrains.kotlin.psi.KtClassOrObject -import org.jetbrains.kotlin.psi.KtFile -import org.jetbrains.uast.* -import java.util.* - -class KotlinUFile(override val psi: KtFile, override val languagePlugin: UastLanguagePlugin) : UFile { - override val packageName: String - get() = psi.packageFqName.asString() - - override val annotations: List - get() = psi.annotationEntries.map { KotlinUAnnotation(it, this) } - - override val allCommentsInFile by lz { - val comments = ArrayList(0) - psi.accept(object : PsiRecursiveElementWalkingVisitor() { - override fun visitComment(comment: PsiComment) { - comments += UComment(comment, this@KotlinUFile) - } - }) - comments - } - - override val imports by lz { psi.importDirectives.map { KotlinUImportStatement(it, this) } } - - override val classes by lz { - val facadeOrScriptClass = if (psi.isScript()) psi.script?.toLightClass() else psi.findFacadeClass() - val classes = psi.declarations.mapNotNull { (it as? KtClassOrObject)?.toLightClass()?.toUClass() } - - (facadeOrScriptClass?.toUClass()?.let { listOf(it) } ?: emptyList()) + classes - } - - private fun PsiClass.toUClass() = languagePlugin.convertOpt(this, this@KotlinUFile) -} \ No newline at end of file diff --git a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/declarations/KotlinUImportStatement.kt.172 b/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/declarations/KotlinUImportStatement.kt.172 deleted file mode 100644 index a990b42f918..00000000000 --- a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/declarations/KotlinUImportStatement.kt.172 +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.uast.kotlin - -import com.intellij.psi.PsiElement -import org.jetbrains.kotlin.psi.KtExpression -import org.jetbrains.kotlin.psi.KtImportDirective -import org.jetbrains.kotlin.psi.KtReferenceExpression -import org.jetbrains.kotlin.psi.psiUtil.getQualifiedElementSelector -import org.jetbrains.kotlin.resolve.BindingContext -import org.jetbrains.uast.UElement -import org.jetbrains.uast.UImportStatement -import org.jetbrains.uast.USimpleNameReferenceExpression - -class KotlinUImportStatement( - override val psi: KtImportDirective, - givenParent: UElement? -) : KotlinAbstractUElement(givenParent), UImportStatement { - override val isOnDemand: Boolean - get() = psi.isAllUnder - - private val importRef by lz { - psi.importedReference?.let { - ImportReference(it, psi.name ?: psi.text, this, psi) - } - } - - override val importReference: UElement? - get() = importRef - - override fun resolve() = importRef?.resolve() - - private class ImportReference( - override val psi: KtExpression, - override val identifier: String, - givenParent: UElement?, - private val importDirective: KtImportDirective - ) : KotlinAbstractUExpression(givenParent), USimpleNameReferenceExpression { - override val resolvedName: String? - get() = identifier - - override fun asRenderString(): String = importDirective.importedFqName?.asString() ?: psi.text - - override fun resolve(): PsiElement? { - val reference = psi.getQualifiedElementSelector() as? KtReferenceExpression ?: return null - val bindingContext = reference.analyze() - val referenceTarget = bindingContext[BindingContext.REFERENCE_TARGET, reference] ?: return null - return referenceTarget.toSource()?.getMaybeLightElement(this) - } - } -} \ No newline at end of file diff --git a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/declarations/KotlinUMethod.kt.172 b/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/declarations/KotlinUMethod.kt.172 deleted file mode 100644 index 75ca810f498..00000000000 --- a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/declarations/KotlinUMethod.kt.172 +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.uast.kotlin.declarations - -import com.intellij.psi.PsiCodeBlock -import com.intellij.psi.PsiElement -import com.intellij.psi.PsiFile -import com.intellij.psi.PsiMethod -import org.jetbrains.kotlin.asJava.elements.KtLightElement -import org.jetbrains.kotlin.asJava.elements.KtLightMethod -import org.jetbrains.kotlin.asJava.elements.isGetter -import org.jetbrains.kotlin.asJava.elements.isSetter -import org.jetbrains.kotlin.lexer.KtTokens -import org.jetbrains.kotlin.psi.* -import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject -import org.jetbrains.uast.* -import org.jetbrains.uast.java.annotations -import org.jetbrains.uast.java.internal.JavaUElementWithComments -import org.jetbrains.uast.kotlin.* - -open class KotlinUMethod( - psi: KtLightMethod, - givenParent: UElement? -) : KotlinAbstractUElement(givenParent), UAnnotationMethod, JavaUElementWithComments, PsiMethod by psi { - override val comments: List - get() = super.comments - - override val psi: KtLightMethod = unwrap(psi) - - override val uastDefaultValue by lz { - val annotationParameter = psi.kotlinOrigin as? KtParameter ?: return@lz null - val defaultValue = annotationParameter.defaultValue ?: return@lz null - getLanguagePlugin().convertElement(defaultValue, this) as? UExpression - } - - private val kotlinOrigin = (psi.originalElement as KtLightElement<*, *>).kotlinOrigin - - override fun getContainingFile(): PsiFile? = unwrapFakeFileForLightClass(psi.containingFile) - - override fun getNameIdentifier() = UastLightIdentifier(psi, kotlinOrigin as KtNamedDeclaration?) - - override val annotations by lz { - psi.annotations - .mapNotNull { (it as? KtLightElement<*, *>)?.kotlinOrigin as? KtAnnotationEntry } - .map { KotlinUAnnotation(it, this) } - } - - override val uastParameters by lz { - psi.parameterList.parameters.map { KotlinUParameter(it, this) } - } - - override val uastAnchor: UElement - get() = UIdentifier(nameIdentifier, this) - - - override val uastBody by lz { - val bodyExpression = when (kotlinOrigin) { - is KtFunction -> kotlinOrigin.bodyExpression - is KtProperty -> when { - psi.isGetter -> kotlinOrigin.getter?.bodyExpression - psi.isSetter -> kotlinOrigin.setter?.bodyExpression - else -> null - } - else -> null - } ?: return@lz null - - when (bodyExpression) { - !is KtBlockExpression -> { - KotlinUBlockExpression.KotlinLazyUBlockExpression(this, { block -> - val implicitReturn = KotlinUImplicitReturnExpression(block) - val uBody = getLanguagePlugin().convertElement(bodyExpression, implicitReturn) as? UExpression - ?: return@KotlinLazyUBlockExpression emptyList() - listOf(implicitReturn.apply { returnExpression = uBody }) - }) - - } - else -> getLanguagePlugin().convertElement(bodyExpression, this) as? UExpression - } - } - - override val isOverride: Boolean - get() = (kotlinOrigin as? KtCallableDeclaration)?.hasModifier(KtTokens.OVERRIDE_KEYWORD) ?: false - - override fun getBody(): PsiCodeBlock? = super.getBody() - - override fun getOriginalElement(): PsiElement? = super.getOriginalElement() - - override fun equals(other: Any?) = other is KotlinUMethod && psi == other.psi - - companion object { - fun create(psi: KtLightMethod, containingElement: UElement?) = - if (psi.kotlinOrigin is KtConstructor<*>) { - KotlinConstructorUMethod( - psi.kotlinOrigin?.containingClassOrObject, - psi, containingElement - ) - } - else - KotlinUMethod(psi, containingElement) - } -} \ No newline at end of file diff --git a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/declarations/KotlinUVariable.kt.172 b/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/declarations/KotlinUVariable.kt.172 deleted file mode 100644 index 196eb2a12ea..00000000000 --- a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/declarations/KotlinUVariable.kt.172 +++ /dev/null @@ -1,285 +0,0 @@ -/* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.uast.kotlin - -import com.intellij.psi.* -import org.jetbrains.kotlin.asJava.classes.KtLightClass -import org.jetbrains.kotlin.asJava.elements.KtLightElement -import org.jetbrains.kotlin.psi.* -import org.jetbrains.uast.* -import org.jetbrains.uast.internal.acceptList -import org.jetbrains.uast.java.JavaAbstractUExpression -import org.jetbrains.uast.java.JavaUAnnotation -import org.jetbrains.uast.java.annotations -import org.jetbrains.uast.kotlin.declarations.UastLightIdentifier -import org.jetbrains.uast.kotlin.psi.UastKotlinPsiParameter -import org.jetbrains.uast.kotlin.psi.UastKotlinPsiVariable -import org.jetbrains.uast.visitor.UastVisitor - -abstract class AbstractKotlinUVariable(givenParent: UElement?) - : KotlinAbstractUElement(givenParent), PsiVariable, UVariable { - - override val uastInitializer: UExpression? - get() { - val psi = psi - val initializerExpression = when (psi) { - is UastKotlinPsiVariable -> psi.ktInitializer - is UastKotlinPsiParameter -> psi.ktDefaultValue - is KtLightElement<*, *> -> { - val origin = psi.kotlinOrigin - when (origin) { - is KtVariableDeclaration -> origin.initializer - is KtParameter -> origin.defaultValue - else -> null - } - } - else -> null - } ?: return null - return getLanguagePlugin().convertElement(initializerExpression, this) as? UExpression ?: UastEmptyExpression - } - - val delegateExpression: UExpression? by lz { - val psi = psi - val expression = when (psi) { - is KtLightElement<*, *> -> (psi.kotlinOrigin as? KtProperty)?.delegateExpression - is UastKotlinPsiVariable -> (psi.ktElement as? KtProperty)?.delegateExpression - else -> null - } - - expression?.let { getLanguagePlugin().convertElement(it, this) as? UExpression } - } - - override fun getNameIdentifier(): PsiIdentifier { - val kotlinOrigin = (psi as? KtLightElement<*, *>)?.kotlinOrigin - return UastLightIdentifier(psi, kotlinOrigin as KtNamedDeclaration?) - } - - override fun getContainingFile(): PsiFile = unwrapFakeFileForLightClass(psi.containingFile) - - override val annotations: List by lz { psi.annotations.map { JavaUAnnotation(it, this) } } - - override val typeReference by lz { getLanguagePlugin().convertOpt(psi.typeElement, this) } - - override val uastAnchor: UElement? - get() = UIdentifier(nameIdentifier, this) - - override fun equals(other: Any?) = other is AbstractKotlinUVariable && psi == other.psi -} - -class KotlinUVariable( - psi: PsiVariable, - givenParent: UElement? -) : AbstractKotlinUVariable(givenParent), UVariable, PsiVariable by psi { - override val psi = unwrap(psi) - - override val annotations by lz { psi.annotations.map { JavaUAnnotation(it, this) } } - - override val typeReference by lz { getLanguagePlugin().convertOpt(psi.typeElement, this) } - - override fun getInitializer(): PsiExpression? { - return super.getInitializer() - } - - override fun getOriginalElement(): PsiElement? { - return super.getOriginalElement() - } - - override fun getNameIdentifier(): PsiIdentifier { - return super.getNameIdentifier() - } - - override fun getContainingFile(): PsiFile { - return super.getContainingFile() - } -} - -open class KotlinUParameter( - psi: PsiParameter, - givenParent: UElement? -) : AbstractKotlinUVariable(givenParent), UParameter, PsiParameter by psi { - - override val psi = unwrap(psi) - - override fun getInitializer(): PsiExpression? { - return super.getInitializer() - } - - override fun getOriginalElement(): PsiElement? { - return super.getOriginalElement() - } - - override fun getNameIdentifier(): PsiIdentifier { - return super.getNameIdentifier() - } - - override fun getContainingFile(): PsiFile { - return super.getContainingFile() - } -} - -open class KotlinUField( - psi: PsiField, - givenParent: UElement? -) : AbstractKotlinUVariable(givenParent), UField, PsiField by psi { - - override val psi = unwrap(psi) - - override fun getInitializer(): PsiExpression? { - return super.getInitializer() - } - - override fun getOriginalElement(): PsiElement? { - return super.getOriginalElement() - } - - override fun getNameIdentifier(): PsiIdentifier { - return super.getNameIdentifier() - } - - override fun getContainingFile(): PsiFile { - return super.getContainingFile() - } - - override fun isPhysical(): Boolean { - return true - } - - override fun accept(visitor: UastVisitor) { - if (visitor.visitField(this)) return - annotations.acceptList(visitor) - uastInitializer?.accept(visitor) - delegateExpression?.accept(visitor) - visitor.afterVisitField(this) - } -} - -open class KotlinULocalVariable( - psi: PsiLocalVariable, - givenParent: UElement? -) : AbstractKotlinUVariable(givenParent), ULocalVariable, PsiLocalVariable by psi { - - override val psi = unwrap(psi) - - override fun getInitializer(): PsiExpression? { - return super.getInitializer() - } - - override fun getOriginalElement(): PsiElement? { - return super.getOriginalElement() - } - - override fun getNameIdentifier(): PsiIdentifier { - return super.getNameIdentifier() - } - - override fun getContainingFile(): PsiFile { - return super.getContainingFile() - } - - override fun accept(visitor: UastVisitor) { - if (visitor.visitLocalVariable(this)) return - annotations.acceptList(visitor) - uastInitializer?.accept(visitor) - delegateExpression?.accept(visitor) - visitor.afterVisitLocalVariable(this) - } -} - -open class KotlinUAnnotatedLocalVariable( - psi: PsiLocalVariable, - uastParent: UElement?, - computeAnnotations: (parent: UElement) -> List -) : KotlinULocalVariable(psi, uastParent) { - - override val annotations: List by lz { computeAnnotations(this) } -} - -open class KotlinUEnumConstant( - psi: PsiEnumConstant, - givenParent: UElement? -) : AbstractKotlinUVariable(givenParent), UEnumConstant, PsiEnumConstant by psi { - override val initializingClass: UClass? by lz { - (psi.initializingClass as? KtLightClass)?.let { initializingClass -> - KotlinUClass.create(initializingClass, this) - } - } - - override val psi = unwrap(psi) - - override fun getContainingFile(): PsiFile { - return super.getContainingFile() - } - - override fun getNameIdentifier(): PsiIdentifier { - return super.getNameIdentifier() - } - - override val kind: UastCallKind - get() = UastCallKind.CONSTRUCTOR_CALL - - override val receiver: UExpression? - get() = null - - override val receiverType: PsiType? - get() = null - - override val methodIdentifier: UIdentifier? - get() = null - - override val classReference: UReferenceExpression? - get() = KotlinEnumConstantClassReference(psi, this) - - override val typeArgumentCount: Int - get() = 0 - - override val typeArguments: List - get() = emptyList() - - override val valueArgumentCount: Int - get() = psi.argumentList?.expressions?.size ?: 0 - - override val valueArguments by lz(fun(): List { - val ktEnumEntry = (psi as? KtLightElement<*, *>)?.kotlinOrigin as? KtEnumEntry ?: return emptyList() - val ktSuperTypeCallEntry = ktEnumEntry.initializerList?.initializers?.firstOrNull() as? KtSuperTypeCallEntry ?: return emptyList() - return ktSuperTypeCallEntry.valueArguments.map { - it.getArgumentExpression()?.let { getLanguagePlugin().convertElement(it, this) } as? UExpression ?: UastEmptyExpression - } - }) - - override val returnType: PsiType? - get() = psi.type - - override fun resolve() = psi.resolveMethod() - - override val methodName: String? - get() = null - - private class KotlinEnumConstantClassReference( - override val psi: PsiEnumConstant, - private val givenParent: UElement? - ) : JavaAbstractUExpression(), USimpleNameReferenceExpression { - override val uastParent: UElement? by lz { - givenParent ?: KotlinUastLanguagePlugin().convertElementWithParent(psi.parent ?: psi.containingFile, null) - } - - override fun resolve() = psi.containingClass - override val resolvedName: String? - get() = psi.containingClass?.name - override val identifier: String - get() = psi.containingClass?.name ?: "" - } -} \ No newline at end of file diff --git a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/ElvisExpression.kt.172 b/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/ElvisExpression.kt.172 deleted file mode 100644 index 07508f4f6e1..00000000000 --- a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/ElvisExpression.kt.172 +++ /dev/null @@ -1,110 +0,0 @@ -package org.jetbrains.uast.kotlin.expressions - -import com.intellij.psi.PsiElement -import com.intellij.psi.PsiMethod -import com.intellij.psi.PsiType -import org.jetbrains.kotlin.psi.KtBinaryExpression -import org.jetbrains.kotlin.psi.KtExpression -import org.jetbrains.kotlin.resolve.BindingContext -import org.jetbrains.kotlin.types.CommonSupertypes -import org.jetbrains.uast.* -import org.jetbrains.uast.kotlin.* -import org.jetbrains.uast.kotlin.kinds.KotlinSpecialExpressionKinds -import org.jetbrains.uast.kotlin.psi.UastKotlinPsiVariable - - -private fun createVariableReferenceExpression(variable: UVariable, containingElement: UElement?) = - object : USimpleNameReferenceExpression { - override val psi: PsiElement? = null - override fun resolve(): PsiElement? = variable - override val uastParent: UElement? = containingElement - override val resolvedName: String? = variable.name - override val annotations: List = emptyList() - override val identifier: String = variable.name.orAnonymous() - } - -private fun createNullLiteralExpression(containingElement: UElement?) = - object : ULiteralExpression { - override val psi: PsiElement? = null - override val uastParent: UElement? = containingElement - override val value: Any? = null - override val annotations: List = emptyList() - } - -private fun createNotEqWithNullExpression(variable: UVariable, containingElement: UElement?) = - object : UBinaryExpression { - override val psi: PsiElement? = null - override val uastParent: UElement? = containingElement - override val leftOperand: UExpression by lz { createVariableReferenceExpression(variable, this) } - override val rightOperand: UExpression by lz { createNullLiteralExpression(this) } - override val operator: UastBinaryOperator = UastBinaryOperator.NOT_EQUALS - override val operatorIdentifier: UIdentifier? = UIdentifier(null, this) - override fun resolveOperator(): PsiMethod? = null - override val annotations: List = emptyList() - } - -private fun createElvisExpressions( - left: KtExpression, - right: KtExpression, - containingElement: UElement?, - psiParent: PsiElement): List { - - val declaration = KotlinUDeclarationsExpression(containingElement) - val tempVariable = KotlinULocalVariable(UastKotlinPsiVariable.create(left, declaration, psiParent), declaration) - declaration.declarations = listOf(tempVariable) - - val ifExpression = object : UIfExpression { - override val psi: PsiElement? = null - override val uastParent: UElement? = containingElement - override val condition: UExpression by lz { createNotEqWithNullExpression(tempVariable, this) } - override val thenExpression: UExpression? by lz { createVariableReferenceExpression(tempVariable, this) } - override val elseExpression: UExpression? by lz { KotlinConverter.convertExpression(right, this ) } - override val isTernary: Boolean = false - override val annotations: List = emptyList() - override val ifIdentifier: UIdentifier = UIdentifier(null, this) - override val elseIdentifier: UIdentifier? = UIdentifier(null, this) - } - - return listOf(declaration, ifExpression) -} - -fun createElvisExpression(elvisExpression: KtBinaryExpression, givenParent: UElement?): UExpression { - val left = elvisExpression.left ?: return UastEmptyExpression - val right = elvisExpression.right ?: return UastEmptyExpression - - return KotlinUElvisExpression(elvisExpression, left, right, givenParent) -} - -class KotlinUElvisExpression( - private val elvisExpression: KtBinaryExpression, - private val left: KtExpression, - private val right: KtExpression, - givenParent: UElement? -) : KotlinAbstractUElement(givenParent), UExpressionList, KotlinEvaluatableUElement { - - override val psi: PsiElement? = elvisExpression - override val kind = KotlinSpecialExpressionKinds.ELVIS - override val annotations: List = emptyList() - override val expressions: List by lz { - createElvisExpressions(left, right, this, elvisExpression.parent) - } - - val lhsDeclaration get() = (expressions[0] as UDeclarationsExpression).declarations.single() - val rhsIfExpression get() = expressions[1] as UIfExpression - - override fun asRenderString(): String { - return kind.name + " " + - expressions.joinToString(separator = "\n", prefix = "{\n", postfix = "\n}") { - it.asRenderString().withMargin - } - } - - override fun getExpressionType(): PsiType? { - val leftType = left.analyze()[BindingContext.EXPRESSION_TYPE_INFO, left]?.type ?: return null - val rightType = right.analyze()[BindingContext.EXPRESSION_TYPE_INFO, right]?.type ?: return null - - return CommonSupertypes - .commonSupertype(listOf(leftType, rightType)) - .toPsiType(this, elvisExpression, boxed = false) - } -} diff --git a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinUBlockExpression.kt.172 b/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinUBlockExpression.kt.172 deleted file mode 100644 index 244e6d7aa04..00000000000 --- a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinUBlockExpression.kt.172 +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.uast.kotlin - -import com.intellij.psi.PsiElement -import org.jetbrains.kotlin.psi.KtAnonymousInitializer -import org.jetbrains.kotlin.psi.KtBlockExpression -import org.jetbrains.uast.* - -class KotlinUBlockExpression( - override val psi: KtBlockExpression, - givenParent: UElement? -) : KotlinAbstractUExpression(givenParent), UBlockExpression, KotlinUElementWithType { - override val expressions by lz { psi.statements.map { KotlinConverter.convertOrEmpty(it, this) } } - - class KotlinLazyUBlockExpression( - override val uastParent: UElement?, - expressionProducer: (expressionParent: UElement) -> List - ) : UBlockExpression { - override val psi: PsiElement? = null - override val annotations: List = emptyList() - override val expressions by lz { expressionProducer(this) } - } - - companion object { - fun create(initializers: List, uastParent: UElement): UBlockExpression { - val languagePlugin = uastParent.getLanguagePlugin() - return KotlinLazyUBlockExpression(uastParent) { expressionParent -> - initializers.map { languagePlugin.convertOpt(it.body, expressionParent) ?: UastEmptyExpression } - } - } - } - - override fun convertParent(): UElement? { - val directParent = super.convertParent() - if (directParent is UnknownKotlinExpression && directParent.psi is KtAnonymousInitializer) { - val containingUClass = directParent.getContainingUClass() ?: return directParent - containingUClass.methods - .find { it is KotlinConstructorUMethod && it.isPrimary || it is KotlinSecondaryConstructorWithInitializersUMethod }?.let { - return it.uastBody - } - } - return directParent - } -} \ No newline at end of file diff --git a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinUCatchClause.kt.172 b/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinUCatchClause.kt.172 deleted file mode 100644 index c2936f10844..00000000000 --- a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinUCatchClause.kt.172 +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.uast.kotlin - -import org.jetbrains.kotlin.psi.KtCatchClause -import org.jetbrains.uast.UCatchClause -import org.jetbrains.uast.UElement -import org.jetbrains.uast.UParameter -import org.jetbrains.uast.UTypeReferenceExpression -import org.jetbrains.uast.kotlin.psi.UastKotlinPsiParameter - -class KotlinUCatchClause( - override val psi: KtCatchClause, - givenParent: UElement? -) : KotlinAbstractUElement(givenParent), UCatchClause { - override val body by lz { KotlinConverter.convertOrEmpty(psi.catchBody, this) } - - override val parameters by lz { - val parameter = psi.catchParameter ?: return@lz emptyList() - listOf(KotlinUParameter(UastKotlinPsiParameter.create(parameter, psi, this, 0), this)) - } - - override val typeReferences by lz { - val parameter = psi.catchParameter ?: return@lz emptyList() - val typeReference = parameter.typeReference ?: return@lz emptyList() - listOf(LazyKotlinUTypeReferenceExpression(typeReference, this) { typeReference.toPsiType(this, boxed = true) } ) - } -} \ No newline at end of file diff --git a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinUCollectionLiteralExpression.kt.172 b/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinUCollectionLiteralExpression.kt.172 deleted file mode 100644 index f2b14e0d8a0..00000000000 --- a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinUCollectionLiteralExpression.kt.172 +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2000-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.uast.kotlin.expressions - -import com.intellij.psi.PsiArrayType -import com.intellij.psi.PsiElement -import com.intellij.psi.PsiMethod -import com.intellij.psi.PsiType -import org.jetbrains.kotlin.psi.KtCollectionLiteralExpression -import org.jetbrains.uast.* -import org.jetbrains.uast.kotlin.KotlinAbstractUExpression -import org.jetbrains.uast.kotlin.KotlinConverter -import org.jetbrains.uast.kotlin.KotlinUElementWithType - -class KotlinUCollectionLiteralExpression( - val sourcePsi: KtCollectionLiteralExpression, - givenParent: UElement? -) : KotlinAbstractUExpression(givenParent), UCallExpression, KotlinUElementWithType { - - override val classReference: UReferenceExpression? get() = null - - override val kind: UastCallKind = UastCallKind.NESTED_ARRAY_INITIALIZER - - override val methodIdentifier: UIdentifier? by lazy { UIdentifier(sourcePsi.leftBracket, this) } - - override val methodName: String? get() = null - - override val receiver: UExpression? get() = null - - override val receiverType: PsiType? get() = null - - override val returnType: PsiType? get() = getExpressionType() - - override val typeArgumentCount: Int get() = typeArguments.size - - override val typeArguments: List get() = listOfNotNull((returnType as? PsiArrayType)?.componentType) - - override val valueArgumentCount: Int - get() = sourcePsi.getInnerExpressions().size - - override val valueArguments by lazy { - sourcePsi.getInnerExpressions().map { KotlinConverter.convertOrEmpty(it, this) } - } - - override fun asRenderString(): String = "collectionLiteral[" + valueArguments.joinToString { it.asRenderString() } + "]" - - override fun resolve(): PsiMethod? = null - - override val psi: PsiElement get() = sourcePsi - -} \ No newline at end of file diff --git a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinUDeclarationsExpression.kt.172 b/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinUDeclarationsExpression.kt.172 deleted file mode 100644 index eb934ef0d54..00000000000 --- a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinUDeclarationsExpression.kt.172 +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.uast - -import com.intellij.psi.PsiElement -import org.jetbrains.uast.kotlin.KotlinAbstractUExpression -import org.jetbrains.uast.kotlin.doConvertParent - -open class KotlinUDeclarationsExpression( - override val psi: PsiElement?, - givenParent: UElement?, - val psiAnchor: PsiElement? = null -) : KotlinAbstractUExpression(givenParent), UDeclarationsExpression { - - override val uastParent: UElement? - get() = if (psiAnchor != null) doConvertParent(this, psiAnchor.parent) else super.uastParent - - constructor(uastParent: UElement?) : this(null, uastParent) - - override lateinit var declarations: List - internal set -} - -class KotlinUDestructuringDeclarationExpression( - givenParent: UElement?, - psiAnchor: PsiElement -) : KotlinUDeclarationsExpression(null, givenParent, psiAnchor) { - - val tempVarAssignment get() = declarations.first() -} diff --git a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinUForEachExpression.kt.172 b/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinUForEachExpression.kt.172 deleted file mode 100644 index c6ce608d15a..00000000000 --- a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinUForEachExpression.kt.172 +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.uast.kotlin - -import org.jetbrains.kotlin.idea.KotlinLanguage -import org.jetbrains.kotlin.psi.KtForExpression -import org.jetbrains.uast.UElement -import org.jetbrains.uast.UForEachExpression -import org.jetbrains.uast.UIdentifier -import org.jetbrains.uast.kotlin.psi.UastKotlinPsiParameter -import org.jetbrains.uast.psi.UastPsiParameterNotResolved - -class KotlinUForEachExpression( - override val psi: KtForExpression, - givenParent: UElement? -) : KotlinAbstractUExpression(givenParent), UForEachExpression { - override val iteratedValue by lz { KotlinConverter.convertOrEmpty(psi.loopRange, this) } - override val body by lz { KotlinConverter.convertOrEmpty(psi.body, this) } - - override val variable by lz { - val parameter = psi.loopParameter?.let { UastKotlinPsiParameter.create(it, psi, this, 0) } - ?: UastPsiParameterNotResolved(psi, KotlinLanguage.INSTANCE) - KotlinUParameter(parameter, this) - } - - override val forIdentifier: UIdentifier - get() = UIdentifier(null, this) -} \ No newline at end of file diff --git a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinULambdaExpression.kt.172 b/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinULambdaExpression.kt.172 deleted file mode 100644 index 3259aa4d6ce..00000000000 --- a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinULambdaExpression.kt.172 +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.uast.kotlin - -import com.intellij.psi.PsiType -import org.jetbrains.kotlin.psi.KtLambdaExpression -import org.jetbrains.uast.UBlockExpression -import org.jetbrains.uast.UElement -import org.jetbrains.uast.ULambdaExpression -import org.jetbrains.uast.kotlin.psi.UastKotlinPsiParameter -import org.jetbrains.uast.withMargin - -class KotlinULambdaExpression( - override val psi: KtLambdaExpression, - givenParent: UElement? -) : KotlinAbstractUExpression(givenParent), ULambdaExpression, KotlinUElementWithType { - val functionalInterfaceType: PsiType? - get() = getFunctionalInterfaceType() - - override val body by lz { KotlinConverter.convertOrEmpty(psi.bodyExpression, this) } - - override val valueParameters by lz { - psi.valueParameters.mapIndexed { i, p -> - KotlinUParameter(UastKotlinPsiParameter.create(p, psi, this, i), this) - } - } - - override fun asRenderString(): String { - val renderedValueParameters = if (valueParameters.isEmpty()) - "" - else - valueParameters.joinToString { it.asRenderString() } + " ->\n" - val expressions = (body as? UBlockExpression)?.expressions - ?.joinToString("\n") { it.asRenderString().withMargin } ?: body.asRenderString() - - return "{ $renderedValueParameters\n$expressions\n}" - } -} \ No newline at end of file diff --git a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinUNamedExpression.kt.172 b/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinUNamedExpression.kt.172 deleted file mode 100644 index 64ccd05600a..00000000000 --- a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinUNamedExpression.kt.172 +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.uast.kotlin - -import com.intellij.psi.PsiElement -import com.intellij.psi.PsiType -import org.jetbrains.kotlin.psi.ValueArgument -import org.jetbrains.uast.* - -class KotlinUNamedExpression private constructor( - override val name: String?, - givenParent: UElement?, - expressionProducer: (UElement) -> UExpression -) : KotlinAbstractUElement(givenParent), UNamedExpression { - - override val expression: UExpression by lz { expressionProducer(this) } - - override val annotations: List = emptyList() - - override val psi: PsiElement? = null - - companion object { - internal fun create(name: String?, valueArgument: ValueArgument, uastParent: UElement?): UNamedExpression { - val expression = valueArgument.getArgumentExpression() - return KotlinUNamedExpression(name, uastParent) { expressionParent -> - expression?.let { expressionParent.getLanguagePlugin().convertOpt(it, expressionParent) } - ?: UastEmptyExpression - } - } - - internal fun create( - name: String?, - valueArguments: List, - uastParent: UElement? - ): UNamedExpression { - return KotlinUNamedExpression(name, uastParent) { expressionParent -> - KotlinUVarargExpression(valueArguments, expressionParent) - } - } - } -} - -class KotlinUVarargExpression( - private val valueArgs: List, - uastParent: UElement? -) : KotlinAbstractUExpression(uastParent), UCallExpression { - override val kind: UastCallKind = UastCallKind.NESTED_ARRAY_INITIALIZER - - override val valueArguments: List by lz { - valueArgs.map { - it.getArgumentExpression()?.let { argumentExpression -> - getLanguagePlugin().convert(argumentExpression, this) - } ?: UastEmptyExpression - } - } - - override val valueArgumentCount: Int - get() = valueArgs.size - - override val psi: PsiElement? - get() = null - - override val methodIdentifier: UIdentifier? - get() = null - - override val classReference: UReferenceExpression? - get() = null - - override val methodName: String? - get() = null - - override val typeArgumentCount: Int - get() = 0 - - override val typeArguments: List - get() = emptyList() - - override val returnType: PsiType? - get() = null - - override fun resolve() = null - - override val receiver: UExpression? - get() = null - - override val receiverType: PsiType? - get() = null -} diff --git a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinUObjectLiteralExpression.kt.172 b/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinUObjectLiteralExpression.kt.172 deleted file mode 100644 index 51fe5966265..00000000000 --- a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinUObjectLiteralExpression.kt.172 +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.uast.kotlin - -import com.intellij.openapi.diagnostic.Attachment -import com.intellij.openapi.diagnostic.Logger -import com.intellij.psi.PsiMethod -import com.intellij.psi.PsiType -import com.intellij.psi.impl.light.LightPsiClassBuilder -import org.jetbrains.kotlin.asJava.classes.KtLightClass -import org.jetbrains.kotlin.asJava.toLightClass -import org.jetbrains.kotlin.psi.KtObjectLiteralExpression -import org.jetbrains.kotlin.psi.KtSuperTypeCallEntry -import org.jetbrains.uast.* - -class KotlinUObjectLiteralExpression( - override val psi: KtObjectLiteralExpression, - givenParent: UElement? -) : KotlinAbstractUExpression(givenParent), UObjectLiteralExpression, KotlinUElementWithType { - - override val declaration: UClass by lz { - val lightClass: KtLightClass? = psi.objectDeclaration.toLightClass() - if (lightClass != null) { - getLanguagePlugin().convert(lightClass, this) - } else { - logger.error( - "Failed to create light class for object declaration", - Attachment(psi.containingFile.virtualFile?.path ?: "", psi.containingFile.text) - ) - - getLanguagePlugin().convert(LightPsiClassBuilder(psi, ""), this) - } - } - - override fun getExpressionType() = psi.objectDeclaration.toPsiType() - - private val superClassConstructorCall by lz { - psi.objectDeclaration.superTypeListEntries.firstOrNull { it is KtSuperTypeCallEntry } as? KtSuperTypeCallEntry - } - - override val classReference: UReferenceExpression? by lz { superClassConstructorCall?.let { ObjectLiteralClassReference(it, this) } } - - override val valueArgumentCount: Int - get() = superClassConstructorCall?.valueArguments?.size ?: 0 - - override val valueArguments by lz { - val psi = superClassConstructorCall ?: return@lz emptyList() - psi.valueArguments.map { KotlinConverter.convertOrEmpty(it.getArgumentExpression(), this) } - } - - override val typeArgumentCount: Int - get() = superClassConstructorCall?.typeArguments?.size ?: 0 - - override val typeArguments by lz { - val psi = superClassConstructorCall ?: return@lz emptyList() - psi.typeArguments.map { it.typeReference.toPsiType(this, boxed = true) } - } - - override fun resolve() = superClassConstructorCall?.resolveCallToDeclaration(this) as? PsiMethod - - private class ObjectLiteralClassReference( - override val psi: KtSuperTypeCallEntry, - givenParent: UElement? - ) : KotlinAbstractUElement(givenParent), USimpleNameReferenceExpression { - - override fun resolve() = (psi.resolveCallToDeclaration(this) as? PsiMethod)?.containingClass - - override val annotations: List - get() = emptyList() - - override val resolvedName: String? - get() = identifier - - override val identifier: String - get() = psi.name ?: "" - } - - companion object { - val logger by lz { Logger.getInstance(KotlinUObjectLiteralExpression::class.java) } - } -} \ No newline at end of file diff --git a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinUSimpleReferenceExpression.kt.172 b/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinUSimpleReferenceExpression.kt.172 deleted file mode 100644 index 90022da8f0d..00000000000 --- a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinUSimpleReferenceExpression.kt.172 +++ /dev/null @@ -1,217 +0,0 @@ -/* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.uast.kotlin - -import com.intellij.psi.PsiElement -import com.intellij.psi.PsiMethod -import com.intellij.psi.PsiNamedElement -import org.jetbrains.kotlin.descriptors.CallableDescriptor -import org.jetbrains.kotlin.descriptors.ConstructorDescriptor -import org.jetbrains.kotlin.descriptors.DeclarationDescriptor -import org.jetbrains.kotlin.lexer.KtTokens -import org.jetbrains.kotlin.psi.* -import org.jetbrains.kotlin.psi.psiUtil.getAssignmentByLHS -import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis -import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall -import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall -import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor -import org.jetbrains.kotlin.utils.addToStdlib.constant -import org.jetbrains.uast.* -import org.jetbrains.uast.visitor.UastVisitor - -open class KotlinUSimpleReferenceExpression( - override val psi: KtSimpleNameExpression, - givenParent: UElement? -) : KotlinAbstractUExpression(givenParent), USimpleNameReferenceExpression, KotlinUElementWithType, KotlinEvaluatableUElement { - private val resolvedDeclaration by lz { psi.resolveCallToDeclaration(this) } - - override val identifier get() = psi.getReferencedName() - - override fun resolve() = resolvedDeclaration - - override val resolvedName: String? - get() = (resolvedDeclaration as? PsiNamedElement)?.name - - override fun accept(visitor: UastVisitor) { - visitor.visitSimpleNameReferenceExpression(this) - - if (psi.parent.destructuringDeclarationInitializer != true) { - visitAccessorCalls(visitor) - } - - visitor.afterVisitSimpleNameReferenceExpression(this) - } - - private fun visitAccessorCalls(visitor: UastVisitor) { - // Visit Kotlin get-set synthetic Java property calls as function calls - val bindingContext = psi.analyze() - val access = psi.readWriteAccess() - val resolvedCall = psi.getResolvedCall(bindingContext) - val resultingDescriptor = resolvedCall?.resultingDescriptor as? SyntheticJavaPropertyDescriptor - if (resultingDescriptor != null) { - val setterValue = if (access.isWrite) { - findAssignment(psi, psi.parent)?.right ?: run { - visitor.afterVisitSimpleNameReferenceExpression(this) - return - } - } else { - null - } - - if (resolvedCall != null) { - if (access.isRead) { - val getDescriptor = resultingDescriptor.getMethod - KotlinAccessorCallExpression(psi, this, resolvedCall, getDescriptor, null).accept(visitor) - } - - if (access.isWrite && setterValue != null) { - val setDescriptor = resultingDescriptor.setMethod - if (setDescriptor != null) { - KotlinAccessorCallExpression(psi, this, resolvedCall, setDescriptor, setterValue).accept(visitor) - } - } - } - } - } - - private tailrec fun findAssignment(prev: PsiElement?, element: PsiElement?): KtBinaryExpression? = when (element) { - is KtBinaryExpression -> if (element.left == prev && element.operationToken == KtTokens.EQ) element else null - is KtQualifiedExpression -> findAssignment(element, element.parent) - is KtSimpleNameExpression -> findAssignment(element, element.parent) - else -> null - } - - class KotlinAccessorCallExpression( - override val psi: KtElement, - override val uastParent: KotlinUSimpleReferenceExpression, - private val resolvedCall: ResolvedCall<*>, - private val accessorDescriptor: DeclarationDescriptor, - val setterValue: KtExpression? - ) : UCallExpression { - override val methodName: String? - get() = accessorDescriptor.name.asString() - - override val receiver: UExpression? - get() { - val containingElement = uastParent.uastParent - return if (containingElement is UQualifiedReferenceExpression && containingElement.selector == this) - containingElement.receiver - else - null - } - - override val annotations: List - get() = emptyList() - - override val receiverType by lz { - val type = (resolvedCall.dispatchReceiver ?: resolvedCall.extensionReceiver)?.type ?: return@lz null - type.toPsiType(this, psi, boxed = true) - } - - override val methodIdentifier: UIdentifier? - get() = UIdentifier(uastParent.psi, this) - - override val classReference: UReferenceExpression? - get() = null - - override val valueArgumentCount: Int - get() = if (setterValue != null) 1 else 0 - - override val valueArguments by lz { - if (setterValue != null) - listOf(KotlinConverter.convertOrEmpty(setterValue, this)) - else - emptyList() - } - - override val typeArgumentCount: Int - get() = resolvedCall.typeArguments.size - - override val typeArguments by lz { - resolvedCall.typeArguments.values.map { it.toPsiType(this, psi, true) } - } - - override val returnType by lz { - (accessorDescriptor as? CallableDescriptor)?.returnType?.toPsiType(this, psi, boxed = false) - } - - override val kind: UastCallKind - get() = UastCallKind.METHOD_CALL - - override fun resolve(): PsiMethod? { - val source = accessorDescriptor.toSource() - return resolveSource(psi, accessorDescriptor, source) - } - } - - enum class ReferenceAccess(val isRead: Boolean, val isWrite: Boolean) { - READ(true, false), WRITE(false, true), READ_WRITE(true, true) - } - - private fun KtExpression.readWriteAccess(): ReferenceAccess { - var expression = getQualifiedExpressionForSelectorOrThis() - loop@ while (true) { - val parent = expression.parent - when (parent) { - is KtParenthesizedExpression, is KtAnnotatedExpression, is KtLabeledExpression -> expression = parent as KtExpression - else -> break@loop - } - } - - val assignment = expression.getAssignmentByLHS() - if (assignment != null) { - return when (assignment.operationToken) { - KtTokens.EQ -> ReferenceAccess.WRITE - else -> ReferenceAccess.READ_WRITE - } - } - - return if ((expression.parent as? KtUnaryExpression)?.operationToken - in constant { setOf(KtTokens.PLUSPLUS, KtTokens.MINUSMINUS) }) - ReferenceAccess.READ_WRITE - else - ReferenceAccess.READ - } -} - -class KotlinClassViaConstructorUSimpleReferenceExpression( - override val psi: KtCallElement, - override val identifier: String, - givenParent: UElement? -) : KotlinAbstractUExpression(givenParent), USimpleNameReferenceExpression, KotlinUElementWithType { - override val resolvedName: String? - get() = (psi.getResolvedCall(psi.analyze())?.resultingDescriptor as? ConstructorDescriptor) - ?.containingDeclaration?.name?.asString() - - override fun resolve(): PsiElement? { - val resolvedCall = psi.getResolvedCall(psi.analyze()) - val resultingDescriptor = resolvedCall?.resultingDescriptor as? ConstructorDescriptor ?: return null - val clazz = resultingDescriptor.containingDeclaration - return clazz.toSource()?.getMaybeLightElement(this) - } -} - -class KotlinStringUSimpleReferenceExpression( - override val identifier: String, - givenParent: UElement? -) : KotlinAbstractUExpression(givenParent), USimpleNameReferenceExpression { - override val psi: PsiElement? - get() = null - override fun resolve() = null - override val resolvedName: String? - get() = identifier -} \ No newline at end of file diff --git a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinUSwitchExpression.kt.172 b/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinUSwitchExpression.kt.172 deleted file mode 100644 index 0d6323304b1..00000000000 --- a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/KotlinUSwitchExpression.kt.172 +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.uast.kotlin - -import com.intellij.psi.PsiElement -import org.jetbrains.kotlin.psi.KtBlockExpression -import org.jetbrains.kotlin.psi.KtWhenEntry -import org.jetbrains.kotlin.psi.KtWhenExpression -import org.jetbrains.uast.* -import org.jetbrains.uast.kotlin.kinds.KotlinSpecialExpressionKinds - -class KotlinUSwitchExpression( - override val psi: KtWhenExpression, - givenParent: UElement? -) : KotlinAbstractUExpression(givenParent), USwitchExpression, KotlinUElementWithType { - override val expression by lz { KotlinConverter.convertOrNull(psi.subjectExpression, this) } - - override val body: UExpressionList by lz { - object : KotlinUExpressionList(psi, KotlinSpecialExpressionKinds.WHEN, this@KotlinUSwitchExpression) { - override fun asRenderString() = expressions.joinToString("\n") { it.asRenderString().withMargin } - }.apply { - expressions = this@KotlinUSwitchExpression.psi.entries.map { KotlinUSwitchEntry(it, this) } - } - } - - override fun asRenderString() = buildString { - val expr = expression?.let { "(" + it.asRenderString() + ") " } ?: "" - appendln("switch $expr {") - appendln(body.asRenderString()) - appendln("}") - } - - override val switchIdentifier: UIdentifier - get() = UIdentifier(null, this) -} - -class KotlinUSwitchEntry( - override val psi: KtWhenEntry, - givenParent: UElement? -) : KotlinAbstractUExpression(givenParent), USwitchClauseExpressionWithBody { - override val caseValues by lz { - psi.conditions.map { KotlinConverter.convertWhenCondition(it, this) ?: UastEmptyExpression } - } - - override val body: UExpressionList by lz { - object : KotlinUExpressionList(psi, KotlinSpecialExpressionKinds.WHEN_ENTRY, this@KotlinUSwitchEntry) { - override fun asRenderString() = buildString { - appendln("{") - expressions.forEach { appendln(it.asRenderString().withMargin) } - appendln("}") - } - }.apply { - val exprPsi = this@KotlinUSwitchEntry.psi.expression - val userExpressions = when (exprPsi) { - is KtBlockExpression -> exprPsi.statements.map { KotlinConverter.convertOrEmpty(it, this) } - else -> listOf(KotlinConverter.convertOrEmpty(exprPsi, this)) - } - expressions = userExpressions + object : UBreakExpression { - override val psi: PsiElement? - get() = null - override val label: String? - get() = null - override val uastParent: UElement? - get() = this@KotlinUSwitchEntry - override val annotations: List - get() = emptyList() - } - } - } - - override fun convertParent(): UElement? { - val result = KotlinConverter.unwrapElements(psi.parent)?.let { parentUnwrapped -> - KotlinUastLanguagePlugin().convertElementWithParent(parentUnwrapped, null) - } - return (result as? KotlinUSwitchExpression)?.body ?: result - } -} \ No newline at end of file diff --git a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/LocalFunction.kt.172 b/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/LocalFunction.kt.172 deleted file mode 100644 index 822e862c5e2..00000000000 --- a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/expressions/LocalFunction.kt.172 +++ /dev/null @@ -1,60 +0,0 @@ -package org.jetbrains.uast.kotlin.expressions - -import com.intellij.psi.PsiType -import com.intellij.psi.PsiVariable -import org.jetbrains.kotlin.psi.KtFunction -import org.jetbrains.uast.* -import org.jetbrains.uast.kotlin.* -import org.jetbrains.uast.kotlin.psi.UastKotlinPsiParameter -import org.jetbrains.uast.kotlin.psi.UastKotlinPsiVariable - - -internal class KotlinLocalFunctionUVariable( - val function: KtFunction, - override val psi: PsiVariable, - givenParent: UElement? -) : KotlinAbstractUElement(givenParent), UVariable, PsiVariable by psi { - override val uastInitializer: UExpression? by lz { - createLocalFunctionLambdaExpression(function, this) - } - override val typeReference: UTypeReferenceExpression? = null - override val uastAnchor: UElement? = null - override val annotations: List = emptyList() -} - - -private class KotlinLocalFunctionULambdaExpression( - override val psi: KtFunction, - givenParent: UElement? -): KotlinAbstractUExpression(givenParent), ULambdaExpression { - val functionalInterfaceType: PsiType? - get() = null - - override val body by lz { KotlinConverter.convertOrEmpty(psi.bodyExpression, this) } - - override val valueParameters by lz { - psi.valueParameters.mapIndexed { i, p -> - KotlinUParameter(UastKotlinPsiParameter.create(p, psi, this, i), this) - } - } - - override fun asRenderString(): String { - val renderedValueParameters = valueParameters.joinToString(prefix = "(", postfix = ")", - transform = KotlinUParameter::asRenderString) - val expressions = (body as? UBlockExpression)?.expressions?.joinToString("\n") { - it.asRenderString().withMargin - } ?: body.asRenderString() - return "fun $renderedValueParameters {\n${expressions.withMargin}\n}" - } -} - - -fun createLocalFunctionDeclaration(function: KtFunction, parent: UElement?): UDeclarationsExpression { - return KotlinUDeclarationsExpression(null, parent, function).apply { - val functionVariable = UastKotlinPsiVariable.create(function.name.orAnonymous(), function, this) - declarations = listOf(KotlinLocalFunctionUVariable(function, functionVariable, this)) - } -} - -fun createLocalFunctionLambdaExpression(function: KtFunction, parent: UElement?): ULambdaExpression = - KotlinLocalFunctionULambdaExpression(function, parent) diff --git a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/internal/KotlinUElementWithComments.kt.172 b/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/internal/KotlinUElementWithComments.kt.172 deleted file mode 100644 index d5049059599..00000000000 --- a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/internal/KotlinUElementWithComments.kt.172 +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.uast.kotlin.internal - -import com.intellij.psi.PsiComment -import com.intellij.psi.PsiElement -import com.intellij.psi.PsiWhiteSpace -import org.jetbrains.kotlin.psi.KtValueArgument -import org.jetbrains.uast.UComment -import org.jetbrains.uast.UElement -import org.jetbrains.uast.UExpression -import org.jetbrains.uast.kotlin.JvmDeclarationUElementPlaceholder - -interface KotlinUElementWithComments : JvmDeclarationUElementPlaceholder { - - override val comments: List - get() { - val psi = psi ?: return emptyList() - val childrenComments = psi.children.filterIsInstance().map { UComment(it, this) } - if (this !is UExpression) return childrenComments - val childrenAndSiblingComments = childrenComments + - psi.nearestCommentSibling(forward = true)?.let { listOf(UComment(it, this)) }.orEmpty() + - psi.nearestCommentSibling(forward = false)?.let { listOf(UComment(it, this)) }.orEmpty() - val parent = psi.parent as? KtValueArgument ?: return childrenAndSiblingComments - - return childrenAndSiblingComments + - parent.nearestCommentSibling(forward = true)?.let { listOf(UComment(it, this)) }.orEmpty() + - parent.nearestCommentSibling(forward = false)?.let { listOf(UComment(it, this)) }.orEmpty() - } - - private fun PsiElement.nearestCommentSibling(forward: Boolean): PsiComment? { - var sibling = if (forward) nextSibling else prevSibling - while (sibling is PsiWhiteSpace && !sibling.text.contains('\n')) { - sibling = if (forward) sibling.nextSibling else sibling.prevSibling - } - return sibling as? PsiComment - } - -} \ No newline at end of file diff --git a/plugins/uast-kotlin/testData/AnnotationComplex.kt.172 b/plugins/uast-kotlin/testData/AnnotationComplex.kt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/plugins/uast-kotlin/testData/AnnotationComplex.log.txt.172 b/plugins/uast-kotlin/testData/AnnotationComplex.log.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/plugins/uast-kotlin/testData/AnnotationComplex.render.txt.172 b/plugins/uast-kotlin/testData/AnnotationComplex.render.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/plugins/uast-kotlin/testData/ClassAnnotation.kt.172 b/plugins/uast-kotlin/testData/ClassAnnotation.kt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/plugins/uast-kotlin/testData/ClassAnnotation.log.txt.172 b/plugins/uast-kotlin/testData/ClassAnnotation.log.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/plugins/uast-kotlin/testData/ClassAnnotation.render.txt.172 b/plugins/uast-kotlin/testData/ClassAnnotation.render.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/plugins/uast-kotlin/testData/Constructors.log.txt.172 b/plugins/uast-kotlin/testData/Constructors.log.txt.172 deleted file mode 100644 index c7555e8f464..00000000000 --- a/plugins/uast-kotlin/testData/Constructors.log.txt.172 +++ /dev/null @@ -1,161 +0,0 @@ -UFile (package = ) - UClass (name = A) - UField (name = str) - UAnnotation (fqName = org.jetbrains.annotations.NotNull) - UAnnotationMethod (name = getStr) - UAnnotationMethod (name = A) - UParameter (name = str) - UAnnotation (fqName = org.jetbrains.annotations.NotNull) - UAnnotationMethod (name = A) - UParameter (name = i) - UAnnotation (fqName = null) - UBlockExpression - UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 1)) - UIdentifier (Identifier (this)) - USimpleNameReferenceExpression (identifier = ) - UQualifiedReferenceExpression - USimpleNameReferenceExpression (identifier = i) - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0)) - UIdentifier (Identifier (toString)) - USimpleNameReferenceExpression (identifier = toString) - UClass (name = AWithInit) - UField (name = str) - UAnnotation (fqName = org.jetbrains.annotations.NotNull) - UAnnotationMethod (name = getStr) - UAnnotationMethod (name = AWithInit) - UParameter (name = str) - UAnnotation (fqName = org.jetbrains.annotations.NotNull) - UBlockExpression - UBlockExpression - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0)) - UIdentifier (Identifier (println)) - USimpleNameReferenceExpression (identifier = println) - UAnnotationMethod (name = AWithInit) - UParameter (name = i) - UAnnotation (fqName = null) - UBlockExpression - UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 1)) - UIdentifier (Identifier (this)) - USimpleNameReferenceExpression (identifier = ) - UQualifiedReferenceExpression - USimpleNameReferenceExpression (identifier = i) - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0)) - UIdentifier (Identifier (toString)) - USimpleNameReferenceExpression (identifier = toString) - UClass (name = AWith2Init) - UField (name = str) - UAnnotation (fqName = org.jetbrains.annotations.NotNull) - UAnnotationMethod (name = getStr) - UAnnotationMethod (name = AWith2Init) - UParameter (name = str) - UAnnotation (fqName = org.jetbrains.annotations.NotNull) - UBlockExpression - UBlockExpression - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) - UIdentifier (Identifier (println)) - USimpleNameReferenceExpression (identifier = println) - ULiteralExpression (value = 1) - UBlockExpression - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) - UIdentifier (Identifier (println)) - USimpleNameReferenceExpression (identifier = println) - ULiteralExpression (value = 2) - UAnnotationMethod (name = AWith2Init) - UParameter (name = i) - UAnnotation (fqName = null) - UBlockExpression - UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 1)) - UIdentifier (Identifier (this)) - USimpleNameReferenceExpression (identifier = ) - UQualifiedReferenceExpression - USimpleNameReferenceExpression (identifier = i) - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0)) - UIdentifier (Identifier (toString)) - USimpleNameReferenceExpression (identifier = toString) - UClass (name = AOnlyInit) - UAnnotationMethod (name = AOnlyInit) - UBlockExpression - UBlockExpression - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) - UIdentifier (Identifier (println)) - USimpleNameReferenceExpression (identifier = println) - ULiteralExpression (value = 1) - UBlockExpression - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) - UIdentifier (Identifier (println)) - USimpleNameReferenceExpression (identifier = println) - ULiteralExpression (value = 2) - UClass (name = AWithSecondary) - UField (name = a) - UAnnotation (fqName = org.jetbrains.annotations.NotNull) - UAnnotationMethod (name = getA) - UAnnotationMethod (name = setA) - UParameter (name = p) - UAnnotation (fqName = org.jetbrains.annotations.NotNull) - UAnnotationMethod (name = AWithSecondary) - UParameter (name = i) - UAnnotation (fqName = null) - UBlockExpression - UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 0)) - UIdentifier (Identifier ()) - USimpleNameReferenceExpression (identifier = ) - UBinaryExpression (operator = =) - USimpleNameReferenceExpression (identifier = a) - UQualifiedReferenceExpression - USimpleNameReferenceExpression (identifier = i) - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0)) - UIdentifier (Identifier (toString)) - USimpleNameReferenceExpression (identifier = toString) - UAnnotationMethod (name = AWithSecondary) - UParameter (name = s) - UAnnotation (fqName = org.jetbrains.annotations.NotNull) - UBlockExpression - UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 0)) - UIdentifier (Identifier ()) - USimpleNameReferenceExpression (identifier = ) - UBinaryExpression (operator = =) - USimpleNameReferenceExpression (identifier = a) - USimpleNameReferenceExpression (identifier = s) - UClass (name = AWithSecondaryInit) - UField (name = a) - UAnnotation (fqName = org.jetbrains.annotations.NotNull) - UAnnotationMethod (name = getA) - UAnnotationMethod (name = setA) - UParameter (name = p) - UAnnotation (fqName = org.jetbrains.annotations.NotNull) - UAnnotationMethod (name = AWithSecondaryInit) - UParameter (name = i) - UAnnotation (fqName = null) - UBlockExpression - UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 0)) - UIdentifier (Identifier ()) - USimpleNameReferenceExpression (identifier = ) - UBlockExpression - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0)) - UIdentifier (Identifier (println)) - USimpleNameReferenceExpression (identifier = println) - UBinaryExpression (operator = =) - USimpleNameReferenceExpression (identifier = a) - UQualifiedReferenceExpression - USimpleNameReferenceExpression (identifier = i) - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0)) - UIdentifier (Identifier (toString)) - USimpleNameReferenceExpression (identifier = toString) - UAnnotationMethod (name = AWithSecondaryInit) - UParameter (name = s) - UAnnotation (fqName = org.jetbrains.annotations.NotNull) - UBlockExpression - UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 0)) - UIdentifier (Identifier ()) - USimpleNameReferenceExpression (identifier = ) - UBinaryExpression (operator = =) - USimpleNameReferenceExpression (identifier = a) - USimpleNameReferenceExpression (identifier = s) - UDeclarationsExpression - ULocalVariable (name = local) - USimpleNameReferenceExpression (identifier = s) - UQualifiedReferenceExpression - USimpleNameReferenceExpression (identifier = local) - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0)) - UIdentifier (Identifier (toString)) - USimpleNameReferenceExpression (identifier = toString) diff --git a/plugins/uast-kotlin/testData/Constructors.render.txt.172 b/plugins/uast-kotlin/testData/Constructors.render.txt.172 deleted file mode 100644 index ec3c796d109..00000000000 --- a/plugins/uast-kotlin/testData/Constructors.render.txt.172 +++ /dev/null @@ -1,81 +0,0 @@ -public final class A { - private final var str: java.lang.String - public final fun getStr() : java.lang.String = UastEmptyExpression - public fun A(str: java.lang.String) = UastEmptyExpression - public fun A(i: int) { - (i.toString()) - } -} - -public final class AWithInit { - private final var str: java.lang.String - public final fun getStr() : java.lang.String = UastEmptyExpression - public fun AWithInit(str: java.lang.String) { - { - println() - } - } - public fun AWithInit(i: int) { - (i.toString()) - } -} - -public final class AWith2Init { - private final var str: java.lang.String - public final fun getStr() : java.lang.String = UastEmptyExpression - public fun AWith2Init(str: java.lang.String) { - { - println(1) - } - { - println(2) - } - } - public fun AWith2Init(i: int) { - (i.toString()) - } -} - -public final class AOnlyInit { - public fun AOnlyInit() { - { - println(1) - } - { - println(2) - } - } -} - -public final class AWithSecondary { - public var a: java.lang.String - public final fun getA() : java.lang.String = UastEmptyExpression - public final fun setA(p: java.lang.String) : void = UastEmptyExpression - public fun AWithSecondary(i: int) { - () - a = i.toString() - } - public fun AWithSecondary(s: java.lang.String) { - () - a = s - } -} - -public final class AWithSecondaryInit { - public var a: java.lang.String - public final fun getA() : java.lang.String = UastEmptyExpression - public final fun setA(p: java.lang.String) : void = UastEmptyExpression - public fun AWithSecondaryInit(i: int) { - () - { - println() - } - a = i.toString() - } - public fun AWithSecondaryInit(s: java.lang.String) { - () - a = s - var local: java.lang.String = s - local.toString() - } -} diff --git a/plugins/uast-kotlin/testData/CycleInTypeParameters.types.txt.172 b/plugins/uast-kotlin/testData/CycleInTypeParameters.types.txt.172 deleted file mode 100644 index abfb578c83c..00000000000 --- a/plugins/uast-kotlin/testData/CycleInTypeParameters.types.txt.172 +++ /dev/null @@ -1,10 +0,0 @@ -UFile (package = ) [public final class CycleInTypeParametersKt {...] - UClass (name = CycleInTypeParametersKt) [public final class CycleInTypeParametersKt {...}] - UField (name = a) [private static final var a: Device = null as? Device] - UAnnotation (fqName = org.jetbrains.annotations.Nullable) [@org.jetbrains.annotations.Nullable] - UBinaryExpressionWithType [null as? Device] : PsiType:Device - ULiteralExpression (value = null) [null] : PsiType:Void - UTypeReferenceExpression (name = Device) [Device] - UAnnotationMethod (name = getA) [public static final fun getA() : Device = UastEmptyExpression] - UClass (name = Device) [public final class Device {...}] - UAnnotationMethod (name = Device) [public fun Device() = UastEmptyExpression] diff --git a/plugins/uast-kotlin/testData/DefaultParameterValues.log.txt.172 b/plugins/uast-kotlin/testData/DefaultParameterValues.log.txt.172 deleted file mode 100644 index d2f13973781..00000000000 --- a/plugins/uast-kotlin/testData/DefaultParameterValues.log.txt.172 +++ /dev/null @@ -1,10 +0,0 @@ -UFile (package = ) - UClass (name = DefaultParameterValuesKt) - UAnnotationMethod (name = foo) - UParameter (name = a) - UAnnotation (fqName = null) - ULiteralExpression (value = 1) - UParameter (name = foo) - UAnnotation (fqName = org.jetbrains.annotations.Nullable) - ULiteralExpression (value = null) - UBlockExpression diff --git a/plugins/uast-kotlin/testData/DefaultParameterValues.render.txt.172 b/plugins/uast-kotlin/testData/DefaultParameterValues.render.txt.172 deleted file mode 100644 index 0d903ca6199..00000000000 --- a/plugins/uast-kotlin/testData/DefaultParameterValues.render.txt.172 +++ /dev/null @@ -1,4 +0,0 @@ -public final class DefaultParameterValuesKt { - public static final fun foo(a: int, foo: java.lang.String) : void { - } -} diff --git a/plugins/uast-kotlin/testData/Delegate.values.txt.172 b/plugins/uast-kotlin/testData/Delegate.values.txt.172 deleted file mode 100644 index 3ab82214b77..00000000000 --- a/plugins/uast-kotlin/testData/Delegate.values.txt.172 +++ /dev/null @@ -1,65 +0,0 @@ -UFile (package = ) [public final class MyColor {...] - UClass (name = MyColor) [public final class MyColor {...}] - UField (name = x) [private final var x: int] - UAnnotation (fqName = null) [@null] - UField (name = y) [private final var y: int] - UAnnotation (fqName = null) [@null] - UField (name = z) [private final var z: int] - UAnnotation (fqName = null) [@null] - UAnnotationMethod (name = getX) [public final fun getX() : int = UastEmptyExpression] - UAnnotationMethod (name = getY) [public final fun getY() : int = UastEmptyExpression] - UAnnotationMethod (name = getZ) [public final fun getZ() : int = UastEmptyExpression] - UAnnotationMethod (name = MyColor) [public fun MyColor(x: int, y: int, z: int) = UastEmptyExpression] - UParameter (name = x) [var x: int] - UAnnotation (fqName = null) [@null] - UParameter (name = y) [var y: int] - UAnnotation (fqName = null) [@null] - UParameter (name = z) [var z: int] - UAnnotation (fqName = null) [@null] - UClass (name = Some) [public final class Some {...}] - UField (name = delegate$delegate) [private final var delegate$delegate: kotlin.Lazy] - UAnnotation (fqName = org.jetbrains.annotations.NotNull) [@org.jetbrains.annotations.NotNull] - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) [lazy({ ...})] = external lazy({ - (18, 2, 3) -})(Undetermined) - UIdentifier (Identifier (lazy)) [UIdentifier (Identifier (lazy))] - USimpleNameReferenceExpression (identifier = lazy) [lazy] = external lazy({ - (18, 2, 3) -})(Undetermined) - ULambdaExpression [{ ...}] = Undetermined - UBlockExpression [{...}] = external (18, 2, 3)(18, 2, 3) - UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 3)) [(18, 2, 3)] = external (18, 2, 3)(18, 2, 3) - UIdentifier (Identifier (MyColor)) [UIdentifier (Identifier (MyColor))] - USimpleNameReferenceExpression (identifier = ) [] = external (18, 2, 3)(18, 2, 3) - ULiteralExpression (value = 18) [18] = 18 - ULiteralExpression (value = 2) [2] = 2 - ULiteralExpression (value = 3) [3] = 3 - UField (name = lambda) [private final var lambda: kotlin.Lazy = lazy({ ...})] - UAnnotation (fqName = org.jetbrains.annotations.NotNull) [@org.jetbrains.annotations.NotNull] - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) [lazy({ ...})] = external lazy({ - (1, 2, 3) -})(Undetermined) - UIdentifier (Identifier (lazy)) [UIdentifier (Identifier (lazy))] - USimpleNameReferenceExpression (identifier = lazy) [lazy] = external lazy({ - (1, 2, 3) -})(Undetermined) - ULambdaExpression [{ ...}] = Undetermined - UBlockExpression [{...}] = external (1, 2, 3)(1, 2, 3) - UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 3)) [(1, 2, 3)] = external (1, 2, 3)(1, 2, 3) - UIdentifier (Identifier (MyColor)) [UIdentifier (Identifier (MyColor))] - USimpleNameReferenceExpression (identifier = ) [] = external (1, 2, 3)(1, 2, 3) - ULiteralExpression (value = 1) [1] = 1 - ULiteralExpression (value = 2) [2] = 2 - ULiteralExpression (value = 3) [3] = 3 - UField (name = nonLazy) [private final var nonLazy: MyColor = (1, 2, 3)] - UAnnotation (fqName = org.jetbrains.annotations.NotNull) [@org.jetbrains.annotations.NotNull] - UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 3)) [(1, 2, 3)] = external (1, 2, 3)(1, 2, 3) - UIdentifier (Identifier (MyColor)) [UIdentifier (Identifier (MyColor))] - USimpleNameReferenceExpression (identifier = ) [] = external (1, 2, 3)(1, 2, 3) - ULiteralExpression (value = 1) [1] = 1 - ULiteralExpression (value = 2) [2] = 2 - ULiteralExpression (value = 3) [3] = 3 - UAnnotationMethod (name = getDelegate) [public final fun getDelegate() : MyColor = UastEmptyExpression] - UAnnotationMethod (name = getLambda) [public final fun getLambda() : kotlin.Lazy = UastEmptyExpression] - UAnnotationMethod (name = getNonLazy) [public final fun getNonLazy() : MyColor = UastEmptyExpression] - UAnnotationMethod (name = Some) [public fun Some() = UastEmptyExpression] diff --git a/plugins/uast-kotlin/testData/DestructuringDeclaration.log.txt.172 b/plugins/uast-kotlin/testData/DestructuringDeclaration.log.txt.172 deleted file mode 100644 index aa299050640..00000000000 --- a/plugins/uast-kotlin/testData/DestructuringDeclaration.log.txt.172 +++ /dev/null @@ -1,21 +0,0 @@ -UFile (package = ) - UClass (name = DestructuringDeclarationKt) - UAnnotationMethod (name = foo) - UBlockExpression - UDeclarationsExpression - ULocalVariable (name = var268d4034) - UBinaryExpression (operator = ) - ULiteralExpression (value = "foo") - ULiteralExpression (value = 1) - ULocalVariable (name = a) - UQualifiedReferenceExpression - USimpleNameReferenceExpression (identifier = var268d4034) - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0)) - UIdentifier (Identifier (component1)) - USimpleNameReferenceExpression (identifier = ) - ULocalVariable (name = b) - UQualifiedReferenceExpression - USimpleNameReferenceExpression (identifier = var268d4034) - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0)) - UIdentifier (Identifier (component2)) - USimpleNameReferenceExpression (identifier = ) diff --git a/plugins/uast-kotlin/testData/DestructuringDeclaration.render.txt.172 b/plugins/uast-kotlin/testData/DestructuringDeclaration.render.txt.172 deleted file mode 100644 index 1517c3ae90e..00000000000 --- a/plugins/uast-kotlin/testData/DestructuringDeclaration.render.txt.172 +++ /dev/null @@ -1,7 +0,0 @@ -public final class DestructuringDeclarationKt { - public static final fun foo() : void { - var var268d4034: = "foo" 1 - var a: java.lang.String = var268d4034.() - var b: int = var268d4034.() - } -} diff --git a/plugins/uast-kotlin/testData/Elvis.log.txt.172 b/plugins/uast-kotlin/testData/Elvis.log.txt.172 deleted file mode 100644 index a277ac953b6..00000000000 --- a/plugins/uast-kotlin/testData/Elvis.log.txt.172 +++ /dev/null @@ -1,46 +0,0 @@ -UFile (package = ) - UClass (name = ElvisKt) - UAnnotationMethod (name = foo) - UParameter (name = bar) - UAnnotation (fqName = org.jetbrains.annotations.NotNull) - UBlockExpression - UReturnExpression - ULiteralExpression (value = null) - UAnnotationMethod (name = bar) - UBlockExpression - UReturnExpression - ULiteralExpression (value = 42) - UAnnotationMethod (name = baz) - UBlockExpression - UReturnExpression - UExpressionList (elvis) - UDeclarationsExpression - ULocalVariable (name = var243c51a0) - UExpressionList (elvis) - UDeclarationsExpression - ULocalVariable (name = varc4aef569) - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) - UIdentifier (Identifier (foo)) - USimpleNameReferenceExpression (identifier = foo) - ULiteralExpression (value = "Lorem ipsum") - UIfExpression - UBinaryExpression (operator = !=) - USimpleNameReferenceExpression (identifier = varc4aef569) - ULiteralExpression (value = null) - USimpleNameReferenceExpression (identifier = varc4aef569) - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) - UIdentifier (Identifier (foo)) - USimpleNameReferenceExpression (identifier = foo) - ULiteralExpression (value = "dolor sit amet") - UIfExpression - UBinaryExpression (operator = !=) - USimpleNameReferenceExpression (identifier = var243c51a0) - ULiteralExpression (value = null) - USimpleNameReferenceExpression (identifier = var243c51a0) - UQualifiedReferenceExpression - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0)) - UIdentifier (Identifier (bar)) - USimpleNameReferenceExpression (identifier = bar) - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0)) - UIdentifier (Identifier (toString)) - USimpleNameReferenceExpression (identifier = toString) diff --git a/plugins/uast-kotlin/testData/Elvis.render.txt.172 b/plugins/uast-kotlin/testData/Elvis.render.txt.172 deleted file mode 100644 index 44cc3027d27..00000000000 --- a/plugins/uast-kotlin/testData/Elvis.render.txt.172 +++ /dev/null @@ -1,17 +0,0 @@ -public final class ElvisKt { - public static final fun foo(bar: java.lang.String) : java.lang.String { - return null - } - public static final fun bar() : int { - return 42 - } - public static final fun baz() : java.lang.String { - return elvis { - var var243c51a0: java.lang.String = elvis { - var varc4aef569: java.lang.String = foo("Lorem ipsum") - if (varc4aef569 != null) varc4aef569 else foo("dolor sit amet") - } - if (var243c51a0 != null) var243c51a0 else bar().toString() - } - } -} diff --git a/plugins/uast-kotlin/testData/EnumValueMembers.log.txt.172 b/plugins/uast-kotlin/testData/EnumValueMembers.log.txt.172 deleted file mode 100644 index abd6fbd0e58..00000000000 --- a/plugins/uast-kotlin/testData/EnumValueMembers.log.txt.172 +++ /dev/null @@ -1,18 +0,0 @@ -UFile (package = ) - UClass (name = Style) - UEnumConstant (name = SHEET) - USimpleNameReferenceExpression (identifier = Style) - ULiteralExpression (value = "foo") - UClass (name = null) - UAnnotationMethod (name = getExitAnimation) - UBlockExpression - UReturnExpression - ULiteralExpression (value = "bar") - UAnnotationMethod (name = SHEET) - UField (name = value) - UAnnotation (fqName = org.jetbrains.annotations.NotNull) - UAnnotationMethod (name = getExitAnimation) - UAnnotationMethod (name = getValue) - UAnnotationMethod (name = Style) - UParameter (name = value) - UAnnotation (fqName = org.jetbrains.annotations.NotNull) diff --git a/plugins/uast-kotlin/testData/EnumValueMembers.render.txt.172 b/plugins/uast-kotlin/testData/EnumValueMembers.render.txt.172 deleted file mode 100644 index 2bcf8c64976..00000000000 --- a/plugins/uast-kotlin/testData/EnumValueMembers.render.txt.172 +++ /dev/null @@ -1,12 +0,0 @@ -public enum Style { - SHEET("foo") { - public fun getExitAnimation() : java.lang.String { - return "bar" - } - fun SHEET() = UastEmptyExpression - } - private final var value: java.lang.String - public abstract fun getExitAnimation() : java.lang.String = UastEmptyExpression - public final fun getValue() : java.lang.String = UastEmptyExpression - protected fun Style(value: java.lang.String) = UastEmptyExpression -} diff --git a/plugins/uast-kotlin/testData/InnerClasses.log.txt.172 b/plugins/uast-kotlin/testData/InnerClasses.log.txt.172 deleted file mode 100644 index 729981260a9..00000000000 --- a/plugins/uast-kotlin/testData/InnerClasses.log.txt.172 +++ /dev/null @@ -1,27 +0,0 @@ -UFile (package = ) - UClass (name = Foo) - UAnnotationMethod (name = Foo) - UClass (name = Bar) - UField (name = a) - UAnnotation (fqName = null) - UField (name = b) - UAnnotation (fqName = null) - UAnnotationMethod (name = getAPlusB) - UBlockExpression - UReturnExpression - UBinaryExpression (operator = +) - USimpleNameReferenceExpression (identifier = a) - USimpleNameReferenceExpression (identifier = b) - UAnnotationMethod (name = getA) - UAnnotationMethod (name = getB) - UAnnotationMethod (name = Bar) - UParameter (name = a) - UAnnotation (fqName = null) - UParameter (name = b) - UAnnotation (fqName = null) - UClass (name = Baz) - UAnnotationMethod (name = doNothing) - UBlockExpression - UReturnExpression - USimpleNameReferenceExpression (identifier = Unit) - UAnnotationMethod (name = Baz) diff --git a/plugins/uast-kotlin/testData/InnerClasses.render.txt.172 b/plugins/uast-kotlin/testData/InnerClasses.render.txt.172 deleted file mode 100644 index 05411c6c1f3..00000000000 --- a/plugins/uast-kotlin/testData/InnerClasses.render.txt.172 +++ /dev/null @@ -1,19 +0,0 @@ -public final class Foo { - public fun Foo() = UastEmptyExpression - public static final class Bar { - private final var a: int - private final var b: int - public final fun getAPlusB() : int { - return a + b - } - public final fun getA() : int = UastEmptyExpression - public final fun getB() : int = UastEmptyExpression - public fun Bar(a: int, b: int) = UastEmptyExpression - public static final class Baz { - public final fun doNothing() : void { - return Unit - } - public fun Baz() = UastEmptyExpression - } - } -} diff --git a/plugins/uast-kotlin/testData/LocalDeclarations.log.txt.172 b/plugins/uast-kotlin/testData/LocalDeclarations.log.txt.172 deleted file mode 100644 index 9dadf83072a..00000000000 --- a/plugins/uast-kotlin/testData/LocalDeclarations.log.txt.172 +++ /dev/null @@ -1,33 +0,0 @@ -UFile (package = ) - UClass (name = LocalDeclarationsKt) - UAnnotationMethod (name = foo) - UBlockExpression - UDeclarationsExpression - UClass (name = Local) - UAnnotationMethod (name = LocalDeclarationsKt$foo$Local) - UDeclarationsExpression - UVariable (name = bar) - ULambdaExpression - UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 0)) - UIdentifier (Identifier (Local)) - USimpleNameReferenceExpression (identifier = ) - UDeclarationsExpression - ULocalVariable (name = baz) - ULambdaExpression - UBlockExpression - UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 0)) - UIdentifier (Identifier (Local)) - USimpleNameReferenceExpression (identifier = ) - UDeclarationsExpression - UVariable (name = someLocalFun) - ULambdaExpression - UParameter (name = text) - ULiteralExpression (value = 42) - UReturnExpression - UBinaryExpression (operator = ==) - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0)) - UIdentifier (Identifier (bar)) - USimpleNameReferenceExpression (identifier = bar) - UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 0)) - UIdentifier (Identifier (Local)) - USimpleNameReferenceExpression (identifier = ) diff --git a/plugins/uast-kotlin/testData/LocalDeclarations.render.txt.172 b/plugins/uast-kotlin/testData/LocalDeclarations.render.txt.172 deleted file mode 100644 index 8768433111f..00000000000 --- a/plugins/uast-kotlin/testData/LocalDeclarations.render.txt.172 +++ /dev/null @@ -1,17 +0,0 @@ -public final class LocalDeclarationsKt { - public static final fun foo() : boolean { - public static final class Local { - public fun LocalDeclarationsKt$foo$Local() = UastEmptyExpression - } - var bar: = fun () { - () - } - var baz: kotlin.jvm.functions.Function0 = fun () { - () - } - var someLocalFun: kotlin.jvm.functions.Function2 = fun (var text: java.lang.String) { - 42 - } - return bar() == () - } -} diff --git a/plugins/uast-kotlin/testData/LocalDeclarations.types.txt.172 b/plugins/uast-kotlin/testData/LocalDeclarations.types.txt.172 deleted file mode 100644 index 2d879604d74..00000000000 --- a/plugins/uast-kotlin/testData/LocalDeclarations.types.txt.172 +++ /dev/null @@ -1,33 +0,0 @@ -UFile (package = ) [public final class LocalDeclarationsKt {...] - UClass (name = LocalDeclarationsKt) [public final class LocalDeclarationsKt {...}] - UAnnotationMethod (name = foo) [public static final fun foo() : boolean {...}] - UBlockExpression [{...}] : PsiType:Void - UDeclarationsExpression [public static final class Local {...}] - UClass (name = Local) [public static final class Local {...}] - UAnnotationMethod (name = LocalDeclarationsKt$foo$Local) [public fun LocalDeclarationsKt$foo$Local() = UastEmptyExpression] - UDeclarationsExpression [var bar: = fun () {...}] - UVariable (name = bar) [var bar: = fun () {...}] - ULambdaExpression [fun () {...}] - UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 0)) [()] : PsiType: - UIdentifier (Identifier (Local)) [UIdentifier (Identifier (Local))] - USimpleNameReferenceExpression (identifier = ) [] : PsiType: - UDeclarationsExpression [var baz: kotlin.jvm.functions.Function0 = fun () {...}] - ULocalVariable (name = baz) [var baz: kotlin.jvm.functions.Function0 = fun () {...}] - ULambdaExpression [fun () {...}] - UBlockExpression [{...}] : PsiType: - UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 0)) [()] : PsiType: - UIdentifier (Identifier (Local)) [UIdentifier (Identifier (Local))] - USimpleNameReferenceExpression (identifier = ) [] : PsiType: - UDeclarationsExpression [var someLocalFun: kotlin.jvm.functions.Function2 = fun (var text: java.lang.String) {...}] - UVariable (name = someLocalFun) [var someLocalFun: kotlin.jvm.functions.Function2 = fun (var text: java.lang.String) {...}] - ULambdaExpression [fun (var text: java.lang.String) {...}] - UParameter (name = text) [var text: java.lang.String] - ULiteralExpression (value = 42) [42] : PsiType:int - UReturnExpression [return bar() == ()] : PsiType:Void - UBinaryExpression (operator = ==) [bar() == ()] : PsiType:boolean - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0)) [bar()] : PsiType: - UIdentifier (Identifier (bar)) [UIdentifier (Identifier (bar))] - USimpleNameReferenceExpression (identifier = bar) [bar] : PsiType: - UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 0)) [()] : PsiType: - UIdentifier (Identifier (Local)) [UIdentifier (Identifier (Local))] - USimpleNameReferenceExpression (identifier = ) [] : PsiType: diff --git a/plugins/uast-kotlin/testData/LocalDeclarations.values.txt.172 b/plugins/uast-kotlin/testData/LocalDeclarations.values.txt.172 deleted file mode 100644 index d4f166a086e..00000000000 --- a/plugins/uast-kotlin/testData/LocalDeclarations.values.txt.172 +++ /dev/null @@ -1,33 +0,0 @@ -UFile (package = ) [public final class LocalDeclarationsKt {...] - UClass (name = LocalDeclarationsKt) [public final class LocalDeclarationsKt {...}] - UAnnotationMethod (name = foo) [public static final fun foo() : boolean {...}] - UBlockExpression [{...}] = Nothing - UDeclarationsExpression [public static final class Local {...}] = Undetermined - UClass (name = Local) [public static final class Local {...}] - UAnnotationMethod (name = LocalDeclarationsKt$foo$Local) [public fun LocalDeclarationsKt$foo$Local() = UastEmptyExpression] - UDeclarationsExpression [var bar: = fun () {...}] = Undetermined - UVariable (name = bar) [var bar: = fun () {...}] - ULambdaExpression [fun () {...}] = Undetermined - UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 0)) [()] = external ()() - UIdentifier (Identifier (Local)) [UIdentifier (Identifier (Local))] - USimpleNameReferenceExpression (identifier = ) [] = external ()() - UDeclarationsExpression [var baz: kotlin.jvm.functions.Function0 = fun () {...}] = Undetermined - ULocalVariable (name = baz) [var baz: kotlin.jvm.functions.Function0 = fun () {...}] - ULambdaExpression [fun () {...}] = Undetermined - UBlockExpression [{...}] = external ()() - UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 0)) [()] = external ()() - UIdentifier (Identifier (Local)) [UIdentifier (Identifier (Local))] - USimpleNameReferenceExpression (identifier = ) [] = external ()() - UDeclarationsExpression [var someLocalFun: kotlin.jvm.functions.Function2 = fun (var text: java.lang.String) {...}] = Undetermined - UVariable (name = someLocalFun) [var someLocalFun: kotlin.jvm.functions.Function2 = fun (var text: java.lang.String) {...}] - ULambdaExpression [fun (var text: java.lang.String) {...}] = Undetermined - UParameter (name = text) [var text: java.lang.String] - ULiteralExpression (value = 42) [42] = 42 - UReturnExpression [return bar() == ()] = Nothing - UBinaryExpression (operator = ==) [bar() == ()] = Undetermined - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0)) [bar()] = external bar()() - UIdentifier (Identifier (bar)) [UIdentifier (Identifier (bar))] - USimpleNameReferenceExpression (identifier = bar) [bar] = external bar()() - UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 0)) [()] = external ()() - UIdentifier (Identifier (Local)) [UIdentifier (Identifier (Local))] - USimpleNameReferenceExpression (identifier = ) [] = external ()() diff --git a/plugins/uast-kotlin/testData/LocalVariableWithAnnotation.kt.172 b/plugins/uast-kotlin/testData/LocalVariableWithAnnotation.kt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/plugins/uast-kotlin/testData/LocalVariableWithAnnotation.log.txt.172 b/plugins/uast-kotlin/testData/LocalVariableWithAnnotation.log.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/plugins/uast-kotlin/testData/LocalVariableWithAnnotation.render.txt.172 b/plugins/uast-kotlin/testData/LocalVariableWithAnnotation.render.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/plugins/uast-kotlin/testData/ParameterPropertyWithAnnotation.log.txt.172 b/plugins/uast-kotlin/testData/ParameterPropertyWithAnnotation.log.txt.172 deleted file mode 100644 index 69573a72273..00000000000 --- a/plugins/uast-kotlin/testData/ParameterPropertyWithAnnotation.log.txt.172 +++ /dev/null @@ -1,31 +0,0 @@ -UFile (package = ) - UClass (name = MyAnnotation) - UClass (name = MyAnnotation2) - UClass (name = MyAnnotation3) - UClass (name = MyAnnotation4) - UClass (name = MyAnnotation5) - UClass (name = Test1) - UField (name = bar) - UAnnotation (fqName = null) - UAnnotationMethod (name = getBar) - UAnnotationMethod (name = setBar) - UParameter (name = p) - UAnnotation (fqName = null) - UAnnotationMethod (name = Test1) - UParameter (name = bar) - UAnnotation (fqName = MyAnnotation) - UAnnotation (fqName = null) - UClass (name = Test2) - UField (name = bar) - UAnnotation (fqName = MyAnnotation5) - UAnnotation (fqName = null) - UAnnotationMethod (name = getBar) - UAnnotation (fqName = MyAnnotation) - UAnnotationMethod (name = setBar) - UAnnotation (fqName = MyAnnotation2) - UParameter (name = p) - UAnnotation (fqName = MyAnnotation3) - UAnnotation (fqName = null) - UAnnotationMethod (name = Test2) - UParameter (name = bar) - UAnnotation (fqName = null) diff --git a/plugins/uast-kotlin/testData/ParameterPropertyWithAnnotation.render.txt.172 b/plugins/uast-kotlin/testData/ParameterPropertyWithAnnotation.render.txt.172 deleted file mode 100644 index 19d3c2b5a8f..00000000000 --- a/plugins/uast-kotlin/testData/ParameterPropertyWithAnnotation.render.txt.172 +++ /dev/null @@ -1,30 +0,0 @@ -public abstract annotation MyAnnotation { -} - -public abstract annotation MyAnnotation2 { -} - -public abstract annotation MyAnnotation3 { -} - -public abstract annotation MyAnnotation4 { -} - -public abstract annotation MyAnnotation5 { -} - -public final class Test1 { - private var bar: int - public final fun getBar() : int = UastEmptyExpression - public final fun setBar(p: int) : void = UastEmptyExpression - public fun Test1(bar: int) = UastEmptyExpression -} - -public final class Test2 { - private var bar: int - @MyAnnotation - public final fun getBar() : int = UastEmptyExpression - @MyAnnotation2 - public final fun setBar(p: int) : void = UastEmptyExpression - public fun Test2(bar: int) = UastEmptyExpression -} diff --git a/plugins/uast-kotlin/testData/ParametersWithDefaultValues.log.txt.172 b/plugins/uast-kotlin/testData/ParametersWithDefaultValues.log.txt.172 deleted file mode 100644 index 325d638ff65..00000000000 --- a/plugins/uast-kotlin/testData/ParametersWithDefaultValues.log.txt.172 +++ /dev/null @@ -1,14 +0,0 @@ -UFile (package = ) - UClass (name = ParametersWithDefaultValuesKt) - UAnnotationMethod (name = foo) - UParameter (name = a) - UAnnotation (fqName = null) - UParameter (name = b) - UAnnotation (fqName = org.jetbrains.annotations.NotNull) - UParameter (name = c) - UAnnotation (fqName = null) - ULiteralExpression (value = 0) - UParameter (name = flag) - UAnnotation (fqName = null) - ULiteralExpression (value = false) - UBlockExpression diff --git a/plugins/uast-kotlin/testData/ParametersWithDefaultValues.render.txt.172 b/plugins/uast-kotlin/testData/ParametersWithDefaultValues.render.txt.172 deleted file mode 100644 index a47a36a47c3..00000000000 --- a/plugins/uast-kotlin/testData/ParametersWithDefaultValues.render.txt.172 +++ /dev/null @@ -1,4 +0,0 @@ -public final class ParametersWithDefaultValuesKt { - public static final fun foo(a: int, b: java.lang.String, c: int, flag: boolean) : void { - } -} diff --git a/plugins/uast-kotlin/testData/PropertyAccessors.render.txt.172 b/plugins/uast-kotlin/testData/PropertyAccessors.render.txt.172 deleted file mode 100644 index 5bf167373ba..00000000000 --- a/plugins/uast-kotlin/testData/PropertyAccessors.render.txt.172 +++ /dev/null @@ -1,11 +0,0 @@ -public final class PropertyTest { - public final fun getStringRepresentation() : java.lang.String { - return this.toString() - } - public final fun setStringRepresentation(value: java.lang.String) : void { - setDataFromString(value) - } - public final fun setDataFromString(data: java.lang.String) : void { - } - public fun PropertyTest() = UastEmptyExpression -} diff --git a/plugins/uast-kotlin/testData/PropertyDelegate.kt.172 b/plugins/uast-kotlin/testData/PropertyDelegate.kt.172 deleted file mode 100644 index 4cc642ec36f..00000000000 --- a/plugins/uast-kotlin/testData/PropertyDelegate.kt.172 +++ /dev/null @@ -1,5 +0,0 @@ -val sdCardPath by lazy { "/sdcard" } - -fun localPropertyTest() { - val sdCardPathLocal by lazy { "/sdcard" } -} \ No newline at end of file diff --git a/plugins/uast-kotlin/testData/PropertyDelegate.log.txt.172 b/plugins/uast-kotlin/testData/PropertyDelegate.log.txt.172 deleted file mode 100644 index 04df9270c82..00000000000 --- a/plugins/uast-kotlin/testData/PropertyDelegate.log.txt.172 +++ /dev/null @@ -1,21 +0,0 @@ -UFile (package = ) - UClass (name = PropertyDelegateKt) - UField (name = sdCardPath$delegate) - UAnnotation (fqName = org.jetbrains.annotations.NotNull) - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) - UIdentifier (Identifier (lazy)) - USimpleNameReferenceExpression (identifier = lazy) - ULambdaExpression - UBlockExpression - ULiteralExpression (value = "/sdcard") - UAnnotationMethod (name = getSdCardPath) - UAnnotationMethod (name = localPropertyTest) - UBlockExpression - UDeclarationsExpression - ULocalVariable (name = sdCardPathLocal) - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) - UIdentifier (Identifier (lazy)) - USimpleNameReferenceExpression (identifier = lazy) - ULambdaExpression - UBlockExpression - ULiteralExpression (value = "/sdcard") diff --git a/plugins/uast-kotlin/testData/PropertyDelegate.render.txt.172 b/plugins/uast-kotlin/testData/PropertyDelegate.render.txt.172 deleted file mode 100644 index ce4553ea29c..00000000000 --- a/plugins/uast-kotlin/testData/PropertyDelegate.render.txt.172 +++ /dev/null @@ -1,7 +0,0 @@ -public final class PropertyDelegateKt { - private static final var sdCardPath$delegate: kotlin.Lazy - public static final fun getSdCardPath() : java.lang.String = UastEmptyExpression - public static final fun localPropertyTest() : void { - var sdCardPathLocal: java.lang.String - } -} diff --git a/plugins/uast-kotlin/testData/PropertyInitializer.render.txt.172 b/plugins/uast-kotlin/testData/PropertyInitializer.render.txt.172 deleted file mode 100644 index ff3776a7a64..00000000000 --- a/plugins/uast-kotlin/testData/PropertyInitializer.render.txt.172 +++ /dev/null @@ -1,10 +0,0 @@ -public final class TestPropertyInitializer { - private var withSetter: java.lang.String = "/sdcard" - public final fun getWithSetter() : java.lang.String { - return field - } - public final fun setWithSetter(p: java.lang.String) : void { - field = p - } - public fun TestPropertyInitializer() = UastEmptyExpression -} diff --git a/plugins/uast-kotlin/testData/PropertyInitializerWithoutSetter.render.txt.172 b/plugins/uast-kotlin/testData/PropertyInitializerWithoutSetter.render.txt.172 deleted file mode 100644 index e3bb6e3d2a7..00000000000 --- a/plugins/uast-kotlin/testData/PropertyInitializerWithoutSetter.render.txt.172 +++ /dev/null @@ -1,7 +0,0 @@ -public final class PropertyInitializerWithoutSetterKt { - private static var withoutSetter: java.lang.String = "/sdcard" - public static final fun getWithoutSetter() : java.lang.String { - return field - } - public static final fun setWithoutSetter(p: java.lang.String) : void = UastEmptyExpression -} diff --git a/plugins/uast-kotlin/testData/PropertyWithAnnotation.log.txt.172 b/plugins/uast-kotlin/testData/PropertyWithAnnotation.log.txt.172 deleted file mode 100644 index c9edf363f64..00000000000 --- a/plugins/uast-kotlin/testData/PropertyWithAnnotation.log.txt.172 +++ /dev/null @@ -1,27 +0,0 @@ -UFile (package = ) - UClass (name = PropertyWithAnnotationKt) - UField (name = prop1) - UAnnotation (fqName = null) - ULiteralExpression (value = 0) - UField (name = prop3) - UAnnotation (fqName = null) - ULiteralExpression (value = 0) - UAnnotationMethod (name = getProp1) - UAnnotationMethod (name = getProp2) - UAnnotation (fqName = TestAnnotation) - UBlockExpression - UReturnExpression - ULiteralExpression (value = 0) - UAnnotationMethod (name = getProp3) - UBlockExpression - UReturnExpression - ULiteralExpression (value = 0) - UAnnotationMethod (name = setProp3) - UAnnotation (fqName = TestAnnotation) - UParameter (name = value) - UAnnotation (fqName = null) - UBlockExpression - UBinaryExpression (operator = =) - USimpleNameReferenceExpression (identifier = field) - USimpleNameReferenceExpression (identifier = value) - UClass (name = TestAnnotation) diff --git a/plugins/uast-kotlin/testData/PropertyWithAnnotation.render.txt.172 b/plugins/uast-kotlin/testData/PropertyWithAnnotation.render.txt.172 deleted file mode 100644 index 091dcdc4693..00000000000 --- a/plugins/uast-kotlin/testData/PropertyWithAnnotation.render.txt.172 +++ /dev/null @@ -1,19 +0,0 @@ -public final class PropertyWithAnnotationKt { - private static final var prop1: int = 0 - private static var prop3: int = 0 - public static final fun getProp1() : int = UastEmptyExpression - @TestAnnotation - public static final fun getProp2() : int { - return 0 - } - public static final fun getProp3() : int { - return 0 - } - @TestAnnotation - public static final fun setProp3(value: int) : void { - field = value - } -} - -public abstract annotation TestAnnotation { -} diff --git a/plugins/uast-kotlin/testData/ReceiverFun.kt.172 b/plugins/uast-kotlin/testData/ReceiverFun.kt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/plugins/uast-kotlin/testData/ReceiverFun.log.txt.172 b/plugins/uast-kotlin/testData/ReceiverFun.log.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/plugins/uast-kotlin/testData/ReceiverFun.render.txt.172 b/plugins/uast-kotlin/testData/ReceiverFun.render.txt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/plugins/uast-kotlin/testData/Simple.render.txt.172 b/plugins/uast-kotlin/testData/Simple.render.txt.172 deleted file mode 100644 index b354c83cca5..00000000000 --- a/plugins/uast-kotlin/testData/Simple.render.txt.172 +++ /dev/null @@ -1,8 +0,0 @@ -public final class Simple { - private final var property: java.lang.String = "Mary" - public final fun method() : void { - println("Hello, world!") - } - public final fun getProperty() : java.lang.String = UastEmptyExpression - public fun Simple() = UastEmptyExpression -} diff --git a/plugins/uast-kotlin/testData/Simple.values.txt.172 b/plugins/uast-kotlin/testData/Simple.values.txt.172 deleted file mode 100644 index 1e41b670245..00000000000 --- a/plugins/uast-kotlin/testData/Simple.values.txt.172 +++ /dev/null @@ -1,13 +0,0 @@ -UFile (package = ) [public final class Simple {...] - UClass (name = Simple) [public final class Simple {...}] - UField (name = property) [private final var property: java.lang.String = "Mary"] - UAnnotation (fqName = org.jetbrains.annotations.NotNull) [@org.jetbrains.annotations.NotNull] - ULiteralExpression (value = "Mary") ["Mary"] = "Mary" - UAnnotationMethod (name = method) [public final fun method() : void {...}] - UBlockExpression [{...}] = external println("Hello, world!")("Hello, world!") - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) [println("Hello, world!")] = external println("Hello, world!")("Hello, world!") - UIdentifier (Identifier (println)) [UIdentifier (Identifier (println))] - USimpleNameReferenceExpression (identifier = println) [println] = external println("Hello, world!")("Hello, world!") - ULiteralExpression (value = "Hello, world!") ["Hello, world!"] = "Hello, world!" - UAnnotationMethod (name = getProperty) [public final fun getProperty() : java.lang.String = UastEmptyExpression] - UAnnotationMethod (name = Simple) [public fun Simple() = UastEmptyExpression] diff --git a/plugins/uast-kotlin/testData/SimpleAnnotated.kt.172 b/plugins/uast-kotlin/testData/SimpleAnnotated.kt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/plugins/uast-kotlin/testData/SimpleScript.log.txt.172 b/plugins/uast-kotlin/testData/SimpleScript.log.txt.172 deleted file mode 100644 index bed93896f9a..00000000000 --- a/plugins/uast-kotlin/testData/SimpleScript.log.txt.172 +++ /dev/null @@ -1,51 +0,0 @@ -UFile (package = ) - UClass (name = SimpleScript) - UAnnotationMethod (name = getBarOrNull) - UParameter (name = flag) - UAnnotation (fqName = null) - UBlockExpression - UReturnExpression - UIfExpression - USimpleNameReferenceExpression (identifier = flag) - UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 1)) - UIdentifier (Identifier (Bar)) - USimpleNameReferenceExpression (identifier = ) - ULiteralExpression (value = 42) - ULiteralExpression (value = null) - UAnnotationMethod (name = SimpleScript) - UParameter (name = p) - UAnnotation (fqName = null) - UBlockExpression - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) - UIdentifier (Identifier (println)) - USimpleNameReferenceExpression (identifier = println) - ULiteralExpression (value = "Hello World!") - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) - UIdentifier (Identifier (getBarOrNull)) - USimpleNameReferenceExpression (identifier = getBarOrNull) - ULiteralExpression (value = true) - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) - UIdentifier (Identifier (println)) - USimpleNameReferenceExpression (identifier = println) - ULiteralExpression (value = "Goodbye World!") - UClass (name = Bar) - UField (name = b) - UAnnotation (fqName = null) - ULiteralExpression (value = 0) - UField (name = a) - UAnnotation (fqName = null) - UAnnotationMethod (name = getB) - UAnnotationMethod (name = getAPlusB) - UBlockExpression - UReturnExpression - UBinaryExpression (operator = +) - USimpleNameReferenceExpression (identifier = a) - USimpleNameReferenceExpression (identifier = b) - UAnnotationMethod (name = getA) - UAnnotationMethod (name = Bar) - UParameter (name = a) - UAnnotation (fqName = null) - UClass (name = Baz) - UAnnotationMethod (name = doSomething) - UBlockExpression - UAnnotationMethod (name = Baz) diff --git a/plugins/uast-kotlin/testData/SimpleScript.render.txt.172 b/plugins/uast-kotlin/testData/SimpleScript.render.txt.172 deleted file mode 100644 index dcf6efc4a65..00000000000 --- a/plugins/uast-kotlin/testData/SimpleScript.render.txt.172 +++ /dev/null @@ -1,25 +0,0 @@ -public class SimpleScript : kotlin.script.templates.standard.ScriptTemplateWithArgs { - public final fun getBarOrNull(flag: boolean) : SimpleScript.Bar { - return if (flag) (42) else null - } - public fun SimpleScript(p: java.lang.String[]) { - println("Hello World!") - getBarOrNull(true) - println("Goodbye World!") - } - public static final class Bar { - private final var b: int = 0 - private final var a: int - public final fun getB() : int = UastEmptyExpression - public final fun getAPlusB() : int { - return a + b - } - public final fun getA() : int = UastEmptyExpression - public fun Bar(a: int) = UastEmptyExpression - public static final class Baz { - public final fun doSomething() : void { - } - public fun Baz() = UastEmptyExpression - } - } -} diff --git a/plugins/uast-kotlin/testData/StringTemplate.render.txt.172 b/plugins/uast-kotlin/testData/StringTemplate.render.txt.172 deleted file mode 100644 index 2d56a3954b6..00000000000 --- a/plugins/uast-kotlin/testData/StringTemplate.render.txt.172 +++ /dev/null @@ -1,10 +0,0 @@ -public final class StringTemplateKt { - private static final var foo: java.lang.String = "lorem" - private static final var bar: java.lang.String = "ipsum" - private static final var baz: java.lang.String = "dolor" - private static final var foobarbaz: java.lang.String = foo + " " + bar + " " + baz - public static final fun getFoo() : java.lang.String = UastEmptyExpression - public static final fun getBar() : java.lang.String = UastEmptyExpression - public static final fun getBaz() : java.lang.String = UastEmptyExpression - public static final fun getFoobarbaz() : java.lang.String = UastEmptyExpression -} diff --git a/plugins/uast-kotlin/testData/StringTemplate.types.txt.172 b/plugins/uast-kotlin/testData/StringTemplate.types.txt.172 deleted file mode 100644 index 96a182d680e..00000000000 --- a/plugins/uast-kotlin/testData/StringTemplate.types.txt.172 +++ /dev/null @@ -1,23 +0,0 @@ -UFile (package = ) [public final class StringTemplateKt {...] - UClass (name = StringTemplateKt) [public final class StringTemplateKt {...}] - UField (name = foo) [private static final var foo: java.lang.String = "lorem"] - UAnnotation (fqName = org.jetbrains.annotations.NotNull) [@org.jetbrains.annotations.NotNull] - ULiteralExpression (value = "lorem") ["lorem"] : PsiType:String - UField (name = bar) [private static final var bar: java.lang.String = "ipsum"] - UAnnotation (fqName = org.jetbrains.annotations.NotNull) [@org.jetbrains.annotations.NotNull] - ULiteralExpression (value = "ipsum") ["ipsum"] : PsiType:String - UField (name = baz) [private static final var baz: java.lang.String = "dolor"] - UAnnotation (fqName = org.jetbrains.annotations.NotNull) [@org.jetbrains.annotations.NotNull] - ULiteralExpression (value = "dolor") ["dolor"] : PsiType:String - UField (name = foobarbaz) [private static final var foobarbaz: java.lang.String = foo + " " + bar + " " + baz] - UAnnotation (fqName = org.jetbrains.annotations.NotNull) [@org.jetbrains.annotations.NotNull] - UPolyadicExpression (operator = +) [foo + " " + bar + " " + baz] : PsiType:String - USimpleNameReferenceExpression (identifier = foo) [foo] : PsiType:String - ULiteralExpression (value = " ") [" "] : PsiType:String - USimpleNameReferenceExpression (identifier = bar) [bar] : PsiType:String - ULiteralExpression (value = " ") [" "] : PsiType:String - USimpleNameReferenceExpression (identifier = baz) [baz] : PsiType:String - UAnnotationMethod (name = getFoo) [public static final fun getFoo() : java.lang.String = UastEmptyExpression] - UAnnotationMethod (name = getBar) [public static final fun getBar() : java.lang.String = UastEmptyExpression] - UAnnotationMethod (name = getBaz) [public static final fun getBaz() : java.lang.String = UastEmptyExpression] - UAnnotationMethod (name = getFoobarbaz) [public static final fun getFoobarbaz() : java.lang.String = UastEmptyExpression] diff --git a/plugins/uast-kotlin/testData/StringTemplateComplex.log.txt.172 b/plugins/uast-kotlin/testData/StringTemplateComplex.log.txt.172 deleted file mode 100644 index 1d3c41687a0..00000000000 --- a/plugins/uast-kotlin/testData/StringTemplateComplex.log.txt.172 +++ /dev/null @@ -1,70 +0,0 @@ -UFile (package = ) - UClass (name = StringTemplateComplexKt) - UField (name = muchRecur) - UAnnotation (fqName = org.jetbrains.annotations.NotNull) - ULiteralExpression (value = "abc") - UField (name = case4) - UAnnotation (fqName = org.jetbrains.annotations.NotNull) - UPolyadicExpression (operator = +) - ULiteralExpression (value = "a ") - ULiteralExpression (value = "literal") - ULiteralExpression (value = " z") - UField (name = case5) - UAnnotation (fqName = org.jetbrains.annotations.NotNull) - UPolyadicExpression (operator = +) - ULiteralExpression (value = "a ") - ULiteralExpression (value = "literal") - ULiteralExpression (value = " ") - ULiteralExpression (value = "literal") - ULiteralExpression (value = " z") - UField (name = literalInLiteral) - UAnnotation (fqName = org.jetbrains.annotations.NotNull) - UPolyadicExpression (operator = +) - ULiteralExpression (value = "a ") - UPolyadicExpression (operator = +) - ULiteralExpression (value = "literal") - USimpleNameReferenceExpression (identifier = case4) - ULiteralExpression (value = " z") - UField (name = literalInLiteral2) - UAnnotation (fqName = org.jetbrains.annotations.NotNull) - UPolyadicExpression (operator = +) - ULiteralExpression (value = "a ") - UQualifiedReferenceExpression - UPolyadicExpression (operator = +) - ULiteralExpression (value = "literal") - USimpleNameReferenceExpression (identifier = case4) - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) - UIdentifier (Identifier (repeat)) - USimpleNameReferenceExpression (identifier = repeat) - ULiteralExpression (value = 4) - ULiteralExpression (value = " z") - UAnnotationMethod (name = getMuchRecur) - UAnnotationMethod (name = getCase4) - UAnnotationMethod (name = getCase5) - UAnnotationMethod (name = getLiteralInLiteral) - UAnnotationMethod (name = getLiteralInLiteral2) - UAnnotationMethod (name = simpleForTemplate) - UParameter (name = i) - UAnnotation (fqName = null) - ULiteralExpression (value = 0) - UBlockExpression - UReturnExpression - USimpleNameReferenceExpression (identifier = i) - UAnnotationMethod (name = foo) - UBlockExpression - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) - UIdentifier (Identifier (println)) - USimpleNameReferenceExpression (identifier = println) - USimpleNameReferenceExpression (identifier = baz) - UDeclarationsExpression - ULocalVariable (name = template1) - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0)) - UIdentifier (Identifier (simpleForTemplate)) - USimpleNameReferenceExpression (identifier = simpleForTemplate) - UDeclarationsExpression - ULocalVariable (name = template2) - UPolyadicExpression (operator = +) - ULiteralExpression (value = ".") - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0)) - UIdentifier (Identifier (simpleForTemplate)) - USimpleNameReferenceExpression (identifier = simpleForTemplate) diff --git a/plugins/uast-kotlin/testData/StringTemplateComplex.render.txt.172 b/plugins/uast-kotlin/testData/StringTemplateComplex.render.txt.172 deleted file mode 100644 index 6f25828dfcc..00000000000 --- a/plugins/uast-kotlin/testData/StringTemplateComplex.render.txt.172 +++ /dev/null @@ -1,20 +0,0 @@ -public final class StringTemplateComplexKt { - private static final var muchRecur: java.lang.String = "abc" - private static final var case4: java.lang.String = "a " + "literal" + " z" - private static final var case5: java.lang.String = "a " + "literal" + " " + "literal" + " z" - private static final var literalInLiteral: java.lang.String = "a " + "literal" + case4 + " z" - private static final var literalInLiteral2: java.lang.String = "a " + "literal" + case4.repeat(4) + " z" - public static final fun getMuchRecur() : java.lang.String = UastEmptyExpression - public static final fun getCase4() : java.lang.String = UastEmptyExpression - public static final fun getCase5() : java.lang.String = UastEmptyExpression - public static final fun getLiteralInLiteral() : java.lang.String = UastEmptyExpression - public static final fun getLiteralInLiteral2() : java.lang.String = UastEmptyExpression - public static final fun simpleForTemplate(i: int) : java.lang.String { - return i - } - public static final fun foo() : void { - println(baz) - var template1: java.lang.String = simpleForTemplate() - var template2: java.lang.String = "." + simpleForTemplate() - } -} diff --git a/plugins/uast-kotlin/testData/StringTemplateComplex.types.txt.172 b/plugins/uast-kotlin/testData/StringTemplateComplex.types.txt.172 deleted file mode 100644 index 8804a1e7a31..00000000000 --- a/plugins/uast-kotlin/testData/StringTemplateComplex.types.txt.172 +++ /dev/null @@ -1,70 +0,0 @@ -UFile (package = ) [public final class StringTemplateComplexKt {...] - UClass (name = StringTemplateComplexKt) [public final class StringTemplateComplexKt {...}] - UField (name = muchRecur) [private static final var muchRecur: java.lang.String = "abc"] - UAnnotation (fqName = org.jetbrains.annotations.NotNull) [@org.jetbrains.annotations.NotNull] - ULiteralExpression (value = "abc") ["abc"] : PsiType:String - UField (name = case4) [private static final var case4: java.lang.String = "a " + "literal" + " z"] - UAnnotation (fqName = org.jetbrains.annotations.NotNull) [@org.jetbrains.annotations.NotNull] - UPolyadicExpression (operator = +) ["a " + "literal" + " z"] : PsiType:String - ULiteralExpression (value = "a ") ["a "] : PsiType:String - ULiteralExpression (value = "literal") ["literal"] : PsiType:String - ULiteralExpression (value = " z") [" z"] : PsiType:String - UField (name = case5) [private static final var case5: java.lang.String = "a " + "literal" + " " + "literal" + " z"] - UAnnotation (fqName = org.jetbrains.annotations.NotNull) [@org.jetbrains.annotations.NotNull] - UPolyadicExpression (operator = +) ["a " + "literal" + " " + "literal" + " z"] : PsiType:String - ULiteralExpression (value = "a ") ["a "] : PsiType:String - ULiteralExpression (value = "literal") ["literal"] : PsiType:String - ULiteralExpression (value = " ") [" "] : PsiType:String - ULiteralExpression (value = "literal") ["literal"] : PsiType:String - ULiteralExpression (value = " z") [" z"] : PsiType:String - UField (name = literalInLiteral) [private static final var literalInLiteral: java.lang.String = "a " + "literal" + case4 + " z"] - UAnnotation (fqName = org.jetbrains.annotations.NotNull) [@org.jetbrains.annotations.NotNull] - UPolyadicExpression (operator = +) ["a " + "literal" + case4 + " z"] : PsiType:String - ULiteralExpression (value = "a ") ["a "] : PsiType:String - UPolyadicExpression (operator = +) ["literal" + case4] : PsiType:String - ULiteralExpression (value = "literal") ["literal"] : PsiType:String - USimpleNameReferenceExpression (identifier = case4) [case4] : PsiType:String - ULiteralExpression (value = " z") [" z"] : PsiType:String - UField (name = literalInLiteral2) [private static final var literalInLiteral2: java.lang.String = "a " + "literal" + case4.repeat(4) + " z"] - UAnnotation (fqName = org.jetbrains.annotations.NotNull) [@org.jetbrains.annotations.NotNull] - UPolyadicExpression (operator = +) ["a " + "literal" + case4.repeat(4) + " z"] : PsiType:String - ULiteralExpression (value = "a ") ["a "] : PsiType:String - UQualifiedReferenceExpression ["literal" + case4.repeat(4)] : PsiType:String - UPolyadicExpression (operator = +) ["literal" + case4] : PsiType:String - ULiteralExpression (value = "literal") ["literal"] : PsiType:String - USimpleNameReferenceExpression (identifier = case4) [case4] : PsiType:String - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) [repeat(4)] : PsiType:String - UIdentifier (Identifier (repeat)) [UIdentifier (Identifier (repeat))] - USimpleNameReferenceExpression (identifier = repeat) [repeat] : PsiType:String - ULiteralExpression (value = 4) [4] : PsiType:int - ULiteralExpression (value = " z") [" z"] : PsiType:String - UAnnotationMethod (name = getMuchRecur) [public static final fun getMuchRecur() : java.lang.String = UastEmptyExpression] - UAnnotationMethod (name = getCase4) [public static final fun getCase4() : java.lang.String = UastEmptyExpression] - UAnnotationMethod (name = getCase5) [public static final fun getCase5() : java.lang.String = UastEmptyExpression] - UAnnotationMethod (name = getLiteralInLiteral) [public static final fun getLiteralInLiteral() : java.lang.String = UastEmptyExpression] - UAnnotationMethod (name = getLiteralInLiteral2) [public static final fun getLiteralInLiteral2() : java.lang.String = UastEmptyExpression] - UAnnotationMethod (name = simpleForTemplate) [public static final fun simpleForTemplate(i: int) : java.lang.String {...}] - UParameter (name = i) [var i: int = 0] - UAnnotation (fqName = null) [@null] - ULiteralExpression (value = 0) [0] : PsiType:int - UBlockExpression [{...}] - UReturnExpression [return i] - USimpleNameReferenceExpression (identifier = i) [i] : PsiType:int - UAnnotationMethod (name = foo) [public static final fun foo() : void {...}] - UBlockExpression [{...}] : PsiType:void - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) [println(baz)] : PsiType:void - UIdentifier (Identifier (println)) [UIdentifier (Identifier (println))] - USimpleNameReferenceExpression (identifier = println) [println] : PsiType:void - USimpleNameReferenceExpression (identifier = baz) [baz] - UDeclarationsExpression [var template1: java.lang.String = simpleForTemplate()] - ULocalVariable (name = template1) [var template1: java.lang.String = simpleForTemplate()] - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0)) [simpleForTemplate()] : PsiType:String - UIdentifier (Identifier (simpleForTemplate)) [UIdentifier (Identifier (simpleForTemplate))] - USimpleNameReferenceExpression (identifier = simpleForTemplate) [simpleForTemplate] : PsiType:String - UDeclarationsExpression [var template2: java.lang.String = "." + simpleForTemplate()] - ULocalVariable (name = template2) [var template2: java.lang.String = "." + simpleForTemplate()] - UPolyadicExpression (operator = +) ["." + simpleForTemplate()] : PsiType:String - ULiteralExpression (value = ".") ["."] : PsiType:String - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0)) [simpleForTemplate()] : PsiType:String - UIdentifier (Identifier (simpleForTemplate)) [UIdentifier (Identifier (simpleForTemplate))] - USimpleNameReferenceExpression (identifier = simpleForTemplate) [simpleForTemplate] : PsiType:String diff --git a/plugins/uast-kotlin/testData/SuperCalls.log.txt.172 b/plugins/uast-kotlin/testData/SuperCalls.log.txt.172 deleted file mode 100644 index 267fa793b30..00000000000 --- a/plugins/uast-kotlin/testData/SuperCalls.log.txt.172 +++ /dev/null @@ -1,109 +0,0 @@ -UFile (package = ) - UClass (name = SuperCallsKt) - UField (name = anon) - UAnnotation (fqName = org.jetbrains.annotations.NotNull) - UObjectLiteralExpression - ULiteralExpression (value = "textForAnon") - UClass (name = null) - UAnnotationMethod (name = bar) - UBlockExpression - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) - UIdentifier (Identifier (cons)) - USimpleNameReferenceExpression (identifier = cons) - UObjectLiteralExpression - ULiteralExpression (value = "inner literal") - UClass (name = null) - UAnnotationMethod (name = SuperCallsKt$anon$1$bar$1) - UAnnotationMethod (name = SuperCallsKt$anon$1) - UClass (name = innerObject) - UField (name = INSTANCE) - UAnnotation (fqName = org.jetbrains.annotations.NotNull) - UAnnotationMethod (name = innerObject) - UBlockExpression - UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 1)) - UIdentifier (Identifier (A)) - USimpleNameReferenceExpression (identifier = ) - ULiteralExpression (value = "inner object") - UClass (name = InnerClass) - UAnnotationMethod (name = InnerClass) - UBlockExpression - UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 1)) - UIdentifier (Identifier (A)) - USimpleNameReferenceExpression (identifier = ) - ULiteralExpression (value = "inner class") - UAnnotationMethod (name = getAnon) - UAnnotationMethod (name = cons) - UParameter (name = a) - UAnnotation (fqName = org.jetbrains.annotations.NotNull) - UBlockExpression - UClass (name = A) - UField (name = str) - UAnnotation (fqName = org.jetbrains.annotations.NotNull) - UAnnotationMethod (name = foo) - UParameter (name = a) - UAnnotation (fqName = null) - UBlockExpression - UAnnotationMethod (name = getStr) - UAnnotationMethod (name = A) - UParameter (name = str) - UAnnotation (fqName = org.jetbrains.annotations.NotNull) - UAnnotationMethod (name = A) - UParameter (name = i) - UAnnotation (fqName = null) - UBlockExpression - UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 1)) - UIdentifier (Identifier (this)) - USimpleNameReferenceExpression (identifier = ) - UQualifiedReferenceExpression - USimpleNameReferenceExpression (identifier = i) - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0)) - UIdentifier (Identifier (toString)) - USimpleNameReferenceExpression (identifier = toString) - UClass (name = B) - UAnnotationMethod (name = B) - UParameter (name = param) - UAnnotation (fqName = org.jetbrains.annotations.NotNull) - UBlockExpression - UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 1)) - UIdentifier (Identifier (A)) - USimpleNameReferenceExpression (identifier = ) - USimpleNameReferenceExpression (identifier = param) - UClass (name = C) - UAnnotationMethod (name = foo) - UParameter (name = a) - UAnnotation (fqName = null) - UBlockExpression - UQualifiedReferenceExpression - USuperExpression (label = null) - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) - UIdentifier (Identifier (foo)) - USimpleNameReferenceExpression (identifier = foo) - USimpleNameReferenceExpression (identifier = a) - UAnnotationMethod (name = C) - UParameter (name = p) - UAnnotation (fqName = org.jetbrains.annotations.NotNull) - UBlockExpression - UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 1)) - UIdentifier (Identifier (super)) - USimpleNameReferenceExpression (identifier = ) - USimpleNameReferenceExpression (identifier = p) - UAnnotationMethod (name = C) - UParameter (name = i) - UAnnotation (fqName = null) - UBlockExpression - UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 1)) - UIdentifier (Identifier (super)) - USimpleNameReferenceExpression (identifier = ) - USimpleNameReferenceExpression (identifier = i) - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0)) - UIdentifier (Identifier (println)) - USimpleNameReferenceExpression (identifier = println) - UClass (name = O) - UField (name = INSTANCE) - UAnnotation (fqName = null) - UAnnotationMethod (name = O) - UBlockExpression - UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 1)) - UIdentifier (Identifier (A)) - USimpleNameReferenceExpression (identifier = ) - ULiteralExpression (value = "text") diff --git a/plugins/uast-kotlin/testData/SuperCalls.render.txt.172 b/plugins/uast-kotlin/testData/SuperCalls.render.txt.172 deleted file mode 100644 index 57d7af7d086..00000000000 --- a/plugins/uast-kotlin/testData/SuperCalls.render.txt.172 +++ /dev/null @@ -1,51 +0,0 @@ -public final class SuperCallsKt { - private static final var anon: A = anonymous object : A("textForAnon") { - fun bar() { - cons(object : A("inner literal")) - } - - object innerObject : A("inner object") - - inner class InnerClass : A("inner class") - } - public static final fun getAnon() : A = UastEmptyExpression - public static final fun cons(a: A) : void { - } -} - -public class A { - private final var str: java.lang.String - public fun foo(a: long) : void { - } - public final fun getStr() : java.lang.String = UastEmptyExpression - public fun A(str: java.lang.String) = UastEmptyExpression - public fun A(i: int) { - (i.toString()) - } -} - -public final class B : A { - public fun B(param: java.lang.String) { - (param) - } -} - -public final class C : A { - public fun foo(a: long) : void { - super.foo(a) - } - public fun C(p: java.lang.String) { - (p) - } - public fun C(i: int) { - (i) - println() - } -} - -public final class O : A { - public static final var INSTANCE: O - private fun O() { - ("text") - } -} diff --git a/plugins/uast-kotlin/testData/TypeInAnnotation.kt.172 b/plugins/uast-kotlin/testData/TypeInAnnotation.kt.172 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/plugins/uast-kotlin/testData/UnexpectedContainerException.render.txt.172 b/plugins/uast-kotlin/testData/UnexpectedContainerException.render.txt.172 deleted file mode 100644 index 7c405437c1d..00000000000 --- a/plugins/uast-kotlin/testData/UnexpectedContainerException.render.txt.172 +++ /dev/null @@ -1,20 +0,0 @@ -public abstract interface Callback { - public abstract fun onError(throwable: java.lang.Throwable) : void = UastEmptyExpression -} - -public final class Model { - public final fun crashMe(clazz: java.lang.Class, factory: kotlin.jvm.functions.Function0) : void { - throw () - } - public fun Model() { - { - crashMe(Callback.java, { - anonymous object : Callback { - override fun onError(throwable: Throwable) { - throw UnsupportedOperationException("") - } - } - }) - } - } -} diff --git a/plugins/uast-kotlin/testData/UnexpectedContainerException.types.txt.172 b/plugins/uast-kotlin/testData/UnexpectedContainerException.types.txt.172 deleted file mode 100644 index 6fcc8963b29..00000000000 --- a/plugins/uast-kotlin/testData/UnexpectedContainerException.types.txt.172 +++ /dev/null @@ -1,39 +0,0 @@ -UFile (package = ) [public abstract interface Callback {...] - UClass (name = Callback) [public abstract interface Callback {...}] - UAnnotationMethod (name = onError) [public abstract fun onError(throwable: java.lang.Throwable) : void = UastEmptyExpression] - UParameter (name = throwable) [var throwable: java.lang.Throwable] - UAnnotation (fqName = org.jetbrains.annotations.NotNull) [@org.jetbrains.annotations.NotNull] - UClass (name = Model) [public final class Model {...}] - UAnnotationMethod (name = crashMe) [public final fun crashMe(clazz: java.lang.Class, factory: kotlin.jvm.functions.Function0) : void {...}] - UParameter (name = clazz) [var clazz: java.lang.Class] - UAnnotation (fqName = org.jetbrains.annotations.NotNull) [@org.jetbrains.annotations.NotNull] - UParameter (name = factory) [var factory: kotlin.jvm.functions.Function0] - UAnnotation (fqName = org.jetbrains.annotations.NotNull) [@org.jetbrains.annotations.NotNull] - UBlockExpression [{...}] : PsiType:Void - UThrowExpression [throw ()] : PsiType:Void - UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 0)) [()] : PsiType:UnsupportedOperationException - UIdentifier (Identifier (UnsupportedOperationException)) [UIdentifier (Identifier (UnsupportedOperationException))] - USimpleNameReferenceExpression (identifier = ) [] : PsiType:UnsupportedOperationException - UAnnotationMethod (name = Model) [public fun Model() {...}] - UBlockExpression [{...}] - UBlockExpression [{...}] : PsiType:void - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 2)) [crashMe(Callback.java, { ...})] : PsiType:void - UIdentifier (Identifier (crashMe)) [UIdentifier (Identifier (crashMe))] - USimpleNameReferenceExpression (identifier = crashMe) [crashMe] : PsiType:void - UQualifiedReferenceExpression [Callback.java] : PsiType:Class - UClassLiteralExpression [Callback] : PsiType:KClass - USimpleNameReferenceExpression (identifier = java) [java] : PsiType:Class - ULambdaExpression [{ ...}] : PsiType: - UBlockExpression [{...}] - UObjectLiteralExpression [anonymous object : Callback {... }] : PsiType:Callback - UClass (name = null) [final class null {...}] - UAnnotationMethod (name = onError) [public fun onError(throwable: java.lang.Throwable) : void {...}] - UParameter (name = throwable) [var throwable: java.lang.Throwable] - UAnnotation (fqName = org.jetbrains.annotations.NotNull) [@org.jetbrains.annotations.NotNull] - UBlockExpression [{...}] : PsiType:Void - UThrowExpression [throw ("")] : PsiType:Void - UCallExpression (kind = UastCallKind(name='constructor_call'), argCount = 1)) [("")] : PsiType:UnsupportedOperationException - UIdentifier (Identifier (UnsupportedOperationException)) [UIdentifier (Identifier (UnsupportedOperationException))] - USimpleNameReferenceExpression (identifier = ) [] : PsiType:UnsupportedOperationException - ULiteralExpression (value = "") [""] : PsiType:String - UAnnotationMethod (name = Model$1$1) [fun Model$1$1() = UastEmptyExpression] diff --git a/plugins/uast-kotlin/testData/WhenAndDestructing.log.txt.172 b/plugins/uast-kotlin/testData/WhenAndDestructing.log.txt.172 deleted file mode 100644 index fe1b4642d28..00000000000 --- a/plugins/uast-kotlin/testData/WhenAndDestructing.log.txt.172 +++ /dev/null @@ -1,42 +0,0 @@ -UFile (package = ) - UClass (name = WhenAndDestructingKt) - UAnnotationMethod (name = getElementsAdditionalResolve) - UParameter (name = string) - UAnnotation (fqName = org.jetbrains.annotations.NotNull) - UBlockExpression - UDeclarationsExpression - ULocalVariable (name = arr) - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 2)) - UIdentifier (Identifier (listOf)) - USimpleNameReferenceExpression (identifier = listOf) - ULiteralExpression (value = "1") - ULiteralExpression (value = "2") - USwitchExpression - USimpleNameReferenceExpression (identifier = string) - UExpressionList (when) - USwitchClauseExpressionWithBody - ULiteralExpression (value = "aaaa") - UExpressionList (when_entry) - UReturnExpression - ULiteralExpression (value = "bindingContext") - UBreakExpression (label = null) - USwitchClauseExpressionWithBody - UExpressionList (when_entry) - UDeclarationsExpression - ULocalVariable (name = var837f1e82) - USimpleNameReferenceExpression (identifier = arr) - ULocalVariable (name = bindingContext) - UQualifiedReferenceExpression - USimpleNameReferenceExpression (identifier = var837f1e82) - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0)) - UIdentifier (Identifier (component1)) - USimpleNameReferenceExpression (identifier = ) - ULocalVariable (name = statementFilter) - UQualifiedReferenceExpression - USimpleNameReferenceExpression (identifier = var837f1e82) - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0)) - UIdentifier (Identifier (component2)) - USimpleNameReferenceExpression (identifier = ) - UReturnExpression - USimpleNameReferenceExpression (identifier = bindingContext) - UBreakExpression (label = null) diff --git a/plugins/uast-kotlin/testData/WhenAndDestructing.render.txt.172 b/plugins/uast-kotlin/testData/WhenAndDestructing.render.txt.172 deleted file mode 100644 index 24f4b7a612b..00000000000 --- a/plugins/uast-kotlin/testData/WhenAndDestructing.render.txt.172 +++ /dev/null @@ -1,21 +0,0 @@ -public final class WhenAndDestructingKt { - public static final fun getElementsAdditionalResolve(string: java.lang.String) : java.lang.String { - var arr: java.util.List = listOf("1", "2") - switch (string) { - "aaaa" -> { - return "bindingContext" - break - } - - -> { - var var837f1e82: = arr - var bindingContext: java.lang.String = var837f1e82.() - var statementFilter: java.lang.String = var837f1e82.() - return bindingContext - break - } - - } - - } -} diff --git a/plugins/uast-kotlin/testData/WhenIs.render.txt.172 b/plugins/uast-kotlin/testData/WhenIs.render.txt.172 deleted file mode 100644 index 917e4a950a4..00000000000 --- a/plugins/uast-kotlin/testData/WhenIs.render.txt.172 +++ /dev/null @@ -1,17 +0,0 @@ -public final class WhenIsKt { - public static final fun foo(bar: java.lang.Object) : java.lang.String { - return switch (bar) { - it is java.lang.String -> { - bar - break - } - - it !is java.lang.String -> { - "" - break - } - - } - - } -} diff --git a/plugins/uast-kotlin/testData/WhenStringLiteral.log.txt.172 b/plugins/uast-kotlin/testData/WhenStringLiteral.log.txt.172 deleted file mode 100644 index af5adb2662f..00000000000 --- a/plugins/uast-kotlin/testData/WhenStringLiteral.log.txt.172 +++ /dev/null @@ -1,33 +0,0 @@ -UFile (package = ) - UClass (name = WhenStringLiteralKt) - UField (name = a) - UAnnotation (fqName = org.jetbrains.annotations.Nullable) - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0)) - UIdentifier (Identifier (readLine)) - USimpleNameReferenceExpression (identifier = readLine) - UField (name = b) - UAnnotation (fqName = null) - USwitchExpression - USimpleNameReferenceExpression (identifier = a) - UExpressionList (when) - USwitchClauseExpressionWithBody - ULiteralExpression (value = "abc") - UExpressionList (when_entry) - ULiteralExpression (value = 1) - UBreakExpression (label = null) - USwitchClauseExpressionWithBody - ULiteralExpression (value = "def") - ULiteralExpression (value = "ghi") - UExpressionList (when_entry) - ULiteralExpression (value = 2) - UBreakExpression (label = null) - USwitchClauseExpressionWithBody - UExpressionList (when_entry) - ULiteralExpression (value = 3) - UBreakExpression (label = null) - UAnnotationMethod (name = getA) - UAnnotationMethod (name = getB) - UAnnotationMethod (name = ) - UBlockExpression - ULiteralExpression (value = "abc1") - ULiteralExpression (value = "def1") diff --git a/plugins/uast-kotlin/testData/WhenStringLiteral.render.txt.172 b/plugins/uast-kotlin/testData/WhenStringLiteral.render.txt.172 deleted file mode 100644 index dba73b9ef0b..00000000000 --- a/plugins/uast-kotlin/testData/WhenStringLiteral.render.txt.172 +++ /dev/null @@ -1,27 +0,0 @@ -public final class WhenStringLiteralKt { - private static final var a: java.lang.String = readLine() - private static final var b: int = switch (a) { - "abc" -> { - 1 - break - } - - "def", "ghi" -> { - 2 - break - } - - -> { - 3 - break - } - - } - - public static final fun getA() : java.lang.String = UastEmptyExpression - public static final fun getB() : int = UastEmptyExpression - public static final fun () : void { - "abc1" - "def1" - } -} diff --git a/plugins/uast-kotlin/testData/ea101715.types.txt.172 b/plugins/uast-kotlin/testData/ea101715.types.txt.172 deleted file mode 100644 index c185c5362ff..00000000000 --- a/plugins/uast-kotlin/testData/ea101715.types.txt.172 +++ /dev/null @@ -1,14 +0,0 @@ -UFile (package = ) [public final class Ea101715Kt {...] - UClass (name = Ea101715Kt) [public final class Ea101715Kt {...}] - UAnnotationMethod (name = a) [public static final fun a() : void {...}] - UBlockExpression [{...}] : PsiType:void - UDeclarationsExpression [var a: = Obj(555)] - ULocalVariable (name = a) [var a: = Obj(555)] - UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) [Obj(555)] - UIdentifier (Identifier (Obj)) [UIdentifier (Identifier (Obj))] - USimpleNameReferenceExpression (identifier = Obj) [Obj] - ULiteralExpression (value = 555) [555] : PsiType:int - UClass (name = Obj) [public final class Obj {...}] - UField (name = INSTANCE) [public static final var INSTANCE: Obj] - UAnnotation (fqName = null) [@null] - UAnnotationMethod (name = Obj) [private fun Obj() = UastEmptyExpression] diff --git a/plugins/uast-kotlin/tests/AbstractKotlinRenderLogTest.kt.172 b/plugins/uast-kotlin/tests/AbstractKotlinRenderLogTest.kt.172 deleted file mode 100644 index 337179fbcfc..00000000000 --- a/plugins/uast-kotlin/tests/AbstractKotlinRenderLogTest.kt.172 +++ /dev/null @@ -1,107 +0,0 @@ -package org.jetbrains.uast.test.kotlin - -import com.intellij.psi.PsiElement -import com.intellij.psi.PsiFile -import com.intellij.psi.PsiRecursiveElementVisitor -import org.jetbrains.kotlin.psi.KtFile -import org.jetbrains.kotlin.utils.addToStdlib.assertedCast -import org.jetbrains.uast.UDeclaration -import org.jetbrains.uast.UElement -import org.jetbrains.uast.UFile -import org.jetbrains.uast.kotlin.KOTLIN_CACHED_UELEMENT_KEY -import org.jetbrains.uast.kotlin.KotlinUastLanguagePlugin -import org.jetbrains.uast.test.common.RenderLogTestBase -import org.jetbrains.uast.visitor.UastVisitor -import org.junit.Assert -import java.io.File -import java.util.* - -abstract class AbstractKotlinRenderLogTest : AbstractKotlinUastTest(), RenderLogTestBase { - override fun getTestFile(testName: String, ext: String) = - File(File(TEST_KOTLIN_MODEL_DIR, testName).canonicalPath + '.' + ext) - - override fun check(testName: String, file: UFile) { - check(testName, file, true) - } - - fun check(testName: String, file: UFile, checkParentConsistency: Boolean) { - super.check(testName, file) - - if (checkParentConsistency) { - checkParentConsistency(file) - } - - file.checkContainingFileForAllElements() - } - - private fun checkParentConsistency(file: UFile) { - val parentMap = mutableMapOf() - - file.accept(object : UastVisitor { - private val parentStack = Stack() - - override fun visitElement(node: UElement): Boolean { - val parent = node.uastParent - if (parent == null) { - Assert.assertTrue("Wrong parent of $node", parentStack.empty()) - } - else { - Assert.assertEquals("Wrong parent of $node", parentStack.peek(), parent) - } - node.psi?.let { - if (it !in parentMap) { - parentMap[it] = parentStack.reversed().joinToString { it.asLogString() } - } - } - parentStack.push(node) - return false - } - - override fun afterVisitElement(node: UElement) { - super.afterVisitElement(node) - parentStack.pop() - } - }) - - file.psi.clearUastCaches() - - file.psi.accept(object : PsiRecursiveElementVisitor() { - override fun visitElement(element: PsiElement) { - val uElement = KotlinUastLanguagePlugin().convertElementWithParent(element, null) - val expectedParents = parentMap[element] - if (expectedParents != null) { - assertNotNull("Expected to be able to convert PSI element $element", uElement) - val parents = generateSequence(uElement!!.uastParent) { it.uastParent }.joinToString { it.asLogString() } - assertEquals("Inconsistent parents for ${uElement.asRenderString()}(${uElement.asLogString()})(${uElement.javaClass}) (converted from $element[${element.text}])", expectedParents, parents) - } - super.visitElement(element) - } - }) - } - - private fun UFile.checkContainingFileForAllElements() { - accept(object : UastVisitor { - override fun visitElement(node: UElement): Boolean { - if (node is PsiElement) { - node.containingFile.assertedCast { "containingFile should be KtFile for ${node.asLogString()}" } - } - - val anchorPsi = (node as? UDeclaration)?.uastAnchor?.psi - if (anchorPsi != null) { - anchorPsi.containingFile.assertedCast { "uastAnchor.containingFile should be KtFile for ${node.asLogString()}" } - } - - return false - } - }) - } -} - -private fun PsiFile.clearUastCaches() { - accept(object : PsiRecursiveElementVisitor() { - override fun visitElement(element: PsiElement) { - super.visitElement(element) - element.putUserData(KOTLIN_CACHED_UELEMENT_KEY, null) - } - }) -} diff --git a/plugins/uast-kotlin/tests/KotlinUastApiTest.kt.172 b/plugins/uast-kotlin/tests/KotlinUastApiTest.kt.172 deleted file mode 100644 index 58a5380e82f..00000000000 --- a/plugins/uast-kotlin/tests/KotlinUastApiTest.kt.172 +++ /dev/null @@ -1,303 +0,0 @@ -package org.jetbrains.uast.test.kotlin - -import com.intellij.psi.PsiModifier -import com.intellij.testFramework.UsefulTestCase -import org.jetbrains.kotlin.asJava.toLightAnnotation -import org.jetbrains.kotlin.psi.* -import org.jetbrains.kotlin.psi.psiUtil.getParentOfType -import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf -import org.jetbrains.kotlin.test.testFramework.KtUsefulTestCase -import org.jetbrains.kotlin.utils.addToStdlib.assertedCast -import org.jetbrains.kotlin.utils.addToStdlib.cast -import org.jetbrains.kotlin.utils.sure -import org.jetbrains.uast.* -import org.jetbrains.uast.kotlin.KotlinUastLanguagePlugin -import org.jetbrains.uast.test.env.findElementByText -import org.jetbrains.uast.test.env.findElementByTextFromPsi -import org.jetbrains.uast.visitor.AbstractUastVisitor -import org.junit.Assert -import org.junit.Test - - -class KotlinUastApiTest : AbstractKotlinUastTest() { - override fun check(testName: String, file: UFile) { - } - - @Test fun testAnnotationParameters() { - doTest("AnnotationParameters") { _, file -> - val annotation = file.findElementByText("@IntRange(from = 10, to = 0)") - assertEquals(annotation.findAttributeValue("from")?.evaluate(), 10) - val toAttribute = annotation.findAttributeValue("to")!! - assertEquals(toAttribute.evaluate(), 0) - KtUsefulTestCase.assertInstanceOf(annotation.psi.toUElement(), UAnnotation::class.java) - KtUsefulTestCase.assertInstanceOf( - annotation.psi.cast().toLightAnnotation().toUElement(), - UAnnotation::class.java - ) - KtUsefulTestCase.assertInstanceOf(toAttribute.uastParent, UNamedExpression::class.java) - KtUsefulTestCase.assertInstanceOf(toAttribute.psi.toUElement()?.uastParent, UNamedExpression::class.java) - } - } - - @Test fun testConvertStringTemplate() { - doTest("StringTemplateInClass") { _, file -> - val literalExpression = file.findElementByText("lorem") - val psi = literalExpression.psi!! - Assert.assertTrue(psi is KtLiteralStringTemplateEntry) - val literalExpressionAgain = psi.toUElement() - Assert.assertTrue(literalExpressionAgain is ULiteralExpression) - - } - } - - @Test fun testConvertStringTemplateWithExpectedType() { - doTest("StringTemplateWithVar") { _, file -> - val index = file.psi.text.indexOf("foo") - val stringTemplate = file.psi.findElementAt(index)!!.getParentOfType(false) - val uLiteral = stringTemplate.toUElementOfType() - assertNull(uLiteral) - } - } - - @Test fun testNameContainingFile() { - doTest("NameContainingFile") { _, file -> - val foo = file.findElementByText("class Foo") - assertEquals(file.psi, foo.nameIdentifier!!.containingFile) - - val bar = file.findElementByText("fun bar() {}") - assertEquals(file.psi, bar.nameIdentifier!!.containingFile) - - val xyzzy = file.findElementByText("val xyzzy: Int = 0") - assertEquals(file.psi, xyzzy.nameIdentifier!!.containingFile) - } - } - - @Test fun testInterfaceMethodWithBody() { - doTest("DefaultImpls") { _, file -> - val bar = file.findElementByText("fun bar() = \"Hello!\"") - assertFalse(bar.containingFile.text!!, bar.psi.modifierList.hasExplicitModifier(PsiModifier.DEFAULT)) - assertTrue(bar.containingFile.text!!, bar.psi.modifierList.hasModifierProperty(PsiModifier.DEFAULT)) - } - } - - @Test fun testParameterPropertyWithAnnotation() { - doTest("ParameterPropertyWithAnnotation") { _, file -> - val test1 = file.classes.find { it.name == "Test1" }!! - - val constructor1 = test1.methods.find { it.name == "Test1" }!! - assertTrue(constructor1.uastParameters.first().annotations.any { it.qualifiedName == "MyAnnotation" }) - - val getter1 = test1.methods.find { it.name == "getBar" }!! - assertFalse(getter1.annotations.any { it.qualifiedName == "MyAnnotation" }) - - val setter1 = test1.methods.find { it.name == "setBar" }!! - assertFalse(setter1.annotations.any { it.qualifiedName == "MyAnnotation" }) - assertFalse(setter1.uastParameters.first().annotations.any { it.qualifiedName == "MyAnnotation" }) - - - val test2 = file.classes.find { it.name == "Test2" }!! - val constructor2 = test2.methods.find { it.name == "Test2" }!! - assertFalse(constructor2.uastParameters.first().annotations.any { it.qualifiedName?.startsWith("MyAnnotation") ?: false }) - - val getter2 = test2.methods.find { it.name == "getBar" }!! - getter2.annotations.single { it.qualifiedName == "MyAnnotation" } - - val setter2 = test2.methods.find { it.name == "setBar" }!! - setter2.annotations.single { it.qualifiedName == "MyAnnotation2" } - setter2.uastParameters.first().annotations.single { it.qualifiedName == "MyAnnotation3" } - - test2.fields.find { it.name == "bar" }!!.annotations.single { it.qualifiedName == "MyAnnotation5" } - } - } - - @Test fun testElvisType() { - doTest("ElvisType") { _, file -> - val elvisExpression = file.findElementByText("text ?: return") - assertEquals("String", elvisExpression.getExpressionType()!!.presentableText) - } - } - - @Test fun testFindAttributeDefaultValue() { - doTest("AnnotationParameters") { _, file -> - val witDefaultValue = file.findElementByText("@WithDefaultValue") - assertEquals(42, witDefaultValue.findAttributeValue("value")!!.evaluate()) - assertEquals(42, witDefaultValue.findAttributeValue(null)!!.evaluate()) - } - } - - @Test fun testIfCondition() { - doTest("IfStatement") { _, file -> - val psiFile = file.psi - val element = psiFile.findElementAt(psiFile.text.indexOf("\"abc\""))!! - val binaryExpression = element.getParentOfType(false)!! - val uBinaryExpression = KotlinUastLanguagePlugin().convertElementWithParent(binaryExpression, null)!! - UsefulTestCase.assertInstanceOf(uBinaryExpression.uastParent, UIfExpression::class.java) - } - } - - @Test - fun testWhenStringLiteral() { - doTest("WhenStringLiteral") { _, file -> - - file.findElementByTextFromPsi("abc").let { literalExpression -> - val psi = literalExpression.psi!! - Assert.assertTrue(psi is KtLiteralStringTemplateEntry) - UsefulTestCase.assertInstanceOf(literalExpression.uastParent, USwitchClauseExpressionWithBody::class.java) - } - - file.findElementByTextFromPsi("def").let { literalExpression -> - val psi = literalExpression.psi!! - Assert.assertTrue(psi is KtLiteralStringTemplateEntry) - UsefulTestCase.assertInstanceOf(literalExpression.uastParent, USwitchClauseExpressionWithBody::class.java) - } - - file.findElementByTextFromPsi("def1").let { literalExpression -> - val psi = literalExpression.psi!! - Assert.assertTrue(psi is KtLiteralStringTemplateEntry) - UsefulTestCase.assertInstanceOf(literalExpression.uastParent, UBlockExpression::class.java) - } - - - } - } - - @Test - fun testWhenAndDestructing() { - doTest("WhenAndDestructing") { _, file -> - - file.findElementByTextFromPsi("val (bindingContext, statementFilter) = arr").let { e -> - val uBlockExpression = e.getParentOfType() - Assert.assertNotNull(uBlockExpression) - val uMethod = uBlockExpression!!.getParentOfType() - Assert.assertNotNull(uMethod) - } - - } - } - - @Test - fun testBrokenMethodTypeResolve() { - doTest("BrokenMethod") { _, file -> - - file.accept(object : AbstractUastVisitor() { - override fun visitCallExpression(node: UCallExpression): Boolean { - node.returnType - return false - } - }) - } - } - - @Test - fun testTypeAliases() { - doTest("TypeAliases") { _, file -> - val g = (file.psi as KtFile).declarations.single { it.name == "G" } as KtTypeAlias - val originalType = g.getTypeReference()!!.typeElement as KtFunctionType - val originalTypeParameters = originalType.parameterList.toUElement() as UDeclarationsExpression - Assert.assertTrue((originalTypeParameters.declarations.single() as UParameter).type.isValid) - } - } - - @Test - fun testResolvedDeserializedMethod() = doTest("Resolve") { _, file -> - val barMethod = file.psi.findElementAt(file.psi.text.indexOf("bar")).sure { "sourceElement" } - .parentsWithSelf.mapNotNull { it.toUElementOfType() }.firstOrNull().sure { "parent UMethod" } - - fun UElement.assertResolveCall(callText: String, methodName: String = callText.substringBefore("(")) { - this.findElementByTextFromPsi(callText).let { - val resolve = it.resolve().sure { "resolving '$callText'" } - assertEquals(methodName, resolve.name) - } - } - barMethod.assertResolveCall("foo()") - barMethod.assertResolveCall("inlineFoo()") - barMethod.assertResolveCall("forEach { println(it) }", "forEach") - barMethod.assertResolveCall("joinToString()") - barMethod.assertResolveCall("last()") - } - - @Test - fun testUtilsStreamLambda() { - doTest("Lambdas") { _, file -> - val lambda = file.findElementByTextFromPsi("{ it.isEmpty() }") - assertEquals( - "kotlin.jvm.functions.Function1", - lambda.getExpressionType()?.canonicalText - ) - val uCallExpression = lambda.uastParent.assertedCast { "UCallExpression expected" } - assertTrue(uCallExpression.valueArguments.contains(lambda)) - } - } - - @Test - fun testLambdaParamCall() { - doTest("Lambdas") { _, file -> - val lambdaCall = file.findElementByTextFromPsi("selectItemFunction()") - assertEquals( - "UIdentifier (Identifier (selectItemFunction))", - lambdaCall.methodIdentifier?.asLogString() - ) - assertEquals( - "selectItemFunction", - lambdaCall.methodIdentifier?.name - ) - assertEquals( - "invoke", - lambdaCall.methodName - ) - val receiver = lambdaCall.receiver ?: kotlin.test.fail("receiver expected") - assertEquals("UReferenceExpression", receiver.asLogString()) - val uParameter = (receiver as UReferenceExpression).resolve().toUElement() ?: kotlin.test.fail("uelement expected") - assertEquals("UParameter (name = selectItemFunction)", uParameter.asLogString()) - } - } - - @Test - fun testLocalLambdaCall() { - doTest("Lambdas") { _, file -> - val lambdaCall = file.findElementByTextFromPsi("baz()") - assertEquals( - "UIdentifier (Identifier (baz))", - lambdaCall.methodIdentifier?.asLogString() - ) - assertEquals( - "baz", - lambdaCall.methodIdentifier?.name - ) - assertEquals( - "invoke", - lambdaCall.methodName - ) - val receiver = lambdaCall.receiver ?: kotlin.test.fail("receiver expected") - assertEquals("UReferenceExpression", receiver.asLogString()) - val uParameter = (receiver as UReferenceExpression).resolve().toUElement() ?: kotlin.test.fail("uelement expected") - assertEquals("ULocalVariable (name = baz)", uParameter.asLogString()) - } - } - - @Test - fun testLocalDeclarationCall() { - doTest("LocalDeclarations") { _, file -> - val localFunction = file.findElementByTextFromPsi("bar() == Local()"). - findElementByText("bar()") - assertEquals( - "UIdentifier (Identifier (bar))", - localFunction.methodIdentifier?.asLogString() - ) - assertEquals( - "bar", - localFunction.methodIdentifier?.name - ) - assertEquals( - "bar", - localFunction.methodName - ) - assertNull(localFunction.resolve()) - val receiver = localFunction.receiver ?: kotlin.test.fail("receiver expected") - assertEquals("UReferenceExpression", receiver.asLogString()) - val uParameter = (receiver as UReferenceExpression).resolve().toUElement() ?: kotlin.test.fail("uelement expected") - assertEquals("ULambdaExpression", uParameter.asLogString()) - } - } - -} diff --git a/plugins/uast-kotlin/tests/SimpleKotlinRenderLogTest.kt.172 b/plugins/uast-kotlin/tests/SimpleKotlinRenderLogTest.kt.172 deleted file mode 100644 index 9841846a29e..00000000000 --- a/plugins/uast-kotlin/tests/SimpleKotlinRenderLogTest.kt.172 +++ /dev/null @@ -1,65 +0,0 @@ -package org.jetbrains.uast.test.kotlin - -import org.junit.Test - -class SimpleKotlinRenderLogTest : AbstractKotlinRenderLogTest() { - @Test fun testLocalDeclarations() = doTest("LocalDeclarations") - - @Test fun testSimple() = doTest("Simple") - - @Test fun testWhenIs() = doTest("WhenIs") - - @Test fun testDefaultImpls() = doTest("DefaultImpls") - - @Test fun testElvis() = doTest("Elvis") - - @Test fun testPropertyAccessors() = doTest("PropertyAccessors") - - @Test fun testPropertyInitializer() = doTest("PropertyInitializer") - - @Test fun testPropertyInitializerWithoutSetter() = doTest("PropertyInitializerWithoutSetter") - - @Test fun testAnnotationParameters() = doTest("AnnotationParameters") - - @Test fun testEnumValueMembers() = doTest("EnumValueMembers") - - @Test fun testStringTemplate() = doTest("StringTemplate") - - @Test fun testStringTemplateComplex() = doTest("StringTemplateComplex") - - @Test fun testQualifiedConstructorCall() = doTest("QualifiedConstructorCall") - - @Test fun testPropertyDelegate() = doTest("PropertyDelegate") - - @Test fun testPropertyWithAnnotation() = doTest("PropertyWithAnnotation") - - @Test fun testIfStatement() = doTest("IfStatement") - - @Test fun testInnerClasses() = doTest("InnerClasses") - - @Test fun testSimpleScript() = doTest("SimpleScript") { testName, file -> check(testName, file, false) } - - @Test fun testDestructuringDeclaration() = doTest("DestructuringDeclaration") - - @Test fun testDefaultParameterValues() = doTest("DefaultParameterValues") - - @Test fun testParameterPropertyWithAnnotation() = doTest("ParameterPropertyWithAnnotation") - - @Test fun testParametersWithDefaultValues() = doTest("ParametersWithDefaultValues") - - @Test fun testUnexpectedContainer() = doTest("UnexpectedContainerException") { testName, file -> check(testName, file, false) } - - @Test fun testWhenStringLiteral() = doTest("WhenStringLiteral") { testName, file -> check(testName, file, false) } - - @Test - fun testWhenAndDestructing() = doTest("WhenAndDestructing") { testName, file -> check(testName, file, false) } - - @Test - fun testSuperCalls() = doTest("SuperCalls") - - @Test - fun testConstructors() = doTest("Constructors") - - @Test - fun testLambdas() = doTest("Lambdas") -} diff --git a/ultimate/resources/META-INF/kotlin-spring.xml.172 b/ultimate/resources/META-INF/kotlin-spring.xml.172 deleted file mode 100644 index 8d87a408fe4..00000000000 --- a/ultimate/resources/META-INF/kotlin-spring.xml.172 +++ /dev/null @@ -1,77 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/ultimate/src/org/jetbrains/kotlin/idea/jam/KotlinJamReferenceContributor.kt.172 b/ultimate/src/org/jetbrains/kotlin/idea/jam/KotlinJamReferenceContributor.kt.172 deleted file mode 100644 index 2860e10b445..00000000000 --- a/ultimate/src/org/jetbrains/kotlin/idea/jam/KotlinJamReferenceContributor.kt.172 +++ /dev/null @@ -1,57 +0,0 @@ -package org.jetbrains.kotlin.idea.jam - -import com.intellij.codeInsight.completion.CompletionUtil -import com.intellij.jam.JamService -import com.intellij.jam.JamStringAttributeElement -import com.intellij.jam.reflect.JamStringAttributeMeta -import com.intellij.psi.PsiElementRef -import com.intellij.psi.PsiReference -import com.intellij.psi.PsiReferenceRegistrar -import com.intellij.util.SmartList -import org.jetbrains.kotlin.asJava.toLightAnnotation -import org.jetbrains.kotlin.asJava.unwrapped -import org.jetbrains.kotlin.idea.references.AbstractKotlinReferenceContributor -import org.jetbrains.kotlin.psi.KtAnnotationEntry -import org.jetbrains.kotlin.psi.KtStringTemplateExpression -import org.jetbrains.kotlin.psi.KtValueArgument -import org.jetbrains.kotlin.psi.psiUtil.isPlain -import org.jetbrains.kotlin.psi.psiUtil.parents - -// Based on the JamReferenceContributor -class KotlinJamReferenceContributor : AbstractKotlinReferenceContributor() { - @Suppress("UNCHECKED_CAST") - override fun registerReferenceProviders(registrar: PsiReferenceRegistrar) { - registrar.registerMultiProvider { expression -> - if (!expression.isPlain()) return@registerMultiProvider PsiReference.EMPTY_ARRAY - val argument = expression - .parents - .filterIsInstance() - .firstOrNull() { it.parent?.parent is KtAnnotationEntry } ?: return@registerMultiProvider PsiReference.EMPTY_ARRAY - val annotationEntry = argument.parent.parent as KtAnnotationEntry - val lightAnnotation = (CompletionUtil.getOriginalOrSelf(annotationEntry)).toLightAnnotation() - ?: return@registerMultiProvider PsiReference.EMPTY_ARRAY - - val service = JamService.getJamService(expression.project) - val annotationMeta = service.getMeta(lightAnnotation) - ?: return@registerMultiProvider PsiReference.EMPTY_ARRAY - val attributeName = argument.getArgumentName()?.asName?.asString() - val attribute = annotationMeta.findAttribute(attributeName) as? JamStringAttributeMeta - ?: return@registerMultiProvider PsiReference.EMPTY_ARRAY - val jam = attribute.getJam(PsiElementRef.real(lightAnnotation)) - val converter = attribute.converter - when (jam) { - is JamStringAttributeElement<*> -> converter.createReferences(jam as JamStringAttributeElement) - is List<*> -> { - val list = SmartList() - for (item in jam) { - val jamElement = item as? JamStringAttributeElement ?: continue - if (jamElement.psiElement?.unwrapped != expression) continue - list += converter.createReferences(jamElement) - } - list.toTypedArray() - } - else -> PsiReference.EMPTY_ARRAY - } - } - } -} diff --git a/ultimate/src/org/jetbrains/kotlin/idea/spring/generate/generateDependenciesUtils.kt.172 b/ultimate/src/org/jetbrains/kotlin/idea/spring/generate/generateDependenciesUtils.kt.172 deleted file mode 100644 index 1697650ce99..00000000000 --- a/ultimate/src/org/jetbrains/kotlin/idea/spring/generate/generateDependenciesUtils.kt.172 +++ /dev/null @@ -1,512 +0,0 @@ -/* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.kotlin.idea.spring.generate - -import com.intellij.codeInsight.lookup.LookupElement -import com.intellij.codeInsight.lookup.LookupElementBuilder -import com.intellij.codeInsight.template.Expression -import com.intellij.codeInsight.template.ExpressionContext -import com.intellij.codeInsight.template.TemplateBuilderImpl -import com.intellij.codeInsight.template.TextResult -import com.intellij.codeInspection.SmartHashMap -import com.intellij.openapi.application.ApplicationManager -import com.intellij.openapi.application.runWriteAction -import com.intellij.openapi.project.Project -import com.intellij.openapi.util.Key -import com.intellij.psi.* -import com.intellij.psi.util.PropertyUtil -import com.intellij.psi.util.PsiTypesUtil -import com.intellij.spring.CommonSpringModel -import com.intellij.spring.model.CommonSpringBean -import com.intellij.spring.model.SpringBeanPointer -import com.intellij.spring.model.SpringModelSearchParameters -import com.intellij.spring.model.actions.generate.GenerateSpringBeanDependenciesUtil -import com.intellij.spring.model.actions.generate.GenerateSpringBeanDependenciesUtil.* -import com.intellij.spring.model.actions.generate.SpringBeanClassMember -import com.intellij.spring.model.highlighting.SpringConstructorArgResolveUtil -import com.intellij.spring.model.utils.SpringBeanCoreUtils -import com.intellij.spring.model.utils.SpringBeanUtils -import com.intellij.spring.model.utils.SpringModelSearchers -import com.intellij.spring.model.utils.SpringModelUtils -import com.intellij.spring.model.xml.DomSpringBean -import com.intellij.spring.model.xml.beans.Beans -import com.intellij.spring.model.xml.beans.SpringBean -import com.intellij.util.IncorrectOperationException -import com.intellij.util.xml.DomElement -import com.intellij.util.xml.DomUtil -import org.jetbrains.annotations.NotNull -import org.jetbrains.annotations.TestOnly -import org.jetbrains.kotlin.asJava.classes.KtLightClass -import org.jetbrains.kotlin.asJava.elements.KtLightMethod -import org.jetbrains.kotlin.descriptors.CallableDescriptor -import org.jetbrains.kotlin.descriptors.ClassDescriptor -import org.jetbrains.kotlin.idea.caches.project.getModuleInfo -import org.jetbrains.kotlin.idea.caches.project.forcedModuleInfo -import org.jetbrains.kotlin.idea.caches.resolve.* -import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaOrKotlinMemberDescriptor -import org.jetbrains.kotlin.idea.caches.resolve.util.getParameterDescriptor -import org.jetbrains.kotlin.idea.completion.BasicLookupElementFactory -import org.jetbrains.kotlin.idea.completion.InsertHandlerProvider -import org.jetbrains.kotlin.idea.core.KotlinNameSuggester -import org.jetbrains.kotlin.idea.core.NewDeclarationNameValidator -import org.jetbrains.kotlin.idea.core.ShortenReferences -import org.jetbrains.kotlin.idea.core.getOrCreateCompanionObject -import org.jetbrains.kotlin.idea.editor.BatchTemplateRunner -import org.jetbrains.kotlin.idea.spring.beanClass -import org.jetbrains.kotlin.idea.spring.effectiveBeanClasses -import org.jetbrains.kotlin.idea.util.CallType -import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers -import org.jetbrains.kotlin.load.java.propertyNameBySetMethodName -import org.jetbrains.kotlin.name.Name -import org.jetbrains.kotlin.psi.* -import org.jetbrains.kotlin.psi.psiUtil.isIdentifier -import org.jetbrains.kotlin.types.KotlinType -import org.jetbrains.kotlin.types.expressions.TypeReconstructionUtil -import org.jetbrains.kotlin.utils.SmartList -import org.jetbrains.kotlin.utils.ifEmpty -import java.util.* - -// TODO: GenerateSpringBeanDependenciesUtil.ensureFileWritable() is not accessible here -private fun DomElement.ensureFileWritable() = ensureFileWritable(DomUtil.getFile(this).virtualFile, manager.project) - -// TODO: GenerateSpringBeanDependenciesUtil.getReferenceName() is not accessible here -private fun getReferencedName(currentBean: SpringBean, bean: SpringBeanPointer): String? { - val model = SpringModelUtils.getInstance().getSpringModel(currentBean) - return SpringBeanCoreUtils.getReferencedName(bean, model.allCommonBeans) -} - -// TODO: GenerateSpringBeanDependenciesUtil.getExistedSetter() is not accessible here -private fun getExistedSetter(currentBeanClass: PsiClass, setterPsiClass: PsiClass): PsiMethod? { - val psiClassType = JavaPsiFacade.getInstance(setterPsiClass.project).elementFactory.createType(setterPsiClass) - return currentBeanClass.allMethods.firstOrNull { - PropertyUtil.isSimplePropertySetter(it) && it.parameterList.parameters.first().type.isAssignableFrom(psiClassType) - } -} - -// TODO: GenerateSpringBeanDependenciesUtil.findConstructor() is not accessible here -private fun findConstructor(constructors: Array, psiParameterTypes: List): PsiMethod? { - return constructors.firstOrNull { - val parameters = it.parameterList.parameters - if (it.parameterList.parametersCount != psiParameterTypes.size) return@firstOrNull false - (psiParameterTypes zip parameters).all { it.first.isAssignableFrom(it.second.type) } - } -} - -// TODO: GenerateSpringBeanDependenciesUtil.findExistedConstructor() is not accessible here -private fun findExistedConstructor( - currentBean: SpringBean, - currentBeanClass: PsiClass, - candidateParameterClasses: Array -): PsiMethod? { - val constructors = SpringConstructorArgResolveUtil.findMatchingMethods(currentBean) - for (candidateBeanClass in candidateParameterClasses) { - for (constructor in constructors) { - val psiParameterTypes = SmartList().apply { - constructor.parameterList.parameters.mapTo(this) { it.type } - add(PsiTypesUtil.getClassType(candidateBeanClass)) - } - findConstructor(currentBeanClass.constructors, psiParameterTypes)?.let { return it } - } - } - - return null -} - -// TODO: GenerateSpringBeanDependenciesUtil.createSpringBean() is not accessible here -private fun createSpringBean(parentBeans: Beans, psiClass: PsiClass): SpringBean? { - if (!((parentBeans as DomElement)).ensureFileWritable()) return null - - return parentBeans.addBean().apply { - clazz.stringValue = psiClass.qualifiedName - id.stringValue = SpringBeanCoreUtils.suggestBeanNames(this).firstOrNull() ?: "" - } -} - -private fun SpringBean.getFactoryFunctionName(factoryBeanClass: KtClass): String { - factoryMethod.stringValue?.let { if (!it.isBlank()) return it } - - val existingNames = factoryBeanClass.declarations.mapNotNull { if (it is KtFunction || it is KtClassOrObject) it.name else null } - return KotlinNameSuggester.suggestNameByName("create${beanClass()!!.name}") { it !in existingNames } -} - -internal val PsiClass.defaultTypeText: String - get() { - val qName = qualifiedName ?: return "Any" - val typeParameters = typeParameters - if (typeParameters.isEmpty()) return qName - return TypeReconstructionUtil.getTypeNameAndStarProjectionsString(qName, typeParameters.size) - } - -private fun createSettable( - candidateBean: SpringBeanPointer, - currentBeanClass: KtLightClass, - candidateBeanClasses: Array, - injectionKind: SpringDependencyInjectionKind -): KtNamedDeclaration { - val project = currentBeanClass.project - val psiFactory = KtPsiFactory(project) - val beanName = candidateBean.name - try { - val candidateClass = candidateBeanClasses.first() - val propertyName = if (beanName != null && beanName.isIdentifier()) beanName else candidateClass.name!! - - val prototype: KtNamedDeclaration = when (injectionKind) { - SpringDependencyInjectionKind.SETTER -> { - psiFactory.createFunction("fun set${propertyName.capitalize()}(${propertyName.decapitalize()}: ${candidateClass.defaultTypeText}) { }") - } - - SpringDependencyInjectionKind.LATEINIT_PROPERTY -> { - psiFactory.createProperty("lateinit var ${propertyName.decapitalize()}: ${candidateClass.defaultTypeText}") - } - - else -> error("Unexpected injection kind: $injectionKind") - } - return currentBeanClass.kotlinOrigin!!.addDeclaration(prototype).apply { ShortenReferences.DEFAULT.process(this) } - } - catch (e: IncorrectOperationException) { - throw RuntimeException(e) - } -} - -internal fun getSuggestedNames( - beanPointer: SpringBeanPointer, - declaration: KtCallableDeclaration, - excludedInValidator: List = listOf(declaration), - existingNames: Collection = emptyList(), - getType: CallableDescriptor.() -> KotlinType? -): Collection { - val names = LinkedHashSet() - - val newDeclarationNameValidator = - NewDeclarationNameValidator(declaration.parent, null, NewDeclarationNameValidator.Target.VARIABLES, excludedInValidator) - fun validate(name: String) = name !in existingNames && newDeclarationNameValidator(name) - - SpringBeanUtils.getInstance() - .findBeanNames(beanPointer.springBean) - .asSequence() - .filter { it.isIdentifier() } - .mapTo(names) { KotlinNameSuggester.suggestNameByName(it, ::validate) } - - (declaration.resolveToDescriptor() as CallableDescriptor).getType()?.let { - names += KotlinNameSuggester.suggestNamesByType(it, ::validate) - } - - return names -} - -internal fun TemplateBuilderImpl.appendVariableTemplate( - variable: KtCallableDeclaration, - candidateBeanClasses: Array, - computeSuggestions: (() -> Collection)? -) { - if (computeSuggestions != null) { - val suggestedNames = computeSuggestions() - val defaultName = variable.name ?: "" - val nameExpression = object : Expression() { - override fun calculateResult(context: ExpressionContext) = TextResult(defaultName) - - override fun calculateQuickResult(context: ExpressionContext) = calculateResult(context) - - override fun calculateLookupItems(context: ExpressionContext): Array? { - PsiDocumentManager.getInstance(context.project).commitAllDocuments() - return suggestedNames.map { LookupElementBuilder.create(it) }.toTypedArray() - - } - } - replaceElement(variable.nameIdentifier, "names", nameExpression, true) - } - - val superTypeVariants = getSuperTypeVariants(candidateBeanClasses) - if (superTypeVariants.size > 1) { - val lookupFactory = BasicLookupElementFactory(variable.project, InsertHandlerProvider(CallType.TYPE) { emptyList() }) - val typeReferenceExpression = object : Expression() { - override fun calculateResult(context: ExpressionContext) = TextResult(candidateBeanClasses.first().qualifiedName ?: "") - - override fun calculateQuickResult(context: ExpressionContext) = calculateResult(context) - - override fun calculateLookupItems(context: ExpressionContext): Array? { - return superTypeVariants - .mapTo(LinkedHashSet()) { lookupFactory.createLookupElementForJavaClass(it, qualifyNestedClasses = true) } - .toTypedArray() - } - } - replaceElement(variable.typeReference, "type", typeReferenceExpression, true) - } -} - -private fun BatchTemplateRunner.addCreateFunctionTemplate( - function: KtFunction, - candidateBeanClasses: Map>, - dependency: SpringBeanPointer -) { - val parameterList = function.valueParameterList!! - val builder = TemplateBuilderImpl(parameterList) - addTemplateFactory(parameterList) { - for ((paramIndex, candidateBeanClassesForParam) in candidateBeanClasses) { - builder.appendVariableTemplate(function.valueParameters[paramIndex], candidateBeanClassesForParam) { - getSuggestedNames(dependency, function, listOf(function.valueParameters[paramIndex], function)) { - valueParameters[paramIndex].type - } - } - } - - builder.buildInlineTemplate() - } -} - -private fun BatchTemplateRunner.addCreatePropertyTemplate(property: KtProperty, candidateBeanClasses: Array) { - val builder = TemplateBuilderImpl(property) - addTemplateFactory(property) { - builder.appendVariableTemplate(property, candidateBeanClasses, null) - builder.buildInlineTemplate() - } -} - -private fun BatchTemplateRunner.addCreateFunctionTemplate( - function: KtFunction, - paramIndex: Int, - candidateBeanClasses: Array, - dependency: SpringBeanPointer -) { - addCreateFunctionTemplate(function, mapOf(paramIndex to candidateBeanClasses), dependency) -} - -private fun getOrCreateSetter( - candidateBean: SpringBeanPointer, - currentBeanClass: KtLightClass, - candidateBeanClasses: Array, - templatesHolder: BatchTemplateRunner, - injectionKind: SpringDependencyInjectionKind -): PsiNamedElement? { - for (candidateBeanClass in candidateBeanClasses) { - getExistedSetter(currentBeanClass, candidateBeanClass)?.let { return it } - } - - if (!ensureFileWritable(currentBeanClass)) return null - val settable = createSettable(candidateBean, currentBeanClass, candidateBeanClasses, injectionKind) - when (settable) { - is KtNamedFunction -> templatesHolder.addCreateFunctionTemplate(settable, 0, candidateBeanClasses, candidateBean) - is KtProperty -> templatesHolder.addCreatePropertyTemplate(settable, candidateBeanClasses) - } - - return settable -} - -private fun createSetterDependency( - currentBean: SpringBean, - dependency: SpringBeanPointer, - injectionKind: SpringDependencyInjectionKind -): BatchTemplateRunner? { - val templatesHolder = BatchTemplateRunner(currentBean.manager.project) - val currentBeanClass = currentBean.beanClass() as? KtLightClass ?: return null - val candidateBeanClasses = dependency.effectiveBeanClasses().ifEmpty { return null } - val setter = getOrCreateSetter(dependency, currentBeanClass, candidateBeanClasses, templatesHolder, injectionKind) ?: return null - currentBean.addProperty().apply { - name.ensureXmlElementExists() - name.stringValue = when (setter) { - is PsiMethod, is KtFunction -> propertyNameBySetMethodName(Name.identifier(setter.name!!), false)!!.asString() - else -> setter.name - } - refAttr.setStringValue(getReferencedName(currentBean, dependency)) - } - return templatesHolder -} - -private fun addConstructorParameter( - currentBeanClass: KtLightClass, - candidateBeanClass: PsiClass, - constructor: KtFunction -) { - val psiFactory = KtPsiFactory(currentBeanClass) - - val validator = NewDeclarationNameValidator(constructor, null, NewDeclarationNameValidator.Target.VARIABLES) - val resolutionFacade = currentBeanClass.kotlinOrigin!!.getResolutionFacade() - val defaultType = (candidateBeanClass.getJavaOrKotlinMemberDescriptor(resolutionFacade) as ClassDescriptor).defaultType - val name = KotlinNameSuggester.suggestNamesByType(defaultType, validator).first() - - val parameter = psiFactory.createParameter("$name: ${candidateBeanClass.defaultTypeText}") - constructor.getValueParameterList()!!.addParameter(parameter).apply { ShortenReferences.DEFAULT.process(this) } -} - -private fun findProperConstructorAndAddParameter( - currentBean: SpringBean, - dependency: SpringBeanPointer, - currentBeanClass: KtLightClass, - candidateBeanClass: PsiClass, - holder: BatchTemplateRunner -): PsiMethod? { - val lightConstructor = currentBean.resolvedConstructorArgs.resolvedMethod as? KtLightMethod ?: return null - val constructorOrigin = lightConstructor.kotlinOrigin - val properConstructor = when (constructorOrigin) { - is KtFunction -> constructorOrigin - is KtClass -> constructorOrigin.createPrimaryConstructorIfAbsent() - else -> return null - } - addConstructorParameter(currentBeanClass, candidateBeanClass, properConstructor) - holder.addCreateFunctionTemplate(properConstructor, properConstructor.getValueParameters().lastIndex, arrayOf(candidateBeanClass), dependency) - return lightConstructor -} - -private fun createConstructorWithTemplate( - currentBean: SpringBean, - dependency: SpringBeanPointer, - templatesHolder: BatchTemplateRunner -) { - val beanClass = currentBean.beanClass() as? KtLightClass ?: return - val ktBeanClass = beanClass.kotlinOrigin as? KtClass ?: return - - try { - val psiFactory = KtPsiFactory(beanClass) - val factoryFunction = when { - currentBean.factoryBean.exists() -> { - // TODO: Support non-Kotlin factory beans - val factoryClass = currentBean.factoryBean.value?.beanClass as? KtLightClass ?: return - val ktFactoryClass = factoryClass.kotlinOrigin as? KtClass ?: return - val funName = currentBean.getFactoryFunctionName(ktFactoryClass) - val funText = "fun $funName(): ${beanClass.defaultTypeText} {\n return null \n}" - ktFactoryClass.addDeclaration(psiFactory.createFunction(funText)) - } - currentBean.factoryMethod.exists() -> { - val funName = currentBean.getFactoryFunctionName(ktBeanClass) - val funText = "@JvmStatic fun $funName(): ${beanClass.defaultTypeText} {\n return null \n}" - ktBeanClass.getOrCreateCompanionObject().addDeclaration(psiFactory.createFunction(funText)) - } - else -> { - if (ktBeanClass.hasPrimaryConstructor() || ktBeanClass.getSecondaryConstructors().isNotEmpty()) { - ktBeanClass.addDeclaration(psiFactory.createSecondaryConstructor("constructor()")) - } - else { - ktBeanClass.createPrimaryConstructorIfAbsent() - } - } - } as KtFunction - - ShortenReferences.DEFAULT.process(factoryFunction) - - val dummyMethod = JavaPsiFacade.getElementFactory(beanClass.project).createMethod("foo", PsiType.VOID) - dummyMethod.containingFile.forcedModuleInfo = ktBeanClass.getModuleInfo() - SpringConstructorArgResolveUtil.suggestParamsForConstructorArgs(currentBean).forEach { dummyMethod.parameterList.add(it) } - - val parameterList = factoryFunction.valueParameterList!! - val indexOffset = parameterList.parameters.size - val candidateClassMap = SmartHashMap>() - val resolutionFacade = ktBeanClass.getResolutionFacade() - for ((i, psiParam) in dummyMethod.parameterList.parameters.withIndex()) { - val descriptor = psiParam.getParameterDescriptor(resolutionFacade)!! - val ktParameter = psiFactory.createParameter( - "${psiParam.name}: ${IdeDescriptorRenderers.SOURCE_CODE_NOT_NULL_TYPE_APPROXIMATION.renderType(descriptor.type)}" - ) - parameterList.addParameter(ktParameter) - (psiParam.type as? PsiClassType)?.resolve()?.let { candidateClassMap[i + indexOffset] = arrayOf(it) } - } - - templatesHolder.addCreateFunctionTemplate(factoryFunction, candidateClassMap, dependency) - } - catch (e: IncorrectOperationException) { - throw RuntimeException(e) - } -} - -private fun createConstructorDependency( - currentBean: SpringBean, - dependency: SpringBeanPointer -): BatchTemplateRunner? { - val templatesHolder = BatchTemplateRunner(currentBean.manager.project) - val currentBeanClass = currentBean.beanClass() as? KtLightClass ?: return null - val candidateBeanClasses = dependency.effectiveBeanClasses().ifEmpty { return null } - var existedConstructor = findExistedConstructor(currentBean, currentBeanClass, candidateBeanClasses) - if (existedConstructor == null) { - if (!ensureFileWritable(currentBeanClass)) return null - existedConstructor = findProperConstructorAndAddParameter(currentBean, dependency, currentBeanClass, candidateBeanClasses.first(), templatesHolder) - } - - val newConstructorArg = currentBean.addConstructorArg() - newConstructorArg.refAttr.stringValue = getReferencedName(currentBean, dependency) - if (existedConstructor == null && SpringConstructorArgResolveUtil.findMatchingMethods(currentBean).isEmpty()) { - createConstructorWithTemplate(currentBean, dependency, templatesHolder) - } - - return templatesHolder -} - -private fun generateDependency( - springBean: SpringBean, - dependency: SpringBeanPointer, - injectionKind: SpringDependencyInjectionKind -): BatchTemplateRunner? { - return runWriteAction { - if (injectionKind.isSetter) { - createSetterDependency(springBean, dependency, injectionKind) - } - else { - createConstructorDependency(springBean, dependency) - } - } -} - -enum class SpringDependencyInjectionKind(val isSetter: Boolean) { - CONSTRUCTOR(false), - SETTER(true), - LATEINIT_PROPERTY(true) -} - -@set:TestOnly -var Project.beanFilter: (SpringBeanPointer) -> Boolean - by NotNullableUserDataProperty(Key.create("BEAN_CHOOSER")) { true } - -@NotNull -private fun chooseDependentBeans( - candidates: Set, - project: Project, - isSetterDependency: Boolean -): List> { - return if (ApplicationManager.getApplication().isUnitTestMode) { - candidates.map { it.springBean }.filter(project.beanFilter) - } - else { - GenerateSpringBeanDependenciesUtil.chooseDependentBeans(candidates, project, isSetterDependency) - } -} - -fun generateDependenciesFor( - springModel: CommonSpringModel, - klass: KtLightClass, - injectionKind: SpringDependencyInjectionKind -): List { - val project = klass.project - val isSetter = injectionKind.isSetter - - SpringModelSearchers - .findBeans(springModel, SpringModelSearchParameters.byClass(klass)) - .asSequence() - .map { it.springBean } - .filterIsInstance() - .firstOrNull { acceptBean(it, false) } - ?.let { springBean -> - if (!springBean.ensureFileWritable()) return emptyList() - if (springBean.beanClass() == null) return emptyList() - val dependencies = chooseDependentBeans(getCandidates(springBean, isSetter), project, isSetter) - return dependencies.mapNotNull { generateDependency(springBean, it, injectionKind) } - } - - val dependencies = chooseDependentBeans(getCandidates(springModel, klass, isSetter), project, isSetter) - val beanXml = dependencies.singleOrNull()?.springBean as? DomSpringBean ?: return emptyList() - val beansXml = beanXml.getParentOfType(Beans::class.java, false) ?: return emptyList() - val newBean = createSpringBean(beansXml, klass) ?: return emptyList() - - return dependencies.mapNotNull { generateDependency(newBean, it, injectionKind) } -} diff --git a/ultimate/src/org/jetbrains/kotlin/idea/spring/inspections/KotlinSpringComponentScanInspection.kt.172 b/ultimate/src/org/jetbrains/kotlin/idea/spring/inspections/KotlinSpringComponentScanInspection.kt.172 deleted file mode 100644 index 75aa7228848..00000000000 --- a/ultimate/src/org/jetbrains/kotlin/idea/spring/inspections/KotlinSpringComponentScanInspection.kt.172 +++ /dev/null @@ -1,34 +0,0 @@ -package org.jetbrains.kotlin.idea.spring.inspections - -import com.intellij.codeInspection.ProblemsHolder -import com.intellij.openapi.module.Module -import com.intellij.openapi.module.ModuleUtilCore -import com.intellij.psi.PsiClass -import com.intellij.psi.PsiElementVisitor -import com.intellij.spring.model.highlighting.jam.SpringComponentScanInspection -import org.jetbrains.kotlin.asJava.toLightClass -import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection -import org.jetbrains.kotlin.idea.inspections.registerWithElementsUnwrapped -import org.jetbrains.kotlin.psi.KtClassOrObject -import org.jetbrains.kotlin.psi.KtVisitorVoid - -class KotlinSpringComponentScanInspection : AbstractKotlinInspection() { - private val javaInspection by lazy { - object : SpringComponentScanInspection() { - // make base method visible - override public fun checkClass(aClass: PsiClass, holder: ProblemsHolder, module: Module) = super.checkClass(aClass, holder, module) - } - } - - override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { - return object: KtVisitorVoid() { - override fun visitClassOrObject(classOrObject: KtClassOrObject) { - val module = ModuleUtilCore.findModuleForPsiElement(classOrObject) ?: return - val lightClass = classOrObject.toLightClass() ?: return - val tmpHolder = ProblemsHolder(holder.manager, classOrObject.containingFile, isOnTheFly) - javaInspection.checkClass(lightClass, tmpHolder, module) - tmpHolder.resultsArray.registerWithElementsUnwrapped(holder, isOnTheFly) - } - } - } -} \ No newline at end of file diff --git a/ultimate/src/org/jetbrains/kotlin/idea/spring/inspections/SpringKotlinAutowiredMembersInspection.kt.172 b/ultimate/src/org/jetbrains/kotlin/idea/spring/inspections/SpringKotlinAutowiredMembersInspection.kt.172 deleted file mode 100644 index ee388c55681..00000000000 --- a/ultimate/src/org/jetbrains/kotlin/idea/spring/inspections/SpringKotlinAutowiredMembersInspection.kt.172 +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.kotlin.idea.spring.inspections - -import com.intellij.codeInspection.ProblemsHolder -import com.intellij.psi.PsiElementVisitor -import com.intellij.spring.model.highlighting.SpringJavaAutowiredMembersInspection -import org.jetbrains.kotlin.asJava.toLightClass -import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection -import org.jetbrains.kotlin.idea.inspections.registerWithElementsUnwrapped -import org.jetbrains.kotlin.psi.KtClassOrObject -import org.jetbrains.kotlin.psi.KtVisitorVoid - -class SpringKotlinAutowiredMembersInspection : AbstractKotlinInspection() { - private val javaInspection by lazy { SpringJavaAutowiredMembersInspection() } - - override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { - return object: KtVisitorVoid() { - override fun visitClassOrObject(classOrObject: KtClassOrObject) { - val lightClass = classOrObject.toLightClass() ?: return - javaInspection.checkClass(lightClass, holder.manager, isOnTheFly)?.registerWithElementsUnwrapped(holder, isOnTheFly) - } - } - } -} diff --git a/ultimate/src/org/jetbrains/kotlin/idea/spring/inspections/SpringKotlinAutowiringInspection.kt.172 b/ultimate/src/org/jetbrains/kotlin/idea/spring/inspections/SpringKotlinAutowiringInspection.kt.172 deleted file mode 100644 index 2d7f9ff7c38..00000000000 --- a/ultimate/src/org/jetbrains/kotlin/idea/spring/inspections/SpringKotlinAutowiringInspection.kt.172 +++ /dev/null @@ -1,182 +0,0 @@ -package org.jetbrains.kotlin.idea.spring.inspections - -import com.intellij.codeInsight.AnnotationUtil -import com.intellij.codeInsight.FileModificationService -import com.intellij.codeInsight.lookup.LookupElement -import com.intellij.codeInsight.template.* -import com.intellij.codeInspection.LocalQuickFix -import com.intellij.codeInspection.ProblemDescriptor -import com.intellij.codeInspection.ProblemsHolder -import com.intellij.openapi.fileEditor.FileEditorManager -import com.intellij.openapi.fileEditor.OpenFileDescriptor -import com.intellij.openapi.project.Project -import com.intellij.psi.* -import com.intellij.psi.util.PropertyUtil -import com.intellij.spring.CommonSpringModel -import com.intellij.spring.SpringBundle -import com.intellij.spring.model.SpringBeanPointer -import com.intellij.spring.model.converters.SpringConverterUtil -import com.intellij.spring.model.highlighting.SpringAutowireUtil -import com.intellij.spring.model.highlighting.SpringJavaAutowiringInspection -import org.jetbrains.kotlin.asJava.elements.KtLightField -import org.jetbrains.kotlin.asJava.elements.KtLightMethod -import org.jetbrains.kotlin.asJava.toLightClass -import org.jetbrains.kotlin.asJava.toLightElements -import org.jetbrains.kotlin.asJava.toLightMethods -import org.jetbrains.kotlin.idea.core.ShortenReferences -import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection -import org.jetbrains.kotlin.idea.inspections.registerWithElementsUnwrapped -import org.jetbrains.kotlin.psi.* -import org.jetbrains.kotlin.psi.psiUtil.* - -class SpringKotlinAutowiringInspection : AbstractKotlinInspection() { - // Based on SpringJavaAutowiringInspection.AddSpringBeanQualifierFix - class AddQualifierFix( - modifierListOwner: KtModifierListOwner, - private val beanPointers: Collection>, - private val annotationFqName: String - ) : LocalQuickFix { - private val elementPointer = modifierListOwner.createSmartPointer() - - override fun getName() = SpringBundle.message("SpringAutowiringInspection.add.qualifier.fix") - - override fun getFamilyName() = name - - private fun getQualifierNamesSuggestNamesExpression(expression: KtStringTemplateExpression): Expression { - return object : Expression() { - override fun calculateResult(context: ExpressionContext): Result? { - PsiDocumentManager.getInstance(context.project).commitAllDocuments() - return TextResult(expression.plainContent) - } - - override fun calculateQuickResult(context: ExpressionContext) = this.calculateResult(context) - - override fun calculateLookupItems(context: ExpressionContext): Array? { - PsiDocumentManager.getInstance(context.project).commitAllDocuments() - return beanPointers.sortedBy { it.name ?: "" }.mapNotNull { SpringConverterUtil.createCompletionVariant(it) }.toTypedArray() - } - } - } - - private fun createQualifierNameTemplate(expression: KtStringTemplateExpression): Template { - val builder = TemplateBuilderImpl(expression.containingFile) - builder.replaceRange( - expression.getContentRange().shiftRight(expression.startOffset), - getQualifierNamesSuggestNamesExpression(expression) - ) - return builder.buildInlineTemplate() - } - - override fun applyFix(project: Project, descriptor: ProblemDescriptor) { - val modifierListOwner = elementPointer.element ?: return - if (!FileModificationService.getInstance().preparePsiElementForWrite(modifierListOwner)) return - if (beanPointers.isEmpty()) return - - val defaultBeanName = with(beanPointers.first().name) { if (isNullOrBlank()) "Unknown" else this } - val entry = KtPsiFactory(project).createAnnotationEntry("@$annotationFqName(\"$defaultBeanName\")") - val addedEntry = modifierListOwner.addAnnotationEntry(entry) - - ShortenReferences.DEFAULT.process(addedEntry) - - val stringTemplate = addedEntry.valueArguments.first().getArgumentExpression() as? KtStringTemplateExpression ?: return - val virtualFile = modifierListOwner.containingFile.virtualFile!! - val editor = FileEditorManager.getInstance(project).openTextEditor(OpenFileDescriptor(project, virtualFile, 0), false)!! - PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.document) - TemplateManager.getInstance(project).startTemplate(editor, createQualifierNameTemplate(stringTemplate)) - } - } - - private val javaInspection by lazy { SpringJavaAutowiringInspection() } - - override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : KtVisitorVoid() { - // TODO: SpringJavaAutowiringInspection.checkAutowiredMethod() is not accessible here - private fun checkAutowiredMethod(psiMethod: PsiMethod, holder: ProblemsHolder, springModel: CommonSpringModel, required: Boolean) { - val resourceAnnotation = SpringAutowireUtil.getResourceAnnotation(psiMethod) - when { - resourceAnnotation != null -> { - val propertyType = PropertyUtil.getPropertyType(psiMethod) ?: return - SpringJavaAutowiringInspection.checkAutowiredPsiMember(psiMethod, propertyType, holder, springModel, required) - } - psiMethod.parameterList.parametersCount == 0 && - SpringAutowireUtil.isAutowiredByAnnotation(psiMethod) -> { - val nameIdentifier = psiMethod.nameIdentifier ?: return - val message = SpringBundle.message("bean.autowiring.by.type.no.parameter.for.autowired.method", - if (psiMethod.isConstructor) "constructor" else "method") - holder.registerProblem(nameIdentifier, message) - } - else -> { - for (parameter in psiMethod.parameterList.parameters) { - if (AnnotationUtil.isAnnotated(parameter, "org.springframework.beans.factory.annotation.Value", true)) continue - SpringJavaAutowiringInspection.checkAutowiredPsiMember(parameter, parameter.type, holder, springModel, required) - } - } - } - } - - private fun Array.registerAdjustedProblems() { - registerWithElementsUnwrapped(holder, isOnTheFly) { qf, element -> - // Can't access AddSpringBeanQualifierFix class directly - - val klass = qf.javaClass - if (!klass.name.endsWith("AddSpringBeanQualifierFix")) return@registerWithElementsUnwrapped qf - - try { - val fields = klass.declaredFields - @Suppress("UNCHECKED_CAST") - val beanPointers = fields[1].apply { isAccessible = true }.get(qf) as Collection> - val annotationFqName = fields[2].apply { isAccessible = true }.get(qf) as String - val modifierListOwner = element.getNonStrictParentOfType() - ?: return@registerWithElementsUnwrapped qf - AddQualifierFix(modifierListOwner, beanPointers, annotationFqName) - } - catch (e: Exception) { - return@registerWithElementsUnwrapped null - } - } - } - - private fun T.processLightMember( - action: T.(holder: ProblemsHolder, model: CommonSpringModel, required: Boolean) -> Unit - ) { - val model = SpringAutowireUtil.getProcessingSpringModel(containingClass) ?: return - val required = SpringAutowireUtil.isRequired(this) - val tmpHolder = ProblemsHolder(holder.manager, containingFile, isOnTheFly) - action(this, tmpHolder, model, required) - tmpHolder.resultsArray.registerAdjustedProblems() - } - - private fun PsiMethod.processLightMethod() { - if (!SpringAutowireUtil.isInjectionPoint(this)) return - processLightMember { holder, model, required -> checkAutowiredMethod(this, holder, model, required) } - } - - private fun PsiField.processLightField() { - if (!SpringAutowireUtil.isAutowiredByAnnotation(this)) return - processLightMember { holder, model, required -> - SpringJavaAutowiringInspection.checkAutowiredPsiMember(this, type, holder, model, required) - } - } - - private fun PsiClass.processLightClass() { - javaInspection.checkClass(this, holder.manager, isOnTheFly)?.registerAdjustedProblems() - } - - override fun visitNamedFunction(function: KtNamedFunction) { - function.toLightMethods().firstOrNull()?.processLightMethod() - } - - override fun visitProperty(property: KtProperty) { - if (property.name != null) // It is here because `lightElement.name` returns `` instead of `null` suddenly - for (lightElement in property.toLightElements()) { - when (lightElement) { - is KtLightMethod -> lightElement.processLightMethod() - is KtLightField -> lightElement.processLightField() - } - } - } - - override fun visitClassOrObject(classOrObject: KtClassOrObject) { - classOrObject.toLightClass()?.processLightClass() - } - } -} \ No newline at end of file diff --git a/ultimate/src/org/jetbrains/kotlin/idea/spring/lineMarking/KotlinSpringClassAnnotator.kt.172 b/ultimate/src/org/jetbrains/kotlin/idea/spring/lineMarking/KotlinSpringClassAnnotator.kt.172 deleted file mode 100644 index 8d6623683b5..00000000000 --- a/ultimate/src/org/jetbrains/kotlin/idea/spring/lineMarking/KotlinSpringClassAnnotator.kt.172 +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.kotlin.idea.spring.lineMarking - -import com.intellij.codeInsight.daemon.GutterIconNavigationHandler -import com.intellij.codeInsight.daemon.LineMarkerInfo -import com.intellij.codeInsight.daemon.RelatedItemLineMarkerInfo -import com.intellij.navigation.GotoRelatedItem -import com.intellij.openapi.editor.markup.GutterIconRenderer -import com.intellij.openapi.util.NotNullLazyValue -import com.intellij.psi.PsiElement -import com.intellij.psi.PsiNameIdentifierOwner -import com.intellij.spring.gutter.SpringClassAnnotator -import com.intellij.util.Function -import com.intellij.util.SmartList -import org.jetbrains.kotlin.asJava.elements.KtLightAnnotationForSourceEntry -import org.jetbrains.kotlin.asJava.elements.KtLightElement -import org.jetbrains.kotlin.asJava.elements.KtLightIdentifier -import org.jetbrains.kotlin.asJava.elements.KtLightMethod -import org.jetbrains.kotlin.asJava.toLightAnnotation -import org.jetbrains.kotlin.asJava.toLightClass -import org.jetbrains.kotlin.asJava.toLightElements -import org.jetbrains.kotlin.asJava.toLightMethods -import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptor -import org.jetbrains.kotlin.psi.* -import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject -import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypeAndBranch -import org.jetbrains.kotlin.resolve.annotations.hasJvmStaticAnnotation -import javax.swing.Icon - -class KotlinSpringClassAnnotator : SpringClassAnnotator() { - override fun getElementToProcess(psiElement: PsiElement): PsiElement? { - if (psiElement is KtLightIdentifier) return psiElement.parent - psiElement.getParentOfTypeAndBranch { nameIdentifier }?.let { return it.toLightClass() } - psiElement.getParentOfTypeAndBranch { nameIdentifier }?.let { function -> - val containingClassOrObject = function.containingClassOrObject - val classForLightMethod = if (containingClassOrObject is KtObjectDeclaration - && containingClassOrObject.isCompanion() - && function.resolveToDescriptor().hasJvmStaticAnnotation()) { - containingClassOrObject.containingClassOrObject - } - else { - containingClassOrObject - } - return classForLightMethod?.toLightClass()?.methods?.firstOrNull { (it as? KtLightMethod)?.kotlinOrigin == function } - } - psiElement.getParentOfTypeAndBranch> { getConstructorKeyword() ?: getValueParameterList() }?.let { - return it.toLightMethods().firstOrNull() - } - psiElement.getParentOfTypeAndBranch { nameIdentifier }?.let { return it } - psiElement.getParentOfTypeAndBranch { nameIdentifier }?.let { if (it.valOrVarKeyword != null) return it } - psiElement.getParentOfTypeAndBranch { - (typeReference?.typeElement as? KtUserType)?.referenceExpression?.getReferencedNameElement() - }?.let { return it.toLightAnnotation() } - return null - } - - private fun doCollectMarkers(psiElement: PsiElement, result: MutableCollection>) { - if (psiElement is KtProperty || psiElement is KtParameter) { - for (it in (psiElement as KtDeclaration).toLightElements()) { - val nameIdentifier = (it as? PsiNameIdentifierOwner)?.nameIdentifier ?: continue - super.collectNavigationMarkers(nameIdentifier, result) - } - return - } - - // Workaround for SpringClassAnnotator - (getElementToProcess(psiElement) as? KtLightAnnotationForSourceEntry)?.let { return super.collectNavigationMarkers(it, result) } - - super.collectNavigationMarkers(psiElement, result) - } - - // TODO - // Weak references to light elements may be reclaimed by GC after original file is modified causing line markers to misbehave - // This workaround allows reuse of SpringClassAnnotator logic and avoids binding of line markers to light elements - - private val toolTipProviderField by lazy { LineMarkerInfo::class.java.getDeclaredField("myTooltipProvider").apply { isAccessible = true } } - private val iconField by lazy { LineMarkerInfo::class.java.getDeclaredField("myIcon").apply { isAccessible = true } } - private val iconAlignmentField by lazy { LineMarkerInfo::class.java.getDeclaredField("myIconAlignment").apply { isAccessible = true } } - private val targetsField by lazy { RelatedItemLineMarkerInfo::class.java.getDeclaredField("myTargets").apply { isAccessible = true } } - - override fun collectNavigationMarkers(psiElement: PsiElement, result: MutableCollection>) { - val newItems = SmartList>() - - doCollectMarkers(psiElement, newItems) - - newItems.mapNotNullTo(result) { item -> - val itemElement = item.element - val elementToAnnotate = when (itemElement) { - is KtLightIdentifier -> itemElement.origin - is KtLightElement<*, *> -> itemElement.kotlinOrigin - else -> return@mapNotNullTo item - } - if (elementToAnnotate == null) return@mapNotNullTo null - if (alreadyMarked(result, elementToAnnotate, item.navigationHandler)) return@mapNotNullTo null - - @Suppress("UNCHECKED_CAST") - RelatedItemLineMarkerInfo( - elementToAnnotate, - elementToAnnotate.textRange, - iconField.get(item) as Icon?, - item.updatePass, - toolTipProviderField.get(item) as Function, - item.navigationHandler, - iconAlignmentField.get(item) as GutterIconRenderer.Alignment, - targetsField.get(item) as NotNullLazyValue> - ) - } - } - - private fun alreadyMarked(result: MutableCollection>, - elementToAnnotate: PsiElement, - navigationHandler: GutterIconNavigationHandler<*>?) = - result.any { - when (it) { - is RelatedItemLineMarkerInfo<*> -> { - it.element == elementToAnnotate && it.navigationHandler == navigationHandler - } - else -> false - } - } -} \ No newline at end of file diff --git a/ultimate/src/org/jetbrains/kotlin/idea/spring/references/KotlinSpringReferenceContributor.kt.172 b/ultimate/src/org/jetbrains/kotlin/idea/spring/references/KotlinSpringReferenceContributor.kt.172 deleted file mode 100644 index 1a5c72bdc9b..00000000000 --- a/ultimate/src/org/jetbrains/kotlin/idea/spring/references/KotlinSpringReferenceContributor.kt.172 +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.kotlin.idea.spring.references - -import com.intellij.openapi.util.TextRange -import com.intellij.psi.PsiReference -import com.intellij.psi.PsiReferenceBase -import com.intellij.psi.PsiReferenceRegistrar -import com.intellij.spring.constants.SpringAnnotationsConstants -import com.intellij.spring.constants.SpringConstants -import com.intellij.spring.model.utils.resources.SpringResourcesBuilder -import com.intellij.spring.model.utils.resources.SpringResourcesUtil -import com.intellij.spring.references.SpringBeanNamesReferenceProvider -import com.intellij.spring.references.SpringBeanReference -import org.jetbrains.kotlin.asJava.toLightClass -import org.jetbrains.kotlin.descriptors.CallableDescriptor -import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor -import org.jetbrains.kotlin.descriptors.ConstructorDescriptor -import org.jetbrains.kotlin.idea.caches.resolve.analyze -import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptor -import org.jetbrains.kotlin.idea.imports.importableFqName -import org.jetbrains.kotlin.idea.references.AbstractKotlinReferenceContributor -import org.jetbrains.kotlin.psi.* -import org.jetbrains.kotlin.psi.psiUtil.getContentRange -import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType -import org.jetbrains.kotlin.psi.psiUtil.isPlain -import org.jetbrains.kotlin.psi.psiUtil.plainContent -import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall -import org.jetbrains.kotlin.resolve.descriptorUtil.overriddenTreeAsSequence -import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode -import org.jetbrains.kotlin.resolve.source.getPsi - -// TODO: Use Kotlin patterns -class KotlinSpringReferenceContributor : AbstractKotlinReferenceContributor() { - override fun registerReferenceProviders(registrar: PsiReferenceRegistrar) { - registrar.registerProvider { - if (!it.isPlain()) return@registerProvider null - - val callExpression = (it.parent as? KtValueArgument)?.getStrictParentOfType() ?: return@registerProvider null - val context = callExpression.analyze(BodyResolveMode.PARTIAL) - val resolvedCall = callExpression.getResolvedCall(context) ?: return@registerProvider null - val callable = resolvedCall.resultingDescriptor as? CallableMemberDescriptor ?: return@registerProvider null - if (!callable.overriddenTreeAsSequence(true).any { - it.containingDeclaration.importableFqName?.asString() == SpringConstants.BEAN_FACTORY_CLASS - }) return@registerProvider null - if (callable.name.asString() !in SpringBeanNamesReferenceProvider.METHODS) return@registerProvider null - - SpringBeanReference(it, it.getContentRange()) - } - - registrar.registerProvider(PsiReferenceRegistrar.HIGHER_PRIORITY) { - if (!it.isPlain()) return@registerProvider null - - val argument = it.parent as? KtValueArgument ?: return@registerProvider null - val argumentName = argument.getArgumentName() ?: return@registerProvider null - if (argumentName.asName.asString() != "name") return@registerProvider null - - val entry = argument.getStrictParentOfType() ?: return@registerProvider null - val context = entry.analyze(BodyResolveMode.PARTIAL) - val resolvedCall = entry.getResolvedCall(context) ?: return@registerProvider null - val annotation = (resolvedCall.resultingDescriptor as? ConstructorDescriptor)?.containingDeclaration ?: return@registerProvider null - if (annotation.importableFqName?.asString() != SpringAnnotationsConstants.JAVAX_RESOURCE) return@registerProvider null - - val contentRange = it.getContentRange() - var startOffset = contentRange.startOffset - val isFactoryBeanRef: Boolean - if (it.plainContent.startsWith("&")) { - startOffset++ - isFactoryBeanRef = true - } - else { - isFactoryBeanRef = false - } - - val callable = (it.getStrictParentOfType()?.parent as? KtModifierList)?.parent as? KtCallableDeclaration - val callableType = (callable?.resolveToDescriptor() as? CallableDescriptor)?.returnType - val requiredSuperClass = callableType?.constructor?.declarationDescriptor?.source?.getPsi() as? KtClass - - SpringBeanReference(it, TextRange(startOffset, contentRange.endOffset), requiredSuperClass?.toLightClass(), isFactoryBeanRef) - } - - registrar.registerProvider(PsiReferenceRegistrar.HIGHER_PRIORITY) { - if (!it.isPlain()) return@registerProvider null - - val argument = it.parent as? KtValueArgument ?: return@registerProvider null - val argumentName = argument.getArgumentName() - if (argumentName != null && argumentName.asName.asString() != "value") return@registerProvider null - - val entry = argument.getStrictParentOfType() ?: return@registerProvider null - val context = entry.analyze(BodyResolveMode.PARTIAL) - val resolvedCall = entry.getResolvedCall(context) ?: return@registerProvider null - val annotation = (resolvedCall.resultingDescriptor as? ConstructorDescriptor)?.containingDeclaration ?: return@registerProvider null - if (annotation.importableFqName?.asString() != SpringAnnotationsConstants.SCOPE) return@registerProvider null - - KtSpringBeanScopeReference(it) - } - - registrar.registerMultiProvider { - if (!it.isPlain()) return@registerMultiProvider PsiReference.EMPTY_ARRAY - - val callExpression = (it.parent as? KtValueArgument)?.getStrictParentOfType() - ?: return@registerMultiProvider PsiReference.EMPTY_ARRAY - val context = callExpression.analyze(BodyResolveMode.PARTIAL) - val resolvedCall = callExpression.getResolvedCall(context) ?: return@registerMultiProvider PsiReference.EMPTY_ARRAY - val classDescriptor = (resolvedCall.resultingDescriptor as? ConstructorDescriptor)?.containingDeclaration - ?: return@registerMultiProvider PsiReference.EMPTY_ARRAY - val qName = classDescriptor.importableFqName?.asString() - if (qName != SpringConstants.CLASS_PATH_XML_APP_CONTEXT && qName != SpringConstants.CLASS_PATH_RESOURCE) { - return@registerMultiProvider PsiReference.EMPTY_ARRAY - } - - val content = it.plainContent - val resourcesBuilder = SpringResourcesBuilder.create(it, content).fromRoot(content.startsWith("/")).soft(false) - SpringResourcesUtil.getInstance().getClassPathReferences(resourcesBuilder) - } - - registrar.registerProvider(PsiReferenceRegistrar.HIGHER_PRIORITY) { - if (!it.isPlain()) return@registerProvider null - - val argument = it.parent as? KtValueArgument ?: return@registerProvider null - val argumentName = argument.getArgumentName() - if (argumentName != null && argumentName.asName.asString() != "value") return@registerProvider null - - val entry = argument.getStrictParentOfType() ?: return@registerProvider null - val bindingContext = entry.analyze(BodyResolveMode.PARTIAL) - val resolvedCall = entry.getResolvedCall(bindingContext) ?: return@registerProvider null - val annotation = (resolvedCall.resultingDescriptor as? ConstructorDescriptor)?.containingDeclaration - ?: return@registerProvider null - if (annotation.importableFqName?.asString() != SpringAnnotationsConstants.QUALIFIER) return@registerProvider null - - val annotated = entry.getStrictParentOfType() ?: return@registerProvider null - if (annotated is KtClassOrObject) { - object : PsiReferenceBase(it) { - override fun resolve() = entry - override fun getVariants(): Array = arrayOf() - } - } - else { - KtSpringQualifierReference(it) - } - } - } -} \ No newline at end of file diff --git a/ultimate/src/org/jetbrains/kotlin/idea/spring/references/KtSpringBeanScopeReference.kt.172 b/ultimate/src/org/jetbrains/kotlin/idea/spring/references/KtSpringBeanScopeReference.kt.172 deleted file mode 100644 index 1254d1be575..00000000000 --- a/ultimate/src/org/jetbrains/kotlin/idea/spring/references/KtSpringBeanScopeReference.kt.172 +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.kotlin.idea.spring.references - -import com.intellij.codeInsight.lookup.LookupElementBuilder -import com.intellij.ide.TypePresentationService -import com.intellij.psi.ElementManipulators -import com.intellij.psi.PsiReferenceBase -import com.intellij.spring.model.scope.SpringBeanScope -import com.intellij.spring.model.scope.SpringBeanScopeManager -import org.jetbrains.kotlin.psi.KtStringTemplateExpression -import org.jetbrains.kotlin.psi.psiUtil.plainContent - -class KtSpringBeanScopeReference( - element: KtStringTemplateExpression -) : PsiReferenceBase(element, ElementManipulators.getManipulator(element).getRangeInElement(element)) { - private fun getScopes(): Sequence { - return SpringBeanScope.getDefaultScopes().asSequence() + SpringBeanScopeManager.getInstance().getCustomBeanScopes(element) - } - - private fun getLookupElement(scope: String): LookupElementBuilder { - return LookupElementBuilder - .create(scope) - .withIcon(TypePresentationService.getService().getTypeIcon(SpringBeanScope::class.java)) - } - - override fun resolve() = if (element.plainContent in getScopes().map { it.value }) element else null - - override fun getVariants() = getScopes().map { getLookupElement(it.value) }.toList().toTypedArray() -} diff --git a/ultimate/src/org/jetbrains/kotlin/idea/spring/references/KtSpringQualifierReference.kt.172 b/ultimate/src/org/jetbrains/kotlin/idea/spring/references/KtSpringQualifierReference.kt.172 deleted file mode 100644 index 17c5d6bb0ab..00000000000 --- a/ultimate/src/org/jetbrains/kotlin/idea/spring/references/KtSpringQualifierReference.kt.172 +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.kotlin.idea.spring.references - -import com.intellij.codeInsight.lookup.LookupElement -import com.intellij.psi.* -import com.intellij.spring.model.DefaultSpringBeanQualifier -import com.intellij.spring.model.converters.SpringConverterUtil -import com.intellij.spring.model.highlighting.SpringAutowireUtil -import com.intellij.spring.model.jam.qualifiers.SpringJamQualifier -import com.intellij.spring.model.utils.SpringModelSearchers -import com.intellij.spring.references.SpringQualifierReference -import org.jetbrains.kotlin.asJava.elements.KtLightElement -import org.jetbrains.kotlin.asJava.toLightAnnotation -import org.jetbrains.kotlin.asJava.toLightElements -import org.jetbrains.kotlin.idea.caches.resolve.analyze -import org.jetbrains.kotlin.idea.imports.importableFqName -import org.jetbrains.kotlin.idea.search.allScope -import org.jetbrains.kotlin.idea.spring.springModel -import org.jetbrains.kotlin.psi.KtAnnotationEntry -import org.jetbrains.kotlin.psi.KtFile -import org.jetbrains.kotlin.psi.KtProperty -import org.jetbrains.kotlin.psi.KtStringTemplateExpression -import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType -import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType -import org.jetbrains.kotlin.psi.psiUtil.plainContent -import org.jetbrains.kotlin.psi.psiUtil.startOffset -import org.jetbrains.kotlin.resolve.BindingContext -import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode -import java.util.* - -// Based on com.intellij.spring.references.SpringQualifierReference -// It inherits from SpringQualifierReference to allow reuse of existing Java inspections which explicitly check for SpringQualifierReference -class KtSpringQualifierReference(element: KtStringTemplateExpression) : SpringQualifierReference(StringTemplatePsiLiteralWrapper(element)) { - class StringTemplatePsiLiteralWrapper( - val element: KtStringTemplateExpression - ) : PsiElement by element, PsiLiteralExpression, KtLightElement, PsiCompiledElement { - - override fun getValue() = element.plainContent - override fun getType() = PsiType.getJavaLangString(element.manager, element.project.allScope()) - - override val clsDelegate: KtStringTemplateExpression - get() = element - override val kotlinOrigin: KtStringTemplateExpression - get() = element - - override fun getMirror() = null - } - - private fun getAnnotationFqName(): String? { - val annotationEntry = element.getStrictParentOfType() ?: return null - val context = annotationEntry.analyze(BodyResolveMode.PARTIAL) - val annotationType = context[BindingContext.TYPE, annotationEntry.typeReference] ?: return null - return annotationType.constructor.declarationDescriptor?.importableFqName?.asString() - } - - override fun multiResolve(incompleteCode: Boolean): Array { - val annotationEntry = element.getStrictParentOfType() ?: return ResolveResult.EMPTY_ARRAY - val lightAnnotation = annotationEntry.toLightAnnotation() ?: return ResolveResult.EMPTY_ARRAY - val springModel = element.springModel ?: return ResolveResult.EMPTY_ARRAY - - val results = ArrayList() - val jamQualifier = SpringJamQualifier(lightAnnotation, null) - - val qualifiedBeans = springModel.findQualifiedBeans(jamQualifier) - qualifiedBeans.mapTo(results) { PsiElementResolveResult(it.springBean.springQualifier!!.identifyingPsiElement) } - - val qualifierValue = jamQualifier.qualifierValue - if (qualifierValue != null) { - val beanPointer = SpringModelSearchers.findBean(springModel, qualifierValue) - val psiElement = if (beanPointer != null && beanPointer.isValid) beanPointer.psiElement else null - if (psiElement != null) results += PsiElementResolveResult(psiElement) - } - - return results.toTypedArray() - } - - // We can't get light elements for property in the synthetic completion KtFile, so look for original one instead - private fun getOriginalProperty(): KtProperty? { - val currentProperty = element.getStrictParentOfType() ?: return null - val originalFile = element.containingFile.originalFile as? KtFile ?: return null - return originalFile.findElementAt(currentProperty.startOffset)?.getNonStrictParentOfType() - } - - override fun getVariants(): Array { - val annotationFqName = getAnnotationFqName() ?: return LookupElement.EMPTY_ARRAY - val springModel = element.springModel ?: return LookupElement.EMPTY_ARRAY - val property = getOriginalProperty() ?: return LookupElement.EMPTY_ARRAY - val lightElement = property.toLightElements().firstOrNull { - it is PsiField || (it is PsiMethod && !it.name.startsWith("set")) - } - val expectedPsiType = when (lightElement) { - is PsiMethod -> lightElement.returnType - is PsiField -> lightElement.type - else -> null - } ?: return LookupElement.EMPTY_ARRAY - return SpringAutowireUtil - .autowireByType(springModel, expectedPsiType) - .mapNotNull { - val qualifier = it.springBean.springQualifier - val value = qualifier?.qualifierValue - when { - qualifier == null -> - SpringConverterUtil.createCompletionVariant(it) - value != null && (qualifier is DefaultSpringBeanQualifier || qualifier.qualifierType?.qualifiedName == annotationFqName) -> - SpringConverterUtil.createCompletionVariant(it, value) - else -> - null - } - } - .toTypedArray() - } -} \ No newline at end of file diff --git a/ultimate/testData/inspections/spring/unconfiguredFacet/inspectionData/inspections.test.172 b/ultimate/testData/inspections/spring/unconfiguredFacet/inspectionData/inspections.test.172 deleted file mode 100644 index 5b39763229b..00000000000 --- a/ultimate/testData/inspections/spring/unconfiguredFacet/inspectionData/inspections.test.172 +++ /dev/null @@ -1,2 +0,0 @@ -// INSPECTION_CLASS: org.jetbrains.kotlin.idea.spring.inspections.KotlinSpringFacetCodeInspection -// FIXTURE_CLASS: org.jetbrains.kotlin.idea.spring.tests.SpringTestFixtureExtension \ No newline at end of file diff --git a/ultimate/testData/quickFixes/spring/addQualifierAnnotation/ambiguousBean.kt.172 b/ultimate/testData/quickFixes/spring/addQualifierAnnotation/ambiguousBean.kt.172 deleted file mode 100644 index 9c0833c2348..00000000000 --- a/ultimate/testData/quickFixes/spring/addQualifierAnnotation/ambiguousBean.kt.172 +++ /dev/null @@ -1,27 +0,0 @@ -// "Add qualifier" "true" -// FIXTURE_CLASS: org.jetbrains.kotlin.idea.spring.tests.SpringTestFixtureExtension -// CONFIGURE_SPRING_FILE_SET -// WITH_RUNTIME -// DISABLE-ERRORS - -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.stereotype.Component -import org.springframework.context.annotation.ComponentScan -import org.springframework.context.annotation.Configuration -import org.springframework.beans.factory.annotation.Qualifier - -@Configuration -@ComponentScan -open class InvalidAutowiredByTypeQualifiers - -abstract class BaseBarBean -@Component -open class BarBean1 : BaseBarBean() -@Component -open class BarBean2 : BaseBarBean() - -@Component -open class MultipleAutowiredCandidates() { - @Autowired - lateinit var bean: BaseBarBean -} \ No newline at end of file diff --git a/ultimate/testData/quickFixes/spring/addQualifierAnnotation/ambiguousBean.kt.after.172 b/ultimate/testData/quickFixes/spring/addQualifierAnnotation/ambiguousBean.kt.after.172 deleted file mode 100644 index b6e8b6ee50e..00000000000 --- a/ultimate/testData/quickFixes/spring/addQualifierAnnotation/ambiguousBean.kt.after.172 +++ /dev/null @@ -1,28 +0,0 @@ -// "Add qualifier" "true" -// FIXTURE_CLASS: org.jetbrains.kotlin.idea.spring.tests.SpringTestFixtureExtension -// CONFIGURE_SPRING_FILE_SET -// WITH_RUNTIME -// DISABLE-ERRORS - -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.stereotype.Component -import org.springframework.context.annotation.ComponentScan -import org.springframework.context.annotation.Configuration -import org.springframework.beans.factory.annotation.Qualifier - -@Configuration -@ComponentScan -open class InvalidAutowiredByTypeQualifiers - -abstract class BaseBarBean -@Component -open class BarBean1 : BaseBarBean() -@Component -open class BarBean2 : BaseBarBean() - -@Component -open class MultipleAutowiredCandidates() { - @Qualifier("barBean1") - @Autowired - lateinit var bean: BaseBarBean -} \ No newline at end of file diff --git a/ultimate/testData/spring/core/generate/autowiredDependencies/multiplePropertiesAnnotationConfig.kt.after.172 b/ultimate/testData/spring/core/generate/autowiredDependencies/multiplePropertiesAnnotationConfig.kt.after.172 deleted file mode 100644 index e07d5d8b94e..00000000000 --- a/ultimate/testData/spring/core/generate/autowiredDependencies/multiplePropertiesAnnotationConfig.kt.after.172 +++ /dev/null @@ -1,26 +0,0 @@ -// ACTION_CLASS: org.jetbrains.kotlin.idea.spring.generate.GenerateKotlinAutowiredDependencyAction -// CHOOSE_BEAN: barBean, application -package a - -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.beans.factory.annotation.Qualifier -import org.springframework.stereotype.Component -import org.springframework.context.annotation.Configuration -import org.springframework.context.annotation.ComponentScan - -@Component -open class FooBean { - @Qualifier("application") - @Autowired - lateinit var application: Application - @Autowired - lateinit var barBean: BarBean - -} - -@Component -open class BarBean - -@Configuration -@ComponentScan -open class Application \ No newline at end of file diff --git a/ultimate/testData/spring/core/references/completion/handler/packageReferenceEnter.kt.172 b/ultimate/testData/spring/core/references/completion/handler/packageReferenceEnter.kt.172 deleted file mode 100644 index 41ee6c3cbd4..00000000000 --- a/ultimate/testData/spring/core/references/completion/handler/packageReferenceEnter.kt.172 +++ /dev/null @@ -1,11 +0,0 @@ -// ELEMENT: java -// CHAR: \n - -import org.springframework.context.annotation.ComponentScan -import org.springframework.context.annotation.Configuration - -@Configuration -@ComponentScan(basePackages = arrayOf("java")) -open class App { - -} \ No newline at end of file diff --git a/ultimate/testData/spring/core/references/completion/handler/packageReferenceEnter.kt.after.172 b/ultimate/testData/spring/core/references/completion/handler/packageReferenceEnter.kt.after.172 deleted file mode 100644 index 2a2eadee882..00000000000 --- a/ultimate/testData/spring/core/references/completion/handler/packageReferenceEnter.kt.after.172 +++ /dev/null @@ -1,11 +0,0 @@ -// ELEMENT: java -// CHAR: \n - -import org.springframework.context.annotation.ComponentScan -import org.springframework.context.annotation.Configuration - -@Configuration -@ComponentScan(basePackages = arrayOf("javava")) -open class App { - -} \ No newline at end of file diff --git a/ultimate/testData/spring/core/references/completion/handler/packageReferenceTab.kt.172 b/ultimate/testData/spring/core/references/completion/handler/packageReferenceTab.kt.172 deleted file mode 100644 index db5ba7d9225..00000000000 --- a/ultimate/testData/spring/core/references/completion/handler/packageReferenceTab.kt.172 +++ /dev/null @@ -1,11 +0,0 @@ -// ELEMENT: java -// CHAR: \t - -import org.springframework.context.annotation.ComponentScan -import org.springframework.context.annotation.Configuration - -@Configuration -@ComponentScan(basePackages = arrayOf("java")) -open class App { - -} \ No newline at end of file diff --git a/ultimate/testData/spring/core/references/completion/handler/packageReferenceTab.kt.after.172 b/ultimate/testData/spring/core/references/completion/handler/packageReferenceTab.kt.after.172 deleted file mode 100644 index 17e1f5d7589..00000000000 --- a/ultimate/testData/spring/core/references/completion/handler/packageReferenceTab.kt.after.172 +++ /dev/null @@ -1,11 +0,0 @@ -// ELEMENT: java -// CHAR: \t - -import org.springframework.context.annotation.ComponentScan -import org.springframework.context.annotation.Configuration - -@Configuration -@ComponentScan(basePackages = arrayOf("java")) -open class App { - -} \ No newline at end of file diff --git a/ultimate/testData/spring/core/references/completion/variants/packageReference.kt.172 b/ultimate/testData/spring/core/references/completion/variants/packageReference.kt.172 deleted file mode 100644 index 326f884cbb3..00000000000 --- a/ultimate/testData/spring/core/references/completion/variants/packageReference.kt.172 +++ /dev/null @@ -1,12 +0,0 @@ -// NUMBER: 2 -// EXIST: { lookupString:"java" } -// EXIST: { lookupString:"javax" } - -import org.springframework.context.annotation.ComponentScan -import org.springframework.context.annotation.Configuration - -@Configuration -@ComponentScan(basePackages = arrayOf("java")) -open class App { - -} \ No newline at end of file diff --git a/ultimate/tests/org/jetbrains/kotlin/idea/spring/tests/SpringTestFixtureExtension.kt.172 b/ultimate/tests/org/jetbrains/kotlin/idea/spring/tests/SpringTestFixtureExtension.kt.172 deleted file mode 100644 index 45bae44b840..00000000000 --- a/ultimate/tests/org/jetbrains/kotlin/idea/spring/tests/SpringTestFixtureExtension.kt.172 +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.kotlin.idea.spring.tests - -import com.intellij.facet.impl.FacetUtil -import com.intellij.openapi.module.Module -import com.intellij.openapi.util.io.FileUtil -import com.intellij.psi.PsiFile -import com.intellij.spring.facet.SpringFacet -import com.intellij.spring.facet.SpringFileSet -import com.intellij.testFramework.fixtures.CodeInsightTestFixture -import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture -import com.intellij.util.PathUtil -import org.jetbrains.kotlin.idea.test.ConfigLibraryUtil -import org.jetbrains.kotlin.idea.test.TestFixtureExtension -import org.jetbrains.kotlin.test.InTextDirectivesUtils -import java.io.File - -@Suppress("unused") -class SpringTestFixtureExtension() : TestFixtureExtension { - private var module: Module? = null - - override fun setUp(module: Module) { - this.module = module - - val springClasspath = System.getProperty("spring.classpath") - ?: throw RuntimeException("Unable to get a valid classpath from 'spring.classpath' property, please set it accordingly"); - - ConfigLibraryUtil.addLibrary(module, "spring", null, springClasspath.split(File.pathSeparator).toTypedArray()) - - FacetUtil.addFacet(module, SpringFacet.getSpringFacetType()) - } - - fun configureFileSet(fixture: CodeInsightTestFixture, configFiles: Collection): SpringFileSet { - return configureFileSet(fixture, "default", module!!, configFiles) - } - - fun configureFileSet(fixture: CodeInsightTestFixture, id: String, module: Module, configFiles: Collection): SpringFileSet { - return module.getSpringFacetWithAssertion().addFileSet(id, id).apply { - configFiles.forEach { addFile(fixture.copyFileToProject(it)) } - } - } - - fun Module.getSpringFacetWithAssertion() = SpringFacet.getInstance(this) ?: error("No Spring facet in ${this}") - - override fun tearDown() { - try { - // clear existing SpringFacet configuration before running next test - module?.let { module -> - SpringFacet.getInstance(module)?.let { facet -> - facet.removeFileSets() - FacetUtil.deleteFacet(facet) - } - ConfigLibraryUtil.removeLibrary(module, "spring") - } - } - finally { - module = null - } - } -} - -fun SpringTestFixtureExtension.loadConfigByMainFilePath(testPath: String, fixture: JavaCodeInsightTestFixture) { - val mainFileName = PathUtil.getFileName(testPath) - val baseName = FileUtil.getNameWithoutExtension(mainFileName) - val configFileName = if (baseName.endsWith("Xml")) "$baseName-config.xml" else mainFileName - configureFileSet(fixture, listOf(PathUtil.toSystemIndependentName("${PathUtil.getParentPath(testPath)}/$configFileName"))) -} - -fun configureSpringFileSetByDirective(module: Module, directives: String, psiFiles: Collection) { - if (!InTextDirectivesUtils.isDirectiveDefined(directives, "// CONFIGURE_SPRING_FILE_SET")) return - val fileSet = SpringFacet.getInstance(module)!!.addFileSet("default", "default")!! - psiFiles.forEach { fileSet.addFile(it.virtualFile) } -} \ No newline at end of file diff --git a/ultimate/tests/org/jetbrains/kotlin/idea/spring/tests/gutter/AbstractSpringClassAnnotatorTest.kt.172 b/ultimate/tests/org/jetbrains/kotlin/idea/spring/tests/gutter/AbstractSpringClassAnnotatorTest.kt.172 deleted file mode 100644 index 9f8c3b6e4bc..00000000000 --- a/ultimate/tests/org/jetbrains/kotlin/idea/spring/tests/gutter/AbstractSpringClassAnnotatorTest.kt.172 +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.jetbrains.kotlin.idea.spring.tests.gutter - -import com.google.gson.JsonArray -import com.google.gson.JsonObject -import com.google.gson.JsonParser -import com.intellij.codeInsight.daemon.LineMarkerProviders -import com.intellij.openapi.util.io.FileUtil -import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase -import icons.SpringApiIcons -import junit.framework.Assert -import junit.framework.AssertionFailedError -import org.jetbrains.kotlin.compatibility.projectDisposableEx -import org.jetbrains.kotlin.idea.KotlinLanguage -import org.jetbrains.kotlin.idea.jsonUtils.getString -import org.jetbrains.kotlin.idea.spring.lineMarking.KotlinSpringClassAnnotator -import org.jetbrains.kotlin.idea.spring.tests.SpringTestFixtureExtension -import org.jetbrains.kotlin.idea.test.ConfigLibraryUtil -import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase -import org.jetbrains.kotlin.idea.test.PluginTestCaseBase -import org.jetbrains.kotlin.idea.test.TestFixtureExtension -import org.jetbrains.kotlin.test.KotlinTestUtils -import java.io.File - -abstract class AbstractSpringClassAnnotatorTest : KotlinLightCodeInsightFixtureTestCase() { - override fun getProjectDescriptor() = LightCodeInsightFixtureTestCase.JAVA_LATEST - - override fun setUp() { - super.setUp() - TestFixtureExtension.loadFixture(myModule) - Assert.assertTrue("Kotlin-ultimate service was not found, make sure that " + - "is replaced in `plugin.xml` with data from `ultimate-plugin.xml`", - LineMarkerProviders.INSTANCE.allForLanguage(KotlinLanguage.INSTANCE).any { it is KotlinSpringClassAnnotator } - ) - } - - protected fun doTest(path: String) { - val configFilePath = "${KotlinTestUtils.getHomeDirectory()}/$path" - val configFile = File(configFilePath) - val testRoot = configFile.parentFile - - val config = JsonParser().parse(FileUtil.loadFile(configFile, true)) as JsonObject - - PluginTestCaseBase.addJdk(myFixture.projectDisposableEx, PluginTestCaseBase::mockJdk) - - val withRuntime = config["withRuntime"]?.asBoolean ?: false - if (withRuntime) { - ConfigLibraryUtil.configureKotlinRuntimeAndSdk(myModule, PluginTestCaseBase.mockJdk()) - } - - try { - val springConfigFiles = (config["springConfig"] as JsonArray).map { it.asString } - myFixture.testDataPath = testRoot.absolutePath - for (file in testRoot.listFiles()) { - val name = file.name - if (file.isDirectory) myFixture.copyDirectoryToProject(name, name) else myFixture.configureByFile(name) - } - TestFixtureExtension.getFixture()!!.configureFileSet(myFixture, springConfigFiles) - - val fileName = config.getString("file") - val iconName = config.getString("icon") - val icon = SpringApiIcons::class.java.getField(iconName)[null] - - val gutterMark = myFixture.findGutter(fileName)!!.let { - if (it.icon == icon) it - else myFixture.findGuttersAtCaret().let { gutters -> - gutters.firstOrNull() { it.icon == icon } - ?: throw AssertionFailedError("no $icon in gutters: ${gutters.map { it.icon }}") - } - } - - val tooltip = config.getString("tooltip") - Assert.assertEquals(tooltip, gutterMark.tooltipText) - - val naming = config.getString("naming") - val targets = (config["targets"] as JsonArray).map { it.asString } - when (naming) { - "bean" -> checkBeanGutterTargets(gutterMark, targets) - "property" -> checkBeanPropertyTargets(gutterMark, targets) - "generic" -> checkPsiElementGutterTargets(gutterMark, targets) - else -> error("Unexpected naming: $naming") - } - } - finally { - if (withRuntime) { - ConfigLibraryUtil.unConfigureKotlinRuntimeAndSdk(myModule, PluginTestCaseBase.mockJdk()) - } - } - } - - override fun tearDown() { - TestFixtureExtension.unloadFixture() - super.tearDown() - } -} diff --git a/ultimate/tests/org/jetbrains/kotlin/idea/spring/tests/inspections/AbstractSpringInspectionTest.kt.172 b/ultimate/tests/org/jetbrains/kotlin/idea/spring/tests/inspections/AbstractSpringInspectionTest.kt.172 deleted file mode 100644 index 2db33c7d35f..00000000000 --- a/ultimate/tests/org/jetbrains/kotlin/idea/spring/tests/inspections/AbstractSpringInspectionTest.kt.172 +++ /dev/null @@ -1,14 +0,0 @@ -package org.jetbrains.kotlin.idea.spring.tests.inspections - -import com.intellij.psi.PsiFile -import org.jetbrains.kotlin.idea.codeInsight.AbstractInspectionTest -import org.jetbrains.kotlin.idea.spring.tests.configureSpringFileSetByDirective - -abstract class AbstractSpringInspectionTest : AbstractInspectionTest() { - - override val forceUsePackageFolder: Boolean = true - - override fun configExtra(psiFiles: List, options: String) { - configureSpringFileSetByDirective(myFixture.module, options, psiFiles) - } -} \ No newline at end of file diff --git a/versions.gradle.kts.172 b/versions.gradle.kts.172 deleted file mode 100644 index 0d7ae442a94..00000000000 --- a/versions.gradle.kts.172 +++ /dev/null @@ -1,140 +0,0 @@ - -extra["versions.intellijSdk"] = "172.4343.14" -extra["versions.androidBuildTools"] = "r23.0.1" -extra["versions.idea.NodeJS"] = "172.3757.32" -//extra["versions.androidStudioRelease"] = "3.1.0.5" -//extra["versions.androidStudioBuild"] = "173.4506631" - -val gradleJars = listOf( - "gradle-api", - "gradle-tooling-api", - "gradle-base-services", - "gradle-wrapper", - "gradle-core", - "gradle-base-services-groovy" -) - -val androidStudioVersion = if (extra.has("versions.androidStudioRelease")) - extra["versions.androidStudioRelease"]?.toString()?.replace(".", "")?.substring(0, 2) -else - null - -val intellijVersion = rootProject.extra["versions.intellijSdk"] as String -val intellijVersionDelimiterIndex = intellijVersion.indexOfAny(charArrayOf('.', '-')) -if (intellijVersionDelimiterIndex == -1) { - error("Invalid IDEA version $intellijVersion") -} - -val platformBaseVersion = intellijVersion.substring(0, intellijVersionDelimiterIndex) -val platform = androidStudioVersion?.let { "AS$it" } ?: platformBaseVersion - -when (platform) { - "182" -> { - extra["versions.jar.guava"] = "23.6-jre" - extra["versions.jar.groovy-all"] = "2.4.12" - extra["versions.jar.lombok-ast"] = "0.2.3" - extra["versions.jar.swingx-core"] = "1.6.2-2" - extra["versions.jar.kxml2"] = "2.3.0" - extra["versions.jar.streamex"] = "0.6.5" - extra["versions.jar.gson"] = "2.8.4" - extra["versions.jar.oro"] = "2.0.8" - extra["versions.jar.picocontainer"] = "1.2" - for (jar in gradleJars) { - extra["versions.jar.$jar"] = "4.5.1" - } - - extra["ignore.jar.snappy-in-java"] = true - } - "181" -> { - extra["versions.jar.guava"] = "21.0" - extra["versions.jar.groovy-all"] = "2.4.12" - extra["versions.jar.lombok-ast"] = "0.2.3" - extra["versions.jar.swingx-core"] = "1.6.2-2" - extra["versions.jar.kxml2"] = "2.3.0" - extra["versions.jar.streamex"] = "0.6.5" - extra["versions.jar.gson"] = "2.8.2" - extra["versions.jar.oro"] = "2.0.8" - extra["versions.jar.snappy-in-java"] = "0.5.1" - for (jar in gradleJars) { - extra["versions.jar.$jar"] = "4.4" - } - } - "173" -> { - extra["versions.jar.guava"] = "21.0" - extra["versions.jar.groovy-all"] = "2.4.12" - extra["versions.jar.lombok-ast"] = "0.2.3" - extra["versions.jar.swingx-core"] = "1.6.2" - extra["versions.jar.kxml2"] = "2.3.0" - extra["versions.jar.streamex"] = "0.6.5" - extra["versions.jar.gson"] = "2.8.2" - extra["versions.jar.snappy-in-java"] = "0.5.1" - for (jar in gradleJars) { - extra["versions.jar.$jar"] = "4.0" - } - extra["ignore.jar.lombok-ast-0.2.3"] = true - } - "172" -> { - extra["versions.jar.guava"] = "21.0" - extra["versions.jar.groovy-all"] = "2.4.6" - extra["versions.jar.lombok-ast"] = "0.2.3" - extra["versions.jar.swingx-core"] = "1.6.2" - extra["versions.jar.kxml2"] = "2.3.0" - extra["versions.jar.streamex"] = "0.6.2" - extra["versions.jar.gson"] = "2.5" - extra["versions.jar.snappy-in-java"] = "0.5.1" - for (jar in gradleJars) { - extra["versions.jar.$jar"] = "3.5" - } - } - "AS31" -> { - extra["versions.jar.guava"] = "21.0" - extra["versions.jar.groovy-all"] = "2.4.12" - extra["versions.jar.swingx-core"] = "1.6.2" - extra["versions.jar.kxml2"] = "2.3.0" - extra["versions.jar.streamex"] = "0.6.5" - extra["versions.jar.gson"] = "2.8.2" - extra["versions.jar.snappy-in-java"] = "0.5.1" - for (jar in gradleJars) { - extra["versions.jar.$jar"] = "4.0" - } - - extra["ignore.jar.common"] = true - extra["ignore.jar.lombok-ast"] = true - } - "AS32" -> { - extra["versions.jar.guava"] = "21.0" - extra["versions.jar.groovy-all"] = "2.4.12" - extra["versions.jar.swingx-core"] = "1.6.2" - extra["versions.jar.kxml2"] = "2.3.0" - extra["versions.jar.streamex"] = "0.6.5" - extra["versions.jar.gson"] = "2.8.2" - extra["versions.jar.oro"] = "2.0.8" - extra["versions.jar.snappy-in-java"] = "0.5.1" - for (jar in gradleJars) { - extra["versions.jar.$jar"] = "4.4" - } - - extra["ignore.jar.common"] = true - extra["ignore.jar.lombok-ast"] = true - } - "AS33" -> { - extra["versions.jar.guava"] = "21.0" - extra["versions.jar.groovy-all"] = "2.4.12" - extra["versions.jar.swingx-core"] = "1.6.2" - extra["versions.jar.kxml2"] = "2.3.0" - extra["versions.jar.streamex"] = "0.6.5" - extra["versions.jar.gson"] = "2.8.2" - extra["versions.jar.oro"] = "2.0.8" - extra["versions.jar.snappy-in-java"] = "0.5.1" - for (jar in gradleJars) { - extra["versions.jar.$jar"] = "4.4" - } - - extra["ignore.jar.common"] = true - extra["ignore.jar.lombok-ast"] = true - } -} - -if (!extra.has("versions.androidStudioRelease")) { - extra["ignore.jar.android-base-common"] = true -}