Build: Drop IntelliJ 2018.3 and Android Studio 3.4 support

Delete *.183 and *.as34 bunch-files
This commit is contained in:
Michael Kuzmin
2019-12-18 20:29:48 +03:00
parent ae0efa77e3
commit 254dc8f71c
132 changed files with 0 additions and 11036 deletions
-8
View File
@@ -1,8 +0,0 @@
org.gradle.jvmargs=-Duser.country=US -Dkotlin.daemon.jvm.options=-Xmx1600m -Dfile.encoding=UTF-8
cacheRedirectorEnabled=true
#buildSrc.kotlin.repo=https://jcenter.bintray.com
#buildSrc.kotlin.version=1.1.50
intellijUltimateEnabled=false
@@ -1,57 +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.cli.jvm.compiler
import com.intellij.codeInsight.ExternalAnnotationsManager
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.*
class MockExternalAnnotationsManager : ExternalAnnotationsManager() {
override fun chooseAnnotationsPlace(element: PsiElement): AnnotationPlace? = null
override fun isExternalAnnotationWritable(listOwner: PsiModifierListOwner, annotationFQN: String): Boolean = false
override fun isExternalAnnotation(annotation: PsiAnnotation): Boolean = false
override fun findExternalAnnotationsFiles(listOwner: PsiModifierListOwner): List<PsiFile>? = null
override fun findExternalAnnotation(listOwner: PsiModifierListOwner, annotationFQN: String): PsiAnnotation? = null
override fun findExternalAnnotations(listOwner: PsiModifierListOwner): Array<out PsiAnnotation>? = null
override fun annotateExternally(
listOwner: PsiModifierListOwner,
annotationFQName: String,
fromFile: PsiFile,
value: Array<out PsiNameValuePair>?
) {
throw UnsupportedOperationException("not implemented")
}
override fun deannotate(listOwner: PsiModifierListOwner, annotationFQN: String): Boolean {
throw UnsupportedOperationException("not implemented")
}
override fun editExternalAnnotation(
listOwner: PsiModifierListOwner,
annotationFQN: String,
value: Array<out PsiNameValuePair>?
): Boolean {
throw UnsupportedOperationException("not implemented")
}
override fun hasAnnotationRootsForFile(file: VirtualFile): Boolean {
throw UnsupportedOperationException("not implemented")
}
}
-272
View File
@@ -1,272 +0,0 @@
-injars '<kotlin-compiler-jar-before-shrink>'(
!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 '<kotlin-compiler-jar>'
-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 org.jetbrains.annotations.ReadOnly
-dontwarn org.jetbrains.annotations.Mutable
-dontwarn com.intellij.util.io.TarUtil
-dontwarn com.intellij.util.io.Compressor$Tar
-dontwarn org.slf4j.**
# Annotations from intellijCore/annotations.jar that not presented in org.jetbrains.annotations
-dontwarn org.jetbrains.annotations.Async*
-dontwarn org.jetbrains.annotations.Nls$Capitalization
# Nullability annotations used in Guava
-dontwarn org.checkerframework.checker.nullness.compatqual.NullableDecl
-dontwarn org.checkerframework.checker.nullness.compatqual.MonotonicNonNullDecl
-dontwarn org.checkerframework.checker.nullness.qual.Nullable
-dontwarn org.checkerframework.checker.nullness.qual.MonotonicNonNull
# Depends on apache batick which has lots of dependencies
-dontwarn com.intellij.util.SVGLoader*
-dontwarn org.apache.batik.script.rhino.RhinoInterpreter
-dontwarn org.apache.batik.script.rhino.RhinoInterpreterFactory
# The appropriate jar is either loaded separately or added explicitly to the classpath then needed
-dontwarn org.jetbrains.kotlin.scripting.compiler.plugin.ScriptingCompilerConfigurationComponentRegistrar
-dontwarn org.jdom.xpath.jaxen.*
-dontwarn com.intellij.util.io.Decompressor*
-dontwarn org.w3c.dom.Location
-dontwarn org.w3c.dom.Window
#-libraryjars '<rtjar>'
#-libraryjars '<jssejar>'
#-libraryjars '<bootstrap.runtime>'
#-libraryjars '<bootstrap.reflect>'
#-libraryjars '<bootstrap.script.runtime>'
#-libraryjars '<tools.jar>'
-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.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(...); }
# Without this class PluginManagerCore.loadDescriptorFromJar fails
-keep class org.jdom.output.XMLOutputter { *; }
# 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();
}
-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.tree.InsnList { *; }
-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 { *; }
-keepclassmembers class com.intellij.util.PathUtil {
public static java.lang.String getJarPathForClass(java.lang.Class);
}
-keepclassmembers class com.intellij.util.PathUtil {
public static java.lang.String getJarPathForClass(java.lang.Class);
}
# remove when KT-18563 would be fixed
-keep class org.jetbrains.kotlin.psi.psiUtil.PsiUtilsKt { *; }
-keep class net.jpountz.lz4.* { *; }
# used in LazyScriptDescriptor
-keep class org.jetbrains.kotlin.utils.addToStdlib.AddToStdlibKt { *; }
-keep class com.intellij.openapi.vfs.impl.jar.CoreJarFileSystem { *; }
# used in REPL
# TODO: pack jline directly to scripting-compiler jars instead
-keep class org.jline.reader.LineReaderBuilder { *; }
-keep class org.jline.reader.LineReader { *; }
-keep class org.jline.reader.History { *; }
-keep class org.jline.reader.EndOfFileException { *; }
-keep class org.jline.reader.UserInterruptException { *; }
-keep class org.jline.terminal.impl.jna.JnaSupportImpl { *; }
-keep class org.jline.terminal.impl.jansi.JansiSupportImpl { *; }
-keepclassmembers class * implements java.io.Serializable {
static final long serialVersionUID;
}
-272
View File
@@ -1,272 +0,0 @@
-injars '<kotlin-compiler-jar-before-shrink>'(
!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 '<kotlin-compiler-jar>'
-dontnote **
-dontwarn com.intellij.util.ui.IsRetina*
-dontwarn com.intellij.util.ui.UIUtilities
-dontwarn com.intellij.util.RetinaImage*
-dontwarn apple.awt.*
-dontwarn dk.brics.automaton.*
-dontwarn org.fusesource.**
-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 org.jetbrains.annotations.ReadOnly
-dontwarn org.jetbrains.annotations.Mutable
-dontwarn com.intellij.util.io.TarUtil
-dontwarn com.intellij.util.io.Compressor$Tar
-dontwarn org.slf4j.**
# Annotations from intellijCore/annotations.jar that not presented in org.jetbrains.annotations
-dontwarn org.jetbrains.annotations.Async*
-dontwarn org.jetbrains.annotations.Nls$Capitalization
# Nullability annotations used in Guava
-dontwarn org.checkerframework.checker.nullness.compatqual.NullableDecl
-dontwarn org.checkerframework.checker.nullness.compatqual.MonotonicNonNullDecl
-dontwarn org.checkerframework.checker.nullness.qual.Nullable
-dontwarn org.checkerframework.checker.nullness.qual.MonotonicNonNull
# Depends on apache batick which has lots of dependencies
-dontwarn com.intellij.util.SVGLoader*
-dontwarn org.apache.batik.script.rhino.RhinoInterpreter
-dontwarn org.apache.batik.script.rhino.RhinoInterpreterFactory
# The appropriate jar is either loaded separately or added explicitly to the classpath then needed
-dontwarn org.jetbrains.kotlin.scripting.compiler.plugin.ScriptingCompilerConfigurationComponentRegistrar
-dontwarn org.jdom.xpath.jaxen.*
-dontwarn com.intellij.util.io.Decompressor*
-dontwarn org.w3c.dom.Location
-dontwarn org.w3c.dom.Window
#-libraryjars '<rtjar>'
#-libraryjars '<jssejar>'
#-libraryjars '<bootstrap.runtime>'
#-libraryjars '<bootstrap.reflect>'
#-libraryjars '<bootstrap.script.runtime>'
#-libraryjars '<tools.jar>'
-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.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(...); }
# Without this class PluginManagerCore.loadDescriptorFromJar fails
-keep class org.jdom.output.XMLOutputter { *; }
# 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();
}
-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 { *; }
-keepclassmembers class com.intellij.util.PathUtil {
public static java.lang.String getJarPathForClass(java.lang.Class);
}
-keepclassmembers class com.intellij.util.PathUtil {
public static java.lang.String getJarPathForClass(java.lang.Class);
}
# remove when KT-18563 would be fixed
-keep class org.jetbrains.kotlin.psi.psiUtil.PsiUtilsKt { *; }
-keep class net.jpountz.lz4.* { *; }
# used in LazyScriptDescriptor
-keep class org.jetbrains.kotlin.utils.addToStdlib.AddToStdlibKt { *; }
-keep class com.intellij.openapi.vfs.impl.jar.CoreJarFileSystem { *; }
# used in REPL
# TODO: pack jline directly to scripting-compiler jars instead
-keep class org.jline.reader.LineReaderBuilder { *; }
-keep class org.jline.reader.LineReader { *; }
-keep class org.jline.reader.History { *; }
-keep class org.jline.reader.EndOfFileException { *; }
-keep class org.jline.reader.UserInterruptException { *; }
-keep class org.jline.terminal.impl.jna.JnaSupportImpl { *; }
-keep class org.jline.terminal.impl.jansi.JansiSupportImpl { *; }
-keepclassmembers class * implements java.io.Serializable {
static final long serialVersionUID;
}
@@ -1,284 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.fir.java
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Pair
import com.intellij.psi.*
import com.intellij.psi.impl.cache.ModifierFlags
import com.intellij.psi.impl.compiled.ClsClassImpl
import com.intellij.psi.impl.compiled.ClsFileImpl
import com.intellij.psi.impl.file.PsiPackageImpl
import com.intellij.psi.impl.java.stubs.*
import com.intellij.psi.impl.java.stubs.impl.*
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.stubs.StubElement
import com.intellij.util.ArrayUtil
import org.jetbrains.kotlin.builtins.jvm.JavaToKotlinClassMap
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.descriptors.Visibilities
import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.declarations.*
import org.jetbrains.kotlin.fir.psi
import org.jetbrains.kotlin.fir.resolve.firProvider
import org.jetbrains.kotlin.fir.resolve.fullyExpandedType
import org.jetbrains.kotlin.fir.resolve.toSymbol
import org.jetbrains.kotlin.fir.resolve.transformers.resolveSupertypesInTheAir
import org.jetbrains.kotlin.fir.symbols.StandardClassIds
import org.jetbrains.kotlin.fir.symbols.impl.FirClassSymbol
import org.jetbrains.kotlin.fir.types.*
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.jvm.JvmPrimitiveType
import org.jetbrains.kotlin.resolve.jvm.KotlinFinderMarker
class FirJavaElementFinder(
private val session: FirSession,
project: Project
) : PsiElementFinder(), KotlinFinderMarker {
private val psiManager = PsiManager.getInstance(project)
private val firProvider = session.firProvider
override fun findPackage(qualifiedName: String): PsiPackage? {
if (firProvider.getClassNamesInPackage(FqName(qualifiedName)).isEmpty()) return null
return PsiPackageImpl(psiManager, qualifiedName)
}
override fun getClasses(psiPackage: PsiPackage, scope: GlobalSearchScope): Array<PsiClass> {
return firProvider
.getClassNamesInPackage(FqName(psiPackage.qualifiedName))
.mapNotNull { findClass(psiPackage.qualifiedName + "." + it.identifier, scope) }
.toTypedArray()
}
override fun findClasses(qualifiedName: String, scope: GlobalSearchScope): Array<PsiClass> {
return findClass(qualifiedName, scope)?.let(::arrayOf) ?: emptyArray()
}
override fun findClass(qualifiedName: String, scope: GlobalSearchScope): PsiClass? {
if (qualifiedName.endsWith(".")) return null
val classId = ClassId.topLevel(FqName(qualifiedName))
val firClass =
firProvider.getFirClassifierByFqName(classId) as? FirRegularClass
?: return null
val ktFile = firClass.psi?.containingFile as? KtFile ?: return null
val fileStub = createJavaFileStub(classId.packageFqName, listOf(ktFile))
return buildStub(firClass, fileStub).psi
}
private fun buildStub(firClass: FirRegularClass, parent: StubElement<*>): PsiClassStub<*> {
val classId = firClass.classId
val stub = PsiClassStubImpl<ClsClassImpl>(
JavaStubElementTypes.CLASS, parent, classId.asSingleFqName().asString(), firClass.name.identifier, null,
PsiClassStubImpl.packFlags(
false,
firClass.classKind == ClassKind.INTERFACE,
firClass.classKind == ClassKind.ENUM_CLASS, false, false,
firClass.classKind == ClassKind.ANNOTATION_CLASS, false, false,
false, false
)
)
PsiModifierListStubImpl(stub, firClass.packFlags())
newTypeParameterList(
stub,
firClass.typeParameters.map { Pair(it.name.asString(), arrayOf(CommonClassNames.JAVA_LANG_OBJECT)) }
)
val superTypeRefs = when {
firClass.resolvePhase > FirResolvePhase.SUPER_TYPES -> firClass.superTypeRefs
else -> firClass.resolveSupertypesInTheAir(session)
}
stub.addSupertypesReferencesLists(firClass, superTypeRefs, session)
for (nestedClass in firClass.declarations.filterIsInstance<FirRegularClass>()) {
buildStub(nestedClass, stub)
}
return stub
}
}
private fun FirRegularClass.packFlags(): Int {
var flags = when (visibility) {
Visibilities.PRIVATE -> ModifierFlags.PRIVATE_MASK
Visibilities.PROTECTED -> ModifierFlags.PROTECTED_MASK
Visibilities.PUBLIC -> ModifierFlags.PUBLIC_MASK
else -> ModifierFlags.PACKAGE_LOCAL_MASK
}
flags = flags or when (modality) {
Modality.FINAL -> ModifierFlags.FINAL_MASK
Modality.ABSTRACT -> ModifierFlags.ABSTRACT_MASK
else -> 0
}
if (classId.isNestedClass && !isInner) {
flags = flags or ModifierFlags.STATIC_MASK
}
return flags
}
private fun PsiClassStubImpl<*>.addSupertypesReferencesLists(
firRegularClass: FirRegularClass,
superTypeRefs: List<FirTypeRef>,
session: FirSession
) {
require(superTypeRefs.all { it is FirResolvedTypeRef }) {
"Supertypes for light class $qualifiedName are being added too early"
}
val isInterface = firRegularClass.classKind == ClassKind.INTERFACE
val interfaceNames = mutableListOf<String>()
var superName: String? = null
for (superTypeRef in superTypeRefs) {
val superConeType = superTypeRef.coneTypeSafe<ConeClassLikeType>() ?: continue
val supertypeFirClass = superConeType.toFirClass(session) ?: continue
val canonicalString = superConeType.mapToCanonicalString(session)
if (isInterface || supertypeFirClass.classKind == ClassKind.INTERFACE) {
interfaceNames.add(canonicalString)
} else {
superName = canonicalString
}
}
if (this.isInterface) {
if (interfaceNames.isNotEmpty() && this.isAnnotationType) {
interfaceNames.remove(CommonClassNames.JAVA_LANG_ANNOTATION_ANNOTATION)
}
newReferenceList(JavaStubElementTypes.EXTENDS_LIST, this, ArrayUtil.toStringArray(interfaceNames))
newReferenceList(JavaStubElementTypes.IMPLEMENTS_LIST, this, ArrayUtil.EMPTY_STRING_ARRAY)
} else {
if (superName == null || "java/lang/Object" == superName || this.isEnum && "java/lang/Enum" == superName) {
newReferenceList(JavaStubElementTypes.EXTENDS_LIST, this, ArrayUtil.EMPTY_STRING_ARRAY)
} else {
newReferenceList(JavaStubElementTypes.EXTENDS_LIST, this, arrayOf(superName))
}
newReferenceList(JavaStubElementTypes.IMPLEMENTS_LIST, this, ArrayUtil.toStringArray(interfaceNames))
}
}
private fun newReferenceList(type: JavaClassReferenceListElementType, parent: StubElement<*>, types: Array<String>) {
PsiClassReferenceListStubImpl(type, parent, types)
}
private fun newTypeParameterList(parent: StubElement<*>, parameters: List<Pair<String, Array<String>>>) {
val listStub = PsiTypeParameterListStubImpl(parent)
for (parameter in parameters) {
val parameterStub = PsiTypeParameterStubImpl(listStub, parameter.first)
newReferenceList(JavaStubElementTypes.EXTENDS_BOUND_LIST, parameterStub, parameter.second)
}
}
private fun createJavaFileStub(packageFqName: FqName, files: Collection<KtFile>): PsiJavaFileStub {
val javaFileStub = PsiJavaFileStubImpl(packageFqName.asString(), /*compiled = */true)
javaFileStub.psiFactory = ClsStubPsiFactory.INSTANCE
val fakeFile = object : ClsFileImpl(files.first().viewProvider) {
override fun getStub() = javaFileStub
override fun getPackageName() = packageFqName.asString()
override fun isPhysical() = false
override fun getText(): String {
return files.singleOrNull()?.text ?: super.getText()
}
}
javaFileStub.psi = fakeFile
return javaFileStub
}
private fun ConeClassLikeType.toFirClass(session: FirSession): FirRegularClass? {
val expandedType = this.fullyExpandedType(session)
return (expandedType.lookupTag.toSymbol(session) as? FirClassSymbol)?.fir as? FirRegularClass
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
// JVM TYPE MAPPING
// TODO: reuse other type mapping implementations when possible
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
private const val ERROR_TYPE_STUB = CommonClassNames.JAVA_LANG_OBJECT
private fun ConeKotlinType.mapToCanonicalString(session: FirSession): String {
return when (this) {
is ConeClassLikeType -> mapToCanonicalString(session)
is ConeTypeVariableType, is ConeFlexibleType, is ConeCapturedType,
is ConeDefinitelyNotNullType, is ConeIntersectionType, is ConeStubType, is ConeIntegerLiteralType ->
error("Unexpected type: $this [${this::class}]")
is ConeLookupTagBasedType -> lookupTag.name.asString()
}
}
private fun ConeClassLikeType.mapToCanonicalString(session: FirSession): String {
return when (this) {
is ConeClassErrorType -> ERROR_TYPE_STUB
else -> fullyExpandedType(session).mapToCanonicalNoExpansionString(session)
}
}
private fun ConeClassLikeType.mapToCanonicalNoExpansionString(session: FirSession): String {
if (lookupTag.classId == StandardClassIds.Array) {
return when (val typeProjection = typeArguments[0]) {
is ConeStarProjection -> CommonClassNames.JAVA_LANG_OBJECT
is ConeTypedProjection -> {
if (typeProjection.kind == ProjectionKind.IN)
CommonClassNames.JAVA_LANG_VOID
else
(typeProjection.type as ConeClassLikeType).mapToCanonicalString(session)
}
else -> ERROR_TYPE_STUB
} + "[]"
}
val context = ConeTypeCheckerContext(isErrorTypeEqualsToAnything = false, isStubTypeEqualsToAnything = true, session = session)
with(context) {
val typeConstructor = typeConstructor()
typeConstructor.getPrimitiveType()?.let { return JvmPrimitiveType.get(it).wrapperFqName.asString() }
typeConstructor.getPrimitiveArrayType()?.let { return JvmPrimitiveType.get(it).javaKeywordName + "[]" }
val kotlinClassFqName = typeConstructor.getClassFqNameUnsafe() ?: return ERROR_TYPE_STUB
val mapped = JavaToKotlinClassMap.mapKotlinToJava(kotlinClassFqName)?.asSingleFqName() ?: kotlinClassFqName
return mapped.toString() +
typeArguments.takeIf { it.isNotEmpty() }
?.joinToString(separator = ", ", prefix = "<", postfix = ">") { it.mapToCanonicalString(session) }
.orEmpty()
}
}
private fun ConeKotlinTypeProjection.mapToCanonicalString(session: FirSession): String {
return when (this) {
is ConeStarProjection -> "?"
is ConeTypedProjection -> {
val wildcard = when (kind) {
ProjectionKind.STAR -> error("Should be handled in the case above")
ProjectionKind.IN -> "? super "
ProjectionKind.OUT -> "? extends "
ProjectionKind.INVARIANT -> ""
}
wildcard + type.mapToCanonicalString(session)
}
else -> ERROR_TYPE_STUB
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-23
View File
@@ -1,23 +0,0 @@
org.gradle.jvmargs=-Duser.country=US -Dkotlin.daemon.jvm.options=-Xmx1600m -Dfile.encoding=UTF-8
cacheRedirectorEnabled=true
kotlin.compiler.effectSystemEnabled=true
kotlin.compiler.newInferenceEnabled=true
#maven.repository.mirror=http://repository.jetbrains.com/remote-repos/
#bootstrap.kotlin.repo=https://dl.bintray.com/kotlin/kotlin-dev
#bootstrap.kotlin.version=1.1.50-dev-1451
#signingRequired=true
intellijUltimateEnabled=false
## The following properties can be added to your local.properties file to customize the build:
#jpsBuild=true
#cidrPluginsEnabled=true
## Used for compare gradle and jps build
#kotlin.build.postprocessing=false
#kotlin.build.java9=false
#kotlin.build.useBootstrapStdlib=true
-15
View File
@@ -1,15 +0,0 @@
versions.intellijSdk=183.6156.11
versions.androidBuildTools=r23.0.1
versions.idea.NodeJS=181.3494.12
versions.jar.guava=25.1-jre
versions.jar.groovy-all=2.4.15
versions.jar.lombok-ast=0.2.3
versions.jar.swingx-core=1.6.2-2
versions.jar.kxml2=2.3.0
versions.jar.streamex=0.6.7
versions.jar.gson=2.8.5
versions.jar.oro=2.0.8
versions.jar.picocontainer=1.2
versions.jar.asm-all=7.0
ignore.jar.snappy-in-java=true
versions.gradle-api=4.5.1
-19
View File
@@ -1,19 +0,0 @@
versions.intellijSdk=183.4284.36
versions.androidBuildTools=r23.0.1
versions.idea.NodeJS=181.3494.12
versions.androidStudioRelease=3.4.0.4
versions.androidStudioBuild=183.5141831
versions.jar.guava=25.1-jre
versions.jar.groovy-all=2.4.15
versions.jar.lombok-ast=0.2.3
versions.jar.swingx-core=1.6.2-2
versions.jar.kxml2=2.3.0
versions.jar.streamex=0.6.7
versions.jar.gson=2.8.5
versions.jar.oro=2.0.8
versions.jar.picocontainer=1.2
ignore.jar.snappy-in-java=true
ignore.jar.common=true
ignore.jar.lombok-ast=true
versions.jar.asm-all=7.0
versions.gradle-api=4.5.1
@@ -1,17 +0,0 @@
package org.jetbrains.kotlin.idea.caches.project
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
// NO-OP implementation, full implementation only for AS3.3, AS3.4
fun collectModuleInfoByUserData(
project: Project,
virtualFile: VirtualFile
): List<IdeaModuleInfo> = emptyList()
fun collectModuleInfoByUserData(
psiElement: PsiElement
): List<IdeaModuleInfo> = emptyList()
@@ -1,90 +0,0 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.caches.project
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.LIBRARY_KEY
import org.jetbrains.kotlin.idea.MODULE_ROOT_TYPE_KEY
import org.jetbrains.kotlin.idea.SDK_KEY
import org.jetbrains.kotlin.idea.caches.project.UserDataModuleContainer.ForPsiElement
import org.jetbrains.kotlin.idea.caches.project.UserDataModuleContainer.ForVirtualFile
import org.jetbrains.kotlin.idea.core.getSourceType
import org.jetbrains.kotlin.utils.addIfNotNull
// This file declares non-exported API for overriding module info with user-data
private sealed class UserDataModuleContainer {
abstract fun <T> getUserData(key: Key<T>): T?
abstract fun getModule(): Module?
data class ForVirtualFile(val virtualFile: VirtualFile, val project: Project) : UserDataModuleContainer() {
override fun <T> getUserData(key: Key<T>): T? = virtualFile.getUserData(key)
override fun getModule(): Module? = ModuleUtilCore.findModuleForFile(virtualFile, project)
}
data class ForPsiElement(val psiElement: PsiElement) : UserDataModuleContainer() {
override fun <T> getUserData(key: Key<T>): T? {
return psiElement.getUserData(key)
?: psiElement.containingFile?.getUserData(key)
?: psiElement.containingFile?.originalFile?.virtualFile?.getUserData(key)
}
override fun getModule(): Module? = ModuleUtilCore.findModuleForPsiElement(psiElement)
}
}
private fun collectModuleInfoByUserData(
project: Project,
container: UserDataModuleContainer
): List<IdeaModuleInfo> {
fun forModule(): ModuleSourceInfo? {
val rootType = container.getUserData(MODULE_ROOT_TYPE_KEY) ?: return null
val module = container.getModule() ?: return null
return when (rootType.getSourceType()) {
null -> null
SourceType.PRODUCTION -> module.productionSourceInfo()
SourceType.TEST -> module.testSourceInfo()
}
}
val result = mutableListOf<IdeaModuleInfo>()
result.addIfNotNull(forModule())
val library = container.getUserData(LIBRARY_KEY)
if (library != null) {
result.addAll(createLibraryInfo(project, library))
}
val sdk = container.getUserData(SDK_KEY)
if (sdk != null) {
result.add(SdkInfo(project, sdk))
}
return result
}
fun collectModuleInfoByUserData(
project: Project,
virtualFile: VirtualFile
): List<IdeaModuleInfo> = collectModuleInfoByUserData(project, ForVirtualFile(virtualFile, project))
fun collectModuleInfoByUserData(
psiElement: PsiElement
): List<IdeaModuleInfo> = collectModuleInfoByUserData(psiElement.project, ForPsiElement(psiElement))
@@ -1,34 +0,0 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.util.Key
import org.jetbrains.jps.model.module.JpsModuleSourceRootType
// WARNING, this API is used by AS3.3+
const val LIBRARY_KEY_NAME = "Kt_Library"
const val SDK_KEY_NAME = "Kt_Sdk"
const val MODULE_ROOT_TYPE_KEY_NAME = "Kt_SourceRootType"
@JvmField
val MODULE_ROOT_TYPE_KEY = getOrCreateKey<JpsModuleSourceRootType<*>>(MODULE_ROOT_TYPE_KEY_NAME)
@JvmField
val SDK_KEY = getOrCreateKey<Sdk>(SDK_KEY_NAME)
@JvmField
val LIBRARY_KEY = getOrCreateKey<Library>(LIBRARY_KEY_NAME)
inline fun <reified T> getOrCreateKey(name: String): Key<T> {
@Suppress("DEPRECATION", "UNCHECKED_CAST")
val existingKey = Key.findKeyByName(name) as Key<T>?
return existingKey ?: Key.create<T>(name)
}
@@ -1,114 +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.completion
import com.intellij.codeInsight.lookup.Lookup
import com.intellij.codeInsight.lookup.LookupEvent
import com.intellij.codeInsight.lookup.LookupListener
import com.intellij.codeInsight.lookup.LookupManager
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.ProjectComponent
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.RangeMarker
import com.intellij.openapi.editor.event.CaretEvent
import com.intellij.openapi.editor.event.CaretListener
import com.intellij.openapi.editor.event.EditorFactoryEvent
import com.intellij.openapi.editor.event.EditorFactoryListener
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
class LookupCancelWatcher(val project: Project) : ProjectComponent {
private class Reminiscence(editor: Editor, offset: Int) {
var editor: Editor? = editor
private var marker: RangeMarker? = editor.document.createRangeMarker(offset, offset)
// forget about auto-popup cancellation when the caret is moved to the start or before it
private var editorListener: CaretListener? = object : CaretListener {
override fun caretPositionChanged(e: CaretEvent) {
if (!marker!!.isValid || editor.logicalPositionToOffset(e.newPosition) <= offset) {
dispose()
}
}
}
init {
ApplicationManager.getApplication()!!.assertIsDispatchThread()
editor.caretModel.addCaretListener(editorListener!!)
}
fun matches(editor: Editor, offset: Int): Boolean {
return editor == this.editor && marker?.startOffset == offset
}
fun dispose() {
ApplicationManager.getApplication()!!.assertIsDispatchThread()
if (marker != null) {
editor!!.caretModel.removeCaretListener(editorListener!!)
marker = null
editor = null
editorListener = null
}
}
}
private var lastReminiscence: Reminiscence? = null
companion object {
fun getInstance(project: Project): LookupCancelWatcher = project.getComponent(LookupCancelWatcher::class.java)!!
val AUTO_POPUP_AT = Key<Int>("LookupCancelWatcher.AUTO_POPUP_AT")
}
fun wasAutoPopupRecentlyCancelled(editor: Editor, offset: Int): Boolean {
return lastReminiscence?.matches(editor, offset) ?: false
}
private val lookupCancelListener = object : LookupListener {
override fun lookupCanceled(event: LookupEvent) {
val lookup = event.lookup
if (event.isCanceledExplicitly && lookup.isCompletion) {
val offset = lookup.currentItem?.getUserData(AUTO_POPUP_AT)
if (offset != null) {
lastReminiscence?.dispose()
if (offset <= lookup.editor.document.textLength) {
lastReminiscence = Reminiscence(lookup.editor, offset)
}
}
}
}
}
override fun initComponent() {
EditorFactory.getInstance().addEditorFactoryListener(
object : EditorFactoryListener {
override fun editorReleased(event: EditorFactoryEvent) {
if (lastReminiscence?.editor == event.editor) {
lastReminiscence!!.dispose()
}
}
},
project
)
LookupManager.getInstance(project).addPropertyChangeListener { event ->
if (event.propertyName == LookupManager.PROP_ACTIVE_LOOKUP) {
(event.newValue as Lookup?)?.addLookupListener(lookupCancelListener)
}
}
}
}
@@ -1,114 +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.completion
import com.intellij.codeInsight.lookup.Lookup
import com.intellij.codeInsight.lookup.LookupEvent
import com.intellij.codeInsight.lookup.LookupListener
import com.intellij.codeInsight.lookup.LookupManager
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.ProjectComponent
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.RangeMarker
import com.intellij.openapi.editor.event.CaretEvent
import com.intellij.openapi.editor.event.CaretListener
import com.intellij.openapi.editor.event.EditorFactoryEvent
import com.intellij.openapi.editor.event.EditorFactoryListener
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
class LookupCancelWatcher(val project: Project) : ProjectComponent {
private class Reminiscence(editor: Editor, offset: Int) {
var editor: Editor? = editor
private var marker: RangeMarker? = editor.document.createRangeMarker(offset, offset)
// forget about auto-popup cancellation when the caret is moved to the start or before it
private var editorListener: CaretListener? = object : CaretListener {
override fun caretPositionChanged(e: CaretEvent) {
if (!marker!!.isValid || editor.logicalPositionToOffset(e.newPosition) <= offset) {
dispose()
}
}
}
init {
ApplicationManager.getApplication()!!.assertIsDispatchThread()
editor.caretModel.addCaretListener(editorListener!!)
}
fun matches(editor: Editor, offset: Int): Boolean {
return editor == this.editor && marker?.startOffset == offset
}
fun dispose() {
ApplicationManager.getApplication()!!.assertIsDispatchThread()
if (marker != null) {
editor!!.caretModel.removeCaretListener(editorListener!!)
marker = null
editor = null
editorListener = null
}
}
}
private var lastReminiscence: Reminiscence? = null
companion object {
fun getInstance(project: Project): LookupCancelWatcher = project.getComponent(LookupCancelWatcher::class.java)!!
val AUTO_POPUP_AT = Key<Int>("LookupCancelWatcher.AUTO_POPUP_AT")
}
fun wasAutoPopupRecentlyCancelled(editor: Editor, offset: Int): Boolean {
return lastReminiscence?.matches(editor, offset) ?: false
}
private val lookupCancelListener = object : LookupListener {
override fun lookupCanceled(event: LookupEvent) {
val lookup = event.lookup
if (event.isCanceledExplicitly && lookup.isCompletion) {
val offset = lookup.currentItem?.getUserData(AUTO_POPUP_AT)
if (offset != null) {
lastReminiscence?.dispose()
if (offset <= lookup.editor.document.textLength) {
lastReminiscence = Reminiscence(lookup.editor, offset)
}
}
}
}
}
override fun initComponent() {
EditorFactory.getInstance().addEditorFactoryListener(
object : EditorFactoryListener {
override fun editorReleased(event: EditorFactoryEvent) {
if (lastReminiscence?.editor == event.editor) {
lastReminiscence!!.dispose()
}
}
},
project
)
LookupManager.getInstance(project).addPropertyChangeListener { event ->
if (event.propertyName == LookupManager.PROP_ACTIVE_LOOKUP) {
(event.newValue as Lookup?)?.addLookupListener(lookupCancelListener)
}
}
}
}
@@ -1,3 +0,0 @@
class IDESettingsFUSCollector {
// Not whitelisted
}
@@ -1,3 +0,0 @@
class IDESettingsFUSCollector {
// Not whitelisted
}
@@ -1,18 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.statistics
open class KotlinFUSLogger {
companion object {
fun log(group: FUSEventGroups, event: String) {
// Not whitelisted for 183
}
fun log(group: FUSEventGroups, event: String, eventData: Map<String, String>) {
// Not whitelisted for 183
}
}
}
@@ -1,18 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.statistics
open class KotlinFUSLogger {
companion object {
fun log(group: FUSEventGroups, event: String) {
// Not whitelisted for AS
}
fun log(group: FUSEventGroups, event: String, eventData: Map<String, String>) {
// Not whitelisted for AS
}
}
}
@@ -1,3 +0,0 @@
class ProjectConfigurationCollector {
// Not whitelisted
}
@@ -1,3 +0,0 @@
class ProjectConfigurationCollector {
// Not whitelisted
}
@@ -1,8 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.configuration
fun suggestNativeDebug(projectPath: String) {}
@@ -1,14 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.gradle.execution
import com.intellij.openapi.module.Module
import org.jetbrains.plugins.gradle.settings.GradleSystemRunningSettings
//BUNCH: 183
fun isDelegatedBuild(module: Module): Boolean {
return GradleSystemRunningSettings.getInstance().isUseGradleAwareMake()
}
@@ -1,88 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.run
import com.intellij.execution.Location
import com.intellij.execution.actions.ConfigurationContext
import com.intellij.execution.actions.ConfigurationFromContext
import com.intellij.openapi.externalSystem.service.execution.ExternalSystemRunConfiguration
import com.intellij.openapi.module.Module
import com.intellij.openapi.util.Ref
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.caches.project.isNewMPPModule
import org.jetbrains.kotlin.idea.project.platform
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.plugins.gradle.execution.test.runner.*
import org.jetbrains.plugins.gradle.service.execution.GradleRunConfiguration
import org.jetbrains.plugins.gradle.util.GradleConstants
abstract class AbstractKotlinMultiplatformTestClassGradleConfigurationProducer : AbstractKotlinTestClassGradleConfigurationProducer() {
override val forceGradleRunner: Boolean get() = true
override val hasTestFramework: Boolean get() = true
abstract fun isApplicable(module: Module, platform: TargetPlatform): Boolean
final override fun isApplicable(module: Module): Boolean {
if (!module.isNewMPPModule) {
return false
}
val platform = module.platform ?: return false
return isApplicable(module, platform)
}
override fun isPreferredConfiguration(self: ConfigurationFromContext?, other: ConfigurationFromContext): Boolean {
return other.isJpsJunitConfiguration()
}
override fun shouldReplace(self: ConfigurationFromContext, other: ConfigurationFromContext): Boolean {
return other.isJpsJunitConfiguration()
}
}
abstract class AbstractKotlinTestClassGradleConfigurationProducer
: TestClassGradleConfigurationProducer(), KotlinGradleConfigurationProducer
{
override fun isConfigurationFromContext(configuration: ExternalSystemRunConfiguration, context: ConfigurationContext): Boolean {
if (!context.check()) {
return false
}
if (!forceGradleRunner) {
return super.isConfigurationFromContext(configuration, context)
}
if (GradleConstants.SYSTEM_ID != configuration.settings.externalSystemId) return false
return doIsConfigurationFromContext(configuration, context)
}
override fun setupConfigurationFromContext(
configuration: ExternalSystemRunConfiguration,
context: ConfigurationContext,
sourceElement: Ref<PsiElement>
): Boolean {
if (!context.check()) {
return false
}
if (!forceGradleRunner) {
return super.setupConfigurationFromContext(configuration, context, sourceElement)
}
if (GradleConstants.SYSTEM_ID != configuration.settings.externalSystemId) return false
if (sourceElement.isNull) return false
(configuration as? GradleRunConfiguration)?.isScriptDebugEnabled = false
return doSetupConfigurationFromContext(configuration, context, sourceElement)
}
private fun ConfigurationContext.check(): Boolean {
return hasTestFramework && module != null && isApplicable(module)
}
override fun getPsiClassForLocation(contextLocation: Location<*>) = getTestClassForKotlinTest(contextLocation)
override fun getPsiMethodForLocation(contextLocation: Location<*>) = getTestMethodForKotlinTest(contextLocation)
}
@@ -1,87 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.run
import com.intellij.execution.Location
import com.intellij.execution.actions.ConfigurationContext
import com.intellij.execution.actions.ConfigurationFromContext
import com.intellij.openapi.externalSystem.service.execution.ExternalSystemRunConfiguration
import com.intellij.openapi.module.Module
import com.intellij.openapi.util.Ref
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.caches.project.isNewMPPModule
import org.jetbrains.kotlin.idea.project.platform
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.plugins.gradle.execution.test.runner.TestMethodGradleConfigurationProducer
import org.jetbrains.plugins.gradle.service.execution.GradleRunConfiguration
import org.jetbrains.plugins.gradle.util.GradleConstants
abstract class AbstractKotlinMultiplatformTestMethodGradleConfigurationProducer : AbstractKotlinTestMethodGradleConfigurationProducer() {
override val forceGradleRunner: Boolean get() = true
override val hasTestFramework: Boolean get() = true
abstract fun isApplicable(module: Module, platform: TargetPlatform): Boolean
final override fun isApplicable(module: Module): Boolean {
if (!module.isNewMPPModule) {
return false
}
val platform = module.platform ?: return false
return isApplicable(module, platform)
}
override fun isPreferredConfiguration(self: ConfigurationFromContext?, other: ConfigurationFromContext): Boolean {
return other.isJpsJunitConfiguration()
}
override fun shouldReplace(self: ConfigurationFromContext, other: ConfigurationFromContext): Boolean {
return other.isJpsJunitConfiguration()
}
}
abstract class AbstractKotlinTestMethodGradleConfigurationProducer
: TestMethodGradleConfigurationProducer(), KotlinGradleConfigurationProducer
{
override fun isConfigurationFromContext(configuration: ExternalSystemRunConfiguration, context: ConfigurationContext): Boolean {
if (!context.check()) {
return false
}
if (!forceGradleRunner) {
return super.isConfigurationFromContext(configuration, context)
}
if (GradleConstants.SYSTEM_ID != configuration.settings.externalSystemId) return false
return doIsConfigurationFromContext(configuration, context)
}
override fun setupConfigurationFromContext(
configuration: ExternalSystemRunConfiguration,
context: ConfigurationContext,
sourceElement: Ref<PsiElement>
): Boolean {
if (!context.check()) {
return false
}
if (!forceGradleRunner) {
return super.setupConfigurationFromContext(configuration, context, sourceElement)
}
if (GradleConstants.SYSTEM_ID != configuration.settings.externalSystemId) return false
if (sourceElement.isNull) return false
(configuration as? GradleRunConfiguration)?.isScriptDebugEnabled = false
return doSetupConfigurationFromContext(configuration, context, sourceElement)
}
private fun ConfigurationContext.check(): Boolean {
return hasTestFramework && module != null && isApplicable(module)
}
override fun getPsiMethodForLocation(contextLocation: Location<*>) = getTestMethodForKotlinTest(contextLocation)
}
@@ -1,66 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.scripting.gradle
import com.intellij.openapi.externalSystem.service.project.autoimport.ConfigurationFileCrcFactory
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.plugins.gradle.settings.GradleLocalSettings
import java.nio.file.Paths
import java.util.*
class GradleScriptInputsWatcher(val project: Project) {
private val comparator = Comparator<VirtualFile> { f1, f2 -> (f1.timeStamp - f2.timeStamp).toInt() }
private val storage = TreeSet(comparator)
init {
initStorage(project)
}
private fun initStorage(project: Project) {
val localSettings = GradleLocalSettings.getInstance(project)
localSettings.externalConfigModificationStamps.forEach { (path, stamp) ->
val file = VfsUtil.findFile(Paths.get(path), true)
if (file != null && !file.isDirectory) {
val calculateCrc = ConfigurationFileCrcFactory(project, file).create()
if (calculateCrc != stamp) {
addToStorage(file)
}
}
}
}
fun lastModifiedFileTimeStamp(file: VirtualFile): Long = lastModifiedRelatedFile(file)?.timeStamp ?: 0
fun areRelatedFilesUpToDate(file: VirtualFile, timeStamp: Long): Boolean {
return lastModifiedFileTimeStamp(file) <= timeStamp
}
fun addToStorage(file: VirtualFile) {
if (storage.contains(file)) {
storage.remove(file)
}
storage.add(file)
}
private fun lastModifiedRelatedFile(file: VirtualFile): VirtualFile? {
if (storage.isEmpty()) return null
val iterator = storage.descendingIterator()
if (!iterator.hasNext()) return null
var lastModifiedFile = iterator.next()
while (lastModifiedFile == file && iterator.hasNext()) {
lastModifiedFile = iterator.next()
}
if (lastModifiedFile == file) return null
return lastModifiedFile
}
}
@@ -1,9 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.gradle
class KaptImportingTest {
}
@@ -1,9 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.gradle
class KaptImportingTest {
}
@@ -1,8 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.gradle
fun KaptImportingTest.isAndroidStudio() = true
@@ -1,70 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.gradle
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.roots.*
import com.intellij.openapi.roots.impl.ModulesOrderEnumerator
import com.intellij.util.text.VersionComparatorUtil
import org.jetbrains.kotlin.idea.codeInsight.gradle.MultiplePluginVersionGradleImportingTestCase
import org.jetbrains.kotlin.idea.util.sourceRoots
import org.junit.Test
import java.io.File
class NewMultiplatformKaptProjectImportingTest : MultiplePluginVersionGradleImportingTestCase() {
override fun isApplicableTest(): Boolean {
val isOldGradlePlugin = gradleKotlinPluginVersion != MINIMAL_SUPPORTED_VERSION
&& VersionComparatorUtil.compare(gradleKotlinPluginVersion, "1.3.40") < 0
return !isOldGradlePlugin && VersionComparatorUtil.compare(gradleVersion, "4.0") >= 0
}
@Test
fun testRuntimeClasspath() {
configureByFiles()
val projectPath = this.projectPath
val expectedRoots = listOf(
"build/tmp/kapt3/classes/main",
"build/classes/java/main",
"build/classes/kotlin/jvm/main",
"build/processedResources/jvm/main"
).map {
File(projectPath, it).apply { mkdirs() }
}
importProject()
val jvmMainModule = ModuleManager.getInstance(project).modules.first { it.name == "project_jvmMain" }
val enumerator = ModulesOrderEnumerator(listOf(jvmMainModule))
val roots = enumerator.classesRoots
fun isRootPresent(file: File) = roots.any { it.path == ExternalSystemApiUtil.toCanonicalPath(file.path) }
val missingRoots = expectedRoots.filter { !isRootPresent(it) }
assert(missingRoots.isEmpty()) {
"Missing roots found: " + missingRoots.joinToString()
}
}
override fun importProject() {
val isCreateEmptyContentRootDirectories = currentExternalProjectSettings.isCreateEmptyContentRootDirectories
currentExternalProjectSettings.isCreateEmptyContentRootDirectories = true
try {
super.importProject()
} finally {
currentExternalProjectSettings.isCreateEmptyContentRootDirectories = isCreateEmptyContentRootDirectories
}
}
override fun testDataDirName(): String {
return "newMultiplatformImport"
}
}
@@ -1,639 +0,0 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.gradle
import com.intellij.openapi.roots.DependencyScope
import com.intellij.util.text.VersionComparatorUtil
import org.jetbrains.jps.model.java.JavaResourceRootType
import org.jetbrains.jps.model.java.JavaSourceRootType
import org.jetbrains.kotlin.config.*
import org.jetbrains.kotlin.idea.codeInsight.gradle.MultiplePluginVersionGradleImportingTestCase
import org.jetbrains.kotlin.platform.CommonPlatforms
import org.jetbrains.kotlin.platform.js.JsPlatforms
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
import org.jetbrains.kotlin.test.KotlinTestUtils
import org.jetbrains.plugins.gradle.tooling.annotation.PluginTargetVersions
import org.junit.After
import org.junit.Before
import org.junit.Test
class NewMultiplatformProjectImportingTest : MultiplePluginVersionGradleImportingTestCase() {
@Before
fun saveSdksBeforeTest() {
val kotlinSdks = sdkCreationChecker?.getKotlinSdks() ?: emptyList()
if (kotlinSdks.isNotEmpty()) {
fail("Found Kotlin SDK before importing test. Sdk list: $kotlinSdks")
}
}
@After
fun checkSdkCreated() {
if (sdkCreationChecker?.isKotlinSdkCreated() == false) {
fail("Kotlin SDK was not created during import of MPP Project.")
}
}
@Test
@PluginTargetVersions(gradleVersion = "4.0+", pluginVersion = "1.3.10+")
fun testProjectDependency() {
configureByFiles()
importProject()
checkProjectStructure() {
allModules {
languageVersion("1.3")
apiVersion("1.3")
when (module.name) {
"project", "app", "lib" -> additionalArguments(null)
"app_jvmMain", "app_jvmTest", "lib_jvmMain", "lib_jvmTest" ->
additionalArguments(
if (VersionComparatorUtil.compare(gradleKotlinPluginVersion, "1.3.50") < 0)
"-version"
else
"-Xallow-no-source-files"
)
else -> additionalArguments("-version")
}
}
module("project")
module("app")
module("app_commonMain") {
platform(CommonPlatforms.defaultCommonPlatform)
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-common:${gradleKotlinPluginVersion}", DependencyScope.COMPILE)
moduleDependency("lib_commonMain", DependencyScope.COMPILE)
sourceFolder("app/src/commonMain/kotlin", SourceKotlinRootType)
sourceFolder("app/src/commonMain/resources", ResourceKotlinRootType)
inheritProjectOutput()
}
module("app_commonTest") {
platform(CommonPlatforms.defaultCommonPlatform)
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-common:${gradleKotlinPluginVersion}", DependencyScope.TEST)
moduleDependency("lib_commonMain", DependencyScope.TEST)
moduleDependency("app_commonMain", DependencyScope.TEST)
sourceFolder("app/src/commonTest/kotlin", TestSourceKotlinRootType)
sourceFolder("app/src/commonTest/resources", TestResourceKotlinRootType)
inheritProjectOutput()
}
module("app_jsMain") {
platform(JsPlatforms.defaultJsPlatform)
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-js:${gradleKotlinPluginVersion}", DependencyScope.COMPILE)
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-common:${gradleKotlinPluginVersion}", DependencyScope.COMPILE)
moduleDependency("lib_jsMain", DependencyScope.COMPILE)
moduleDependency("lib_commonMain", DependencyScope.COMPILE)
moduleDependency("app_commonMain", DependencyScope.COMPILE)
sourceFolder("app/src/jsMain/kotlin", SourceKotlinRootType)
sourceFolder("app/src/jsMain/resources", ResourceKotlinRootType)
outputPath("app/build/classes/kotlin/js/main", true)
}
module("app_jsTest") {
platform(JsPlatforms.defaultJsPlatform)
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-js:${gradleKotlinPluginVersion}", DependencyScope.TEST)
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-common:${gradleKotlinPluginVersion}", DependencyScope.TEST)
moduleDependency("lib_jsMain", DependencyScope.TEST)
moduleDependency("lib_commonMain", DependencyScope.TEST)
moduleDependency("app_commonMain", DependencyScope.TEST)
moduleDependency("app_commonTest", DependencyScope.TEST)
moduleDependency("app_jsMain", DependencyScope.TEST)
sourceFolder("app/src/jsTest/kotlin", TestSourceKotlinRootType)
sourceFolder("app/src/jsTest/resources", TestResourceKotlinRootType)
outputPath("app/build/classes/kotlin/js/test", false)
}
module("app_jvmMain") {
platform(JvmPlatforms.jvm16)
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib:${gradleKotlinPluginVersion}", DependencyScope.COMPILE)
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-common:${gradleKotlinPluginVersion}", DependencyScope.COMPILE)
libraryDependency("Gradle: org.jetbrains:annotations:13.0", DependencyScope.COMPILE)
moduleDependency("lib_jvmMain", DependencyScope.COMPILE)
moduleDependency("lib_commonMain", DependencyScope.COMPILE)
moduleDependency("app_main", DependencyScope.COMPILE)
moduleDependency("app_commonMain", DependencyScope.COMPILE)
sourceFolder("app/src/jvmMain/kotlin", JavaSourceRootType.SOURCE)
sourceFolder("app/src/jvmMain/resources", JavaResourceRootType.RESOURCE)
outputPath("app/build/classes/kotlin/jvm/main", true)
}
module("app_jvmTest") {
platform(JvmPlatforms.jvm16)
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib:${gradleKotlinPluginVersion}", DependencyScope.TEST)
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-common:${gradleKotlinPluginVersion}", DependencyScope.TEST)
libraryDependency("Gradle: org.jetbrains:annotations:13.0", DependencyScope.TEST)
moduleDependency("lib_jvmMain", DependencyScope.TEST)
moduleDependency("lib_commonMain", DependencyScope.TEST)
moduleDependency("app_test", DependencyScope.TEST)
moduleDependency("app_jvmMain", DependencyScope.TEST)
moduleDependency("app_commonMain", DependencyScope.TEST)
moduleDependency("app_commonTest", DependencyScope.TEST)
sourceFolder("app/src/jvmTest/kotlin", JavaSourceRootType.TEST_SOURCE)
sourceFolder("app/src/jvmTest/resources", JavaResourceRootType.TEST_RESOURCE)
outputPath("app/build/classes/kotlin/jvm/test", false)
}
module("app_main") {
platform(JvmPlatforms.jvm18)
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib:${gradleKotlinPluginVersion}", DependencyScope.COMPILE)
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-common:${gradleKotlinPluginVersion}", DependencyScope.COMPILE)
libraryDependency("Gradle: org.jetbrains:annotations:13.0", DependencyScope.COMPILE)
moduleDependency("lib_commonMain", DependencyScope.COMPILE)
sourceFolder("app/src/main/java", JavaSourceRootType.SOURCE)
sourceFolder("app/src/main/kotlin", JavaSourceRootType.SOURCE)
sourceFolder("app/src/main/resources", JavaResourceRootType.RESOURCE)
inheritProjectOutput()
}
module("app_test") {
platform(JvmPlatforms.jvm18)
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib:${gradleKotlinPluginVersion}", DependencyScope.TEST)
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-common:${gradleKotlinPluginVersion}", DependencyScope.TEST)
libraryDependency("Gradle: org.jetbrains:annotations:13.0", DependencyScope.TEST)
moduleDependency("lib_commonMain", DependencyScope.TEST)
moduleDependency("app_main", DependencyScope.TEST)
sourceFolder("app/src/test/java", JavaSourceRootType.TEST_SOURCE)
sourceFolder("app/src/test/kotlin", JavaSourceRootType.TEST_SOURCE)
sourceFolder("app/src/test/resources", JavaResourceRootType.TEST_RESOURCE)
inheritProjectOutput()
}
module("lib")
module("lib_commonMain") {
platform(CommonPlatforms.defaultCommonPlatform)
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-common:${gradleKotlinPluginVersion}", DependencyScope.COMPILE)
sourceFolder("lib/src/commonMain/kotlin", SourceKotlinRootType)
sourceFolder("lib/src/commonMain/resources", ResourceKotlinRootType)
inheritProjectOutput()
}
module("lib_commonTest") {
platform(CommonPlatforms.defaultCommonPlatform)
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-common:${gradleKotlinPluginVersion}", DependencyScope.TEST)
moduleDependency("lib_commonMain", DependencyScope.TEST)
sourceFolder("lib/src/commonTest/kotlin", TestSourceKotlinRootType)
sourceFolder("lib/src/commonTest/resources", TestResourceKotlinRootType)
inheritProjectOutput()
}
module("lib_jsMain") {
platform(JsPlatforms.defaultJsPlatform)
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-js:${gradleKotlinPluginVersion}", DependencyScope.COMPILE)
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-common:${gradleKotlinPluginVersion}", DependencyScope.COMPILE)
moduleDependency("lib_commonMain", DependencyScope.COMPILE)
sourceFolder("lib/src/jsMain/kotlin", SourceKotlinRootType)
sourceFolder("lib/src/jsMain/resources", ResourceKotlinRootType)
outputPath("lib/build/classes/kotlin/js/main", true)
}
module("lib_jsTest") {
platform(JsPlatforms.defaultJsPlatform)
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-js:${gradleKotlinPluginVersion}", DependencyScope.TEST)
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-common:${gradleKotlinPluginVersion}", DependencyScope.TEST)
moduleDependency("lib_commonMain", DependencyScope.TEST)
moduleDependency("lib_commonTest", DependencyScope.TEST)
moduleDependency("lib_jsMain", DependencyScope.TEST)
sourceFolder("lib/src/jsTest/kotlin", TestSourceKotlinRootType)
sourceFolder("lib/src/jsTest/resources", TestResourceKotlinRootType)
outputPath("lib/build/classes/kotlin/js/test", false)
}
module("lib_jvmMain") {
platform(JvmPlatforms.jvm16)
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib:${gradleKotlinPluginVersion}", DependencyScope.COMPILE)
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-common:${gradleKotlinPluginVersion}", DependencyScope.COMPILE)
libraryDependency("Gradle: org.jetbrains:annotations:13.0", DependencyScope.COMPILE)
moduleDependency("lib_commonMain", DependencyScope.COMPILE)
sourceFolder("lib/src/jvmMain/kotlin", JavaSourceRootType.SOURCE)
sourceFolder("lib/src/jvmMain/resources", JavaResourceRootType.RESOURCE)
outputPath("lib/build/classes/kotlin/jvm/main", true)
}
module("lib_jvmTest") {
platform(JvmPlatforms.jvm16)
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib:${gradleKotlinPluginVersion}", DependencyScope.TEST)
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-common:${gradleKotlinPluginVersion}", DependencyScope.TEST)
libraryDependency("Gradle: org.jetbrains:annotations:13.0", DependencyScope.TEST)
moduleDependency("lib_commonTest", DependencyScope.TEST)
moduleDependency("lib_commonMain", DependencyScope.TEST)
moduleDependency("lib_jvmMain", DependencyScope.TEST)
sourceFolder("lib/src/jvmTest/kotlin", JavaSourceRootType.TEST_SOURCE)
sourceFolder("lib/src/jvmTest/resources", JavaResourceRootType.TEST_RESOURCE)
outputPath("lib/build/classes/kotlin/jvm/test", false)
}
}
}
@Test
fun testFileCollectionDependency() {
configureByFiles()
importProject()
checkProjectStructure(
exhaustiveModuleList = false,
exhaustiveSourceSourceRootList = false
) {
module("project_jvmMain") {
libraryDependencyByUrl("file://$projectPath/a", DependencyScope.COMPILE)
libraryDependencyByUrl("file://$projectPath/b", DependencyScope.COMPILE)
moduleDependency("project_commonMain", DependencyScope.COMPILE)
moduleDependency("project_main", DependencyScope.COMPILE)
}
}
}
@Test
@PluginTargetVersions(gradleVersion = "4.0+", pluginVersion = "1.3.30+")
fun testUnresolvedDependency() {
configureByFiles()
importProject()
checkProjectStructure(
exhaustiveSourceSourceRootList = false,
exhaustiveDependencyList = false
) {
module("project")
module("project_commonMain")
module("project_commonTest")
module("project_jvmMain")
module("project_jvmTest")
module("project_main")
module("project_test")
}
}
@Test
@PluginTargetVersions(gradleVersion = "4.0+", pluginVersion = "1.3.30+")
fun testAndroidDependencyOnMPP() {
configureByFiles()
createProjectSubFile(
"local.properties",
"sdk.dir=/${KotlinTestUtils.getAndroidSdkSystemIndependentPath()}"
)
importProject()
checkProjectStructure {
module("project")
module("app") {
libraryDependency("Gradle: android-android-26", DependencyScope.COMPILE)
libraryDependency("Gradle: android.arch.core:common:1.1.0@jar", DependencyScope.COMPILE)
libraryDependency("Gradle: android.arch.core:runtime-1.1.0", DependencyScope.COMPILE)
libraryDependency("Gradle: android.arch.lifecycle:common:1.1.0@jar", DependencyScope.COMPILE)
libraryDependency("Gradle: android.arch.lifecycle:livedata-core-1.1.0", DependencyScope.COMPILE)
libraryDependency("Gradle: android.arch.lifecycle:runtime-1.1.0", DependencyScope.COMPILE)
libraryDependency("Gradle: android.arch.lifecycle:viewmodel-1.1.0", DependencyScope.COMPILE)
libraryDependency("Gradle: com.android.support.constraint:constraint-layout-1.1.3", DependencyScope.COMPILE)
libraryDependency("Gradle: com.android.support.constraint:constraint-layout-solver:1.1.3@jar", DependencyScope.COMPILE)
libraryDependency("Gradle: com.android.support.test.espresso:espresso-core-3.0.2", DependencyScope.TEST)
libraryDependency("Gradle: com.android.support.test.espresso:espresso-idling-resource-3.0.2", DependencyScope.TEST)
libraryDependency("Gradle: com.android.support.test:monitor-1.0.2", DependencyScope.TEST)
libraryDependency("Gradle: com.android.support.test:runner-1.0.2", DependencyScope.TEST)
libraryDependency("Gradle: com.android.support:animated-vector-drawable-27.1.1", DependencyScope.COMPILE)
libraryDependency("Gradle: com.android.support:appcompat-v7-27.1.1", DependencyScope.COMPILE)
libraryDependency("Gradle: com.android.support:support-annotations:27.1.1@jar", DependencyScope.COMPILE)
libraryDependency("Gradle: com.android.support:support-compat-27.1.1", DependencyScope.COMPILE)
libraryDependency("Gradle: com.android.support:support-core-ui-27.1.1", DependencyScope.COMPILE)
libraryDependency("Gradle: com.android.support:support-core-utils-27.1.1", DependencyScope.COMPILE)
libraryDependency("Gradle: com.android.support:support-fragment-27.1.1", DependencyScope.COMPILE)
libraryDependency("Gradle: com.android.support:support-vector-drawable-27.1.1", DependencyScope.COMPILE)
libraryDependency("Gradle: com.google.code.findbugs:jsr305:2.0.1@jar", DependencyScope.TEST)
libraryDependency("Gradle: com.squareup:javawriter:2.1.1@jar", DependencyScope.TEST)
libraryDependency("Gradle: javax.inject:javax.inject:1@jar", DependencyScope.TEST)
libraryDependency("Gradle: junit:junit:4.12@jar", DependencyScope.TEST)
libraryDependency("Gradle: net.sf.kxml:kxml2:2.3.0@jar", DependencyScope.TEST)
libraryDependency("Gradle: org.hamcrest:hamcrest-core:1.3@jar", DependencyScope.TEST)
libraryDependency("Gradle: org.hamcrest:hamcrest-integration:1.3@jar", DependencyScope.TEST)
libraryDependency("Gradle: org.hamcrest:hamcrest-library:1.3@jar", DependencyScope.TEST)
if (gradleKotlinPluginVersion != MINIMAL_SUPPORTED_VERSION) {
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-android-extensions-runtime:${gradleKotlinPluginVersion}@jar", DependencyScope.COMPILE)
}
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-common:${gradleKotlinPluginVersion}@jar", DependencyScope.COMPILE)
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-jdk7:${gradleKotlinPluginVersion}@jar", DependencyScope.COMPILE)
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib:${gradleKotlinPluginVersion}@jar", DependencyScope.COMPILE)
libraryDependency("Gradle: org.jetbrains:annotations:13.0@jar", DependencyScope.COMPILE)
moduleDependency("shared", DependencyScope.COMPILE)
moduleDependency("shared_androidMain", DependencyScope.COMPILE)
moduleDependency("shared_androidTest", DependencyScope.TEST)
moduleDependency("shared_commonMain", DependencyScope.COMPILE)
moduleDependency("shared_commonTest", DependencyScope.TEST)
}
module("shared")
module("shared_commonMain") {
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-common:${gradleKotlinPluginVersion}", DependencyScope.COMPILE)
sourceFolder("shared/src/commonMain/kotlin", SourceKotlinRootType)
sourceFolder("shared/src/commonMain/resources", ResourceKotlinRootType)
}
module("shared_commonTest") {
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-common:${gradleKotlinPluginVersion}", DependencyScope.TEST)
moduleDependency("shared_commonMain", DependencyScope.TEST)
sourceFolder("shared/src/commonTest/kotlin", TestSourceKotlinRootType)
sourceFolder("shared/src/commonTest/resources", TestResourceKotlinRootType)
}
module("shared_androidMain") {
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-common:${gradleKotlinPluginVersion}", DependencyScope.COMPILE)
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib:${gradleKotlinPluginVersion}", DependencyScope.COMPILE)
libraryDependency("Gradle: org.jetbrains:annotations:13.0", DependencyScope.COMPILE)
moduleDependency("shared_commonMain", DependencyScope.COMPILE)
sourceFolder("shared/src/androidMain/kotlin", JavaSourceRootType.SOURCE)
sourceFolder("shared/src/androidMain/resources", JavaResourceRootType.RESOURCE)
}
module("shared_androidTest") {
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-common:${gradleKotlinPluginVersion}", DependencyScope.TEST)
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib:${gradleKotlinPluginVersion}", DependencyScope.TEST)
libraryDependency("Gradle: org.jetbrains:annotations:13.0", DependencyScope.TEST)
moduleDependency("shared_androidMain", DependencyScope.TEST)
moduleDependency("shared_commonMain", DependencyScope.TEST)
moduleDependency("shared_commonTest", DependencyScope.TEST)
sourceFolder("shared/src/androidTest/kotlin", JavaSourceRootType.TEST_SOURCE)
sourceFolder("shared/src/androidTest/resources", JavaResourceRootType.TEST_RESOURCE)
}
var nativeVersion = gradleKotlinPluginVersion
module("shared_iOSMain") {
libraryDependency("Kotlin/Native $nativeVersion - stdlib", DependencyScope.PROVIDED)
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-common:${gradleKotlinPluginVersion}", DependencyScope.COMPILE)
moduleDependency("shared_commonMain", DependencyScope.COMPILE)
sourceFolder("shared/src/iOSMain/kotlin", SourceKotlinRootType)
sourceFolder("shared/src/iOSMain/resources", ResourceKotlinRootType)
}
module("shared_iOSTest") {
libraryDependency("Kotlin/Native $nativeVersion - stdlib", DependencyScope.PROVIDED)
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-common:${gradleKotlinPluginVersion}", DependencyScope.TEST)
moduleDependency("shared_iOSMain", DependencyScope.TEST)
moduleDependency("shared_commonMain", DependencyScope.TEST)
moduleDependency("shared_commonTest", DependencyScope.TEST)
sourceFolder("shared/src/iOSTest/kotlin", TestSourceKotlinRootType)
sourceFolder("shared/src/iOSTest/resources", TestResourceKotlinRootType)
}
}
}
@Test
fun testTestTasks() {
val files = configureByFiles()
importProject()
checkProjectStructure(exhaustiveSourceSourceRootList = false) {
module("project")
module("common")
module("jvm")
module("js")
module("project_commonMain")
module("project_commonTest") {
moduleDependency("project_commonMain", DependencyScope.TEST)
}
module("project_jvmMain") {
moduleDependency("project_commonMain", DependencyScope.COMPILE)
}
module("project_jvmTest") {
moduleDependency("project_commonMain", DependencyScope.TEST)
moduleDependency("project_commonTest", DependencyScope.TEST)
moduleDependency("project_jvmMain", DependencyScope.TEST)
}
}
val commonTestFile = files.find { it.path.contains("commonTest") }!!
val commonTasks = findTasksToRun(commonTestFile)
if (commonTasks != null) {
assertEquals(listOf(":cleanJvmTest", ":jvmTest"), commonTasks)
}
val jvmTestFile = files.find { it.path.contains("jvmTest") }!!
val jvmTasks = findTasksToRun(jvmTestFile)
if (jvmTasks != null) {
assertEquals(listOf(":cleanJvmTest", ":jvmTest"), jvmTasks)
}
}
@Test
fun testDependencyOnRoot() {
configureByFiles()
importProject()
checkProjectStructure(exhaustiveSourceSourceRootList = false) {
module("project")
module("project_commonMain")
module("project_commonTest") {
moduleDependency("project_commonMain", DependencyScope.TEST)
}
module("project_jvmMain") {
moduleDependency("project_commonMain", DependencyScope.COMPILE)
}
module("project_jvmTest") {
moduleDependency("project_commonMain", DependencyScope.TEST)
moduleDependency("project_commonTest", DependencyScope.TEST)
moduleDependency("project_jvmMain", DependencyScope.TEST)
}
module("subproject")
module("subproject_commonMain") {
moduleDependency("project_commonMain", DependencyScope.COMPILE)
}
module("subproject_commonTest") {
moduleDependency("project_commonMain", DependencyScope.TEST)
moduleDependency("subproject_commonMain", DependencyScope.TEST)
}
module("subproject_jvmMain") {
moduleDependency("project_commonMain", DependencyScope.COMPILE)
moduleDependency("subproject_commonMain", DependencyScope.COMPILE)
moduleDependency("project_jvmMain", DependencyScope.COMPILE)
}
module("subproject_jvmTest") {
moduleDependency("project_commonMain", DependencyScope.TEST)
moduleDependency("subproject_commonMain", DependencyScope.TEST)
moduleDependency("subproject_commonTest", DependencyScope.TEST)
moduleDependency("project_jvmMain", DependencyScope.TEST)
moduleDependency("subproject_jvmMain", DependencyScope.TEST)
}
}
}
@Test
@PluginTargetVersions(gradleVersion = "4.0+", pluginVersion = "1.3.10+")
fun testNestedDependencies() {
configureByFiles()
importProject()
checkProjectStructure(exhaustiveSourceSourceRootList = false) {
module("project")
module("aaa")
module("aaa_commonMain") {
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-common:${gradleKotlinPluginVersion}", DependencyScope.COMPILE)
moduleDependency("bbb_commonMain", DependencyScope.COMPILE)
moduleDependency("ccc_commonMain", DependencyScope.COMPILE)
}
module("aaa_commonTest") {
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-common:${gradleKotlinPluginVersion}", DependencyScope.TEST)
moduleDependency("aaa_commonMain", DependencyScope.TEST)
moduleDependency("bbb_commonMain", DependencyScope.TEST)
moduleDependency("ccc_commonMain", DependencyScope.TEST)
}
module("aaa_jvmMain") {
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-common:${gradleKotlinPluginVersion}", DependencyScope.COMPILE)
moduleDependency("aaa_commonMain", DependencyScope.COMPILE)
moduleDependency("bbb_commonMain", DependencyScope.COMPILE)
moduleDependency("bbb_jvmMain", DependencyScope.COMPILE)
moduleDependency("ccc_commonMain", DependencyScope.COMPILE)
moduleDependency("ccc_jvmMain", DependencyScope.COMPILE)
}
module("aaa_jvmTest") {
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-common:${gradleKotlinPluginVersion}", DependencyScope.TEST)
moduleDependency("aaa_commonMain", DependencyScope.TEST)
moduleDependency("aaa_commonTest", DependencyScope.TEST)
moduleDependency("aaa_jvmMain", DependencyScope.TEST)
moduleDependency("bbb_commonMain", DependencyScope.TEST)
moduleDependency("bbb_jvmMain", DependencyScope.TEST)
moduleDependency("ccc_commonMain", DependencyScope.TEST)
moduleDependency("ccc_jvmMain", DependencyScope.TEST)
}
module("bbb")
module("bbb_commonMain") {
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-common:${gradleKotlinPluginVersion}", DependencyScope.COMPILE)
moduleDependency("ccc_commonMain", DependencyScope.COMPILE)
}
module("bbb_commonTest") {
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-common:${gradleKotlinPluginVersion}", DependencyScope.TEST)
moduleDependency("bbb_commonMain", DependencyScope.TEST)
moduleDependency("ccc_commonMain", DependencyScope.TEST)
}
module("bbb_jvmMain") {
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-common:${gradleKotlinPluginVersion}", DependencyScope.COMPILE)
moduleDependency("bbb_commonMain", DependencyScope.COMPILE)
moduleDependency("ccc_commonMain", DependencyScope.COMPILE)
moduleDependency("ccc_jvmMain", DependencyScope.COMPILE)
}
module("bbb_jvmTest") {
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-common:${gradleKotlinPluginVersion}", DependencyScope.TEST)
moduleDependency("bbb_commonMain", DependencyScope.TEST)
moduleDependency("bbb_commonTest", DependencyScope.TEST)
moduleDependency("bbb_jvmMain", DependencyScope.TEST)
moduleDependency("ccc_commonMain", DependencyScope.TEST)
moduleDependency("ccc_jvmMain", DependencyScope.TEST)
}
module("ccc")
module("ccc_commonMain") {
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-common:${gradleKotlinPluginVersion}", DependencyScope.COMPILE)
}
module("ccc_commonTest") {
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-common:${gradleKotlinPluginVersion}", DependencyScope.TEST)
moduleDependency("ccc_commonMain", DependencyScope.TEST)
}
module("ccc_jvmMain") {
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-common:${gradleKotlinPluginVersion}", DependencyScope.COMPILE)
moduleDependency("ccc_commonMain", DependencyScope.COMPILE)
}
module("ccc_jvmTest") {
libraryDependency("Gradle: org.jetbrains.kotlin:kotlin-stdlib-common:${gradleKotlinPluginVersion}", DependencyScope.TEST)
moduleDependency("ccc_commonMain", DependencyScope.TEST)
moduleDependency("ccc_commonTest", DependencyScope.TEST)
moduleDependency("ccc_jvmMain", DependencyScope.TEST)
}
}
}
@Test
@PluginTargetVersions(gradleVersion = "4.0+", pluginVersion = "1.3.20+")
fun testDetectAndroidSources() {
configureByFiles()
createProjectSubFile(
"local.properties",
"sdk.dir=/${KotlinTestUtils.getAndroidSdkSystemIndependentPath()}"
)
importProject(true)
checkProjectStructure(exhaustiveModuleList = false, exhaustiveDependencyList = false, exhaustiveSourceSourceRootList = false) {
module("multiplatformb") {
sourceFolder("multiplatformb/src/androidMain/kotlin", JavaSourceRootType.SOURCE)
}
}
}
/**
* This test is inherited form testPlatformToCommonExpectedByInComposite and actually tests
* dependencies in multiplatform project included in composite build
*/
@Test
@PluginTargetVersions(gradleVersion = "4.0+", pluginVersion = "1.3.20+")
fun testPlatformToCommonExpByInComposite() {
configureByFiles()
importProject(true)
checkProjectStructure(exhaustiveSourceSourceRootList = false) {
module("project")
module("project.commonMain")
module("project.commonTest") {
moduleDependency("project.commonMain", DependencyScope.TEST)
}
module("toInclude")
module("toInclude.commonMain")
module("toInclude.commonTest") {
moduleDependency("toInclude.commonMain", DependencyScope.TEST)
}
module("toInclude.jsMain") {
moduleDependency("toInclude.commonMain", DependencyScope.COMPILE)
}
module("toInclude.jsTest") {
moduleDependency("toInclude.commonMain", DependencyScope.TEST)
moduleDependency("toInclude.commonTest", DependencyScope.TEST)
moduleDependency("toInclude.jsMain", DependencyScope.TEST)
}
module("toInclude.jvmMain") {
moduleDependency("toInclude.commonMain", DependencyScope.COMPILE)
}
module("toInclude.jvmTest") {
moduleDependency("toInclude.commonMain", DependencyScope.TEST)
moduleDependency("toInclude.commonTest", DependencyScope.TEST)
moduleDependency("toInclude.jvmMain", DependencyScope.TEST)
}
}
}
@Test
@PluginTargetVersions(gradleVersion = "4.0+", pluginVersion = "1.3.20+")
fun testProductionOnTestFlag() {
configureByFiles()
importProject(true)
checkProjectStructure(false, false, false ) {
module("project.javaModule.test") {
moduleDependency("project.mppModule.jvmTest", DependencyScope.COMPILE, true)
}
}
}
private fun checkProjectStructure(
exhaustiveModuleList: Boolean = true,
exhaustiveSourceSourceRootList: Boolean = true,
exhaustiveDependencyList: Boolean = true,
body: ProjectInfo.() -> Unit = {}
) {
checkProjectStructure(
myProject,
projectPath,
exhaustiveModuleList,
exhaustiveSourceSourceRootList,
exhaustiveDependencyList,
false,
body)
}
fun importProject(useQualifiedNames: Boolean) {
val isUseQualifiedModuleNames = currentExternalProjectSettings.isUseQualifiedModuleNames
currentExternalProjectSettings.isUseQualifiedModuleNames = useQualifiedNames
try {
importProject()
} finally {
currentExternalProjectSettings.isUseQualifiedModuleNames = isUseQualifiedModuleNames
}
}
override fun importProject() {
val isCreateEmptyContentRootDirectories = currentExternalProjectSettings.isCreateEmptyContentRootDirectories
currentExternalProjectSettings.isCreateEmptyContentRootDirectories = true
try {
super.importProject()
} finally {
currentExternalProjectSettings.isCreateEmptyContentRootDirectories = isCreateEmptyContentRootDirectories
}
}
override fun testDataDirName(): String {
return "newMultiplatformImport"
}
}
@@ -1,13 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.gradle
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.kotlin.idea.codeInsight.gradle.MultiplePluginVersionGradleImportingTestCase
fun MultiplePluginVersionGradleImportingTestCase.findTasksToRun(file: VirtualFile): List<String>? {
return null
}
@@ -1,261 +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.google.common.collect.Multimap;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.io.StreamUtil;
import com.intellij.testFramework.IdeaTestUtil;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import org.codehaus.groovy.runtime.typehandling.ShortTypeHandling;
import org.gradle.tooling.BuildActionExecuter;
import org.gradle.tooling.GradleConnector;
import org.gradle.tooling.ProjectConnection;
import org.gradle.tooling.internal.consumer.DefaultGradleConnector;
import org.gradle.tooling.model.DomainObjectSet;
import org.gradle.tooling.model.idea.IdeaModule;
import org.gradle.util.GradleVersion;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.gradle.model.ExternalProject;
import org.jetbrains.plugins.gradle.model.ProjectImportAction;
import org.jetbrains.plugins.gradle.service.execution.GradleExecutionHelper;
import org.jetbrains.plugins.gradle.tooling.builder.ModelBuildScriptClasspathBuilderImpl;
import org.jetbrains.plugins.gradle.util.GradleConstants;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.TestName;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assume.assumeThat;
// part of org.jetbrains.plugins.gradle.tooling.builder.AbstractModelBuilderTest
@RunWith(value = Parameterized.class)
public abstract class AbstractModelBuilderTest {
public static final Object[][] SUPPORTED_GRADLE_VERSIONS = {{"4.9"}};
private static final Pattern TEST_METHOD_NAME_PATTERN = Pattern.compile("(.*)\\[(\\d*: with Gradle-.*)\\]");
private static File ourTempDir;
@NotNull
private final String gradleVersion;
private File testDir;
private ProjectImportAction.AllModels allModels;
@Rule public TestName name = new TestName();
@Rule public VersionMatcherRule versionMatcherRule = new VersionMatcherRule();
public AbstractModelBuilderTest(@NotNull String gradleVersion) {
this.gradleVersion = gradleVersion;
}
@Parameterized.Parameters(name = "{index}: with Gradle-{0}")
public static Collection<Object[]> data() {
return Arrays.asList(SUPPORTED_GRADLE_VERSIONS);
}
@Before
public void setUp() throws Exception {
assumeThat(gradleVersion, versionMatcherRule.getMatcher());
ensureTempDirCreated();
String methodName = name.getMethodName();
Matcher m = TEST_METHOD_NAME_PATTERN.matcher(methodName);
if (m.matches()) {
methodName = m.group(1);
}
testDir = new File(ourTempDir, methodName);
FileUtil.ensureExists(testDir);
InputStream buildScriptStream = getClass().getResourceAsStream("/" + methodName + "/" + GradleConstants.DEFAULT_SCRIPT_NAME);
try {
FileUtil.writeToFile(
new File(testDir, GradleConstants.DEFAULT_SCRIPT_NAME),
FileUtil.loadTextAndClose(buildScriptStream)
);
}
finally {
StreamUtil.closeStream(buildScriptStream);
}
InputStream settingsStream = getClass().getResourceAsStream("/" + methodName + "/" + GradleConstants.SETTINGS_FILE_NAME);
try {
if (settingsStream != null) {
FileUtil.writeToFile(
new File(testDir, GradleConstants.SETTINGS_FILE_NAME),
FileUtil.loadTextAndClose(settingsStream)
);
}
}
finally {
StreamUtil.closeStream(settingsStream);
}
GradleConnector connector = GradleConnector.newConnector();
URI distributionUri = new DistributionLocator().getDistributionFor(GradleVersion.version(gradleVersion));
connector.useDistribution(distributionUri);
connector.forProjectDirectory(testDir);
int daemonMaxIdleTime = 10;
try {
daemonMaxIdleTime = Integer.parseInt(System.getProperty("gradleDaemonMaxIdleTime", "10"));
}
catch (NumberFormatException ignore) {
}
((DefaultGradleConnector) connector).daemonMaxIdleTime(daemonMaxIdleTime, TimeUnit.SECONDS);
ProjectConnection connection = connector.connect();
try {
ProjectImportAction projectImportAction = new ProjectImportAction(false);
projectImportAction.addExtraProjectModelClasses(getModels());
BuildActionExecuter<ProjectImportAction.AllModels> buildActionExecutor = connection.action(projectImportAction);
File initScript = GradleExecutionHelper.generateInitScript(false, getToolingExtensionClasses());
assertNotNull(initScript);
String jdkHome = IdeaTestUtil.requireRealJdkHome();
buildActionExecutor.setJavaHome(new File(jdkHome));
buildActionExecutor.setJvmArguments("-Xmx128m", "-XX:MaxPermSize=64m");
buildActionExecutor
.withArguments("--info", "--recompile-scripts", GradleConstants.INIT_SCRIPT_CMD_OPTION, initScript.getAbsolutePath());
allModels = buildActionExecutor.run();
assertNotNull(allModels);
}
finally {
connection.close();
}
}
@NotNull
private static Set<Class> getToolingExtensionClasses() {
Set<Class> classes = ContainerUtil.<Class>set(
ExternalProject.class,
// gradle-tooling-extension-api jar
ProjectImportAction.class,
// gradle-tooling-extension-impl jar
ModelBuildScriptClasspathBuilderImpl.class,
Multimap.class,
ShortTypeHandling.class
);
ContainerUtil.addAllNotNull(classes, doGetToolingExtensionClasses());
return classes;
}
@NotNull
private static Set<Class> doGetToolingExtensionClasses() {
return Collections.emptySet();
}
@After
public void tearDown() throws Exception {
if (testDir != null) {
FileUtil.delete(testDir);
}
}
protected abstract Set<Class> getModels();
private <T> Map<String, T> getModulesMap(final Class<T> aClass) {
DomainObjectSet<? extends IdeaModule> ideaModules = allModels.getIdeaProject().getModules();
final String filterKey = "to_filter";
Map<String, T> map = ContainerUtil.map2Map(ideaModules, new Function<IdeaModule, Pair<String, T>>() {
@Override
public Pair<String, T> fun(IdeaModule module) {
T value = allModels.getExtraProject(module, aClass);
String key = value != null ? module.getGradleProject().getPath() : filterKey;
return Pair.create(key, value);
}
});
map.remove(filterKey);
return map;
}
private static void ensureTempDirCreated() throws IOException {
if (ourTempDir != null) return;
ourTempDir = new File(FileUtil.getTempDirectory(), "gradleTests");
FileUtil.delete(ourTempDir);
FileUtil.ensureExists(ourTempDir);
}
public static class DistributionLocator {
private static final String RELEASE_REPOSITORY_ENV = "GRADLE_RELEASE_REPOSITORY";
private static final String SNAPSHOT_REPOSITORY_ENV = "GRADLE_SNAPSHOT_REPOSITORY";
private static final String GRADLE_RELEASE_REPO = "https://services.gradle.org/distributions";
private static final String GRADLE_SNAPSHOT_REPO = "https://services.gradle.org/distributions-snapshots";
@NotNull private final String myReleaseRepoUrl;
@NotNull private final String mySnapshotRepoUrl;
public DistributionLocator() {
this(DistributionLocator.getRepoUrl(false), DistributionLocator.getRepoUrl(true));
}
public DistributionLocator(@NotNull String releaseRepoUrl, @NotNull String snapshotRepoUrl) {
myReleaseRepoUrl = releaseRepoUrl;
mySnapshotRepoUrl = snapshotRepoUrl;
}
@NotNull
public URI getDistributionFor(@NotNull GradleVersion version) throws URISyntaxException {
return getDistribution(getDistributionRepository(version), version, "gradle", "bin");
}
@NotNull
private String getDistributionRepository(@NotNull GradleVersion version) {
return version.isSnapshot() ? mySnapshotRepoUrl : myReleaseRepoUrl;
}
private static URI getDistribution(
@NotNull String repositoryUrl,
@NotNull GradleVersion version,
@NotNull String archiveName,
@NotNull String archiveClassifier
) throws URISyntaxException {
return new URI(String.format("%s/%s-%s-%s.zip", repositoryUrl, archiveName, version.getVersion(), archiveClassifier));
}
@NotNull
public static String getRepoUrl(boolean isSnapshotUrl) {
String envRepoUrl = System.getenv(isSnapshotUrl ? SNAPSHOT_REPOSITORY_ENV : RELEASE_REPOSITORY_ENV);
if (envRepoUrl != null) return envRepoUrl;
return isSnapshotUrl ? GRADLE_SNAPSHOT_REPO : GRADLE_RELEASE_REPO;
}
}
}
@@ -1,8 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.codeInsight.gradle
fun isGradleInspectionTestApplicable() = false
@@ -1,30 +0,0 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.config
import org.jetbrains.jps.model.ex.JpsElementTypeBase
import org.jetbrains.jps.model.java.JavaResourceRootProperties
import org.jetbrains.jps.model.java.JavaResourceRootType
import org.jetbrains.jps.model.java.JpsJavaExtensionService
import org.jetbrains.jps.model.module.JpsModuleSourceRootType
sealed class KotlinResourceRootType(val isTest: Boolean) : JpsElementTypeBase<JavaResourceRootProperties>(),
JpsModuleSourceRootType<JavaResourceRootProperties>, KotlinRootType {
override fun createDefaultProperties() =
JpsJavaExtensionService.getInstance().createResourceRootProperties("", false)
override fun isTestRoot() = isTest
override fun isForTests() = isTest
override fun equals(other: Any?) = if (super.equals(other)) true else isSameRootType(this, other)
}
object ResourceKotlinRootType : KotlinResourceRootType(false)
object TestResourceKotlinRootType : KotlinResourceRootType(true)
val ALL_KOTLIN_RESOURCE_ROOT_TYPES = setOf(ResourceKotlinRootType, TestResourceKotlinRootType)
@@ -1,28 +0,0 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.config
import org.jetbrains.jps.model.ex.JpsElementTypeBase
import org.jetbrains.jps.model.java.JavaResourceRootProperties
import org.jetbrains.jps.model.java.JavaResourceRootType
import org.jetbrains.jps.model.java.JpsJavaExtensionService
import org.jetbrains.jps.model.module.JpsModuleSourceRootType
sealed class KotlinResourceRootType(val isTest: Boolean) : JpsElementTypeBase<JavaResourceRootProperties>(),
JpsModuleSourceRootType<JavaResourceRootProperties>, KotlinRootType {
override fun createDefaultProperties() =
JpsJavaExtensionService.getInstance().createResourceRootProperties("", false)
override fun isTestRoot() = isTest
override fun equals(other: Any?) = if (super.equals(other)) true else isSameRootType(this, other)
}
object ResourceKotlinRootType : KotlinResourceRootType(false)
object TestResourceKotlinRootType : KotlinResourceRootType(true)
val ALL_KOTLIN_RESOURCE_ROOT_TYPES = setOf(ResourceKotlinRootType, TestResourceKotlinRootType)
@@ -1,24 +0,0 @@
package org.jetbrains.kotlin.config
import org.jetbrains.jps.model.java.JavaResourceRootType
import org.jetbrains.jps.model.java.JavaSourceRootType
interface KotlinRootType {
fun isTestRoot(): Boolean
}
//Hack required to fix critical bug KT-27718 it should be removed after support of source root types other than JavaSourceRootType in Idea Core
fun isSameRootType(kotlinRoot: KotlinRootType, other: Any?): Boolean {
if (kotlinRoot.isTestRoot()) {
if (other is JavaResourceRootType || other is JavaSourceRootType) {
val invokeLevel = 3
val stack = Thread.currentThread().stackTrace
if (stack.size > invokeLevel && "isTestSource" == stack[invokeLevel].methodName && "com.intellij.openapi.roots.impl.SourceFolderImpl" == stack[invokeLevel].className) {
if (JavaResourceRootType.TEST_RESOURCE == other || JavaSourceRootType.TEST_SOURCE == other) {
return true
}
}
}
}
return false
}
@@ -1,31 +0,0 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.config
import org.jetbrains.jps.model.ex.JpsElementTypeBase
import org.jetbrains.jps.model.java.JavaSourceRootProperties
import org.jetbrains.jps.model.java.JavaSourceRootType
import org.jetbrains.jps.model.java.JpsJavaExtensionService
import org.jetbrains.jps.model.module.JpsModuleSourceRootType
sealed class KotlinSourceRootType(val isTest: Boolean) : JpsElementTypeBase<JavaSourceRootProperties>(), JpsModuleSourceRootType<JavaSourceRootProperties>, KotlinRootType {
override fun createDefaultProperties() = JpsJavaExtensionService.getInstance().createSourceRootProperties("")
override fun isTestRoot() = isTest
override fun isForTests() = isTest
override fun equals(other: Any?) = if (super.equals(other)) true else isSameRootType(this, other)
}
object SourceKotlinRootType : KotlinSourceRootType(false)
object TestSourceKotlinRootType : KotlinSourceRootType(true)
val ALL_KOTLIN_SOURCE_ROOT_TYPES = setOf(SourceKotlinRootType, TestSourceKotlinRootType)
@@ -1,31 +0,0 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.config
import org.jetbrains.jps.model.ex.JpsElementTypeBase
import org.jetbrains.jps.model.java.JavaSourceRootProperties
import org.jetbrains.jps.model.java.JavaSourceRootType
import org.jetbrains.jps.model.java.JpsJavaExtensionService
import org.jetbrains.jps.model.module.JpsModuleSourceRootType
sealed class KotlinSourceRootType(val isTest: Boolean) : JpsElementTypeBase<JavaSourceRootProperties>(), JpsModuleSourceRootType<JavaSourceRootProperties>, KotlinRootType {
override fun createDefaultProperties() = JpsJavaExtensionService.getInstance().createSourceRootProperties("")
override fun isTestRoot() = isTest
fun isForTests() = isTest
override fun equals(other: Any?) = if (super.equals(other)) true else isSameRootType(this, other)
}
object SourceKotlinRootType : KotlinSourceRootType(false)
object TestSourceKotlinRootType : KotlinSourceRootType(true)
val ALL_KOTLIN_SOURCE_ROOT_TYPES = setOf(SourceKotlinRootType, TestSourceKotlinRootType)
@@ -1,13 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.scratch.output
import com.intellij.openapi.command.CommandProcessor
// BUNCH: 183
fun executeCommand(command: () -> Unit) {
CommandProcessor.getInstance().executeCommand(null, command, null, null)
}
@@ -1,19 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
@file:Suppress("UnstableApiUsage")
package org.jetbrains.kotlin.idea.scratch.output
import com.intellij.openapi.editor.InlayModel
// BUNCH: 183
fun InlayModel.addInlay(offset: Int, renderer: InlayScratchFileRenderer) {
addInlineElement(offset, true, renderer)
}
// BUNCH: 183
fun InlayModel.getInlays(start: Int, end: Int) =
getInlineElementsInRange(start, end).filter { it.renderer is InlayScratchFileRenderer }
@@ -1,79 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.scratch.ui
import com.intellij.execution.ui.ConfigurationModuleSelector
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.ModuleType
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.vcs.changes.committed.LabeledComboBoxAction
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.project.productionSourceInfo
import org.jetbrains.kotlin.idea.caches.project.testSourceInfo
import org.jetbrains.kotlin.idea.scratch.ScratchFile
import org.jetbrains.kotlin.idea.scratch.isKotlinWorksheet
import javax.swing.JComponent
class ModulesComboBoxAction(private val scratchFile: ScratchFile) : LabeledComboBoxAction(KotlinBundle.message("scratch.module.combobox")) {
override fun createPopupActionGroup(button: JComponent): DefaultActionGroup {
val actionGroup = DefaultActionGroup()
actionGroup.add(ModuleIsNotSelectedAction(ConfigurationModuleSelector.NO_MODULE_TEXT))
val modules = ModuleManager.getInstance(scratchFile.project).modules.filter {
it.productionSourceInfo() != null || it.testSourceInfo() != null
}
actionGroup.addAll(modules.map { SelectModuleAction(it) })
return actionGroup
}
/**
* By default this action uses big font for label, so we have to decrease it
* to make it look the same as in [CheckboxAction].
*/
override fun createCustomComponent(presentation: Presentation): JComponent {
val customComponent = super.createCustomComponent(presentation)
customComponent.components.forEach { it.font = UIUtil.getFont(UIUtil.FontSize.SMALL, it.font) }
return customComponent
}
override fun update(e: AnActionEvent) {
super.update(e)
val selectedModule = scratchFile.module?.takeIf { !it.isDisposed }
e.presentation.apply {
icon = selectedModule?.let { ModuleType.get(it).icon }
text = selectedModule?.name ?: ConfigurationModuleSelector.NO_MODULE_TEXT
}
e.presentation.isVisible = isModuleSelectorVisible()
}
@TestOnly
fun isModuleSelectorVisible(): Boolean {
return !scratchFile.file.isKotlinWorksheet
}
private inner class ModuleIsNotSelectedAction(placeholder: String) : DumbAwareAction(placeholder) {
override fun actionPerformed(e: AnActionEvent) {
scratchFile.setModule(null)
}
}
private inner class SelectModuleAction(private val module: Module) :
DumbAwareAction(module.name, null, ModuleType.get(module).icon) {
override fun actionPerformed(e: AnActionEvent) {
scratchFile.setModule(module)
}
}
}
@@ -1,19 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.scratch.ui
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.actionSystem.ex.CheckboxAction
import com.intellij.util.ui.JBUI
import javax.swing.JComponent
abstract class SmallBorderCheckboxAction(text: String, description: String? = null) : CheckboxAction(text, description, null) {
override fun createCustomComponent(presentation: Presentation): JComponent {
val checkbox = super.createCustomComponent(presentation)
checkbox.border = JBUI.Borders.emptyRight(4)
return checkbox
}
}
@@ -1,21 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.maven
import com.intellij.openapi.util.AsyncResult
import org.jetbrains.idea.maven.model.MavenArtifact
import org.jetbrains.idea.maven.project.MavenProject
import org.jetbrains.idea.maven.project.MavenProjectsManager
//BUNCH: 183
fun scheduleArtifactsDownloading(
projectsManager: MavenProjectsManager,
projects: List<MavenProject>,
toBeDownloaded: List<MavenArtifact>
) {
//true, false, AsyncResult()
projectsManager.scheduleArtifactsDownloading(projects, toBeDownloaded, true, false, AsyncResult())
}
@@ -1,8 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.debugger.filter
class KotlinSyntheticTypeComponentProvider : KotlinSyntheticTypeComponentProviderBase()
@@ -1,102 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.testFramework
import com.intellij.ide.startup.impl.StartupManagerImpl
import com.intellij.lang.LanguageAnnotators
import com.intellij.lang.LanguageExtensionPoint
import com.intellij.lang.annotation.Annotator
import com.intellij.openapi.Disposable
import com.intellij.openapi.editor.Document
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.openapi.startup.StartupManager
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.impl.PsiDocumentManagerBase
import com.intellij.testFramework.EdtTestUtil
import com.intellij.testFramework.PlatformTestUtil
import com.intellij.testFramework.runInEdtAndWait
import com.intellij.util.ThrowableRunnable
import com.intellij.util.ui.UIUtil
import org.jetbrains.kotlin.idea.parameterInfo.HintType
import java.io.PrintWriter
import java.io.StringWriter
fun commitAllDocuments() {
ProjectManagerEx.getInstanceEx().openProjects.forEach { project ->
val psiDocumentManagerBase = PsiDocumentManager.getInstance(project) as PsiDocumentManagerBase
EdtTestUtil.runInEdtAndWait(ThrowableRunnable {
psiDocumentManagerBase.clearUncommittedDocuments()
psiDocumentManagerBase.commitAllDocuments()
})
}
}
fun commitDocument(project: Project, document: Document) {
val psiDocumentManagerBase = PsiDocumentManager.getInstance(project) as PsiDocumentManagerBase
EdtTestUtil.runInEdtAndWait(ThrowableRunnable {
psiDocumentManagerBase.commitDocument(document)
})
}
fun saveDocument(document: Document) {
val fileDocumentManager = FileDocumentManager.getInstance()
runInEdtAndWait {
fileDocumentManager.saveDocument(document)
}
}
fun enableHints(enable: Boolean) =
HintType.values().forEach { it.option.set(enable) }
fun dispatchAllInvocationEvents() {
runInEdtAndWait {
UIUtil.dispatchAllInvocationEvents()
}
}
fun loadProjectWithName(path: String, name: String): Project? =
ProjectManagerEx.getInstanceEx().loadProject(name, path)
fun closeProject(project: Project) {
dispatchAllInvocationEvents()
val projectManagerEx = ProjectManagerEx.getInstanceEx()
projectManagerEx.closeAndDispose(project)
}
fun runStartupActivities(project: Project) {
with(StartupManager.getInstance(project) as StartupManagerImpl) {
scheduleInitialVfsRefresh()
runStartupActivities()
runPostStartupActivities()
}
}
fun waitForAllEditorsFinallyLoaded(project: Project) {
// 183 does not have this public api
}
// BUNCH: 183
fun replaceWithCustomHighlighter(parentDisposable: Disposable, fromImplementationClass: String, toImplementationClass: String) {
// 183 does not have this public api
}
fun logMessage(message: () -> String) {
println("-- ${message()}")
}
fun logMessage(t: Throwable, message: () -> String) {
val writer = StringWriter()
PrintWriter(writer).use {
t.printStackTrace(it)
}
println("-- ${message()}:\n$writer")
}
@@ -1,5 +0,0 @@
<idea-plugin>
<extensions defaultExtensionNs="com.intellij">
<externalAnnotator language="kotlin" implementationClass="org.jetbrains.android.inspections.lint.AndroidLintExternalAnnotator"/>
</extensions>
</idea-plugin>
@@ -1,131 +0,0 @@
<idea-plugin>
<extensionPoints>
<extensionPoint qualifiedName="org.jetbrains.kotlin.updater" beanClass="com.intellij.openapi.fileTypes.FileTypeExtensionPoint"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.projectConfigurator" interface="org.jetbrains.kotlin.idea.configuration.KotlinProjectConfigurator"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.declarationAttributeAltererExtension"
interface="org.jetbrains.kotlin.extensions.DeclarationAttributeAltererExtension"
area="IDEA_PROJECT"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.androidDexer"
interface="org.jetbrains.kotlin.idea.debugger.evaluate.classLoading.AndroidDexer"
area="IDEA_PROJECT"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.android.model.androidModuleInfoProvider"
interface="org.jetbrains.kotlin.android.model.AndroidModuleInfoProvider"
area="IDEA_MODULE"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.idePlatformKindResolution"
interface="org.jetbrains.kotlin.caches.resolve.IdePlatformKindResolution"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.highlighterExtension"
interface="org.jetbrains.kotlin.idea.highlighter.HighlighterExtension"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.ultraLightClassModifierExtension"
interface="org.jetbrains.kotlin.asJava.UltraLightClassModifierExtension"
area="IDEA_PROJECT"/>
<extensionPoint name="scratchFileLanguageProvider" beanClass="com.intellij.lang.LanguageExtensionPoint">
<with attribute="implementationClass" implements="org.jetbrains.kotlin.idea.scratch.ScratchFileLanguageProvider"/>
</extensionPoint>
<extensionPoint qualifiedName="org.jetbrains.kotlin.binaryExtension"
interface="org.jetbrains.kotlin.idea.util.KotlinBinaryExtension"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.facetValidatorCreator"
interface="org.jetbrains.kotlin.idea.facet.KotlinFacetValidatorCreator"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.clearBuildState"
interface="org.jetbrains.kotlin.idea.compiler.configuration.ClearBuildStateExtension"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.newFileHook"
interface="org.jetbrains.kotlin.idea.actions.NewKotlinFileHook"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.completionExtension"
interface="org.jetbrains.kotlin.idea.completion.KotlinCompletionExtension"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.buildSystemTypeDetector"
interface="org.jetbrains.kotlin.idea.configuration.BuildSystemTypeDetector"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.idePlatformKind"
interface="org.jetbrains.kotlin.platform.IdePlatformKind"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.idePlatformKindTooling"
interface="org.jetbrains.kotlin.idea.platform.IdePlatformKindTooling"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.scriptAdditionalIdeaDependenciesProvider"
interface="org.jetbrains.kotlin.idea.core.script.dependencies.ScriptAdditionalIdeaDependenciesProvider"
area="IDEA_PROJECT"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.scriptDefinitionsProvider"
interface="kotlin.script.experimental.intellij.ScriptDefinitionsProvider"
area="IDEA_PROJECT"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.syntheticScopeProviderExtension"
interface="org.jetbrains.kotlin.synthetic.SyntheticScopeProviderExtension"
area="IDEA_PROJECT"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.resolveScopeEnlarger"
interface="org.jetbrains.kotlin.idea.caches.resolve.util.KotlinResolveScopeEnlarger"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.j2kConverterExtension"
interface="org.jetbrains.kotlin.j2k.J2kConverterExtension"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.scriptDiagnosticFixProvider"
interface="org.jetbrains.kotlin.idea.script.ScriptDiagnosticFixProvider"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.scripting.idea.loader"
interface="org.jetbrains.kotlin.idea.core.script.configuration.loader.ScriptConfigurationLoader"
area="IDEA_PROJECT"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.scripting.idea.listener"
interface="org.jetbrains.kotlin.idea.core.script.configuration.listener.ScriptChangeListener"
area="IDEA_PROJECT"/>
</extensionPoints>
<extensions defaultExtensionNs="org.jetbrains.kotlin">
<projectConfigurator implementation="org.jetbrains.kotlin.idea.configuration.KotlinJavaModuleConfigurator"/>
<projectConfigurator implementation="org.jetbrains.kotlin.idea.configuration.KotlinJsModuleConfigurator"/>
<scriptDefinitionContributor
id="ScriptTemplatesFromCompilerSettingsProvider"
implementation="org.jetbrains.kotlin.idea.script.ScriptTemplatesFromCompilerSettingsProvider"/>
<scriptDefinitionContributor
id="BridgeScriptDefinitionsContributor"
implementation="org.jetbrains.kotlin.idea.script.BridgeScriptDefinitionsContributor"/>
<scriptDefinitionContributor
id="ScriptTemplatesFromDependenciesProvider"
implementation="org.jetbrains.kotlin.idea.script.ScriptTemplatesFromDependenciesProvider"/>
<scriptDefinitionContributor id="StandardScriptDefinitionContributor"
order="last"
implementation="org.jetbrains.kotlin.idea.core.script.StandardScriptDefinitionContributor"/>
<scriptDefinitionContributor id="ConsoleScriptDefinitionContributor"
implementation="org.jetbrains.kotlin.console.ConsoleScriptDefinitionContributor"/>
<idePlatformKindResolution implementation="org.jetbrains.kotlin.caches.resolve.JvmPlatformKindResolution"/>
<idePlatformKindResolution implementation="org.jetbrains.kotlin.caches.resolve.JsPlatformKindResolution"/>
<idePlatformKindResolution implementation="org.jetbrains.kotlin.caches.resolve.CommonPlatformKindResolution"/>
<scratchFileLanguageProvider language="kotlin" implementationClass="org.jetbrains.kotlin.idea.scratch.KtScratchFileLanguageProvider"/>
<scriptAdditionalIdeaDependenciesProvider implementation="org.jetbrains.kotlin.idea.scratch.ScratchAdditionalIdeaDependenciesProvider"/>
<j2kConverterExtension implementation="org.jetbrains.kotlin.idea.j2k.OldJ2kConverterExtension"/>
<j2kConverterExtension implementation="org.jetbrains.kotlin.nj2k.NewJ2kConverterExtension"/>
</extensions>
<extensions defaultExtensionNs="com.intellij">
<registryKey key="kotlin.android.import.mpp.all.transitive"
description="Add all transitive dependencies on MPP modules when Android project is imported"
defaultValue="true"
restartRequired="false"/>
<registryKey key="kotlin.use.fir.resolution"
description="Use Kotlin resolution via frontend IR for reference resolve and diagnostics in IDEA"
defaultValue="false"
restartRequired="true"/>
<fileEditorProvider implementation="org.jetbrains.kotlin.idea.scratch.ui.KtScratchFileEditorProvider"/>
<registryKey key="kotlin.experimental.project.wizard"
description="Use experimental project wizard for creating new Kotlin projects"
defaultValue="false"
restartRequired="false"/>
<moduleBuilder builderClass="org.jetbrains.kotlin.tools.projectWizard.wizard.NewProjectWizardModuleBuilder"/>
</extensions>
</idea-plugin>
@@ -1,122 +0,0 @@
<idea-plugin>
<extensionPoints>
<extensionPoint qualifiedName="org.jetbrains.kotlin.updater" beanClass="com.intellij.openapi.fileTypes.FileTypeExtensionPoint"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.projectConfigurator" interface="org.jetbrains.kotlin.idea.configuration.KotlinProjectConfigurator"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.declarationAttributeAltererExtension"
interface="org.jetbrains.kotlin.extensions.DeclarationAttributeAltererExtension"
area="IDEA_PROJECT"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.idePlatformKindResolution"
interface="org.jetbrains.kotlin.caches.resolve.IdePlatformKindResolution"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.highlighterExtension"
interface="org.jetbrains.kotlin.idea.highlighter.HighlighterExtension"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.lightClassApplicabilityCheckExtension"
interface="org.jetbrains.kotlin.extensions.LightClassApplicabilityCheckExtension"
area="IDEA_PROJECT"/>
<extensionPoint name="scratchFileLanguageProvider" beanClass="com.intellij.lang.LanguageExtensionPoint">
<with attribute="implementationClass" implements="org.jetbrains.kotlin.idea.scratch.ScratchFileLanguageProvider"/>
</extensionPoint>
<extensionPoint qualifiedName="org.jetbrains.kotlin.binaryExtension"
interface="org.jetbrains.kotlin.idea.util.KotlinBinaryExtension"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.facetValidatorCreator"
interface="org.jetbrains.kotlin.idea.facet.KotlinFacetValidatorCreator"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.clearBuildState"
interface="org.jetbrains.kotlin.idea.compiler.configuration.ClearBuildStateExtension"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.newFileHook"
interface="org.jetbrains.kotlin.idea.actions.NewKotlinFileHook"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.completionExtension"
interface="org.jetbrains.kotlin.idea.completion.KotlinCompletionExtension"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.buildSystemTypeDetector"
interface="org.jetbrains.kotlin.idea.configuration.BuildSystemTypeDetector"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.idePlatformKind"
interface="org.jetbrains.kotlin.platform.IdePlatformKind"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.idePlatformKindTooling"
interface="org.jetbrains.kotlin.idea.platform.IdePlatformKindTooling"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.scriptAdditionalIdeaDependenciesProvider"
interface="org.jetbrains.kotlin.idea.core.script.dependencies.ScriptAdditionalIdeaDependenciesProvider"
area="IDEA_PROJECT"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.scriptDefinitionsProvider"
interface="kotlin.script.experimental.intellij.ScriptDefinitionsProvider"
area="IDEA_PROJECT"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.syntheticScopeProviderExtension"
interface="org.jetbrains.kotlin.synthetic.SyntheticScopeProviderExtension"
area="IDEA_PROJECT"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.resolveScopeEnlarger"
interface="org.jetbrains.kotlin.idea.caches.resolve.util.KotlinResolveScopeEnlarger"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.j2kConverterExtension"
interface="org.jetbrains.kotlin.j2k.J2kConverterExtension"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.scriptDiagnosticFixProvider"
interface="org.jetbrains.kotlin.idea.script.ScriptDiagnosticFixProvider"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.scripting.idea.loader"
interface="org.jetbrains.kotlin.idea.core.script.configuration.loader.ScriptConfigurationLoader"
area="IDEA_PROJECT"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.scripting.idea.listener"
interface="org.jetbrains.kotlin.idea.core.script.configuration.listener.ScriptChangeListener"
area="IDEA_PROJECT"/>
</extensionPoints>
<extensions defaultExtensionNs="org.jetbrains.kotlin">
<projectConfigurator implementation="org.jetbrains.kotlin.idea.configuration.KotlinJavaModuleConfigurator"/>
<projectConfigurator implementation="org.jetbrains.kotlin.idea.configuration.KotlinJsModuleConfigurator"/>
<scriptDefinitionContributor
id="ScriptTemplatesFromCompilerSettingsProvider"
implementation="org.jetbrains.kotlin.idea.script.ScriptTemplatesFromCompilerSettingsProvider"/>
<scriptDefinitionContributor
id="BridgeScriptDefinitionsContributor"
implementation="org.jetbrains.kotlin.idea.script.BridgeScriptDefinitionsContributor"/>
<scriptDefinitionContributor
id="ScriptTemplatesFromDependenciesProvider"
implementation="org.jetbrains.kotlin.idea.script.ScriptTemplatesFromDependenciesProvider"/>
<scriptDefinitionContributor id="StandardScriptDefinitionContributor"
order="last"
implementation="org.jetbrains.kotlin.idea.core.script.StandardScriptDefinitionContributor"/>
<scriptDefinitionContributor id="ConsoleScriptDefinitionContributor"
implementation="org.jetbrains.kotlin.console.ConsoleScriptDefinitionContributor"/>
<idePlatformKindResolution implementation="org.jetbrains.kotlin.caches.resolve.JvmPlatformKindResolution"/>
<idePlatformKindResolution implementation="org.jetbrains.kotlin.caches.resolve.JsPlatformKindResolution"/>
<idePlatformKindResolution implementation="org.jetbrains.kotlin.caches.resolve.CommonPlatformKindResolution"/>
<scratchFileLanguageProvider language="kotlin" implementationClass="org.jetbrains.kotlin.idea.scratch.KtScratchFileLanguageProvider"/>
<scriptAdditionalIdeaDependenciesProvider implementation="org.jetbrains.kotlin.idea.scratch.ScratchAdditionalIdeaDependenciesProvider"/>
<j2kConverterExtension implementation="org.jetbrains.kotlin.idea.j2k.OldJ2kConverterExtension"/>
<j2kConverterExtension implementation="org.jetbrains.kotlin.nj2k.NewJ2kConverterExtension"/>
</extensions>
<extensions defaultExtensionNs="com.intellij">
<registryKey key="kotlin.android.import.mpp.all.transitive"
description="Add all transitive dependencies on MPP modules when Android project is imported"
defaultValue="true"
restartRequired="false"/>
<registryKey key="kotlin.use.fir.resolution"
description="Use Kotlin resolution via frontend IR for reference resolve and diagnostics in IDEA"
defaultValue="false"
restartRequired="true"/>
<fileEditorProvider implementation="org.jetbrains.kotlin.idea.scratch.ui.KtScratchFileEditorProvider"/>
<registryKey key="kotlin.experimental.project.wizard"
description="Use experimental project wizard for creating new Kotlin projects"
defaultValue="false"
restartRequired="false"/>
<moduleBuilder builderClass="org.jetbrains.kotlin.tools.projectWizard.wizard.NewProjectWizardModuleBuilder"/>
</extensions>
</idea-plugin>
@@ -1,4 +0,0 @@
<idea-plugin>
<extensions defaultExtensionNs="Git4Idea">
</extensions>
</idea-plugin>
@@ -1,54 +0,0 @@
<idea-plugin>
<extensions defaultExtensionNs="org.jetbrains.plugins.gradle">
<frameworkSupport implementation="org.jetbrains.kotlin.idea.configuration.GradleKotlinMPPSourceSetsFrameworkSupportProvider"/>
<frameworkSupport implementation="org.jetbrains.kotlin.idea.configuration.GradleKotlinJavaFrameworkSupportProvider"/>
<frameworkSupport implementation="org.jetbrains.kotlin.idea.configuration.GradleKotlinJSBrowserFrameworkSupportProvider"/>
<frameworkSupport implementation="org.jetbrains.kotlin.idea.configuration.GradleKotlinJSNodeFrameworkSupportProvider"/>
<kotlinDslFrameworkSupport implementation="org.jetbrains.kotlin.idea.configuration.KotlinDslGradleKotlinMPPFrameworkSupportProvider"/>
<kotlinDslFrameworkSupport implementation="org.jetbrains.kotlin.idea.configuration.KotlinDslGradleKotlinJavaFrameworkSupportProvider"/>
<kotlinDslFrameworkSupport implementation="org.jetbrains.kotlin.idea.configuration.KotlinDslGradleKotlinJSBrowserFrameworkSupportProvider"/>
<kotlinDslFrameworkSupport implementation="org.jetbrains.kotlin.idea.configuration.KotlinDslGradleKotlinJSNodeFrameworkSupportProvider"/>
<pluginDescriptions implementation="org.jetbrains.kotlin.idea.configuration.KotlinGradlePluginDescription"/>
<projectResolve implementation="org.jetbrains.kotlin.idea.configuration.KotlinGradleProjectResolverExtension" order="first"/>
<projectResolve implementation="org.jetbrains.kotlin.kapt.idea.KaptProjectResolverExtension" order="last"/>
<projectResolve implementation="org.jetbrains.kotlin.allopen.ide.AllOpenProjectResolverExtension" order="last"/>
<projectResolve implementation="org.jetbrains.kotlin.noarg.ide.NoArgProjectResolverExtension" order="last"/>
<projectResolve implementation="org.jetbrains.kotlin.samWithReceiver.ide.SamWithReceiverProjectResolverExtension" order="last"/>
</extensions>
<extensions defaultExtensionNs="com.intellij">
<externalProjectDataService implementation="org.jetbrains.kotlin.idea.configuration.KotlinGradleSourceSetDataService"/>
<externalProjectDataService implementation="org.jetbrains.kotlin.idea.configuration.KotlinGradleProjectDataService"/>
<externalProjectDataService implementation="org.jetbrains.kotlin.idea.configuration.KotlinGradleLibraryDataService"/>
<externalProjectDataService implementation="org.jetbrains.kotlin.idea.configuration.KotlinTargetDataService"/>
<externalProjectDataService implementation="org.jetbrains.kotlin.idea.KotlinJavaMPPSourceSetDataService"/>
<externalProjectDataService implementation="org.jetbrains.kotlin.idea.configuration.KotlinNativeLibraryDataService"/>
<externalSystemTaskNotificationListener implementation="org.jetbrains.kotlin.idea.scripting.gradle.GradleScriptDefinitionsUpdater"/>
<runConfigurationProducer implementation="org.jetbrains.kotlin.idea.run.KotlinJvmTestClassGradleConfigurationProducer"/>
<runConfigurationProducer implementation="org.jetbrains.kotlin.idea.run.KotlinJvmTestMethodGradleConfigurationProducer"/>
<orderEnumerationHandlerFactory implementation="org.jetbrains.kotlin.android.KotlinAndroidGradleOrderEnumerationHandler$FactoryImpl" order="first"/>
</extensions>
<extensions defaultExtensionNs="org.jetbrains.kotlin">
<gradleProjectImportHandler implementation="org.jetbrains.kotlin.allopen.ide.AllOpenGradleProjectImportHandler"/>
<gradleProjectImportHandler implementation="org.jetbrains.kotlin.scripting.idea.plugin.ScriptingGradleProjectImportHandler"/>
<gradleProjectImportHandler implementation="org.jetbrains.kotlin.kapt.idea.KaptGradleProjectImportHandler"/>
<gradleProjectImportHandler implementation="org.jetbrains.kotlin.noarg.ide.NoArgGradleProjectImportHandler"/>
<gradleProjectImportHandler implementation="org.jetbrains.kotlin.samWithReceiver.ide.SamWithReceiverGradleProjectImportHandler"/>
<gradleProjectImportHandler implementation="org.jetbrains.kotlinx.serialization.idea.KotlinSerializationGradleImportHandler"/>
<projectConfigurator implementation="org.jetbrains.kotlin.idea.configuration.KotlinGradleModuleConfigurator"/>
<projectConfigurator implementation="org.jetbrains.kotlin.idea.configuration.KotlinJsGradleModuleConfigurator"/>
<gradleModelFacade implementation="org.jetbrains.kotlin.idea.inspections.gradle.DefaultGradleModelFacade"/>
<scriptDefinitionContributor implementation="org.jetbrains.kotlin.idea.scripting.gradle.GradleScriptDefinitionsContributor" order="first"/>
<scriptAdditionalIdeaDependenciesProvider implementation="org.jetbrains.kotlin.idea.scripting.gradle.GradleScriptAdditionalIdeaDependenciesProvider"/>
<moduleBuilder implementation="org.jetbrains.kotlin.ide.konan.gradle.KotlinGradleNativeMultiplatformModuleBuilder"/>
<moduleBuilder implementation="org.jetbrains.kotlin.idea.configuration.KotlinGradleSharedMultiplatformModuleBuilder"/>
<moduleBuilder implementation="org.jetbrains.kotlin.idea.configuration.KotlinGradleWebMultiplatformModuleBuilder"/>
<moduleBuilder implementation="org.jetbrains.kotlin.idea.configuration.KotlinGradleMobileMultiplatformModuleBuilder"/>
<moduleBuilder implementation="org.jetbrains.kotlin.idea.configuration.KotlinGradleMobileSharedMultiplatformModuleBuilder"/>
</extensions>
</idea-plugin>
@@ -1,54 +0,0 @@
<idea-plugin>
<extensions defaultExtensionNs="org.jetbrains.plugins.gradle">
<frameworkSupport implementation="org.jetbrains.kotlin.idea.configuration.GradleKotlinMPPSourceSetsFrameworkSupportProvider"/>
<frameworkSupport implementation="org.jetbrains.kotlin.idea.configuration.GradleKotlinJavaFrameworkSupportProvider"/>
<frameworkSupport implementation="org.jetbrains.kotlin.idea.configuration.GradleKotlinJSBrowserFrameworkSupportProvider"/>
<frameworkSupport implementation="org.jetbrains.kotlin.idea.configuration.GradleKotlinJSNodeFrameworkSupportProvider"/>
<kotlinDslFrameworkSupport implementation="org.jetbrains.kotlin.idea.configuration.KotlinDslGradleKotlinMPPFrameworkSupportProvider"/>
<kotlinDslFrameworkSupport implementation="org.jetbrains.kotlin.idea.configuration.KotlinDslGradleKotlinJavaFrameworkSupportProvider"/>
<kotlinDslFrameworkSupport implementation="org.jetbrains.kotlin.idea.configuration.KotlinDslGradleKotlinJSBrowserFrameworkSupportProvider"/>
<kotlinDslFrameworkSupport implementation="org.jetbrains.kotlin.idea.configuration.KotlinDslGradleKotlinJSNodeFrameworkSupportProvider"/>
<pluginDescriptions implementation="org.jetbrains.kotlin.idea.configuration.KotlinGradlePluginDescription"/>
<projectResolve implementation="org.jetbrains.kotlin.idea.configuration.KotlinGradleProjectResolverExtension" order="first"/>
<projectResolve implementation="org.jetbrains.kotlin.kapt.idea.KaptProjectResolverExtension" order="last"/>
<projectResolve implementation="org.jetbrains.kotlin.allopen.ide.AllOpenProjectResolverExtension" order="last"/>
<projectResolve implementation="org.jetbrains.kotlin.noarg.ide.NoArgProjectResolverExtension" order="last"/>
<projectResolve implementation="org.jetbrains.kotlin.samWithReceiver.ide.SamWithReceiverProjectResolverExtension" order="last"/>
</extensions>
<extensions defaultExtensionNs="com.intellij">
<externalProjectDataService implementation="org.jetbrains.kotlin.idea.configuration.KotlinGradleSourceSetDataService"/>
<externalProjectDataService implementation="org.jetbrains.kotlin.idea.configuration.KotlinGradleProjectDataService"/>
<externalProjectDataService implementation="org.jetbrains.kotlin.idea.configuration.KotlinGradleLibraryDataService"/>
<externalProjectDataService implementation="org.jetbrains.kotlin.idea.configuration.KotlinTargetDataService"/>
<externalProjectDataService implementation="org.jetbrains.kotlin.idea.KotlinJavaMPPSourceSetDataService"/>
<externalProjectDataService implementation="org.jetbrains.kotlin.idea.configuration.KotlinNativeLibraryDataService"/>
<externalSystemTaskNotificationListener implementation="org.jetbrains.kotlin.idea.scripting.gradle.GradleScriptDefinitionsUpdater"/>
<runConfigurationProducer implementation="org.jetbrains.kotlin.idea.run.KotlinJvmTestClassGradleConfigurationProducer"/>
<runConfigurationProducer implementation="org.jetbrains.kotlin.idea.run.KotlinJvmTestMethodGradleConfigurationProducer"/>
</extensions>
<extensions defaultExtensionNs="org.jetbrains.kotlin">
<gradleProjectImportHandler implementation="org.jetbrains.kotlin.allopen.ide.AllOpenGradleProjectImportHandler"/>
<gradleProjectImportHandler implementation="org.jetbrains.kotlin.scripting.idea.plugin.ScriptingGradleProjectImportHandler"/>
<gradleProjectImportHandler implementation="org.jetbrains.kotlin.kapt.idea.KaptGradleProjectImportHandler"/>
<gradleProjectImportHandler implementation="org.jetbrains.kotlin.noarg.ide.NoArgGradleProjectImportHandler"/>
<gradleProjectImportHandler implementation="org.jetbrains.kotlin.samWithReceiver.ide.SamWithReceiverGradleProjectImportHandler"/>
<gradleProjectImportHandler implementation="org.jetbrains.kotlinx.serialization.idea.KotlinSerializationGradleImportHandler"/>
<projectConfigurator implementation="org.jetbrains.kotlin.idea.configuration.KotlinGradleModuleConfigurator"/>
<projectConfigurator implementation="org.jetbrains.kotlin.idea.configuration.KotlinJsGradleModuleConfigurator"/>
<gradleModelFacade implementation="org.jetbrains.kotlin.idea.inspections.gradle.DefaultGradleModelFacade"/>
<scriptDefinitionContributor implementation="org.jetbrains.kotlin.idea.scripting.gradle.GradleScriptDefinitionsContributor" order="first"/>
<scriptAdditionalIdeaDependenciesProvider implementation="org.jetbrains.kotlin.idea.scripting.gradle.GradleScriptAdditionalIdeaDependenciesProvider"/>
<moduleBuilder implementation="org.jetbrains.kotlin.ide.konan.gradle.KotlinGradleNativeMultiplatformModuleBuilder"/>
<moduleBuilder implementation="org.jetbrains.kotlin.idea.configuration.KotlinGradleSharedMultiplatformModuleBuilder"/>
<moduleBuilder implementation="org.jetbrains.kotlin.idea.configuration.KotlinGradleWebMultiplatformModuleBuilder"/>
<moduleBuilder implementation="org.jetbrains.kotlin.idea.configuration.KotlinGradleMobileMultiplatformModuleBuilder"/>
<moduleBuilder implementation="org.jetbrains.kotlin.idea.configuration.KotlinGradleMobileSharedMultiplatformModuleBuilder"/>
</extensions>
</idea-plugin>
-43
View File
@@ -1,43 +0,0 @@
<idea-plugin>
<extensionPoints>
<extensionPoint qualifiedName="org.jetbrains.kotlin.gradleProjectImportHandler" area="IDEA_PROJECT"
interface="org.jetbrains.kotlin.idea.configuration.GradleProjectImportHandler"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.gradleModelFacade"
interface="org.jetbrains.kotlin.idea.inspections.gradle.KotlinGradleModelFacade"/>
</extensionPoints>
<extensions defaultExtensionNs="org.jetbrains.kotlin">
<buildSystemTypeDetector implementation="org.jetbrains.kotlin.idea.configuration.GradleDetector"/>
<scriptDiagnosticFixProvider implementation="org.jetbrains.kotlin.idea.scripting.gradle.GradleScriptDiagnosticFixProvider"/>
</extensions>
<extensions defaultExtensionNs="org.jetbrains.kotlin.scripting.idea">
<listener order="first" implementation="org.jetbrains.kotlin.idea.scripting.gradle.GradleScriptListener"/>
<loader order="first" implementation="org.jetbrains.kotlin.idea.scripting.gradle.GradleScriptConfigurationLoader"/>
</extensions>
<extensions defaultExtensionNs="org.jetbrains.plugins.gradle">
<orderEnumerationHandlerFactory implementation="org.jetbrains.kotlin.idea.gradle.execution.KotlinGradleOrderEnumerationHandler$Factory" order="first"/>
<projectResolve implementation="org.jetbrains.kotlin.idea.configuration.KotlinMPPGradleProjectResolver"/>
</extensions>
<extensions defaultExtensionNs="com.intellij">
<projectTaskRunner implementation="org.jetbrains.kotlin.idea.gradle.execution.KotlinMPPGradleProjectTaskRunner" order="first, before gradle"/>
<externalProjectDataService implementation="org.jetbrains.kotlin.idea.configuration.KotlinSourceSetDataService"/>
<externalProjectDataService implementation="org.jetbrains.kotlin.idea.configuration.KotlinGradleProjectSettingsDataService"/>
<registryKey key="kotlin.mpp.tests.force.gradle"
description="Run multi-platform tests with Gradle runner even if the platform runner is used by default.
This setting currently affects only HMPP projects. You may need to delete existing test configurations for the change to take place."
defaultValue="true"
restartRequired="false"/>
<projectService serviceImplementation="org.jetbrains.kotlin.idea.scripting.gradle.GradleScriptInputsWatcher"/>
</extensions>
<actions>
<action id="Kotlin.Gradle.ShowDslLogs" class="org.jetbrains.kotlin.idea.actions.ShowKotlinGradleDslLogs"
text="Show Kotlin Gradle DSL Logs" description="Show Kotlin Gradle DSL logs">
</action>
</actions>
</idea-plugin>
-226
View File
@@ -1,226 +0,0 @@
<idea-plugin>
<extensionPoints>
<extensionPoint qualifiedName="org.jetbrains.kotlin.platformGradleDetector"
interface="org.jetbrains.kotlin.idea.inspections.gradle.KotlinPlatformGradleDetector"/>
</extensionPoints>
<application-components>
<component>
<implementation-class>org.jetbrains.kotlin.idea.JvmPluginStartupComponent</implementation-class>
</component>
</application-components>
<project-components>
<component>
<implementation-class>org.jetbrains.kotlin.idea.compiler.KotlinCompilerManager</implementation-class>
</component>
<component>
<implementation-class>org.jetbrains.kotlin.idea.configuration.ui.KotlinConfigurationCheckerComponent</implementation-class>
</component>
<component>
<implementation-class>org.jetbrains.kotlin.idea.scratch.ScratchFileModuleInfoProvider</implementation-class>
</component>
</project-components>
<actions>
<!-- Kotlin Console REPL-->
<action id="KotlinConsoleREPL" class="org.jetbrains.kotlin.console.actions.RunKotlinConsoleAction"
text="Kotlin REPL"
icon="/org/jetbrains/kotlin/idea/icons/kotlin_launch_configuration.png">
<add-to-group group-id="KotlinToolsGroup" anchor="last"/>
</action>
<action id="ConfigureKotlinInProject" class="org.jetbrains.kotlin.idea.actions.ConfigureKotlinJavaInProjectAction"
text="Configure Kotlin in Project">
<add-to-group group-id="KotlinToolsGroup"/>
</action>
<action id="ConfigureKotlinJsInProject" class="org.jetbrains.kotlin.idea.actions.ConfigureKotlinJsInProjectAction"
text="Configure Kotlin (JavaScript) in Project">
<add-to-group group-id="KotlinToolsGroup"/>
</action>
<action id="ShowKotlinBytecode" class="org.jetbrains.kotlin.idea.actions.ShowKotlinBytecodeAction"
text="Show Kotlin Bytecode">
<add-to-group group-id="KotlinToolsGroup"/>
</action>
<action id="CreateIncrementalCompilationBackup"
class="org.jetbrains.kotlin.idea.internal.makeBackup.CreateIncrementalCompilationBackup" internal="true">
<add-to-group group-id="KotlinInternalGroup"/>
</action>
<action id="ReactivePostOpenProjectActionsAction" class="org.jetbrains.kotlin.idea.actions.internal.ReactivePostOpenProjectActionsAction"
text="Kotlin Project Post-Open Activity" internal="true">
<add-to-group group-id="KotlinInternalGroup"/>
</action>
<action id="AddToProblemApiInspection" class="org.jetbrains.kotlin.idea.inspections.api.AddIncompatibleApiAction"
text="Report as incompatible API">
</action>
<group id="Kotlin.XDebugger.Actions">
<!-- TODO(design)-->
<action id="Kotlin.XDebugger.CoroutinesDump"
class="org.jetbrains.kotlin.idea.debugger.coroutines.CoroutineDumpAction"
text="Get Coroutines Dump"
icon="/org/jetbrains/kotlin/idea/icons/kotlin.png"/>
</group>
<action id="Kotlin.XDebugger.ToggleKotlinVariableView"
class="org.jetbrains.kotlin.idea.debugger.ToggleKotlinVariablesView"
text="Show Kotlin Variables Only">
<add-to-group group-id="XDebugger.Settings" relative-to-action="XDebugger.Inline" anchor="after"/>
</action>
<action id="InspectBreakpointApplicability" class="org.jetbrains.kotlin.idea.debugger.breakpoints.InspectBreakpointApplicabilityAction"
text="Inspect Breakpoint Applicability" internal="true">
<add-to-group group-id="KotlinInternalGroup"/>
</action>
</actions>
<extensions defaultExtensionNs="com.intellij">
<projectService serviceInterface="org.jetbrains.kotlin.console.KotlinConsoleKeeper"
serviceImplementation="org.jetbrains.kotlin.console.KotlinConsoleKeeper"/>
<buildProcess.parametersProvider implementation="org.jetbrains.kotlin.idea.compiler.configuration.KotlinBuildProcessParametersProvider"/>
<projectService serviceInterface="org.jetbrains.kotlin.idea.debugger.evaluate.KotlinDebuggerCaches"
serviceImplementation="org.jetbrains.kotlin.idea.debugger.evaluate.KotlinDebuggerCaches"/>
<projectService serviceInterface="org.jetbrains.kotlin.idea.scratch.ScratchFileAutoRunner"
serviceImplementation="org.jetbrains.kotlin.idea.scratch.ScratchFileAutoRunner"/>
<projectService serviceImplementation="org.jetbrains.kotlin.idea.versions.SuppressNotificationState"/>
<applicationService serviceImplementation="org.jetbrains.kotlin.idea.debugger.ToggleKotlinVariablesState"/>
<debugger.asyncStackTraceProvider implementation="org.jetbrains.kotlin.idea.debugger.KotlinCoroutinesAsyncStackTraceProvider"/>
<debugger.jvmSmartStepIntoHandler implementation="org.jetbrains.kotlin.idea.debugger.stepping.smartStepInto.KotlinSmartStepIntoHandler"/>
<debugger.positionManagerFactory implementation="org.jetbrains.kotlin.idea.debugger.KotlinPositionManagerFactory"/>
<debugger.codeFragmentFactory implementation="org.jetbrains.kotlin.idea.debugger.evaluate.KotlinCodeFragmentFactory"/>
<debuggerEditorTextProvider language="kotlin" implementationClass="org.jetbrains.kotlin.idea.debugger.KotlinEditorTextProvider"/>
<debuggerClassFilterProvider implementation="org.jetbrains.kotlin.idea.debugger.filter.KotlinDebuggerInternalClassesFilterProvider"/>
<debugger.nodeRenderer implementation="org.jetbrains.kotlin.idea.debugger.render.KotlinClassWithDelegatedPropertyRenderer"/>
<debugger.sourcePositionProvider implementation="org.jetbrains.kotlin.idea.debugger.KotlinSourcePositionProvider"/>
<debugger.sourcePositionHighlighter implementation="org.jetbrains.kotlin.idea.debugger.KotlinSourcePositionHighlighter"/>
<debugger.frameExtraVarsProvider implementation="org.jetbrains.kotlin.idea.debugger.KotlinFrameExtraVariablesProvider"/>
<debugger.extraSteppingFilter implementation="org.jetbrains.kotlin.idea.KotlinExtraSteppingFilter"/>
<xdebugger.settings implementation="org.jetbrains.kotlin.idea.debugger.KotlinDebuggerSettings"/>
<xdebugger.breakpointType implementation="org.jetbrains.kotlin.idea.debugger.breakpoints.KotlinFieldBreakpointType"/>
<xdebugger.breakpointType implementation="org.jetbrains.kotlin.idea.debugger.breakpoints.KotlinLineBreakpointType" order="first"/>
<xdebugger.breakpointType implementation="org.jetbrains.kotlin.idea.debugger.breakpoints.KotlinFunctionBreakpointType"/>
<debugger.syntheticProvider implementation="org.jetbrains.kotlin.idea.debugger.filter.KotlinSyntheticTypeComponentProvider"/>
<debugger.javaBreakpointHandlerFactory implementation="org.jetbrains.kotlin.idea.debugger.breakpoints.KotlinFieldBreakpointHandlerFactory"/>
<debugger.javaBreakpointHandlerFactory implementation="org.jetbrains.kotlin.idea.debugger.breakpoints.KotlinLineBreakpointHandlerFactory"/>
<debugger.javaBreakpointHandlerFactory implementation="org.jetbrains.kotlin.idea.debugger.breakpoints.KotlinFunctionBreakpointHandlerFactory"/>
<debugger.jvmSteppingCommandProvider implementation="org.jetbrains.kotlin.idea.debugger.stepping.KotlinSteppingCommandProvider"/>
<debugger.simplePropertyGetterProvider implementation="org.jetbrains.kotlin.idea.debugger.stepping.KotlinSimpleGetterProvider"/>
<framework.type implementation="org.jetbrains.kotlin.idea.framework.JavaFrameworkType"/>
<projectTemplatesFactory implementation="org.jetbrains.kotlin.idea.framework.KotlinTemplatesFactory" />
<library.presentationProvider implementation="org.jetbrains.kotlin.idea.framework.JavaRuntimePresentationProvider"/>
<configurationType implementation="org.jetbrains.kotlin.idea.run.KotlinRunConfigurationType"/>
<configurationType implementation="org.jetbrains.kotlin.idea.run.KotlinJUnitConfigurationType"/>
<configurationType implementation="org.jetbrains.kotlin.idea.run.script.standalone.KotlinStandaloneScriptRunConfigurationType"/>
<runConfigurationProducer implementation="org.jetbrains.kotlin.idea.run.KotlinRunConfigurationProducer"/>
<runConfigurationProducer implementation="org.jetbrains.kotlin.idea.run.script.standalone.KotlinStandaloneScriptRunConfigurationProducer"/>
<library.type implementation="org.jetbrains.kotlin.idea.framework.JSLibraryType"/>
<library.javaSourceRootDetector implementation="org.jetbrains.kotlin.idea.configuration.KotlinSourceRootDetector"/>
<multipleRunLocationsProvider implementation="org.jetbrains.kotlin.idea.run.multiplatform.KotlinMultiplatformRunLocationsProvider"/>
<editorNotificationProvider implementation="org.jetbrains.kotlin.idea.configuration.KotlinSetupEnvironmentNotificationProvider"/>
<postStartupActivity implementation="org.jetbrains.kotlin.idea.configuration.JvmStartupActivity"/>
<editorNotificationProvider implementation="org.jetbrains.kotlin.idea.debugger.KotlinAlternativeSourceNotificationProvider"/>
<editorNotificationProvider implementation="org.jetbrains.kotlin.idea.inspections.JavaOutsideModuleDetector"/>
<consoleFilterProvider implementation="org.jetbrains.kotlin.idea.run.KotlinConsoleFilterProvider"/>
<exceptionFilter implementation="org.jetbrains.kotlin.idea.filters.KotlinExceptionFilterFactory" order="first"/>
<externalSystemTaskNotificationListener implementation="org.jetbrains.kotlin.idea.configuration.KotlinExternalSystemSyncListener"/>
<lang.surroundDescriptor language="kotlin"
implementationClass="org.jetbrains.kotlin.idea.debugger.evaluate.surroundWith.KotlinDebuggerExpressionSurroundDescriptor"/>
<editorNotificationProvider implementation="org.jetbrains.kotlin.idea.versions.UnsupportedAbiVersionNotificationPanelProvider"/>
<scratch.creationHelper language="kotlin"
implementationClass="org.jetbrains.kotlin.idea.scratch.KtScratchFileCreationHelper"/>
<runLineMarkerContributor language="kotlin"
implementationClass="org.jetbrains.kotlin.idea.scratch.actions.ScratchRunLineMarkerContributor"/>
<localInspection
groupName="Plugin DevKit"
shortName="IncompatibleAPI"
enabledByDefault="false"
level="ERROR"
displayName="Incompatible API usage"
implementationClass="org.jetbrains.kotlin.idea.inspections.api.IncompatibleAPIInspection"/>
<projectService serviceInterface="org.jetbrains.uast.kotlin.KotlinUastResolveProviderService"
serviceImplementation="org.jetbrains.uast.kotlin.internal.IdeaKotlinUastResolveProviderService"/>
<applicationService
serviceInterface="org.jetbrains.kotlin.platform.DefaultIdeTargetPlatformKindProvider"
serviceImplementation="org.jetbrains.kotlin.platform.impl.IdeaDefaultIdeTargetPlatformKindProvider"/>
<applicationService
serviceInterface="org.jetbrains.kotlin.idea.j2k.J2KPostProcessingRegistrar"
serviceImplementation="org.jetbrains.kotlin.idea.j2k.J2KPostProcessingRegistrarImpl"/>
<registryKey key="kotlin.use.ultra.light.classes"
description="Whether to use an experimental implementation of Kotlin-as-Java classes"
defaultValue="true"
restartRequired="false"/>
<registryKey key="kotlin.uast.multiresolve.enabled"
description="Whether to use multi resolve for UAST in Kotlin provided by `Call.resolveCandidates`, otherwise PsiPolyVariantReference-based multiResolve will be performed"
defaultValue="true"
restartRequired="false"/>
<registryKey key="kotlin.jps.instrument.bytecode"
description="Enable bytecode instrumentation for Kotlin classes"
defaultValue="false"
restartRequired="false"/>
</extensions>
<extensions defaultExtensionNs="org.jetbrains.uast">
<uastLanguagePlugin implementation="org.jetbrains.uast.kotlin.KotlinUastLanguagePlugin"/>
</extensions>
<extensions defaultExtensionNs="org.jetbrains.kotlin">
<diagnosticSuppressor implementation="org.jetbrains.kotlin.idea.debugger.DiagnosticSuppressorForDebugger"/>
<storageComponentContainerContributor implementation="org.jetbrains.kotlin.samWithReceiver.ide.IdeSamWithReceiverComponentContributor"/>
<declarationAttributeAltererExtension implementation="org.jetbrains.kotlin.allopen.ide.IdeAllOpenDeclarationAttributeAltererExtension"/>
<ultraLightClassModifierExtension implementation="org.jetbrains.kotlin.allopen.ide.AllOpenUltraLightClassModifierExtension"/>
<storageComponentContainerContributor implementation="org.jetbrains.kotlin.noarg.ide.IdeNoArgComponentContainerContributor"/>
<expressionCodegenExtension implementation="org.jetbrains.kotlin.noarg.ide.IdeNoArgExpressionCodegenExtension"/>
<ultraLightClassModifierExtension implementation="org.jetbrains.kotlin.noarg.ide.NoArgUltraLightClassModifierExtension"/>
<defaultErrorMessages implementation="org.jetbrains.kotlin.noarg.diagnostic.DefaultErrorMessagesNoArg"/>
<completionExtension implementation="org.jetbrains.kotlin.idea.properties.PropertyKeyCompletion"/>
<newFileHook implementation="org.jetbrains.kotlin.idea.configuration.NewKotlinFileConfigurationHook"/>
<quickFixContributor implementation="org.jetbrains.kotlin.idea.quickfix.JvmQuickFixRegistrar"/>
<clearBuildState implementation="org.jetbrains.kotlin.idea.compiler.configuration.ClearBuildManagerState"/>
<facetValidatorCreator implementation="org.jetbrains.kotlin.idea.facet.KotlinLibraryValidatorCreator"/>
<gradleFrameworkSupport implementation="org.jetbrains.kotlin.gradle.kdsl.frameworkSupport.GradleJavaFrameworkSupportProvider" />
<gradleFrameworkSupport implementation="org.jetbrains.kotlin.gradle.kdsl.frameworkSupport.GradleKotlinDSLKotlinJavaFrameworkSupportProvider" />
<gradleFrameworkSupport implementation="org.jetbrains.kotlin.gradle.kdsl.frameworkSupport.GradleKotlinDSLKotlinJSFrameworkSupportProvider" />
<gradleFrameworkSupport implementation="org.jetbrains.kotlin.gradle.kdsl.frameworkSupport.GradleGroovyFrameworkSupportProvider" />
<syntheticScopeProviderExtension implementation="org.jetbrains.kotlin.idea.debugger.evaluate.DebuggerFieldSyntheticScopeProvider"/>
<expressionCodegenExtension implementation="org.jetbrains.kotlin.idea.debugger.evaluate.DebuggerFieldExpressionCodegenExtension"/>
<completionInformationProvider implementation="org.jetbrains.kotlin.idea.debugger.evaluate.DebuggerFieldCompletionInformationProvider" />
<kotlinIndicesHelperExtension implementation="org.jetbrains.kotlin.idea.debugger.evaluate.DebuggerFieldKotlinIndicesHelperExtension"/>
</extensions>
</idea-plugin>
-71
View File
@@ -1,71 +0,0 @@
<idea-plugin xmlns:xi="http://www.w3.org/2001/XInclude" version="2" url="http://kotlinlang.org" allow-bundled-update="true">
<id>org.jetbrains.kotlin</id>
<name>Kotlin</name>
<description><![CDATA[
The Kotlin plugin provides language support in IntelliJ IDEA and Android Studio.
<br>
<a href="http://kotlinlang.org/docs/tutorials/getting-started.html">Getting Started in IntelliJ IDEA</a><br>
<a href="http://kotlinlang.org/docs/tutorials/kotlin-android.html">Getting Started in Android Studio</a><br>
<a href="http://slack.kotlinlang.org/">Public Slack</a><br>
<a href="https://youtrack.jetbrains.com/issues/KT">Issue tracker</a><br>
]]></description>
<version>@snapshot@</version>
<vendor url="http://www.jetbrains.com">JetBrains</vendor>
<idea-version since-build="183.3283.2" until-build="183.*"/>
<depends>com.intellij.modules.platform</depends>
<depends optional="true" config-file="junit.xml">JUnit</depends>
<depends optional="true" config-file="gradle.xml">org.jetbrains.plugins.gradle</depends>
<depends optional="true" config-file="gradle-java.xml">org.jetbrains.plugins.gradle.java</depends>
<depends optional="true" config-file="gradle-groovy.xml">org.intellij.groovy</depends>
<depends optional="true" config-file="maven.xml">org.jetbrains.idea.maven</depends>
<depends optional="true" config-file="testng-j.xml">TestNG-J</depends>
<depends optional="true" config-file="android.xml">org.jetbrains.android</depends>
<depends optional="true" config-file="coverage.xml">Coverage</depends>
<depends optional="true" config-file="i18n.xml">com.intellij.java-i18n</depends>
<depends optional="true" config-file="decompiler.xml">org.jetbrains.java.decompiler</depends>
<depends optional="true" config-file="git4idea.xml">Git4Idea</depends>
<depends optional="true" config-file="stream-debugger.xml">org.jetbrains.debugger.streams</depends>
<!-- ULTIMATE-PLUGIN-PLACEHOLDER -->
<!-- CIDR-PLUGIN-PLACEHOLDER-START -->
<depends>com.intellij.modules.idea</depends>
<depends>com.intellij.modules.java</depends>
<depends optional="true" config-file="javaScriptDebug.xml">JavaScriptDebugger</depends>
<depends optional="true" config-file="kotlin-copyright.xml">com.intellij.copyright</depends>
<depends optional="true" config-file="injection.xml">org.intellij.intelliLang</depends>
<!-- CIDR-PLUGIN-PLACEHOLDER-END -->
<xi:include href="plugin-common.xml" xpointer="xpointer(/idea-plugin/*)"/>
<!-- CIDR-PLUGIN-EXCLUDE-START -->
<xi:include href="jvm.xml" xpointer="xpointer(/idea-plugin/*)"/>
<!-- CIDR-PLUGIN-EXCLUDE-END -->
<xi:include href="native.xml" xpointer="xpointer(/idea-plugin/*)"/>
<xi:include href="tipsAndTricks.xml" xpointer="xpointer(/idea-plugin/*)"/>
<xi:include href="extensions/ide.xml" xpointer="xpointer(/idea-plugin/*)"/>
<xi:include href="kotlinx-serialization.xml" xpointer="xpointer(/idea-plugin/*)"/>
<xi:include href="scripting-support.xml" xpointer="xpointer(/idea-plugin/*)"/>
<extensionPoints>
<xi:include href="extensions/compiler.xml" xpointer="xpointer(/idea-plugin/extensionPoints/*)"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.pluginUpdateVerifier"
interface="org.jetbrains.kotlin.idea.update.PluginUpdateVerifier"/>
</extensionPoints>
<xi:include href="plugin-kotlin-extensions.xml" xpointer="xpointer(/idea-plugin/*)"/>
<extensions defaultExtensionNs="com.intellij.jvm">
<declarationSearcher language="kotlin" implementationClass="org.jetbrains.kotlin.idea.jvm.KotlinDeclarationSearcher"/>
</extensions>
</idea-plugin>
-75
View File
@@ -1,75 +0,0 @@
<idea-plugin xmlns:xi="http://www.w3.org/2001/XInclude" version="2" url="http://kotlinlang.org" allow-bundled-update="true">
<id>org.jetbrains.kotlin</id>
<name>Kotlin</name>
<description><![CDATA[
The Kotlin plugin provides language support in IntelliJ IDEA and Android Studio.
<br>
<a href="http://kotlinlang.org/docs/tutorials/getting-started.html">Getting Started in IntelliJ IDEA</a><br>
<a href="http://kotlinlang.org/docs/tutorials/kotlin-android.html">Getting Started in Android Studio</a><br>
<a href="http://slack.kotlinlang.org/">Public Slack</a><br>
<a href="https://youtrack.jetbrains.com/issues/KT">Issue tracker</a><br>
]]></description>
<version>@snapshot@</version>
<vendor url="http://www.jetbrains.com">JetBrains</vendor>
<idea-version since-build="183.1" until-build="183.*"/>
<depends>com.intellij.modules.platform</depends>
<depends>com.intellij.modules.androidstudio</depends>
<depends optional="true" config-file="junit.xml">JUnit</depends>
<depends optional="true" config-file="gradle.xml">org.jetbrains.plugins.gradle</depends>
<depends optional="true" config-file="gradle-java.xml">org.jetbrains.plugins.gradle.java</depends>
<depends optional="true" config-file="gradle-groovy.xml">org.intellij.groovy</depends>
<depends optional="true" config-file="maven.xml">org.jetbrains.idea.maven</depends>
<depends optional="true" config-file="testng-j.xml">TestNG-J</depends>
<depends optional="true" config-file="kotlin-copyright.xml">com.intellij.copyright</depends>
<depends optional="true" config-file="coverage.xml">Coverage</depends>
<depends optional="true" config-file="i18n.xml">com.intellij.java-i18n</depends>
<depends optional="true" config-file="decompiler.xml">org.jetbrains.java.decompiler</depends>
<depends optional="true" config-file="git4idea.xml">Git4Idea</depends>
<depends optional="true" config-file="stream-debugger.xml">org.jetbrains.debugger.streams</depends>
<!-- ULTIMATE-PLUGIN-PLACEHOLDER -->
<!-- CIDR-PLUGIN-PLACEHOLDER-START -->
<depends>com.intellij.modules.java</depends>
<depends optional="true" config-file="javaScriptDebug.xml">JavaScriptDebugger</depends>
<depends optional="true" config-file="kotlin-copyright.xml">com.intellij.copyright</depends>
<depends optional="true" config-file="injection.xml">org.intellij.intelliLang</depends>
<!-- CIDR-PLUGIN-PLACEHOLDER-END -->
<xi:include href="plugin-common.xml" xpointer="xpointer(/idea-plugin/*)"/>
<!-- CIDR-PLUGIN-EXCLUDE-START -->
<xi:include href="jvm.xml" xpointer="xpointer(/idea-plugin/*)"/>
<!-- CIDR-PLUGIN-EXCLUDE-END -->
<xi:include href="native.xml" xpointer="xpointer(/idea-plugin/*)"/>
<xi:include href="tipsAndTricks.xml" xpointer="xpointer(/idea-plugin/*)"/>
<xi:include href="extensions/ide.xml" xpointer="xpointer(/idea-plugin/*)"/>
<xi:include href="kotlinx-serialization.xml" xpointer="xpointer(/idea-plugin/*)"/>
<xi:include href="scripting-support.xml" xpointer="xpointer(/idea-plugin/*)"/>
<extensionPoints>
<xi:include href="extensions/compiler.xml" xpointer="xpointer(/idea-plugin/extensionPoints/*)"/>
<extensionPoint qualifiedName="org.jetbrains.kotlin.pluginUpdateVerifier"
interface="org.jetbrains.kotlin.idea.update.PluginUpdateVerifier"/>
</extensionPoints>
<xi:include href="plugin-kotlin-extensions.xml" xpointer="xpointer(/idea-plugin/*)"/>
<extensions defaultExtensionNs="org.jetbrains.kotlin">
<pluginUpdateVerifier implementation="org.jetbrains.kotlin.idea.update.GooglePluginUpdateVerifier"/>
</extensions>
<extensions defaultExtensionNs="com.intellij.jvm">
<declarationSearcher language="kotlin" implementationClass="org.jetbrains.kotlin.idea.jvm.KotlinDeclarationSearcher"/>
</extensions>
</idea-plugin>
@@ -1,15 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.highlighter.markers
import com.intellij.icons.AllIcons
import javax.swing.Icon
// BUNCH: as35
// BUNCH: as34
internal fun createDslStyleIcon(styleId: Int): Icon {
return AllIcons.Gutter.Colors
}
@@ -1,10 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.quickfix.expectactual
import com.intellij.openapi.util.text.StringUtil
fun escapeXml(text: String): String = StringUtil.escapeXml(text)
@@ -1,395 +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.refactoring.move.moveDeclarations
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.ide.util.EditorHelper
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.PsiReference
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.refactoring.BaseRefactoringProcessor
import com.intellij.refactoring.move.MoveCallback
import com.intellij.refactoring.move.MoveMultipleElementsViewDescriptor
import com.intellij.refactoring.move.moveClassesOrPackages.MoveClassHandler
import com.intellij.refactoring.rename.RenameUtil
import com.intellij.refactoring.util.NonCodeUsageInfo
import com.intellij.refactoring.util.RefactoringUIUtil
import com.intellij.refactoring.util.TextOccurrencesUtil
import com.intellij.usageView.UsageInfo
import com.intellij.usageView.UsageViewBundle
import com.intellij.usageView.UsageViewDescriptor
import com.intellij.usageView.UsageViewUtil
import com.intellij.util.IncorrectOperationException
import com.intellij.util.containers.MultiMap
import gnu.trove.THashMap
import gnu.trove.TObjectHashingStrategy
import org.jetbrains.kotlin.asJava.elements.KtLightDeclaration
import org.jetbrains.kotlin.asJava.findFacadeClass
import org.jetbrains.kotlin.asJava.namedUnwrappedElement
import org.jetbrains.kotlin.asJava.toLightElements
import org.jetbrains.kotlin.idea.codeInsight.shorten.addToBeShortenedDescendantsToWaitingSet
import org.jetbrains.kotlin.idea.core.deleteSingle
import org.jetbrains.kotlin.idea.core.quoteIfNeeded
import org.jetbrains.kotlin.idea.refactoring.broadcastRefactoringExit
import org.jetbrains.kotlin.idea.refactoring.fqName.getKotlinFqName
import org.jetbrains.kotlin.idea.refactoring.move.*
import org.jetbrains.kotlin.idea.refactoring.move.moveFilesOrDirectories.MoveKotlinClassHandler
import org.jetbrains.kotlin.idea.search.projectScope
import org.jetbrains.kotlin.idea.search.restrictByFileType
import org.jetbrains.kotlin.idea.util.projectStructure.module
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
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.isAncestor
import org.jetbrains.kotlin.utils.ifEmpty
import org.jetbrains.kotlin.utils.keysToMap
import java.util.*
interface Mover : (KtNamedDeclaration, KtElement) -> KtNamedDeclaration {
object Default : Mover {
override fun invoke(originalElement: KtNamedDeclaration, targetContainer: KtElement): KtNamedDeclaration {
return when (targetContainer) {
is KtFile -> {
val declarationContainer: KtElement =
if (targetContainer.isScript()) targetContainer.script!!.blockExpression else targetContainer
declarationContainer.add(originalElement) as KtNamedDeclaration
}
is KtClassOrObject -> targetContainer.addDeclaration(originalElement)
else -> error("Unexpected element: ${targetContainer.getElementTextWithContext()}")
}.apply {
val container = originalElement.containingClassOrObject
if (container is KtObjectDeclaration && container.isCompanion() && container.declarations.singleOrNull() == originalElement) {
container.deleteSingle()
}
else {
originalElement.deleteSingle()
}
}
}
}
}
sealed class MoveSource {
abstract val elementsToMove: Collection<KtNamedDeclaration>
class Elements(override val elementsToMove: Collection<KtNamedDeclaration>) : MoveSource()
class File(val file: KtFile) : MoveSource() {
override val elementsToMove: Collection<KtNamedDeclaration>
get() = file.declarations.filterIsInstance<KtNamedDeclaration>()
}
}
fun MoveSource(declaration: KtNamedDeclaration) = MoveSource.Elements(listOf(declaration))
fun MoveSource(declarations: Collection<KtNamedDeclaration>) = MoveSource.Elements(declarations)
fun MoveSource(file: KtFile) = MoveSource.File(file)
class MoveDeclarationsDescriptor @JvmOverloads constructor(
val project: Project,
val moveSource: MoveSource,
val moveTarget: KotlinMoveTarget,
val delegate: MoveDeclarationsDelegate,
val searchInCommentsAndStrings: Boolean = true,
val searchInNonCode: Boolean = true,
val deleteSourceFiles: Boolean = false,
val moveCallback: MoveCallback? = null,
val openInEditor: Boolean = false,
val allElementsToMove: List<PsiElement>? = null,
val analyzeConflicts: Boolean = true,
val searchReferences: Boolean = true
)
class ConflictUsageInfo(element: PsiElement, val messages: Collection<String>) : UsageInfo(element)
private object ElementHashingStrategy : TObjectHashingStrategy<PsiElement> {
override fun equals(e1: PsiElement?, e2: PsiElement?): Boolean {
if (e1 === e2) return true
// Name should be enough to distinguish different light elements based on the same original declaration
if (e1 is KtLightDeclaration<*, *> && e2 is KtLightDeclaration<*, *>) {
return e1.kotlinOrigin == e2.kotlinOrigin && e1.name == e2.name
}
return e1 == e2
}
override fun computeHashCode(e: PsiElement?): Int {
return when (e) {
null -> 0
is KtLightDeclaration<*, *> -> (e.kotlinOrigin?.hashCode() ?: 0) * 31 + (e.name?.hashCode() ?: 0)
else -> e.hashCode()
}
}
}
class MoveKotlinDeclarationsProcessor(
val descriptor: MoveDeclarationsDescriptor,
val mover: Mover = Mover.Default,
private val throwOnConflicts: Boolean = false) : BaseRefactoringProcessor(descriptor.project) {
companion object {
private val REFACTORING_NAME = "Move declarations"
val REFACTORING_ID = "move.kotlin.declarations"
}
val project get() = descriptor.project
private var nonCodeUsages: Array<NonCodeUsageInfo>? = null
private val moveEntireFile = descriptor.moveSource is MoveSource.File
private val elementsToMove = descriptor.moveSource.elementsToMove.filter { e -> e.parent != descriptor.moveTarget.getTargetPsiIfExists(e) }
private val kotlinToLightElementsBySourceFile = elementsToMove
.groupBy { it.containingKtFile }
.mapValues { it.value.keysToMap { it.toLightElements().ifEmpty { listOf(it) } } }
private val conflicts = MultiMap<PsiElement, String>()
override fun getRefactoringId() = REFACTORING_ID
override fun createUsageViewDescriptor(usages: Array<out UsageInfo>): UsageViewDescriptor {
val targetContainerFqName = descriptor.moveTarget.targetContainerFqName?.let {
if (it.isRoot) UsageViewBundle.message("default.package.presentable.name") else it.asString()
}
return MoveMultipleElementsViewDescriptor(elementsToMove.toTypedArray(), targetContainerFqName)
}
fun getConflictsAsUsages(): List<UsageInfo> = conflicts.entrySet().map { ConflictUsageInfo(it.key, it.value) }
public override fun findUsages(): Array<UsageInfo> {
if (!descriptor.searchReferences || elementsToMove.isEmpty()) return UsageInfo.EMPTY_ARRAY
val newContainerName = descriptor.moveTarget.targetContainerFqName?.asString() ?: ""
fun getSearchScope(element: PsiElement): GlobalSearchScope? {
val projectScope = project.projectScope()
val ktDeclaration = element.namedUnwrappedElement as? KtNamedDeclaration ?: return projectScope
if (ktDeclaration.hasModifier(KtTokens.PRIVATE_KEYWORD)) return projectScope
val moveTarget = descriptor.moveTarget
val (oldContainer, newContainer) = descriptor.delegate.getContainerChangeInfo(ktDeclaration, moveTarget)
val targetModule = moveTarget.getTargetModule(project) ?: return projectScope
if (oldContainer != newContainer || ktDeclaration.module != targetModule) return projectScope
// Check if facade class may change
if (newContainer is ContainerInfo.Package) {
val javaScope = projectScope.restrictByFileType(JavaFileType.INSTANCE)
val currentFile = ktDeclaration.containingKtFile
val newFile = when (moveTarget) {
is KotlinMoveTargetForExistingElement -> moveTarget.targetElement as? KtFile ?: return null
is KotlinMoveTargetForDeferredFile -> return javaScope
else -> return null
}
val currentFacade = currentFile.findFacadeClass()
val newFacade = newFile.findFacadeClass()
return if (currentFacade?.qualifiedName != newFacade?.qualifiedName) javaScope else null
}
return null
}
fun collectUsages(kotlinToLightElements: Map<KtNamedDeclaration, List<PsiNamedElement>>, result: MutableCollection<UsageInfo>) {
kotlinToLightElements.values.flatten().flatMapTo(result) { lightElement ->
val searchScope = getSearchScope(lightElement) ?: return@flatMapTo emptyList()
val newFqName = StringUtil.getQualifiedName(newContainerName, lightElement.name)
val newFqNameForKt = StringUtil.getQualifiedName(
newContainerName,
lightElement.namedUnwrappedElement?.name?: lightElement.name
)
val foundReferences = HashSet<PsiReference>()
val results = ReferencesSearch
.search(lightElement, searchScope)
.mapNotNullTo(ArrayList()) { ref ->
if (foundReferences.add(ref) && elementsToMove.none { it.isAncestor(ref.element)}) {
createMoveUsageInfoIfPossible(ref, lightElement, true, false)
}
else null
}
val name = lightElement.getKotlinFqName()?.quoteIfNeeded()?.asString()
if (name != null) {
TextOccurrencesUtil.findNonCodeUsages(
lightElement,
name,
descriptor.searchInCommentsAndStrings,
descriptor.searchInNonCode,
FqName(newFqName).quoteIfNeeded().asString(),
results
)
}
MoveClassHandler.EP_NAME.extensions.forEach { handler ->
if (handler !is MoveKotlinClassHandler) handler.preprocessUsages(results)
}
results
.filter { it is NonCodeUsageInfo && it.file is KtFile }
.forEach {
val newText = NonCodeUsageInfo::class.java.getField("newText")
// A 'newText' is marked as final initially, but here we need to change it to prevent
// light-class names in kotlin files.
val oldAccessibility = newText.isAccessible
newText.isAccessible = true
newText.set(it, newFqNameForKt)
// Restore initial accessibility of 'newText' field.
newText.isAccessible = oldAccessibility
}
results
}
}
val usages = ArrayList<UsageInfo>()
val conflictChecker = MoveConflictChecker(
project,
elementsToMove,
descriptor.moveTarget,
elementsToMove.first(),
allElementsToMove = descriptor.allElementsToMove
)
for ((sourceFile, kotlinToLightElements) in kotlinToLightElementsBySourceFile) {
val internalUsages = LinkedHashSet<UsageInfo>()
val externalUsages = LinkedHashSet<UsageInfo>()
if (moveEntireFile) {
val changeInfo = ContainerChangeInfo(
ContainerInfo.Package(sourceFile.packageFqName),
descriptor.moveTarget.targetContainerFqName?.let { ContainerInfo.Package(it) } ?: ContainerInfo.UnknownPackage
)
internalUsages += sourceFile.getInternalReferencesToUpdateOnPackageNameChange(changeInfo)
}
else {
kotlinToLightElements.keys.forEach {
val packageNameInfo = descriptor.delegate.getContainerChangeInfo(it, descriptor.moveTarget)
internalUsages += it.getInternalReferencesToUpdateOnPackageNameChange(packageNameInfo)
}
}
internalUsages += descriptor.delegate.findInternalUsages(descriptor)
collectUsages(kotlinToLightElements, externalUsages)
if (descriptor.analyzeConflicts) {
conflictChecker.checkAllConflicts(externalUsages, internalUsages, conflicts)
descriptor.delegate.collectConflicts(descriptor, internalUsages, conflicts)
}
usages += internalUsages
usages += externalUsages
}
return UsageViewUtil.removeDuplicatedUsages(usages.toTypedArray())
}
override fun preprocessUsages(refUsages: Ref<Array<UsageInfo>>): Boolean {
return showConflicts(conflicts, refUsages.get())
}
override fun showConflicts(conflicts: MultiMap<PsiElement, String>, usages: Array<out UsageInfo>?): Boolean {
if (throwOnConflicts && !conflicts.isEmpty) throw RefactoringConflictsFoundException()
return super.showConflicts(conflicts, usages)
}
override fun performRefactoring(usages: Array<out UsageInfo>) = doPerformRefactoring(usages.toList())
internal fun doPerformRefactoring(usages: List<UsageInfo>) {
fun moveDeclaration(declaration: KtNamedDeclaration, moveTarget: KotlinMoveTarget): KtNamedDeclaration {
val targetContainer = moveTarget.getOrCreateTargetPsi(declaration)
?: throw AssertionError("Couldn't create Kotlin file for: ${declaration::class.java}: ${declaration.text}")
descriptor.delegate.preprocessDeclaration(descriptor, declaration)
if (moveEntireFile) return declaration
return mover(declaration, targetContainer).apply {
addToBeShortenedDescendantsToWaitingSet()
}
}
val (oldInternalUsages, externalUsages) = usages.partition { it is KotlinMoveUsage && it.isInternal }
val newInternalUsages = ArrayList<UsageInfo>()
markInternalUsages(oldInternalUsages)
val usagesToProcess = ArrayList(externalUsages)
try {
descriptor.delegate.preprocessUsages(descriptor, usages)
val oldToNewElementsMapping = THashMap<PsiElement, PsiElement>(ElementHashingStrategy)
val newDeclarations = ArrayList<KtNamedDeclaration>()
for ((sourceFile, kotlinToLightElements) in kotlinToLightElementsBySourceFile) {
for ((oldDeclaration, oldLightElements) in kotlinToLightElements) {
val elementListener = transaction?.getElementListener(oldDeclaration)
val newDeclaration = moveDeclaration(oldDeclaration, descriptor.moveTarget)
newDeclarations += newDeclaration
oldToNewElementsMapping[oldDeclaration] = newDeclaration
oldToNewElementsMapping[sourceFile] = newDeclaration.containingKtFile
elementListener?.elementMoved(newDeclaration)
for ((oldElement, newElement) in oldLightElements.asSequence().zip(newDeclaration.toLightElements().asSequence())) {
oldToNewElementsMapping[oldElement] = newElement
}
if (descriptor.openInEditor) {
EditorHelper.openInEditor(newDeclaration)
}
}
if (descriptor.deleteSourceFiles) {
sourceFile.delete()
}
}
val internalUsageScopes: List<KtElement> = if (moveEntireFile) {
newDeclarations.asSequence().map { it.containingKtFile }.distinct().toList()
} else {
newDeclarations
}
internalUsageScopes.forEach { newInternalUsages += restoreInternalUsages(it, oldToNewElementsMapping) }
usagesToProcess += newInternalUsages
nonCodeUsages = postProcessMoveUsages(usagesToProcess, oldToNewElementsMapping).toTypedArray()
}
catch (e: IncorrectOperationException) {
nonCodeUsages = null
RefactoringUIUtil.processIncorrectOperation(myProject, e)
}
finally {
cleanUpInternalUsages(newInternalUsages + oldInternalUsages)
}
}
override fun performPsiSpoilingRefactoring() {
nonCodeUsages?.let { nonCodeUsages -> RenameUtil.renameNonCodeUsages(myProject, nonCodeUsages) }
descriptor.moveCallback?.refactoringCompleted()
}
fun execute(usages: List<UsageInfo>) {
execute(usages.toTypedArray())
}
override fun doRun() {
try {
super.doRun()
} finally {
broadcastRefactoringExit(myProject, refactoringId)
}
}
override fun getCommandName(): String = REFACTORING_NAME
}
@@ -1,33 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.reporter
import com.intellij.diagnostic.ITNReporter
import com.intellij.openapi.diagnostic.IdeaLoggingEvent
import com.intellij.openapi.diagnostic.SubmittedReportInfo
import com.intellij.util.Consumer
import java.awt.Component
abstract class ITNReporterCompat : ITNReporter() {
final override fun submit(
events: Array<IdeaLoggingEvent>,
additionalInfo: String?,
parentComponent: Component?,
consumer: Consumer<SubmittedReportInfo>
): Boolean {
return submitCompat(events, additionalInfo, parentComponent, consumer)
}
open fun submitCompat(
events: Array<IdeaLoggingEvent>,
additionalInfo: String?,
parentComponent: Component?,
consumer: Consumer<SubmittedReportInfo>
): Boolean {
@Suppress("IncompatibleAPI")
return super.submit(events, additionalInfo, parentComponent, consumer)
}
}
@@ -1,122 +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.search.ideaExtensions
import com.intellij.codeInsight.JavaTargetElementEvaluator
import com.intellij.codeInsight.TargetElementEvaluatorEx
import com.intellij.codeInsight.TargetElementUtil
import com.intellij.codeInsight.TargetElementUtilExtender
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiReference
import com.intellij.util.BitUtil
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptorWithSource
import org.jetbrains.kotlin.idea.intentions.isAutoCreatedItUsage
import org.jetbrains.kotlin.idea.references.KtDestructuringDeclarationReference
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension
import org.jetbrains.kotlin.resolve.source.getPsi
class KotlinTargetElementEvaluator : TargetElementEvaluatorEx, TargetElementUtilExtender {
companion object {
const val DO_NOT_UNWRAP_LABELED_EXPRESSION = 0x100
const val BYPASS_IMPORT_ALIAS = 0x200
// Place caret after the open curly brace in lambda for generated 'it'
fun findLambdaOpenLBraceForGeneratedIt(ref: PsiReference): PsiElement? {
val element: PsiElement = ref.element
if (element.text != "it") return null
if (element !is KtNameReferenceExpression || !isAutoCreatedItUsage(element)) return null
val itDescriptor = element.resolveMainReferenceToDescriptors().singleOrNull() ?: return null
val descriptorWithSource = itDescriptor.containingDeclaration as? DeclarationDescriptorWithSource ?: return null
val lambdaExpression = descriptorWithSource.source.getPsi()?.parent as? KtLambdaExpression ?: return null
return lambdaExpression.leftCurlyBrace.treeNext?.psi
}
// Navigate to receiver element for this in extension declaration
fun findReceiverForThisInExtensionFunction(ref: PsiReference): PsiElement? {
val element: PsiElement = ref.element
if (element.text != "this") return null
if (element !is KtNameReferenceExpression) return null
val callableDescriptor = element.resolveMainReferenceToDescriptors().singleOrNull() as? CallableDescriptor ?: return null
if (!callableDescriptor.isExtension) return null
val callableDeclaration = callableDescriptor.source.getPsi() as? KtCallableDeclaration ?: return null
return callableDeclaration.receiverTypeReference
}
}
override fun getAdditionalDefinitionSearchFlags() = 0
override fun getAdditionalReferenceSearchFlags() = DO_NOT_UNWRAP_LABELED_EXPRESSION or BYPASS_IMPORT_ALIAS
override fun getAllAdditionalFlags() = additionalDefinitionSearchFlags + additionalReferenceSearchFlags
override fun includeSelfInGotoImplementation(element: PsiElement): Boolean = !(element is KtClass && element.isAbstract())
override fun getElementByReference(ref: PsiReference, flags: Int): PsiElement? {
if (ref is KtSimpleNameReference && ref.expression is KtLabelReferenceExpression) {
val refTarget = ref.resolve() as? KtExpression ?: return null
if (!BitUtil.isSet(flags, DO_NOT_UNWRAP_LABELED_EXPRESSION)) {
return refTarget.getLabeledParent(ref.expression.getReferencedName()) ?: refTarget
}
return refTarget
}
if (!BitUtil.isSet(flags, BYPASS_IMPORT_ALIAS)) {
(ref.element as? KtSimpleNameExpression)?.mainReference?.getImportAlias()?.let { return it }
}
// prefer destructing declaration entry to its target if element name is accepted
if (ref is KtDestructuringDeclarationReference && BitUtil.isSet(flags, TargetElementUtil.ELEMENT_NAME_ACCEPTED)) {
return ref.element
}
val refExpression = ref.element as? KtSimpleNameExpression
val calleeExpression = refExpression?.getParentOfTypeAndBranch<KtCallElement> { calleeExpression }
if (calleeExpression != null) {
(ref.resolve() as? KtConstructor<*>)?.let {
return if (flags and JavaTargetElementEvaluator.NEW_AS_CONSTRUCTOR != 0) it else it.containingClassOrObject
}
}
if (BitUtil.isSet(flags, TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED)) {
return findLambdaOpenLBraceForGeneratedIt(ref)
?: findReceiverForThisInExtensionFunction(ref)
}
return null
}
override fun isIdentifierPart(file: PsiFile, text: CharSequence?, offset: Int): Boolean {
val elementAtCaret = file.findElementAt(offset)
if (elementAtCaret?.node?.elementType == KtTokens.IDENTIFIER) return true
// '(' is considered identifier part if it belongs to primary constructor without 'constructor' keyword
return elementAtCaret?.getNonStrictParentOfType<KtPrimaryConstructor>()?.textOffset == offset
}
}
@@ -1,11 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.slicer.compat
import com.intellij.psi.PsiElement
// BUNCH: 183
internal typealias PsiElement_N183_NN191 = PsiElement?
@@ -1,39 +0,0 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
@file:Suppress("DEPRECATION")
package org.jetbrains.kotlin.idea
import com.intellij.featureStatistics.FeatureStatisticsBundleProvider
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.extensions.Extensions
import java.lang.IllegalStateException
private const val CIDR_FEATURE_STATISTICS_PROVIDER_FQNAME = "com.jetbrains.cidr.lang.OCFeatureStatisticsBundleProvider"
// Remove the function, when there's no dependency to cidr during running Kotlin tests.
fun registerAdditionalResourceBundleInTests() {
if (!ApplicationManager.getApplication().isUnitTestMode) {
return
}
val isAlreadyRegistered = FeatureStatisticsBundleProvider.EP_NAME.extensions.any { provider ->
provider.javaClass.name == CIDR_FEATURE_STATISTICS_PROVIDER_FQNAME
}
if (isAlreadyRegistered) {
throw IllegalStateException("Remove this registration for the current platform: bundle is already registered.")
}
val cidrFSBundleProviderClass = try {
Class.forName(CIDR_FEATURE_STATISTICS_PROVIDER_FQNAME)
} catch (_: ClassNotFoundException) {
return
}
val cidrFSBundleProvider = cidrFSBundleProviderClass.newInstance() as FeatureStatisticsBundleProvider
Extensions.getRootArea().getExtensionPoint(FeatureStatisticsBundleProvider.EP_NAME).registerExtension(cidrFSBundleProvider)
}
@@ -1,152 +0,0 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.update
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.plugins.PluginNode
import com.intellij.openapi.diagnostic.Logger
import org.jetbrains.kotlin.idea.util.isDev
import org.jetbrains.kotlin.idea.util.isEap
import java.io.IOException
import java.net.URL
import java.util.*
import javax.xml.bind.JAXBContext
import javax.xml.bind.JAXBException
import javax.xml.bind.annotation.*
class GooglePluginUpdateVerifier : PluginUpdateVerifier() {
override val verifierName: String
get() = "Android Studio"
// Verifies if a plugin can be installed in Android Studio 3.2+.
// Currently used only by KotlinPluginUpdater.
override fun verify(pluginDescriptor: IdeaPluginDescriptor): PluginVerifyResult? {
if (pluginDescriptor.pluginId.idString != KOTLIN_PLUGIN_ID) {
return null
}
val version = pluginDescriptor.version
if (isEap(version) || isDev(version)) {
return PluginVerifyResult.accept()
}
try {
val url = URL(METADATA_FILE_URL)
val stream = url.openStream()
val context = JAXBContext.newInstance(PluginCompatibility::class.java)
val unmarshaller = context.createUnmarshaller()
val pluginCompatibility = unmarshaller.unmarshal(stream) as PluginCompatibility
val release = getRelease(pluginCompatibility)
?: return PluginVerifyResult.decline("No verified versions for this build.")
return if (release.plugins().any { KOTLIN_PLUGIN_ID == it.id && version == it.version })
PluginVerifyResult.accept()
else
PluginVerifyResult.decline("Version to be verified.")
} catch (e: Exception) {
LOG.info("Exception when verifying plugin ${pluginDescriptor.pluginId.idString} version $version", e)
return when (e) {
is IOException ->
PluginVerifyResult.decline("unable to connect to compatibility verification repository")
is JAXBException -> PluginVerifyResult.decline("unable to parse compatibility verification metadata")
else -> PluginVerifyResult.decline("exception during verification ${e.message}")
}
}
}
private fun getRelease(pluginCompatibility: PluginCompatibility): StudioRelease? {
for (studioRelease in pluginCompatibility.releases()) {
if (buildInRange(studioRelease.name, studioRelease.sinceBuild, studioRelease.untilBuild)) {
return studioRelease
}
}
return null
}
private fun buildInRange(name: String?, sinceBuild: String?, untilBuild: String?): Boolean {
val descriptor = PluginNode()
descriptor.name = name
descriptor.sinceBuild = sinceBuild
descriptor.untilBuild = untilBuild
return PluginManagerCore.isCompatible(descriptor)
}
companion object {
private const val KOTLIN_PLUGIN_ID = "org.jetbrains.kotlin"
private const val METADATA_FILE_URL = "https://dl.google.com/android/studio/plugins/compatibility.xml"
private val LOG = Logger.getInstance(GooglePluginUpdateVerifier::class.java)
private fun PluginCompatibility.releases() = studioRelease ?: emptyArray()
private fun StudioRelease.plugins() = ideaPlugin ?: emptyArray()
@XmlRootElement(name = "plugin-compatibility")
@XmlAccessorType(XmlAccessType.FIELD)
class PluginCompatibility {
@XmlElement(name = "studio-release")
var studioRelease: Array<StudioRelease>? = null
override fun toString(): String {
return "PluginCompatibility(studioRelease=${Arrays.toString(studioRelease)})"
}
}
@XmlAccessorType(XmlAccessType.FIELD)
class StudioRelease {
@XmlAttribute(name = "until-build")
var untilBuild: String? = null
@XmlAttribute(name = "since-build")
var sinceBuild: String? = null
@XmlAttribute
var name: String? = null
@XmlAttribute
var channel: String? = null
@XmlElement(name = "idea-plugin")
var ideaPlugin: Array<IdeaPlugin>? = null
override fun toString(): String {
return "StudioRelease(" +
"untilBuild=$untilBuild, name=$name, ideaPlugin=${Arrays.toString(ideaPlugin)}, " +
"sinceBuild=$sinceBuild, channel=$channel" +
")"
}
}
@XmlAccessorType(XmlAccessType.FIELD)
class IdeaPlugin {
@XmlAttribute
var id: String? = null
@XmlAttribute
var sha256: String? = null
@XmlAttribute
var channel: String? = null
@XmlAttribute
var version: String? = null
@XmlElement(name = "idea-version")
var ideaVersion: IdeaVersion? = null
override fun toString(): String {
return "IdeaPlugin(id=$id, sha256=$sha256, ideaVersion=$ideaVersion, channel=$channel, version=$version)"
}
}
@XmlAccessorType(XmlAccessType.FIELD)
class IdeaVersion {
@XmlAttribute(name = "until-build")
var untilBuild: String? = null
@XmlAttribute(name = "since-build")
var sinceBuild: String? = null
override fun toString(): String {
return "IdeaVersion(untilBuild=$untilBuild, sinceBuild=$sinceBuild)"
}
}
}
}
@@ -1,35 +0,0 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.update
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.openapi.util.registry.Registry
import org.jetbrains.kotlin.idea.PluginUpdateStatus
// Do an additional verification with PluginUpdateVerifier. Enabled only in AS 3.2+
fun verify(updateStatus: PluginUpdateStatus.Update): PluginUpdateStatus {
@Suppress("InvalidBundleOrProperty")
val pluginVerifierEnabled = Registry.`is`("kotlin.plugin.update.verifier.enabled", true)
if (!pluginVerifierEnabled) {
return updateStatus
}
val pluginDescriptor: IdeaPluginDescriptor = updateStatus.pluginDescriptor
val pluginVerifiers = PluginUpdateVerifier.EP_NAME.extensions
for (pluginVerifier in pluginVerifiers) {
val verifyResult = pluginVerifier.verify(pluginDescriptor) ?: continue
if (!verifyResult.verified) {
return PluginUpdateStatus.Unverified(
pluginVerifier.verifierName,
verifyResult.declineMessage,
updateStatus
)
}
}
return updateStatus
}
@@ -1,81 +0,0 @@
<problems>
<problem>
<file>unresolvedPropertyReference.kt</file>
<line>2</line>
<module>testInvalidBundleOrProperty_InvalidBundleOrProperty_0</module>
<entry_point TYPE="file" FQNAME="unresolvedPropertyReference.kt" />
<problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Invalid property key</problem_class>
<description>String literal 'foo.baz' doesn't appear to be valid property key</description>
</problem>
<problem>
<file>unresolvedPropertyReference.kt</file>
<line>3</line>
<module>testInvalidBundleOrProperty_InvalidBundleOrProperty_0</module>
<entry_point TYPE="file" FQNAME="unresolvedPropertyReference.kt" />
<problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Invalid property key</problem_class>
<description>String literal 'foo.baz' doesn't appear to be valid property key</description>
</problem>
<problem>
<file>unresolvedPropertyReference.kt</file>
<line>4</line>
<module>testInvalidBundleOrProperty_InvalidBundleOrProperty_0</module>
<entry_point TYPE="file" FQNAME="unresolvedPropertyReference.kt" />
<problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Invalid property key</problem_class>
<description>String literal 'foo.baz' doesn't appear to be valid property key</description>
</problem>
<problem>
<file>unresolvedPropertyReference.kt</file>
<line>5</line>
<module>testInvalidBundleOrProperty_InvalidBundleOrProperty_0</module>
<entry_point TYPE="file" FQNAME="unresolvedPropertyReference.kt" />
<problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Invalid property key</problem_class>
<description>String literal 'foo.baz' doesn't appear to be valid property key</description>
</problem>
<problem>
<file>tooFewArguments.kt</file>
<line>2</line>
<module>testInvalidBundleOrProperty_InvalidBundleOrProperty_0</module>
<entry_point TYPE="file" FQNAME="tooFewArguments.kt" />
<problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Invalid property key</problem_class>
<description>Property 'foo.bar' expected 1 parameter, passed 0</description>
</problem>
<problem>
<file>tooFewArguments.kt</file>
<line>3</line>
<module>testInvalidBundleOrProperty_InvalidBundleOrProperty_0</module>
<entry_point TYPE="file" FQNAME="tooFewArguments.kt" />
<problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Invalid property key</problem_class>
<description>Property 'foo.bar' expected 1 parameter, passed 0</description>
</problem>
<problem>
<file>unresolvedBundleReference.kt</file>
<line>3</line>
<module>testInvalidBundleOrProperty_InvalidBundleOrProperty_0</module>
<entry_point TYPE="file" FQNAME="unresolvedBundleReference.kt" />
<problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Invalid property key</problem_class>
<description>Invalid resource bundle reference 'TestBundle2'</description>
</problem>
<problem>
<file>unresolvedBundleReference.kt</file>
<line>5</line>
<module>testInvalidBundleOrProperty_InvalidBundleOrProperty_0</module>
<entry_point TYPE="file" FQNAME="unresolvedBundleReference.kt" />
<problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Invalid property key</problem_class>
<description>Invalid resource bundle reference 'TestBundle2'</description>
</problem>
<problem>
<file>unresolvedPropertyReference.kt</file>
<line>6</line>
<module>testInvalidBundleOrProperty_InvalidBundleOrProperty_0</module>
<entry_point TYPE="method" FQNAME="UnresolvedPropertyReferenceKt void test()"/>
<problem_class severity="ERROR" attribute_key="WRONG_REFERENCES_ATTRIBUTES">Invalid property key</problem_class>
<description>String literal 'www' doesn't appear to be valid property key</description>
</problem>
</problems>
@@ -1,12 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.highlighter
// Idea 191 has an additional check for duplicate highlighting
// BUNCH: 183
fun expectedDuplicatedHighlighting(runnable: Runnable) {
runnable.run()
}
@@ -1,13 +0,0 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.jps.build
import org.jetbrains.jps.incremental.CompileContext
import org.jetbrains.jps.incremental.messages.CompilerMessage
fun jpsReportInternalBuilderError(context: CompileContext, error: Throwable) {
KotlinBuilder.LOG.info(error)
}
@@ -1,78 +0,0 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.android.model.impl
import com.android.builder.model.SourceProvider
import com.android.tools.idea.gradle.project.GradleProjectInfo
import com.android.tools.idea.gradle.project.model.AndroidModuleModel
import com.android.tools.idea.res.AppResourceRepository
import com.intellij.openapi.module.Module
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.android.facet.AndroidFacet
import org.jetbrains.kotlin.android.model.AndroidModuleInfoProvider
import java.io.File
class AndroidModuleInfoProviderImpl(override val module: Module) : AndroidModuleInfoProvider {
private val androidFacet: AndroidFacet?
get() = AndroidFacet.getInstance(module)
private val androidModuleModel: AndroidModuleModel?
get() = AndroidModuleModel.get(module)
override fun isAndroidModule() = androidFacet != null
override fun isGradleModule() = GradleProjectInfo.getInstance(module.project).isBuildWithGradle
override fun getAllResourceDirectories(): List<VirtualFile> {
return androidFacet?.allResourceDirectories ?: emptyList()
}
override fun getApplicationPackage() = androidFacet?.manifest?.`package`?.toString()
override fun getMainSourceProvider(): AndroidModuleInfoProvider.SourceProviderMirror? {
return androidFacet?.mainSourceProvider?.let(::SourceProviderMirrorImpl)
}
override fun getApplicationResourceDirectories(createIfNecessary: Boolean): Collection<VirtualFile> {
return AppResourceRepository.getOrCreateInstance(module)?.resourceDirs ?: emptyList()
}
override fun getAllSourceProviders(): List<AndroidModuleInfoProvider.SourceProviderMirror> {
val androidModuleModel = this.androidModuleModel ?: return emptyList()
return androidModuleModel.allSourceProviders.map(::SourceProviderMirrorImpl)
}
override fun getActiveSourceProviders(): List<AndroidModuleInfoProvider.SourceProviderMirror> {
val androidModuleModel = this.androidModuleModel ?: return emptyList()
return androidModuleModel.activeSourceProviders.map(::SourceProviderMirrorImpl)
}
override fun getFlavorSourceProviders(): List<AndroidModuleInfoProvider.SourceProviderMirror> {
val androidModuleModel = this.androidModuleModel ?: return emptyList()
val getFlavorSourceProvidersMethod = try {
AndroidFacet::class.java.getMethod("getFlavorSourceProviders")
} catch (e: NoSuchMethodException) {
null
}
return if (getFlavorSourceProvidersMethod != null) {
@Suppress("UNCHECKED_CAST")
val sourceProviders = getFlavorSourceProvidersMethod.invoke(androidFacet) as? List<SourceProvider>
sourceProviders?.map(::SourceProviderMirrorImpl) ?: emptyList()
} else {
androidModuleModel.flavorSourceProviders.map(::SourceProviderMirrorImpl)
}
}
private class SourceProviderMirrorImpl(val sourceProvider: SourceProvider) :
AndroidModuleInfoProvider.SourceProviderMirror {
override val name: String
get() = sourceProvider.name
override val resDirectories: Collection<File>
get() = sourceProvider.resDirectories
}
}
@@ -1,78 +0,0 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.android.model.impl
import com.android.builder.model.SourceProvider
import com.android.tools.idea.gradle.project.GradleProjectInfo
import com.android.tools.idea.gradle.project.model.AndroidModuleModel
import com.android.tools.idea.res.ResourceRepositoryManager
import com.intellij.openapi.module.Module
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.android.facet.AndroidFacet
import org.jetbrains.kotlin.android.model.AndroidModuleInfoProvider
import java.io.File
class AndroidModuleInfoProviderImpl(override val module: Module) : AndroidModuleInfoProvider {
private val androidFacet: AndroidFacet?
get() = AndroidFacet.getInstance(module)
private val androidModuleModel: AndroidModuleModel?
get() = AndroidModuleModel.get(module)
override fun isAndroidModule() = androidFacet != null
override fun isGradleModule() = GradleProjectInfo.getInstance(module.project).isBuildWithGradle
override fun getAllResourceDirectories(): List<VirtualFile> {
return androidFacet?.allResourceDirectories ?: emptyList()
}
override fun getApplicationPackage() = androidFacet?.manifest?.`package`?.toString()
override fun getMainSourceProvider(): AndroidModuleInfoProvider.SourceProviderMirror? {
return androidFacet?.mainSourceProvider?.let(::SourceProviderMirrorImpl)
}
override fun getApplicationResourceDirectories(createIfNecessary: Boolean): Collection<VirtualFile> {
return ResourceRepositoryManager.getOrCreateInstance(module)?.getAppResources(createIfNecessary)?.resourceDirs ?: emptyList()
}
override fun getAllSourceProviders(): List<AndroidModuleInfoProvider.SourceProviderMirror> {
val androidModuleModel = this.androidModuleModel ?: return emptyList()
return androidModuleModel.allSourceProviders.map(::SourceProviderMirrorImpl)
}
override fun getActiveSourceProviders(): List<AndroidModuleInfoProvider.SourceProviderMirror> {
val androidModuleModel = this.androidModuleModel ?: return emptyList()
return androidModuleModel.activeSourceProviders.map(::SourceProviderMirrorImpl)
}
override fun getFlavorSourceProviders(): List<AndroidModuleInfoProvider.SourceProviderMirror> {
val androidModuleModel = this.androidModuleModel ?: return emptyList()
val getFlavorSourceProvidersMethod = try {
AndroidFacet::class.java.getMethod("getFlavorSourceProviders")
} catch (e: NoSuchMethodException) {
null
}
return if (getFlavorSourceProvidersMethod != null) {
@Suppress("UNCHECKED_CAST")
val sourceProviders = getFlavorSourceProvidersMethod.invoke(androidFacet) as? List<SourceProvider>
sourceProviders?.map(::SourceProviderMirrorImpl) ?: emptyList()
} else {
androidModuleModel.flavorSourceProviders.map(::SourceProviderMirrorImpl)
}
}
private class SourceProviderMirrorImpl(val sourceProvider: SourceProvider) :
AndroidModuleInfoProvider.SourceProviderMirror {
override val name: String
get() = sourceProvider.name
override val resDirectories: Collection<File>
get() = sourceProvider.resDirectories
}
}
@@ -1,200 +0,0 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.kapt.idea
import com.android.tools.idea.gradle.project.model.AndroidModuleModel
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.ProjectKeys
import com.intellij.openapi.externalSystem.model.project.*
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.tooling.model.idea.IdeaModule
import org.jetbrains.kotlin.gradle.AbstractKotlinGradleModelBuilder
import org.jetbrains.kotlin.idea.framework.GRADLE_SYSTEM_ID
import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData
import org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension
import org.jetbrains.plugins.gradle.tooling.ErrorMessageBuilder
import java.io.File
import java.io.Serializable
import java.lang.Exception
import java.lang.reflect.Modifier
interface KaptSourceSetModel : Serializable {
val sourceSetName: String
val isTest: Boolean
val generatedSourcesDir: String
val generatedClassesDir: String
val generatedKotlinSourcesDir: String
val generatedSourcesDirFile get() = generatedSourcesDir.takeIf { it.isNotEmpty() }?.let(::File)
val generatedClassesDirFile get() = generatedClassesDir.takeIf { it.isNotEmpty() }?.let(::File)
val generatedKotlinSourcesDirFile get() = generatedKotlinSourcesDir.takeIf { it.isNotEmpty() }?.let(::File)
}
class KaptSourceSetModelImpl(
override val sourceSetName: String,
override val isTest: Boolean,
override val generatedSourcesDir: String,
override val generatedClassesDir: String,
override val generatedKotlinSourcesDir: String
) : KaptSourceSetModel
interface KaptGradleModel : Serializable {
val isEnabled: Boolean
val buildDirectory: File
val sourceSets: List<KaptSourceSetModel>
}
class KaptGradleModelImpl(
override val isEnabled: Boolean,
override val buildDirectory: File,
override val sourceSets: List<KaptSourceSetModel>
) : KaptGradleModel
@Suppress("unused")
class KaptProjectResolverExtension : AbstractProjectResolverExtension() {
private companion object {
private val LOG = Logger.getInstance(KaptProjectResolverExtension::class.java)
}
override fun getExtraProjectModelClasses() = setOf(KaptGradleModel::class.java)
override fun getToolingExtensionsClasses() = setOf(KaptModelBuilderService::class.java, Unit::class.java)
override fun populateModuleExtraModels(gradleModule: IdeaModule, ideModule: DataNode<ModuleData>) {
val kaptModel = resolverCtx.getExtraProject(gradleModule, KaptGradleModel::class.java)
if (kaptModel != null && kaptModel.isEnabled) {
for (sourceSet in kaptModel.sourceSets) {
populateAndroidModuleModelIfNeeded(ideModule, sourceSet)
val sourceSetDataNode = ideModule.findGradleSourceSet(sourceSet.sourceSetName) ?: continue
fun addSourceSet(path: String, type: ExternalSystemSourceType) {
val contentRootData = ContentRootData(GRADLE_SYSTEM_ID, path)
contentRootData.storePath(type, path)
sourceSetDataNode.createChild(ProjectKeys.CONTENT_ROOT, contentRootData)
}
val sourceType = if (sourceSet.isTest) ExternalSystemSourceType.TEST_GENERATED else ExternalSystemSourceType.SOURCE_GENERATED
sourceSet.generatedSourcesDirFile?.let { addSourceSet(it.absolutePath, sourceType) }
sourceSet.generatedKotlinSourcesDirFile?.let { addSourceSet(it.absolutePath, sourceType) }
sourceSet.generatedClassesDirFile?.let { generatedClassesDir ->
val libraryData = LibraryData(GRADLE_SYSTEM_ID, "kaptGeneratedClasses")
libraryData.addPath(LibraryPathType.BINARY, generatedClassesDir.absolutePath)
val libraryDependencyData = LibraryDependencyData(sourceSetDataNode.data, libraryData, LibraryLevel.MODULE)
sourceSetDataNode.createChild(ProjectKeys.LIBRARY_DEPENDENCY, libraryDependencyData)
}
}
}
super.populateModuleExtraModels(gradleModule, ideModule)
}
private fun populateAndroidModuleModelIfNeeded(ideModule: DataNode<ModuleData>, sourceSet: KaptSourceSetModel) {
ideModule.findAndroidModuleModel()?.let { androidModelAny ->
// We can cast to AndroidModuleModel cause we already checked in findAndroidModuleModel() that the class exists
val generatedKotlinSources = sourceSet.generatedKotlinSourcesDirFile ?: return
val androidModel = androidModelAny.data as? AndroidModuleModel ?: return
val variant = androidModel.findVariantByName(sourceSet.sourceSetName) ?: return
androidModel.registerExtraGeneratedSourceFolder(generatedKotlinSources)
// TODO remove this when IDEA eventually migrate to the newer Android plugin
try {
variant.mainArtifact.generatedSourceFolders += generatedKotlinSources
} catch (e: Throwable) {
// There was an error being thrown here, but the code above doesn't work for the newer versions of Android Studio 3
// (generatedSourceFolders returns a wrapped unmodifiable list), and the thrown exception breaks the import.
// The error will be moved back when I find a work-around for AS3.
}
}
}
private fun DataNode<ModuleData>.findAndroidModuleModel(): DataNode<*>? {
val modelClassName = "com.android.tools.idea.gradle.project.model.AndroidModuleModel"
val node = children.firstOrNull { it.key.dataType == modelClassName } ?: return null
return if (!hasClassInClasspath(modelClassName)) null else node
}
private fun hasClassInClasspath(name: String): Boolean {
return try {
Class.forName(name) != null
} catch (thr: Throwable) {
false
}
}
private fun DataNode<ModuleData>.findGradleSourceSet(sourceSetName: String): DataNode<GradleSourceSetData>? {
val moduleName = data.id
for (child in children) {
val gradleSourceSetData = child.data as? GradleSourceSetData ?: continue
if (gradleSourceSetData.id == "$moduleName:$sourceSetName") {
@Suppress("UNCHECKED_CAST")
return child as DataNode<GradleSourceSetData>?
}
}
return null
}
}
class KaptModelBuilderService : AbstractKotlinGradleModelBuilder() {
override fun getErrorMessageBuilder(project: Project, e: Exception): ErrorMessageBuilder {
return ErrorMessageBuilder.create(project, e, "Gradle import errors")
.withDescription("Unable to build kotlin-kapt plugin configuration")
}
override fun canBuild(modelName: String?): Boolean = modelName == KaptGradleModel::class.java.name
override fun buildAll(modelName: String?, project: Project): Any {
val kaptPlugin: Plugin<*>? = project.plugins.findPlugin("kotlin-kapt")
val kaptIsEnabled = kaptPlugin != null
val sourceSets = mutableListOf<KaptSourceSetModel>()
if (kaptIsEnabled) {
project.getAllTasks(false)[project]?.forEach { compileTask ->
if (compileTask.javaClass.name !in kotlinCompileJvmTaskClasses) return@forEach
val sourceSetName = compileTask.getSourceSetName()
val isTest = sourceSetName.toLowerCase().endsWith("test")
val kaptGeneratedSourcesDir = getKaptDirectory("getKaptGeneratedSourcesDir", project, sourceSetName)
val kaptGeneratedClassesDir = getKaptDirectory("getKaptGeneratedClassesDir", project, sourceSetName)
val kaptGeneratedKotlinSourcesDir = getKaptDirectory("getKaptGeneratedKotlinSourcesDir", project, sourceSetName)
sourceSets += KaptSourceSetModelImpl(
sourceSetName, isTest, kaptGeneratedSourcesDir, kaptGeneratedClassesDir, kaptGeneratedKotlinSourcesDir)
}
}
return KaptGradleModelImpl(kaptIsEnabled, project.buildDir, sourceSets)
}
private fun getKaptDirectory(funName: String, project: Project, sourceSetName: String): String {
val kotlinKaptPlugin = project.plugins.findPlugin("kotlin-kapt") ?: return ""
val targetMethod = kotlinKaptPlugin::class.java.methods.firstOrNull {
Modifier.isStatic(it.modifiers) && it.name == funName && it.parameterCount == 2
} ?: return ""
return (targetMethod(null, project, sourceSetName) as? File)?.absolutePath ?: ""
}
}
@@ -1,169 +0,0 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.kapt.idea
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.ProjectKeys
import com.intellij.openapi.externalSystem.model.project.*
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.tooling.model.idea.IdeaModule
import org.jetbrains.kotlin.gradle.AbstractKotlinGradleModelBuilder
import org.jetbrains.kotlin.idea.framework.GRADLE_SYSTEM_ID
import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData
import org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension
import org.jetbrains.plugins.gradle.tooling.ErrorMessageBuilder
import java.io.File
import java.io.Serializable
import java.lang.Exception
import java.lang.reflect.Modifier
interface KaptSourceSetModel : Serializable {
val sourceSetName: String
val isTest: Boolean
val generatedSourcesDir: String
val generatedClassesDir: String
val generatedKotlinSourcesDir: String
val generatedSourcesDirFile get() = generatedSourcesDir.takeIf { it.isNotEmpty() }?.let(::File)
val generatedClassesDirFile get() = generatedClassesDir.takeIf { it.isNotEmpty() }?.let(::File)
val generatedKotlinSourcesDirFile get() = generatedKotlinSourcesDir.takeIf { it.isNotEmpty() }?.let(::File)
}
class KaptSourceSetModelImpl(
override val sourceSetName: String,
override val isTest: Boolean,
override val generatedSourcesDir: String,
override val generatedClassesDir: String,
override val generatedKotlinSourcesDir: String
) : KaptSourceSetModel
interface KaptGradleModel : Serializable {
val isEnabled: Boolean
val buildDirectory: File
val sourceSets: List<KaptSourceSetModel>
}
class KaptGradleModelImpl(
override val isEnabled: Boolean,
override val buildDirectory: File,
override val sourceSets: List<KaptSourceSetModel>
) : KaptGradleModel
@Suppress("unused")
class KaptProjectResolverExtension : AbstractProjectResolverExtension() {
private companion object {
private val LOG = Logger.getInstance(KaptProjectResolverExtension::class.java)
}
override fun getExtraProjectModelClasses() = setOf(KaptGradleModel::class.java)
override fun getToolingExtensionsClasses() = setOf(KaptModelBuilderService::class.java, Unit::class.java)
override fun populateModuleExtraModels(gradleModule: IdeaModule, ideModule: DataNode<ModuleData>) {
val kaptModel = resolverCtx.getExtraProject(gradleModule, KaptGradleModel::class.java)
if (kaptModel != null && kaptModel.isEnabled) {
for (sourceSet in kaptModel.sourceSets) {
val parentDataNode = ideModule.findParentForSourceSetDataNode(sourceSet.sourceSetName) ?: continue
fun addSourceSet(path: String, type: ExternalSystemSourceType) {
val contentRootData = ContentRootData(GRADLE_SYSTEM_ID, path)
contentRootData.storePath(type, path)
parentDataNode.createChild(ProjectKeys.CONTENT_ROOT, contentRootData)
}
val sourceType =
if (sourceSet.isTest) ExternalSystemSourceType.TEST_GENERATED else ExternalSystemSourceType.SOURCE_GENERATED
sourceSet.generatedSourcesDirFile?.let { addSourceSet(it.absolutePath, sourceType) }
sourceSet.generatedKotlinSourcesDirFile?.let { addSourceSet(it.absolutePath, sourceType) }
sourceSet.generatedClassesDirFile?.let { generatedClassesDir ->
val libraryData = LibraryData(GRADLE_SYSTEM_ID, "kaptGeneratedClasses")
val existingNode =
parentDataNode.children.map { (it.data as? LibraryDependencyData)?.target }
.firstOrNull { it?.externalName == libraryData.externalName }
if (existingNode != null) {
existingNode.addPath(LibraryPathType.BINARY, generatedClassesDir.absolutePath)
} else {
libraryData.addPath(LibraryPathType.BINARY, generatedClassesDir.absolutePath)
val libraryDependencyData = LibraryDependencyData(parentDataNode.data, libraryData, LibraryLevel.MODULE)
parentDataNode.createChild(ProjectKeys.LIBRARY_DEPENDENCY, libraryDependencyData)
}
}
}
}
super.populateModuleExtraModels(gradleModule, ideModule)
}
private fun DataNode<ModuleData>.findParentForSourceSetDataNode(sourceSetName: String): DataNode<ModuleData>? {
val moduleName = data.id
for (child in children) {
val gradleSourceSetData = child.data as? GradleSourceSetData ?: continue
if (gradleSourceSetData.id == "$moduleName:$sourceSetName") {
@Suppress("UNCHECKED_CAST")
return child as? DataNode<ModuleData>
}
}
return this
}
}
class KaptModelBuilderService : AbstractKotlinGradleModelBuilder() {
override fun getErrorMessageBuilder(project: Project, e: Exception): ErrorMessageBuilder {
return ErrorMessageBuilder.create(project, e, "Gradle import errors")
.withDescription("Unable to build kotlin-kapt plugin configuration")
}
override fun canBuild(modelName: String?): Boolean = modelName == KaptGradleModel::class.java.name
override fun buildAll(modelName: String?, project: Project): Any {
val kaptPlugin: Plugin<*>? = project.plugins.findPlugin("kotlin-kapt")
val kaptIsEnabled = kaptPlugin != null
val sourceSets = mutableListOf<KaptSourceSetModel>()
if (kaptIsEnabled) {
project.getAllTasks(false)[project]?.forEach { compileTask ->
if (compileTask.javaClass.name !in kotlinCompileJvmTaskClasses) return@forEach
val sourceSetName = compileTask.getSourceSetName()
val isTest = sourceSetName.toLowerCase().endsWith("test")
val kaptGeneratedSourcesDir = getKaptDirectory("getKaptGeneratedSourcesDir", project, sourceSetName)
val kaptGeneratedClassesDir = getKaptDirectory("getKaptGeneratedClassesDir", project, sourceSetName)
val kaptGeneratedKotlinSourcesDir = getKaptDirectory("getKaptGeneratedKotlinSourcesDir", project, sourceSetName)
sourceSets += KaptSourceSetModelImpl(
sourceSetName, isTest, kaptGeneratedSourcesDir, kaptGeneratedClassesDir, kaptGeneratedKotlinSourcesDir)
}
}
return KaptGradleModelImpl(kaptIsEnabled, project.buildDir, sourceSets)
}
private fun getKaptDirectory(funName: String, project: Project, sourceSetName: String): String {
val kotlinKaptPlugin = project.plugins.findPlugin("kotlin-kapt") ?: return ""
val targetMethod = kotlinKaptPlugin::class.java.methods.firstOrNull {
Modifier.isStatic(it.modifiers) && it.name == funName && it.parameterCount == 2
} ?: return ""
return (targetMethod(null, project, sourceSetName) as? File)?.absolutePath ?: ""
}
}
@@ -1,251 +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 org.jetbrains.kotlin.asJava.LightClassUtil
import org.jetbrains.kotlin.asJava.classes.KtLightClassForLocalDeclaration
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
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.isPropertyParameter
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.uast.*
import org.jetbrains.uast.kotlin.expressions.KotlinLocalFunctionULambdaExpression
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 {
final override val uastParent: UElement? by lz {
givenParent ?: convertParent()
}
protected open fun convertParent(): UElement? {
@Suppress("DEPRECATION")
val psi = psi //TODO: `psi` is deprecated but it seems that it couldn't be simply replaced for this case
var parent = psi?.parent ?: sourcePsi?.parent ?: psi?.containingFile
if (psi is PsiMethod && psi !is KtLightMethod) { // handling of synthetic things not represented in lightclasses directly
when (parent) {
is KtClassBody -> {
val grandParent = parent.parent
doConvertParent(this, grandParent)?.let { return it }
parent = grandParent
}
is KtFile -> {
parent.toUElementOfType<UClass>()?.let { return it } // mutlifile facade class
}
}
}
if (psi is KtLightClassForLocalDeclaration) {
val originParent = psi.kotlinOrigin.parent
parent = when (originParent) {
is KtClassBody -> originParent.parent
else -> originParent
}
}
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
AnnotationUseSiteTarget.FIELD ->
parent = (parentUnwrapped as? KtProperty)
?: (parentUnwrapped as? KtParameter)
?.takeIf { it.isPropertyParameter() }
?.let(LightClassUtil::getLightClassBackingField)
?: parent
AnnotationUseSiteTarget.SETTER_PARAMETER ->
parent = (parentUnwrapped as? KtParameter)
?.toLightSetter()?.parameterList?.parameters?.firstOrNull() ?: 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
}
if (parent is KtPropertyDelegate) {
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}], result = $result")
}
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<KotlinConstructorUMethod>()?.firstOrNull { it.isPrimary }?.let {
return it.uastBody
}
}
}
val result = KotlinUastLanguagePlugin().convertElementWithParent(parentUnwrapped, null)
if (result is KotlinUBlockExpression && element is UClass) {
return KotlinUDeclarationsExpression(result).apply {
declarations = listOf(element)
}
}
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 KotlinLocalFunctionULambdaExpression)
&& 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()
}
if (result is KotlinULambdaExpression.Body && element is UExpression && result.implicitReturn?.returnExpression == element) {
return result.implicitReturn!!
}
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<KtPrimaryConstructor>() ?: 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,
JvmDeclarationUElementPlaceholder {
override val javaPsi: PsiElement? = null
override val psi
get() = sourcePsi
override val annotations: List<UAnnotation>
get() {
val annotatedExpression = sourcePsi?.parent as? KtAnnotatedExpression ?: return emptyList()
return annotatedExpression.annotationEntries.map { KotlinUAnnotation(it, this) }
}
}
@@ -1,615 +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.findFacadeClass
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.DeclarationDescriptor
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.uast.*
import org.jetbrains.uast.kotlin.KotlinConverter.convertDeclaration
import org.jetbrains.uast.kotlin.KotlinConverter.convertDeclarationOrElement
import org.jetbrains.uast.kotlin.declarations.KotlinUIdentifier
import org.jetbrains.uast.kotlin.declarations.KotlinUMethod
import org.jetbrains.uast.kotlin.declarations.KotlinUMethodWithFakeLightDelegate
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
fun getReferenceVariants(ktElement: KtElement, nameHint: String): Sequence<DeclarationDescriptor>
}
var PsiElement.destructuringDeclarationInitializer: Boolean? by UserDataProperty(Key.create("kotlin.uast.destructuringDeclarationInitializer"))
class KotlinUastLanguagePlugin : UastLanguagePlugin {
override val priority = 10
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<out UElement>?): UElement? {
if (!element.isJvmElement) return null
return convertDeclarationOrElement(element, parent, requiredType)
}
override fun convertElementWithParent(element: PsiElement, requiredType: Class<out UElement>?): 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)
}
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)
}
override fun isExpressionValueUsed(element: UExpression): Boolean {
return when (element) {
is KotlinUSimpleReferenceExpression.KotlinAccessorCallExpression -> element.setterValue != null
is KotlinAbstractUExpression -> {
val ktElement = element.sourcePsi as? KtElement ?: return false
ktElement.analyze()[BindingContext.USED_AS_EXPRESSION, ktElement] ?: false
}
else -> false
}
}
}
internal inline fun <reified ActualT : UElement> Class<out UElement>?.el(f: () -> UElement?): UElement? {
return if (this == null || isAssignableFrom(ActualT::class.java)) f() else null
}
internal inline fun <reified ActualT : UElement> Class<out UElement>?.expr(f: () -> UExpression?): UExpression? {
return if (this == null || isAssignableFrom(ActualT::class.java)) f() else null
}
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)
is KtTypeElement -> unwrapElements(element.parent)
is KtSuperTypeList -> unwrapElements(element.parent)
else -> element
}
private val identifiersTokens =
setOf(KtTokens.IDENTIFIER, KtTokens.CONSTRUCTOR_KEYWORD, KtTokens.THIS_KEYWORD, KtTokens.SUPER_KEYWORD, KtTokens.OBJECT_KEYWORD)
internal fun convertPsiElement(element: PsiElement?,
givenParent: UElement?,
requiredType: Class<out UElement>?): UElement? {
fun <P : PsiElement> build(ctor: (P, UElement?) -> UElement): () -> UElement? {
return {
@Suppress("UNCHECKED_CAST")
ctor(element as P, givenParent)
}
}
return with (requiredType) { when (element) {
is KtParameterList -> el<UDeclarationsExpression> {
val declarationsExpression = KotlinUDeclarationsExpression(givenParent)
declarationsExpression.apply {
declarations = element.parameters.mapIndexed { i, p ->
KotlinUParameter(UastKotlinPsiParameter.create(p, element, declarationsExpression, i), p, this)
}
}
}
is KtClassBody -> el<UExpressionList>(build(KotlinUExpressionList.Companion::createClassBody))
is KtCatchClause -> el<UCatchClause>(build(::KotlinUCatchClause))
is KtVariableDeclaration ->
if (element is KtProperty && !element.isLocal) {
el<UField> {
LightClassUtil.getLightClassBackingField(element)?.let {
KotlinUField(it, element, givenParent)
}
}
}
else {
el<UVariable> {
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<UExpression> { UastEmptyExpression(givenParent) }
}
}
is KtLiteralStringTemplateEntry, is KtEscapeStringTemplateEntry -> el<ULiteralExpression>(build(::KotlinStringULiteralExpression))
is KtStringTemplateEntry -> element.expression?.let { convertExpression(it, givenParent, requiredType) } ?: expr<UExpression> { UastEmptyExpression }
is KtWhenEntry -> el<USwitchClauseExpressionWithBody>(build(::KotlinUSwitchEntry))
is KtWhenCondition -> convertWhenCondition(element, givenParent, requiredType)
is KtTypeReference -> el<UTypeReferenceExpression> { LazyKotlinUTypeReferenceExpression(element, givenParent) }
is KtConstructorDelegationCall ->
el<UCallExpression> { KotlinUFunctionCallExpression(element, givenParent) }
is KtSuperTypeCallEntry ->
el<UExpression> {
(element.getParentOfType<KtClassOrObject>(true)?.parent as? KtObjectLiteralExpression)
?.toUElementOfType<UExpression>()
?: KotlinUFunctionCallExpression(element, givenParent)
}
is KtImportDirective -> el<UImportStatement>(build(::KotlinUImportStatement))
else -> {
if (element is LeafPsiElement) {
if (element.elementType in identifiersTokens)
if (element.elementType != KtTokens.OBJECT_KEYWORD || element.getParentOfType<KtObjectDeclaration>(false)?.nameIdentifier == null)
el<UIdentifier>(build(::KotlinUIdentifier))
else null
else if (element.elementType in KtTokens.OPERATIONS && element.parent is KtOperationReferenceExpression)
el<UIdentifier>(build(::KotlinUIdentifier))
else if (element.elementType == KtTokens.LBRACKET && element.parent is KtCollectionLiteralExpression)
el<UIdentifier> {
UIdentifier(
element,
KotlinUCollectionLiteralExpression(
element.parent as KtCollectionLiteralExpression,
null
)
)
}
else null
} else null
}
}}
}
internal fun convertEntry(entry: KtStringTemplateEntry,
givenParent: UElement?,
requiredType: Class<out UElement>? = null): UExpression? {
return with(requiredType) {
if (entry is KtStringTemplateEntryWithExpression) {
expr<UExpression> {
KotlinConverter.convertOrEmpty(entry.expression, givenParent)
}
}
else {
expr<ULiteralExpression> {
if (entry is KtEscapeStringTemplateEntry)
KotlinStringULiteralExpression(entry, givenParent, entry.unescapedValue)
else
KotlinStringULiteralExpression(entry, givenParent)
}
}
}
}
internal fun convertExpression(expression: KtExpression,
givenParent: UElement?,
requiredType: Class<out UElement>? = null): UExpression? {
fun <P : PsiElement> build(ctor: (P, UElement?) -> UExpression): () -> UExpression? {
return {
@Suppress("UNCHECKED_CAST")
ctor(expression as P, givenParent)
}
}
return with (requiredType) { when (expression) {
is KtVariableDeclaration -> expr<UDeclarationsExpression>(build(::convertVariablesDeclaration))
is KtStringTemplateExpression -> {
when {
expression.entries.isEmpty() -> {
expr<ULiteralExpression> { KotlinStringULiteralExpression(expression, givenParent, "") }
}
expression.entries.size == 1 -> convertEntry(expression.entries[0], givenParent, requiredType)
else -> {
expr<UExpression> { KotlinStringTemplateUPolyadicExpression(expression, givenParent) }
}
}
}
is KtDestructuringDeclaration -> expr<UDeclarationsExpression> {
val declarationsExpression = KotlinUDestructuringDeclarationExpression(givenParent, expression)
declarationsExpression.apply {
val tempAssignment = KotlinULocalVariable(UastKotlinPsiVariable.create(expression, declarationsExpression), expression, 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.javaPsi, declarationsExpression, initializer), entry, declarationsExpression)
}
declarations = listOf(tempAssignment) + destructuringAssignments
}
}
is KtLabeledExpression -> expr<ULabeledExpression>(build(::KotlinULabeledExpression))
is KtClassLiteralExpression -> expr<UClassLiteralExpression>(build(::KotlinUClassLiteralExpression))
is KtObjectLiteralExpression -> expr<UObjectLiteralExpression>(build(::KotlinUObjectLiteralExpression))
is KtDotQualifiedExpression -> expr<UQualifiedReferenceExpression>(build(::KotlinUQualifiedReferenceExpression))
is KtSafeQualifiedExpression -> expr<UQualifiedReferenceExpression>(build(::KotlinUSafeQualifiedExpression))
is KtSimpleNameExpression -> expr<USimpleNameReferenceExpression>(build(::KotlinUSimpleReferenceExpression))
is KtCallExpression -> expr<UCallExpression>(build(::KotlinUFunctionCallExpression))
is KtCollectionLiteralExpression -> expr<UCallExpression>(build(::KotlinUCollectionLiteralExpression))
is KtBinaryExpression -> {
if (expression.operationToken == KtTokens.ELVIS) {
expr<UExpressionList>(build(::createElvisExpression))
}
else expr<UBinaryExpression>(build(::KotlinUBinaryExpression))
}
is KtParenthesizedExpression -> expr<UParenthesizedExpression>(build(::KotlinUParenthesizedExpression))
is KtPrefixExpression -> expr<UPrefixExpression>(build(::KotlinUPrefixExpression))
is KtPostfixExpression -> expr<UPostfixExpression>(build(::KotlinUPostfixExpression))
is KtThisExpression -> expr<UThisExpression>(build(::KotlinUThisExpression))
is KtSuperExpression -> expr<USuperExpression>(build(::KotlinUSuperExpression))
is KtCallableReferenceExpression -> expr<UCallableReferenceExpression>(build(::KotlinUCallableReferenceExpression))
is KtIsExpression -> expr<UBinaryExpressionWithType>(build(::KotlinUTypeCheckExpression))
is KtIfExpression -> expr<UIfExpression>(build(::KotlinUIfExpression))
is KtWhileExpression -> expr<UWhileExpression>(build(::KotlinUWhileExpression))
is KtDoWhileExpression -> expr<UDoWhileExpression>(build(::KotlinUDoWhileExpression))
is KtForExpression -> expr<UForEachExpression>(build(::KotlinUForEachExpression))
is KtWhenExpression -> expr<USwitchExpression>(build(::KotlinUSwitchExpression))
is KtBreakExpression -> expr<UBreakExpression>(build(::KotlinUBreakExpression))
is KtContinueExpression -> expr<UContinueExpression>(build(::KotlinUContinueExpression))
is KtReturnExpression -> expr<UReturnExpression>(build(::KotlinUReturnExpression))
is KtThrowExpression -> expr<UThrowExpression>(build(::KotlinUThrowExpression))
is KtBlockExpression -> expr<UBlockExpression> {
if (expression.parent is KtFunctionLiteral
&& expression.parent.parent is KtLambdaExpression
&& givenParent !is KotlinULambdaExpression
) {
KotlinULambdaExpression(expression.parent.parent as KtLambdaExpression, givenParent).body
} else
KotlinUBlockExpression(expression, givenParent)
}
is KtConstantExpression -> expr<ULiteralExpression>(build(::KotlinULiteralExpression))
is KtTryExpression -> expr<UTryExpression>(build(::KotlinUTryExpression))
is KtArrayAccessExpression -> expr<UArrayAccessExpression>(build(::KotlinUArrayAccessExpression))
is KtLambdaExpression -> expr<ULambdaExpression>(build(::KotlinULambdaExpression))
is KtBinaryExpressionWithTypeRHS -> expr<UBinaryExpressionWithType>(build(::KotlinUBinaryExpressionWithType))
is KtClassOrObject -> expr<UDeclarationsExpression> {
expression.toLightClass()?.let { lightClass ->
KotlinUDeclarationsExpression(givenParent).apply {
declarations = listOf(KotlinUClass.create(lightClass, this))
}
} ?: UastEmptyExpression(givenParent)
}
is KtFunction -> if (expression.name.isNullOrEmpty()) {
expr<ULambdaExpression>(build(::createLocalFunctionLambdaExpression))
}
else {
expr<UDeclarationsExpression>(build(::createLocalFunctionDeclaration))
}
else -> expr<UExpression>(build(::UnknownKotlinExpression))
}}
}
internal fun convertWhenCondition(condition: KtWhenCondition,
givenParent: UElement?,
requiredType: Class<out UElement>? = null
): UExpression? {
return with(requiredType) {
when (condition) {
is KtWhenConditionInRange -> expr<UBinaryExpression> {
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<UBinaryExpression> {
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<UExpression> { UastEmptyExpression(givenParent) }
}
}
}
private fun convertEnumEntry(original: KtEnumEntry, givenParent: UElement?): UElement? {
return LightClassUtil.getLightClassBackingField(original)?.let { psiField ->
if (psiField is KtLightFieldImpl.KtLightEnumConstant) {
KotlinUEnumConstant(psiField, psiField.kotlinOrigin, givenParent)
} else {
null
}
}
}
internal fun convertDeclaration(
element: PsiElement,
givenParent: UElement?,
requiredType: Class<out UElement>?
): UElement? {
fun <P : PsiElement> build(ctor: (P, UElement?) -> UElement): () -> UElement? = {
@Suppress("UNCHECKED_CAST")
ctor(element as P, givenParent)
}
fun <P : PsiElement, K : KtElement> buildKt(ktElement: K, ctor: (P, K, UElement?) -> UElement): () -> UElement? = {
@Suppress("UNCHECKED_CAST")
ctor(element as P, ktElement, givenParent)
}
fun <P : PsiElement, K : KtElement> buildKtOpt(ktElement: K?, ctor: (P, K?, UElement?) -> UElement): () -> UElement? = {
@Suppress("UNCHECKED_CAST")
ctor(element as P, ktElement, givenParent)
}
val original = element.originalElement
return with(requiredType) {
when (original) {
is KtLightMethod -> el<UMethod>(build(KotlinUMethod.Companion::create)) // .Companion is needed because of KT-13934
is KtLightClass -> when (original.kotlinOrigin) {
is KtEnumEntry -> el<UEnumConstant> {
convertEnumEntry(original.kotlinOrigin as KtEnumEntry, givenParent)
}
else -> el<UClass> { KotlinUClass.create(original, givenParent) }
}
is KtLightFieldImpl.KtLightEnumConstant -> el<UEnumConstant>(buildKtOpt(original.kotlinOrigin, ::KotlinUEnumConstant))
is KtLightField -> el<UField>(buildKtOpt(original.kotlinOrigin, ::KotlinUField))
is KtLightParameter -> el<UParameter>(buildKtOpt(original.kotlinOrigin, ::KotlinUParameter))
is UastKotlinPsiParameter -> el<UParameter>(buildKt(original.ktParameter, ::KotlinUParameter))
is UastKotlinPsiVariable -> el<UVariable>(buildKt(original.ktElement, ::KotlinUVariable))
is KtEnumEntry -> el<UEnumConstant> {
convertEnumEntry(original, givenParent)
}
is KtClassOrObject -> el<UClass> {
original.toLightClass()?.let { lightClass ->
KotlinUClass.create(lightClass, givenParent)
}
}
is KtFunction ->
if (original.isLocal) {
el<ULambdaExpression> {
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<UMethod> {
val lightMethod = LightClassUtil.getLightClassMethod(original)
if (lightMethod != null)
convertDeclaration(lightMethod, givenParent, requiredType)
else
KotlinUMethodWithFakeLightDelegate(original, givenParent)
}
}
is KtPropertyAccessor -> el<UMethod> {
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<UParameter> {
val lightMethod = when (val ownerFunction = original.ownerFunction) {
is KtFunction -> LightClassUtil.getLightClassMethod(ownerFunction)
is KtPropertyAccessor -> LightClassUtil.getLightClassAccessorMethod(ownerFunction)
else -> null
} ?: return null
val lightParameter = lightMethod.parameterList.parameters.find { it.name == original.name } ?: return null
KotlinUParameter(lightParameter, original, givenParent)
}
is KtFile -> convertKtFile(original, givenParent, requiredType)
is FakeFileForLightClass -> el<UFile> { KotlinUFile(original.navigationElement) }
is KtAnnotationEntry -> el<UAnnotation>(build(::KotlinUAnnotation))
is KtCallExpression ->
if (requiredType != null && UAnnotation::class.java.isAssignableFrom(requiredType)) {
el<UAnnotation> { KotlinUNestedAnnotation.tryCreate(original, givenParent) }
} else null
is KtLightAnnotationForSourceEntry -> convertDeclarationOrElement(original.kotlinOrigin, givenParent, requiredType)
is KtDelegatedSuperTypeEntry -> el<KotlinSupertypeDelegationUExpression> {
KotlinSupertypeDelegationUExpression(original, givenParent)
}
else -> null
}
}
}
fun convertDeclarationOrElement(element: PsiElement, givenParent: UElement?, requiredType: Class<out UElement>?): 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
}
private fun convertNonLocalProperty(
property: KtProperty,
givenParent: UElement?,
requiredType: Class<out UElement>?
): UElement? {
val methods = LightClassUtil.getLightClassPropertyMethods(property)
return methods.backingField?.let { backingField ->
with(requiredType) {
el<UField> { KotlinUField(backingField, (backingField as? KtLightElement<*, *>)?.kotlinOrigin, givenParent) }
}
} ?: methods.getter?.let { getter ->
convertDeclaration(getter, givenParent, requiredType)
}
}
private fun convertKtFile(
element: KtFile,
givenParent: UElement?,
requiredType: Class<out UElement>?
): UElement? {
if (requiredType?.isAssignableFrom(KotlinUClass::class.java) == true)
return element.findFacadeClass()?.let { KotlinUClass.create(it, givenParent) }
if (requiredType?.isAssignableFrom(KotlinUFile::class.java) != false)
return KotlinUFile(element)
return null
}
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 <TDeclaration : KtDeclaration> 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" }
@Suppress("UNCHECKED_CAST")
return declarations.first() as TDeclaration
}
}
private fun convertVariablesDeclaration(
psi: KtVariableDeclaration,
parent: UElement?
): UDeclarationsExpression {
val declarationsExpression = parent as? KotlinUDeclarationsExpression
?: psi.parent.toUElementOfType<UDeclarationsExpression>() as? KotlinUDeclarationsExpression
?: KotlinUDeclarationsExpression(null, parent, psi)
val parentPsiElement = parent?.javaPsi //TODO: looks weird. mb look for the first non-null `javaPsi` in `parents` ?
val variable = KotlinUAnnotatedLocalVariable(
UastKotlinPsiVariable.create(psi, parentPsiElement, declarationsExpression), psi, declarationsExpression) { annotationParent ->
psi.annotationEntries.map { KotlinUAnnotation(it, annotationParent) }
}
return declarationsExpression.apply { declarations = listOf(variable) }
}
val kotlinUastPlugin get() = UastLanguagePlugin.getInstances().find { it.language == KotlinLanguage.INSTANCE } ?: KotlinUastLanguagePlugin()
@@ -1,386 +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 com.intellij.psi.impl.light.LightPsiClassBuilder
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade
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.addIfNotNull
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
import org.jetbrains.uast.*
import org.jetbrains.uast.internal.acceptList
import org.jetbrains.uast.kotlin.declarations.KotlinUIdentifier
import org.jetbrains.uast.kotlin.declarations.KotlinUMethod
import org.jetbrains.uast.kotlin.declarations.UastLightIdentifier
import org.jetbrains.uast.kotlin.kinds.KotlinSpecialExpressionKinds
import org.jetbrains.uast.visitor.UastVisitor
abstract class AbstractKotlinUClass(givenParent: UElement?) : KotlinAbstractUElement(givenParent), UClassTypeSpecific, UAnchorOwner,
JvmDeclarationUElementPlaceholder {
override val uastDeclarations by lz {
mutableListOf<UDeclaration>().apply {
addAll(fields)
addAll(initializers)
addAll(methods)
addAll(innerClasses)
}
}
open val ktClass: KtClassOrObject? get() = (psi as? KtLightClass)?.kotlinOrigin
override val uastSuperTypes: List<UTypeReferenceExpression>
get() = ktClass?.superTypeListEntries.orEmpty().mapNotNull { it.typeReference }.map {
LazyKotlinUTypeReferenceExpression(it, this)
}
val delegateExpressions: List<UExpression>
get() = ktClass?.superTypeListEntries.orEmpty()
.filterIsInstance<KtDelegatedSuperTypeEntry>()
.map { KotlinSupertypeDelegationUExpression(it, this) }
override fun accept(visitor: UastVisitor) {
if (visitor.visitClass(this)) return
delegateExpressions.acceptList(visitor)
annotations.acceptList(visitor)
uastDeclarations.acceptList(visitor)
visitor.afterVisitClass(this)
}
override val annotations: List<UAnnotation> by lz {
(sourcePsi as? KtModifierListOwner)?.annotationEntries.orEmpty().map { KotlinUAnnotation(it, this) }
}
override fun equals(other: Any?) = other is AbstractKotlinUClass && psi == other.psi
override fun hashCode() = psi.hashCode()
}
class KotlinSupertypeDelegationUExpression(override val sourcePsi: KtDelegatedSuperTypeEntry, givenParent: UElement?) :
KotlinAbstractUExpression(givenParent), UExpressionList {
override val psi: PsiElement? get() = sourcePsi
val typeReference: UTypeReferenceExpression? by lazy {
sourcePsi.typeReference?.let { KotlinUTypeReferenceExpression(it.toPsiType(this), it, this) }
}
val delegateExpression: UExpression? by lazy {
sourcePsi.delegateExpression?.let { kotlinUastPlugin.convertElement(it, this, UExpression::class.java) as? UExpression }
}
override val expressions: List<UExpression>
get() = listOfNotNull(typeReference, delegateExpression)
override val kind: UastSpecialExpressionKind get() = KotlinSpecialExpressionKinds.SUPER_DELEGATION
}
open class KotlinUClass private constructor(
psi: KtLightClass,
givenParent: UElement?
) : AbstractKotlinUClass(givenParent), PsiClass by psi {
final override val ktClass = psi.kotlinOrigin
override val javaPsi: KtLightClass = psi
override val sourcePsi: KtClassOrObject? = ktClass
override val psi = unwrap<UClass, PsiClass>(psi)
override fun getSourceElement() = sourcePsi ?: this
override fun getOriginalElement(): PsiElement? = super.getOriginalElement()
override fun getNameIdentifier(): PsiIdentifier? = UastLightIdentifier(psi, ktClass)
override fun getContainingFile(): PsiFile? = unwrapFakeFileForLightClass(psi.containingFile)
override val uastAnchor by lazy { getIdentifierSourcePsi()?.let { KotlinUIdentifier(nameIdentifier, it, this) } }
private fun getIdentifierSourcePsi(): PsiElement? {
ktClass?.nameIdentifier?.let { return it }
(ktClass as? KtObjectDeclaration)?.getObjectKeyword()?.let { return it }
return null
}
override fun getInnerClasses(): Array<UClass> {
// filter DefaultImpls to avoid processing same methods from original interface multiple times
// filter Enum entry classes to avoid duplication with PsiEnumConstant initializer class
return psi.innerClasses.filter {
it.name != JvmAbi.DEFAULT_IMPLS_CLASS_NAME && !it.isEnumEntryLightClass()
}.mapNotNull {
getLanguagePlugin().convertOpt<UClass>(it, this)
}.toTypedArray()
}
override fun getSuperClass(): UClass? = super.getSuperClass()
override fun getFields(): Array<UField> = super.getFields()
override fun getInitializers(): Array<UClassInitializer> = super.getInitializers()
override fun getMethods(): Array<UMethod> {
val hasPrimaryConstructor = ktClass?.hasPrimaryConstructor() ?: false
var secondaryConstructorsCount = 0
fun createUMethod(psiMethod: PsiMethod): UMethod {
return if (psiMethod is KtLightMethod &&
psiMethod.isConstructor) {
if (!hasPrimaryConstructor && secondaryConstructorsCount++ == 0)
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
val result = ArrayList<UMethod>(javaPsi.methods.size)
val handledKtDeclarations = mutableSetOf<PsiElement>()
for (lightMethod in javaPsi.methods) {
if (isDelegatedMethod(lightMethod)) continue
val uMethod = createUMethod(lightMethod)
result.add(uMethod)
handledKtDeclarations.addIfNotNull(uMethod.sourcePsi)
}
val ktDeclarations: List<KtDeclaration> = run ktDeclarations@{
ktClass?.let { return@ktDeclarations it.declarations }
(javaPsi as? KtLightClassForFacade)?.let { facade ->
return@ktDeclarations facade.files.flatMap { file -> file.declarations }
}
emptyList()
}
ktDeclarations.asSequence()
.filterNot { handledKtDeclarations.contains(it) }
.mapNotNullTo(result) { KotlinConverter.convertDeclaration(it, this, null) as? UMethod }
return result.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, psi.kotlinOrigin, 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<KtSuperTypeCallEntry>()
it is KtSecondaryConstructor -> it.getDelegationCall()
else -> null
}
}
val bodyExpressions = getBodyExpressions()
if (delegationCall == null && bodyExpressions.isEmpty()) return@lz null
KotlinUBlockExpression.KotlinLazyUBlockExpression(this) { uastParent ->
SmartList<UExpression>().apply {
delegationCall?.let {
add(KotlinUFunctionCallExpression(it, uastParent))
}
bodyExpressions.forEach {
add(KotlinConverter.convertOrEmpty(it, uastParent))
}
}
}
}
override val uastAnchor: KotlinUIdentifier by lazy {
KotlinUIdentifier(
psi.nameIdentifier,
if (isPrimary) ktClass?.nameIdentifier else (psi.kotlinOrigin as? KtSecondaryConstructor)?.getConstructorKeyword(),
this
)
}
override val javaPsi = psi
open protected fun getBodyExpressions(): List<KtExpression> {
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<KtExpression> = getInitializers() + super.getBodyExpressions()
}
class KotlinUAnonymousClass(
psi: PsiAnonymousClass,
givenParent: UElement?
) : AbstractKotlinUClass(givenParent), UAnonymousClass, PsiAnonymousClass by psi {
override val psi: PsiAnonymousClass = unwrap<UAnonymousClass, PsiAnonymousClass>(psi)
override val javaPsi: PsiAnonymousClass = psi
override val sourcePsi: KtClassOrObject? = ktClass
override fun getOriginalElement(): PsiElement? = super<AbstractKotlinUClass>.getOriginalElement()
override fun getSuperClass(): UClass? = super<AbstractKotlinUClass>.getSuperClass()
override fun getFields(): Array<UField> = super<AbstractKotlinUClass>.getFields()
override fun getMethods(): Array<UMethod> = super<AbstractKotlinUClass>.getMethods()
override fun getInitializers(): Array<UClassInitializer> = super<AbstractKotlinUClass>.getInitializers()
override fun getInnerClasses(): Array<UClass> = super<AbstractKotlinUClass>.getInnerClasses()
override fun getContainingFile(): PsiFile = unwrapFakeFileForLightClass(psi.containingFile)
override val uastAnchor by lazy {
val ktClassOrObject = (psi.originalElement as? KtLightClass)?.kotlinOrigin as? KtObjectDeclaration ?: return@lazy null
KotlinUIdentifier(ktClassOrObject.getObjectKeyword(), this)
}
}
class KotlinScriptUClass(
psi: KtLightClassForScript,
givenParent: UElement?
) : AbstractKotlinUClass(givenParent), PsiClass by psi {
override fun getContainingFile(): PsiFile = unwrapFakeFileForLightClass(psi.containingFile)
override fun getNameIdentifier(): PsiIdentifier? = UastLightIdentifier(psi, psi.kotlinOrigin)
override val uastAnchor by lazy { KotlinUIdentifier(nameIdentifier, sourcePsi?.nameIdentifier, this) }
override val javaPsi: PsiClass = psi
override val sourcePsi: KtClassOrObject? = psi.kotlinOrigin
override val psi = unwrap<UClass, KtLightClassForScript>(psi)
override fun getSuperClass(): UClass? = super.getSuperClass()
override fun getFields(): Array<UField> = super.getFields()
override fun getInitializers(): Array<UClassInitializer> = super.getInitializers()
override fun getInnerClasses(): Array<UClass> =
psi.innerClasses.mapNotNull { getLanguagePlugin().convertOpt<UClass>(it, this) }.toTypedArray()
override fun getMethods(): Array<UMethod> = 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,
givenParent: UElement?
) : KotlinUMethod(psi, psi.kotlinOrigin, givenParent) {
override val uastBody: UExpression? by lz {
val initializers = script.declarations.filterIsInstance<KtScriptInitializer>()
KotlinUBlockExpression.create(initializers, this)
}
override val javaPsi = psi
}
}
/**
* implementation of [UClass] for invalid code, when it is impossible to create a [KtLightClass]
*/
class KotlinInvalidUClass(
override val psi: PsiClass,
givenParent: UElement?
) : AbstractKotlinUClass(givenParent), PsiClass by psi {
constructor(name: String, context: PsiElement, givenParent: UElement?) : this(LightPsiClassBuilder(context, name), givenParent)
override fun getContainingFile(): PsiFile? = uastParent?.getContainingUFile()?.sourcePsi as? PsiFile
override val sourcePsi: PsiElement? get() = null
override val uastAnchor: UIdentifier? get() = null
override val javaPsi: PsiClass get() = psi
override fun getFields(): Array<UField> = emptyArray()
override fun getInitializers(): Array<UClassInitializer> = emptyArray()
override fun getInnerClasses(): Array<UClass> = emptyArray()
override fun getMethods(): Array<UMethod> = emptyArray()
override fun getSuperClass(): UClass? = null
override fun getOriginalElement(): PsiElement? = null
}
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
}
@@ -1,195 +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.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiNameIdentifierOwner
import com.intellij.psi.impl.light.LightMethodBuilder
import com.intellij.psi.impl.light.LightModifierList
import com.intellij.psi.impl.light.LightParameterListBuilder
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.asJava.findFacadeClass
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.utils.SmartList
import org.jetbrains.uast.*
import org.jetbrains.uast.java.internal.JavaUElementWithComments
import org.jetbrains.uast.kotlin.*
open class KotlinUMethod(
psi: PsiMethod,
final override val sourcePsi: KtDeclaration?,
givenParent: UElement?
) : KotlinAbstractUElement(givenParent), UMethodTypeSpecific, UAnchorOwner, JavaUElementWithComments, PsiMethod by psi {
constructor(psi: KtLightMethod, givenParent: UElement?) : this(psi, psi.kotlinOrigin, givenParent)
override val comments: List<UComment>
get() = super<KotlinAbstractUElement>.comments
override val psi: PsiMethod = unwrap<UMethod, PsiMethod>(psi)
override val javaPsi = psi
override fun getSourceElement() = sourcePsi ?: this
private val kotlinOrigin = (psi.originalElement as? KtLightElement<*, *>)?.kotlinOrigin ?: sourcePsi
override fun getContainingFile(): PsiFile? {
kotlinOrigin?.containingFile?.let { return it }
return unwrapFakeFileForLightClass(psi.containingFile)
}
override fun getNameIdentifier() = UastLightIdentifier(psi, kotlinOrigin as KtNamedDeclaration?)
override val annotations: List<UAnnotation> by lz {
psi.annotations
.mapNotNull { (it as? KtLightElement<*, *>)?.kotlinOrigin as? KtAnnotationEntry }
.map { KotlinUAnnotation(it, this) }
}
private val receiver by lz { (sourcePsi as? KtCallableDeclaration)?.receiverTypeReference }
override val uastParameters by lz {
val lightParams = psi.parameterList.parameters
val receiver = receiver ?: return@lz lightParams.map {
KotlinUParameter(it, (it as? KtLightElement<*, *>)?.kotlinOrigin, this)
}
val receiverLight = lightParams.firstOrNull() ?: return@lz emptyList<UParameter>()
val uParameters = SmartList<UParameter>(KotlinReceiverUParameter(receiverLight, receiver, this))
lightParams.drop(1).mapTo(uParameters) { KotlinUParameter(it, (it as? KtLightElement<*, *>)?.kotlinOrigin, this) }
uParameters
}
override val uastAnchor by lazy {
KotlinUIdentifier(
nameIdentifier,
sourcePsi.let { sourcePsi ->
when (sourcePsi) {
is PsiNameIdentifierOwner -> sourcePsi.nameIdentifier
is KtObjectDeclaration -> sourcePsi.getObjectKeyword()
else -> sourcePsi?.navigationElement
}
},
this
)
}
override val uastBody by lz {
if (kotlinOrigin?.canAnalyze() != true) return@lz null // EA-137193
val bodyExpression = when (kotlinOrigin) {
is KtFunction -> kotlinOrigin.bodyExpression
is KtProperty -> when {
psi is KtLightMethod && psi.isGetter -> kotlinOrigin.getter?.bodyExpression
psi is KtLightMethod && psi.isSetter -> kotlinOrigin.setter?.bodyExpression
else -> null
}
else -> null
} ?: return@lz null
wrapExpressionBody(this, bodyExpression)
}
override val isOverride: Boolean
get() = (kotlinOrigin as? KtCallableDeclaration)?.hasModifier(KtTokens.OVERRIDE_KEYWORD) ?: false
override fun equals(other: Any?) = other is KotlinUMethod && psi == other.psi
companion object {
fun create(psi: KtLightMethod, containingElement: UElement?): KotlinUMethod {
val kotlinOrigin = psi.kotlinOrigin
return if (kotlinOrigin is KtConstructor<*>) {
KotlinConstructorUMethod(
kotlinOrigin.containingClassOrObject,
psi,
containingElement
)
} else if (kotlinOrigin is KtParameter && kotlinOrigin.getParentOfType<KtClass>(true)?.isAnnotation() == true)
KotlinUAnnotationMethod(psi, containingElement)
else
KotlinUMethod(psi, containingElement)
}
}
}
open class KotlinUAnnotationMethod(
psi: KtLightMethod,
givenParent: UElement?
) : KotlinUMethod(psi, psi.kotlinOrigin, givenParent), UAnnotationMethod {
override val psi: KtLightMethod = unwrap<UMethod, KtLightMethod>(psi)
override val uastDefaultValue by lz {
val annotationParameter = sourcePsi as? KtParameter ?: return@lz null
val defaultValue = annotationParameter.defaultValue ?: return@lz null
getLanguagePlugin().convertElement(defaultValue, this) as? UExpression
}
}
private fun buildLightMethodFake(original: KtFunction): PsiMethod = object : LightMethodBuilder(
original.manager, original.language, original.name,
LightParameterListBuilder(original.manager, original.language),
LightModifierList(original.manager)
) {
init {
containingClass = original.containingClassOrObject?.toLightClass() ?: original.containingKtFile.findFacadeClass()
}
override fun getParent(): PsiElement? = containingClass
}
class KotlinUMethodWithFakeLightDelegate(val original: KtFunction, givenParent: UElement?) :
KotlinUMethod(buildLightMethodFake(original), original, givenParent) {
override val annotations: List<UAnnotation>
get() = original.annotationEntries.mapNotNull { it.toUElementOfType<UAnnotation>() }
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as KotlinUMethodWithFakeLightDelegate
if (original != other.original) return false
return true
}
override fun hashCode(): Int = original.hashCode()
}
internal fun wrapExpressionBody(function: UElement, bodyExpression: KtExpression): UExpression? = when (bodyExpression) {
!is KtBlockExpression -> {
KotlinUBlockExpression.KotlinLazyUBlockExpression(function) { block ->
val implicitReturn = KotlinUImplicitReturnExpression(block)
val uBody = function.getLanguagePlugin().convertElement(bodyExpression, implicitReturn) as? UExpression
?: return@KotlinLazyUBlockExpression emptyList()
listOf(implicitReturn.apply { returnExpression = uBody })
}
}
else -> function.getLanguagePlugin().convertElement(bodyExpression, function) as? UExpression
}
@@ -1,56 +0,0 @@
package org.jetbrains.uast.kotlin.evaluation
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.uast.UBinaryExpression
import org.jetbrains.uast.UastPostfixOperator
import org.jetbrains.uast.evaluation.AbstractEvaluatorExtension
import org.jetbrains.uast.evaluation.UEvaluationInfo
import org.jetbrains.uast.evaluation.UEvaluationState
import org.jetbrains.uast.kotlin.KotlinBinaryOperators
import org.jetbrains.uast.kotlin.KotlinPostfixOperators
import org.jetbrains.uast.values.*
class KotlinEvaluatorExtension : AbstractEvaluatorExtension(KotlinLanguage.INSTANCE) {
private data class Range(val from: UValue, val to: UValue) {
override fun toString() = "$from..$to"
}
private class UClosedRangeConstant(override val value: Range, override val source: UBinaryExpression?) : UAbstractConstant() {
constructor(from: UValue, to: UValue, source: UBinaryExpression): this(Range(from, to), source)
}
override fun evaluatePostfix(
operator: UastPostfixOperator,
operandValue: UValue,
state: UEvaluationState
): UEvaluationInfo {
return when (operator) {
KotlinPostfixOperators.EXCLEXCL -> when (operandValue.toConstant()) {
UNullConstant -> UValue.UNREACHABLE
is UConstant -> operandValue
else -> UUndeterminedValue
} to state
else -> return super.evaluatePostfix(operator, operandValue, state)
}
}
private fun UValue.contains(value: UValue): UValue {
val range = (this as? UClosedRangeConstant)?.value ?: return UUndeterminedValue
return (value greaterOrEquals range.from) and (value lessOrEquals range.to)
}
override fun evaluateBinary(
binaryExpression: UBinaryExpression,
leftValue: UValue,
rightValue: UValue,
state: UEvaluationState
): UEvaluationInfo {
return when (binaryExpression.operator) {
KotlinBinaryOperators.IN -> rightValue.contains(leftValue)
KotlinBinaryOperators.NOT_IN -> !rightValue.contains(leftValue)
KotlinBinaryOperators.RANGE_TO -> UClosedRangeConstant(leftValue, rightValue, binaryExpression)
else -> UUndeterminedValue
} to state
}
}
@@ -1,121 +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.declarations.KotlinUIdentifier
import org.jetbrains.uast.kotlin.kinds.KotlinSpecialExpressionKinds
import org.jetbrains.uast.kotlin.psi.UastKotlinPsiVariable
private fun createVariableReferenceExpression(variable: UVariable, containingElement: UElement?) =
object : USimpleNameReferenceExpression, JvmDeclarationUElementPlaceholder {
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<UAnnotation> = emptyList()
override val identifier: String = variable.name.orAnonymous()
override val javaPsi: PsiElement? = null
override val sourcePsi: PsiElement? = null
}
private fun createNullLiteralExpression(containingElement: UElement?) =
object : ULiteralExpression, JvmDeclarationUElementPlaceholder {
override val psi: PsiElement? = null
override val uastParent: UElement? = containingElement
override val value: Any? = null
override val annotations: List<UAnnotation> = emptyList()
override val javaPsi: PsiElement? = null
override val sourcePsi: PsiElement? = null
}
private fun createNotEqWithNullExpression(variable: UVariable, containingElement: UElement?) =
object : UBinaryExpression, JvmDeclarationUElementPlaceholder {
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? = KotlinUIdentifier(null, this)
override fun resolveOperator(): PsiMethod? = null
override val annotations: List<UAnnotation> = emptyList()
override val javaPsi: PsiElement? = null
override val sourcePsi: PsiElement? = null
}
private fun createElvisExpressions(
left: KtExpression,
right: KtExpression,
containingElement: UElement?,
psiParent: PsiElement): List<UExpression> {
val declaration = KotlinUDeclarationsExpression(containingElement)
val tempVariable = KotlinULocalVariable(UastKotlinPsiVariable.create(left, declaration, psiParent), left, declaration)
declaration.declarations = listOf(tempVariable)
val ifExpression = object : UIfExpression, JvmDeclarationUElementPlaceholder {
override val psi: PsiElement? = null
override val uastParent: UElement? = containingElement
override val javaPsi: PsiElement? = null
override val sourcePsi: PsiElement? = null
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<UAnnotation> = emptyList()
override val ifIdentifier: UIdentifier = KotlinUIdentifier(null, this)
override val elseIdentifier: UIdentifier? = KotlinUIdentifier(null, this)
}
return listOf(declaration, ifExpression)
}
fun createElvisExpression(elvisExpression: KtBinaryExpression, givenParent: UElement?): UExpression {
val left = elvisExpression.left ?: return UastEmptyExpression(givenParent)
val right = elvisExpression.right ?: return UastEmptyExpression(givenParent)
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 javaPsi: PsiElement? = null
override val sourcePsi: PsiElement? = elvisExpression
override val psi: PsiElement? = sourcePsi
override val kind = KotlinSpecialExpressionKinds.ELVIS
override val annotations: List<UAnnotation> = emptyList()
override val expressions: List<UExpression> 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)
}
}

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