Initial settings for incompatible API inspection

This commit is contained in:
Nikolay Krasko
2018-05-16 14:56:28 +03:00
parent 3ef67e1d9d
commit 580e2972db
19 changed files with 102 additions and 594 deletions
+19
View File
@@ -98,6 +98,25 @@
<option name="insideTryAllowed" value="false" />
</inspection_tool>
<inspection_tool class="IfStatementWithIdenticalBranches" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="IncompatibleAPI" enabled="true" level="ERROR" enabled_by_default="true">
<option name="problems">
<list>
<Problem reference="org.jetbrains.plugins.gradle.util.GradleConstants#KOTLIN_DSL_SCRIPT_EXTENSION" reason="Absent in 172. Please inline." />
<Problem reference="com.intellij.psi.impl.compiled.ClsClassImpl#getQualifiedName" reason="Nullable in 173, platform in 172. Use qualifiedNameEx instead." />
<Problem reference="com.intellij.internal.statistic.utils.StatisticsUtilKt#getEnumUsage" reason="Absent in 172. Use org.jetbrains.kotlin.idea.util.compat.statistic.StatisticKt.getEnumUsage instead." />
<Problem reference="com.intellij.internal.statistic.utils.StatisticsUtilKt#getBooleanUsage" reason="Absent in 172 Use org.jetbrains.kotlin.idea.util.compat.statistic.StatisticKt.getBooleanUsage instead." />
<Problem reference="com.intellij.internal.statistic.AbstractProjectsUsagesCollector" reason="Absent in 172. Use org.jetbrains.kotlin.idea.util.compat.statistic.AbstractProjectsUsagesCollector instead." />
<Problem reference="com.intellij.openapi.progress.ProgressManager#getProgressIndicator" reason="Not null starting from 181. Use getProgressIndicatorNullable instead." />
<Problem reference="com.intellij.testFramework.PlatformTestCase#createModuleAt" reason="Not static anymore in 181 after 7dacf096c47d2125e17031c71a037b63ab00ec53" />
<Problem reference="com.intellij.testFramework.PlatformTestCase#doCreateRealModuleIn" reason="Not static anymore in 181 after 7dacf096c47d2125e17031c71a037b63ab00ec53" />
<Problem reference="com.intellij.openapi.progress.ProgressManager#getProgressIndicator" reason="Nullable in 181. Temporary use progressIndicatorNullable instead." />
<Problem reference="com.intellij.testFramework.fixtures.CodeInsightTestFixture#getProjectDisposable" reason="Method was introduced in 173 and absent in 172. Use getProjectDisposableEx instead. (95eaf81e0ea497f8c69263c11fd3202d28a7a1b2)" />
<Problem reference="org.jetbrains.org.objectweb.asm.Opcodes#V9" reason="Absent in 172 branch. Use V1_9 while 172 is supported." />
<Problem reference="com.intellij.psi.codeStyle.CommonCodeStyleSettings#getSoftMargins" reason="Absent in 172." />
<Problem reference="com.intellij.util.xmlb.XmlSerializer#serializeInto(java.lang.Object, org.jdom.Element)" reason="Absent in 172." />
</list>
</option>
</inspection_tool>
<inspection_tool class="InnerClassMayBeStatic" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="InstanceofCatchParameter" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="InstanceofIncompatibleInterface" enabled="true" level="WARNING" enabled_by_default="true" />
@@ -24,12 +24,13 @@ enum class JvmTarget(override val description: String) : TargetPlatformVersion {
;
val bytecodeVersion: Int by lazy {
@Suppress("DEPRECATION")
when (this) {
JVM_1_6 -> Opcodes.V1_6
JVM_1_8 ->
when {
java.lang.Boolean.valueOf(System.getProperty("kotlin.test.substitute.bytecode.1.8.to.10")) -> Opcodes.V9 + 1
java.lang.Boolean.valueOf(System.getProperty("kotlin.test.substitute.bytecode.1.8.to.1.9")) -> Opcodes.V9
java.lang.Boolean.valueOf(System.getProperty("kotlin.test.substitute.bytecode.1.8.to.10")) -> Opcodes.V1_9 + 1
java.lang.Boolean.valueOf(System.getProperty("kotlin.test.substitute.bytecode.1.8.to.1.9")) -> Opcodes.V1_9
else -> Opcodes.V1_8
}
}
@@ -43,6 +44,7 @@ enum class JvmTarget(override val description: String) : TargetPlatformVersion {
fun fromString(string: String) = values().find { it.description == string }
fun getDescription(bytecodeVersion: Int): String {
@Suppress("DEPRECATION")
val platformDescription = values().find { it.bytecodeVersion == bytecodeVersion }?.description ?:
when (bytecodeVersion) {
Opcodes.V1_7 -> "1.7"
@@ -1,57 +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.config
import org.jetbrains.org.objectweb.asm.Opcodes
enum class JvmTarget(override val description: String) : TargetPlatformVersion {
JVM_1_6("1.6"),
JVM_1_8("1.8"),
;
val bytecodeVersion: Int by lazy {
when (this) {
JVM_1_6 -> Opcodes.V1_6
JVM_1_8 ->
when {
java.lang.Boolean.valueOf(System.getProperty("kotlin.test.substitute.bytecode.1.8.to.10")) -> Opcodes.V1_9 + 1
java.lang.Boolean.valueOf(System.getProperty("kotlin.test.substitute.bytecode.1.8.to.1.9")) -> Opcodes.V1_9
else -> Opcodes.V1_8
}
}
}
companion object {
@JvmField
val DEFAULT = JVM_1_6
@JvmStatic
fun fromString(string: String) = values().find { it.description == string }
fun getDescription(bytecodeVersion: Int): String {
val platformDescription = values().find { it.bytecodeVersion == bytecodeVersion }?.description ?:
when (bytecodeVersion) {
Opcodes.V1_7 -> "1.7"
Opcodes.V1_9 -> "1.9"
else -> null
}
return if (platformDescription != null) "JVM target $platformDescription"
else "JVM bytecode version $bytecodeVersion"
}
}
}
@@ -90,7 +90,7 @@ public class KotlinCommonCodeStyleSettings extends CommonCodeStyleSettings {
}
//noinspection deprecation
DefaultJDOMExternalizer.writeExternal(this, element, new SupportedFieldsDiffFilter(this, supportedFields, defaultSettings));
List<Integer> softMargins = getSoftMargins();
@SuppressWarnings("IncompatibleAPI") List<Integer> softMargins = getSoftMargins();
serializeInto(softMargins, element);
IndentOptions myIndentOptions = getIndentOptions();
@@ -148,6 +148,7 @@ public class KotlinCommonCodeStyleSettings extends CommonCodeStyleSettings {
if (setRootSettingsMethod != null) {
// Method was introduced in 173
setRootSettingsMethod.setAccessible(true);
//noinspection IncompatibleAPI
setRootSettingsMethod.invoke(commonSettings, getSoftMargins());
}
}
@@ -169,6 +170,7 @@ public class KotlinCommonCodeStyleSettings extends CommonCodeStyleSettings {
}
CommonCodeStyleSettings other = (CommonCodeStyleSettings) obj;
//noinspection IncompatibleAPI
if (!getSoftMargins().equals(other.getSoftMargins())) {
return false;
}
@@ -185,6 +187,7 @@ public class KotlinCommonCodeStyleSettings extends CommonCodeStyleSettings {
// SoftMargins.serializeInfo
private void serializeInto(@NotNull List<Integer> softMargins, @NotNull Element element) {
if (softMargins.size() > 0) {
//noinspection IncompatibleAPI
XmlSerializer.serializeInto(this, element);
}
}
@@ -12,4 +12,5 @@ import com.intellij.testFramework.fixtures.CodeInsightTestFixture
* Method was introduced in 173 idea. Should be dropped after abandoning 172 branch.
* BUNCH: 173
*/
@Suppress("IncompatibleAPI")
val CodeInsightTestFixture.projectDisposableEx: Disposable get() = projectDisposable
@@ -12,4 +12,5 @@ import com.intellij.testFramework.fixtures.CodeInsightTestFixture
* Method was introduced in 173 idea. Should be dropped after abandoning 172 branch.
* BUNCH: 173
*/
@Suppress("IncompatibleAPI")
val CodeInsightTestFixture.projectDisposableEx: Disposable get() = project
@@ -24,6 +24,7 @@ import org.jetbrains.kotlin.asJava.classes.KtLightClassBase
import org.jetbrains.kotlin.asJava.elements.KtLightFieldImpl
import org.jetbrains.kotlin.asJava.elements.KtLightMethodImpl
import org.jetbrains.kotlin.idea.decompiler.classFile.KtClsFile
import org.jetbrains.kotlin.idea.util.qualifiedNameEx
import org.jetbrains.kotlin.load.java.structure.LightClassOriginKind
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtClassOrObject
@@ -33,7 +34,7 @@ class KtLightClassForDecompiledDeclaration(
override val kotlinOrigin: KtClassOrObject?,
private val file: KtClsFile
) : KtLightClassBase(clsDelegate.manager) {
val fqName = kotlinOrigin?.fqName ?: FqName(clsDelegate.qualifiedName.orEmpty())
val fqName = kotlinOrigin?.fqName ?: FqName(clsDelegate.qualifiedNameEx.orEmpty())
override fun copy() = this
@@ -1,71 +0,0 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.idea.caches.lightClasses
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiField
import com.intellij.psi.PsiMethod
import com.intellij.psi.impl.compiled.ClsClassImpl
import org.jetbrains.kotlin.asJava.classes.KtLightClassBase
import org.jetbrains.kotlin.asJava.elements.KtLightFieldImpl
import org.jetbrains.kotlin.asJava.elements.KtLightMethodImpl
import org.jetbrains.kotlin.idea.decompiler.classFile.KtClsFile
import org.jetbrains.kotlin.load.java.structure.LightClassOriginKind
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtClassOrObject
class KtLightClassForDecompiledDeclaration(
override val clsDelegate: ClsClassImpl,
override val kotlinOrigin: KtClassOrObject?,
private val file: KtClsFile
) : KtLightClassBase(clsDelegate.manager) {
val fqName = kotlinOrigin?.fqName ?: FqName(clsDelegate.qualifiedName)
override fun copy() = this
override fun getOwnInnerClasses(): List<PsiClass> {
val nestedClasses = kotlinOrigin?.declarations?.filterIsInstance<KtClassOrObject>() ?: emptyList()
return clsDelegate.ownInnerClasses.map { innerClsClass ->
KtLightClassForDecompiledDeclaration(innerClsClass as ClsClassImpl,
nestedClasses.firstOrNull { innerClsClass.name == it.name }, file
)
}
}
override fun getOwnFields(): List<PsiField> {
return clsDelegate.ownFields.map { KtLightFieldImpl.create(LightMemberOriginForCompiledField(it, file), it, this) }
}
override fun getOwnMethods(): List<PsiMethod> {
return clsDelegate.ownMethods.map { KtLightMethodImpl.create(it, LightMemberOriginForCompiledMethod(it, file), this) }
}
override fun getNavigationElement() = kotlinOrigin?.navigationElement ?: file
override fun getParent() = clsDelegate.parent
override fun equals(other: Any?): Boolean =
other is KtLightClassForDecompiledDeclaration &&
fqName == other.fqName
override fun hashCode(): Int =
fqName.hashCode()
override val originKind: LightClassOriginKind
get() = LightClassOriginKind.BINARY
}
@@ -50,4 +50,5 @@ fun <T> Project.executeCommand(name: String, groupId: Any? = null, command: () -
* ProgressManager.getProgressIndicator() is nullable in 181 and dynamic again in 182
* BUNCH: 181
*/
@Suppress("IncompatibleAPI")
val ProgressManager.progressIndicatorNullable: ProgressIndicator? get() = progressIndicator
@@ -0,0 +1,15 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.util
import com.intellij.psi.impl.compiled.ClsClassImpl
/**
* Nullable wrapper for qualifiedName.
* BUNCH: 173
*/
@Suppress("IncompatibleAPI")
val ClsClassImpl.qualifiedNameEx: String? get() = qualifiedName
@@ -12,7 +12,12 @@ import com.intellij.openapi.project.Project;
import com.intellij.testFramework.PlatformTestCase;
import org.jetbrains.annotations.NotNull;
@SuppressWarnings("MethodMayBeStatic")
/**
* Wrapper for CompletionTestCase that deals with compatibility issues.
* Should be dropped after abandoning 173.
* BUNCH: 181
*/
@SuppressWarnings({"MethodMayBeStatic", "IncompatibleAPI"})
abstract public class CompletionTestCaseWrapper extends CompletionTestCase {
protected Module createModuleAtWrapper(String moduleName, Project project, ModuleType moduleType, String path) {
return createModuleAt(moduleName, project, moduleType, path);
@@ -226,6 +226,10 @@ class GradleScriptDefinitionsContributor(private val project: Project) : ScriptD
}
private class ErrorGradleScriptDefinition(message: String? = null) : KotlinScriptDefinition(ScriptTemplateWithArgs::class) {
companion object {
private const val KOTLIN_DSL_SCRIPT_EXTENSION = ".gradle.kts"
}
override val name: String = "Default Kotlin Gradle Script"
override val fileType: LanguageFileType = KotlinFileType.INSTANCE
override val annotationsForSamWithReceivers: List<String> = emptyList()
@@ -234,10 +238,10 @@ class GradleScriptDefinitionsContributor(private val project: Project) : ScriptD
override val dependencyResolver: DependenciesResolver = ErrorScriptDependenciesResolver(message)
override fun getScriptName(script: KtScript) =
Name.identifier(script.containingKtFile.name.removeSuffix(GradleConstants.KOTLIN_DSL_SCRIPT_EXTENSION))
Name.identifier(script.containingKtFile.name.removeSuffix(KOTLIN_DSL_SCRIPT_EXTENSION))
override fun isScript(fileName: String): Boolean =
fileName.endsWith(GradleConstants.KOTLIN_DSL_SCRIPT_EXTENSION)
fileName.endsWith(KOTLIN_DSL_SCRIPT_EXTENSION)
override fun toString(): String = "ErrorGradleScriptDefinition"
}
@@ -1,339 +0,0 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.idea.core.script
import com.intellij.execution.configurations.CommandLineTokenizer
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListenerAdapter
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.fileTypes.LanguageFileType
import com.intellij.openapi.project.Project
import org.gradle.tooling.ProjectConnection
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.framework.GRADLE_SYSTEM_ID
import org.jetbrains.kotlin.lexer.KotlinLexer
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtScript
import org.jetbrains.kotlin.script.KotlinScriptDefinition
import org.jetbrains.kotlin.script.KotlinScriptDefinitionFromAnnotatedTemplate
import org.jetbrains.plugins.gradle.config.GradleSettingsListenerAdapter
import org.jetbrains.plugins.gradle.service.execution.GradleExecutionHelper
import org.jetbrains.plugins.gradle.settings.DistributionType
import org.jetbrains.plugins.gradle.settings.GradleExecutionSettings
import org.jetbrains.plugins.gradle.settings.GradleProjectSettings
import org.jetbrains.plugins.gradle.settings.GradleSettingsListener
import org.jetbrains.plugins.gradle.util.GradleConstants
import java.io.File
import java.util.*
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.reflect.KClass
import kotlin.script.dependencies.Environment
import kotlin.script.dependencies.ScriptContents
import kotlin.script.experimental.dependencies.DependenciesResolver
import kotlin.script.experimental.dependencies.DependenciesResolver.ResolveResult
import kotlin.script.experimental.dependencies.ScriptReport
import kotlin.script.experimental.location.ScriptExpectedLocation
import kotlin.script.templates.standard.ScriptTemplateWithArgs
class GradleScriptDefinitionsContributor(private val project: Project) : ScriptDefinitionContributor {
override val id: String = "Gradle Kotlin DSL"
private val failedToLoad = AtomicBoolean(false)
init {
subscribeToGradleSettingChanges()
}
private fun subscribeToGradleSettingChanges() {
val listener = object : GradleSettingsListenerAdapter() {
override fun onGradleVmOptionsChange(oldOptions: String?, newOptions: String?) {
reload()
}
override fun onGradleHomeChange(oldPath: String?, newPath: String?, linkedProjectPath: String) {
reload()
}
override fun onServiceDirectoryPathChange(oldPath: String?, newPath: String?) {
reload()
}
override fun onGradleDistributionTypeChange(currentValue: DistributionType?, linkedProjectPath: String) {
reload()
}
}
project.messageBus.connect(project).subscribe(GradleSettingsListener.TOPIC, listener)
ServiceManager.getService(project, ScriptModificationListener::class.java)
}
override fun getDefinitions(): List<KotlinScriptDefinition> {
return loadDefinitions()
}
// NOTE: control flow here depends on suppressing exceptions from loadGradleTemplates calls
// TODO: possibly combine exceptions from every loadGradleTemplates call, be mindful of KT-19276
private fun loadDefinitions(): List<KotlinScriptDefinition> {
val kotlinDslDependencySelector = Regex("^gradle-(?:kotlin-dsl|core).*\\.jar\$")
val kotlinDslAdditionalResolverCp = ::kotlinStdlibAndCompiler
failedToLoad.set(false)
// KotlinBuildScript should be last because it has wide scriptFilePattern
val kotlinDslTemplates = loadGradleTemplates(
templateClass = "org.gradle.kotlin.dsl.KotlinInitScript",
dependencySelector = kotlinDslDependencySelector,
additionalResolverClasspath = kotlinDslAdditionalResolverCp
) + loadGradleTemplates(
templateClass = "org.gradle.kotlin.dsl.KotlinSettingsScript",
dependencySelector = kotlinDslDependencySelector,
additionalResolverClasspath = kotlinDslAdditionalResolverCp
) + loadGradleTemplates(
templateClass = "org.gradle.kotlin.dsl.KotlinBuildScript",
dependencySelector = kotlinDslDependencySelector,
additionalResolverClasspath = kotlinDslAdditionalResolverCp
)
if (kotlinDslTemplates.isNotEmpty()) {
return kotlinDslTemplates
}
val default = tryToLoadOldBuildScriptDefinition()
if (default.isNotEmpty()) {
return default
}
return listOf(ErrorGradleScriptDefinition())
}
private fun tryToLoadOldBuildScriptDefinition(): List<KotlinScriptDefinition> {
failedToLoad.set(false)
return loadGradleTemplates(
templateClass = "org.gradle.script.lang.kotlin.KotlinBuildScript",
dependencySelector = Regex("^gradle-(?:script-kotlin|core).*\\.jar\$"),
additionalResolverClasspath = { emptyList() }
)
}
// TODO: check this against kotlin-dsl branch that uses daemon
private fun kotlinStdlibAndCompiler(gradleLibDir: File): List<File> {
// additionally need compiler jar to load gradle resolver
return gradleLibDir.listFiles { file -> file.name.startsWith("kotlin-compiler-embeddable") || file.name.startsWith("kotlin-stdlib") }
.firstOrNull()?.let(::listOf).orEmpty()
}
private fun loadGradleTemplates(
templateClass: String, dependencySelector: Regex,
additionalResolverClasspath: (gradleLibDir: File) -> List<File>
): List<KotlinScriptDefinition> = try {
doLoadGradleTemplates(templateClass, dependencySelector, additionalResolverClasspath)
} catch (t: Throwable) {
// TODO: review exception handling
failedToLoad.set(true)
listOf(ErrorGradleScriptDefinition(t.message))
}
private fun doLoadGradleTemplates(
templateClass: String, dependencySelector: Regex,
additionalResolverClasspath: (gradleLibDir: File) -> List<File>
): List<KotlinScriptDefinition> {
fun createEnvironment(gradleExeSettings: GradleExecutionSettings): Environment {
val gradleJvmOptions = gradleExeSettings.daemonVmOptions?.let { vmOptions ->
CommandLineTokenizer(vmOptions).toList()
.mapNotNull { it?.let { it as? String } }
.filterNot(String::isBlank)
.distinct()
} ?: emptyList()
return mapOf(
"gradleHome" to gradleExeSettings.gradleHome?.let(::File),
"projectRoot" to (project.basePath ?: project.baseDir.canonicalPath)?.let(::File),
"gradleWithConnection" to { action: (ProjectConnection) -> Unit ->
GradleExecutionHelper().execute(project.basePath!!, null) { action(it) }
},
"gradleJavaHome" to gradleExeSettings.javaHome,
"gradleJvmOptions" to gradleJvmOptions,
"getScriptSectionTokens" to ::topLevelSectionCodeTextTokens
)
}
val gradleSettings = ExternalSystemApiUtil.getSettings(project, GradleConstants.SYSTEM_ID)
if (gradleSettings.getLinkedProjectsSettings().isEmpty()) error("Project '${project.name}' isn't linked with Gradle")
val projectSettings = gradleSettings.getLinkedProjectsSettings().filterIsInstance<GradleProjectSettings>().firstOrNull()
?: error("Project '${project.name}' isn't linked with Gradle")
val gradleExeSettings = ExternalSystemApiUtil.getExecutionSettings<GradleExecutionSettings>(
project,
projectSettings.externalProjectPath,
GradleConstants.SYSTEM_ID
)
val gradleHome = gradleExeSettings.gradleHome ?: error("Unable to get Gradle home directory")
val gradleLibDir = File(gradleHome, "lib").let {
it.takeIf { it.exists() && it.isDirectory } ?: error("Invalid Gradle libraries directory $it")
}
val templateClasspath = gradleLibDir.listFiles { it ->
/* an inference problem without explicit 'it', TODO: remove when fixed */
dependencySelector.matches(it.name)
}.takeIf { it.isNotEmpty() }?.asList() ?: error("Missing jars in gradle directory")
return loadDefinitionsFromTemplates(
listOf(templateClass),
templateClasspath,
createEnvironment(gradleExeSettings),
additionalResolverClasspath(gradleLibDir)
).map {
// Expand scope for old gradle script definition
if (it is KotlinScriptDefinitionFromAnnotatedTemplate && !it.scriptExpectedLocations.contains(ScriptExpectedLocation.Project))
GradleKotlinScriptDefinitionFromAnnotatedTemplate(it)
else
it
}
}
fun reloadIfNeccessary() {
if (failedToLoad.compareAndSet(true, false)) {
reload()
}
}
private fun reload() {
ScriptDefinitionsManager.getInstance(project).reloadDefinitionsBy(this)
}
private class ErrorGradleScriptDefinition(message: String? = null) : KotlinScriptDefinition(ScriptTemplateWithArgs::class) {
override val name: String = "Default Kotlin Gradle Script"
override val fileType: LanguageFileType = KotlinFileType.INSTANCE
override val annotationsForSamWithReceivers: List<String> = emptyList()
override val acceptedAnnotations: List<KClass<out Annotation>> = emptyList()
override val dependencyResolver: DependenciesResolver = ErrorScriptDependenciesResolver(message)
override fun getScriptName(script: KtScript) =
Name.identifier(script.containingKtFile.name.removeSuffix(".gradle.kts"))
override fun isScript(fileName: String): Boolean =
fileName.endsWith(".gradle.kts")
override fun toString(): String = "ErrorGradleScriptDefinition"
}
private class ErrorScriptDependenciesResolver(private val message: String? = null) : DependenciesResolver {
override fun resolve(scriptContents: ScriptContents, environment: Environment): ResolveResult {
val failureMessage = if (ReloadGradleTemplatesOnSync.gradleState.isSyncInProgress) {
"Highlighting is impossible during Gradle Import"
} else {
message ?: "Failed to load script definitions by ${GradleScriptDefinitionsContributor::class.java.name}"
}
return ResolveResult.Failure(ScriptReport(failureMessage, ScriptReport.Severity.FATAL))
}
}
}
internal class GradleSyncState {
var isSyncInProgress: Boolean = false
}
class GradleKotlinScriptDefinitionFromAnnotatedTemplate(
base: KotlinScriptDefinitionFromAnnotatedTemplate
) : KotlinScriptDefinitionFromAnnotatedTemplate(base.template, base.environment, base.templateClasspath) {
override val scriptExpectedLocations: List<ScriptExpectedLocation>
get() = listOf(ScriptExpectedLocation.Project)
}
class ReloadGradleTemplatesOnSync : ExternalSystemTaskNotificationListenerAdapter() {
companion object {
internal val gradleState = GradleSyncState()
}
override fun onStart(id: ExternalSystemTaskId, workingDir: String?) {
if (id.type == ExternalSystemTaskType.RESOLVE_PROJECT && id.projectSystemId == GRADLE_SYSTEM_ID) {
gradleState.isSyncInProgress = true
}
}
override fun onEnd(id: ExternalSystemTaskId) {
if (id.type == ExternalSystemTaskType.RESOLVE_PROJECT && id.projectSystemId == GRADLE_SYSTEM_ID) {
gradleState.isSyncInProgress = false
val project = id.findProject() ?: return
val gradleDefinitionsContributor = ScriptDefinitionContributor.find<GradleScriptDefinitionsContributor>(project)
gradleDefinitionsContributor?.reloadIfNeccessary()
}
}
}
class TopLevelSectionTokensEnumerator(script: CharSequence, identifier: String) : Enumeration<KotlinLexer> {
private val lexer = KotlinLexer().apply {
start(script.replace(Regex.fromLiteral("\r"), ""))
var depth = 0
loop@ while (tokenType != null) {
when (tokenType) {
KtTokens.IDENTIFIER -> if (depth == 0 && tokenText == identifier) {
advance()
skipWhiteSpaceAndComments()
if (tokenType == KtTokens.LBRACE)
break@loop
}
KtTokens.LBRACE -> depth += 1
KtTokens.RBRACE -> depth -= 1
}
advance()
}
}
private var depth = 1
private var finished = false
override fun hasMoreElements(): Boolean = !finished && lexer.tokenType != null
override fun nextElement(): KotlinLexer = lexer.apply {
advance()
when (tokenType) {
KtTokens.LBRACE -> depth += 1
KtTokens.RBRACE -> {
if (depth == 1) {
finished = true
}
depth -= 1
}
}
}
private fun KotlinLexer.skipWhiteSpaceAndComments() {
while (tokenType in KtTokens.WHITE_SPACE_OR_COMMENT_BIT_SET) {
advance()
}
}
}
fun topLevelSectionCodeTextTokens(script: CharSequence, sectionIdentifier: String): Sequence<CharSequence> =
TopLevelSectionTokensEnumerator(script, sectionIdentifier).asSequence()
.filter { it.tokenType !in KtTokens.WHITE_SPACE_OR_COMMENT_BIT_SET }
.map { it.tokenSequence }
@@ -5,13 +5,13 @@
package org.jetbrains.kotlin.idea.formatter
import com.intellij.internal.statistic.AbstractProjectsUsagesCollector
import com.intellij.internal.statistic.beans.GroupDescriptor
import com.intellij.internal.statistic.beans.UsageDescriptor
import com.intellij.internal.statistic.utils.getEnumUsage
import com.intellij.openapi.project.Project
import com.intellij.psi.codeStyle.CodeStyleSettingsManager
import org.jetbrains.kotlin.idea.core.formatter.KotlinCodeStyleSettings
import org.jetbrains.kotlin.idea.util.compat.statistic.AbstractProjectsUsagesCollector
import org.jetbrains.kotlin.idea.util.compat.statistic.getEnumUsage
class KotlinFormatterUsageCollector : AbstractProjectsUsagesCollector() {
override fun getGroupId(): GroupDescriptor = GroupDescriptor.create(GROUP_ID)
@@ -1,88 +0,0 @@
/*
* Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.formatter
import com.intellij.internal.statistic.beans.GroupDescriptor
import com.intellij.internal.statistic.beans.UsageDescriptor
import com.intellij.openapi.project.Project
import com.intellij.psi.codeStyle.CodeStyleSettingsManager
import org.jetbrains.kotlin.idea.core.formatter.KotlinCodeStyleSettings
import org.jetbrains.kotlin.idea.util.compat.statistic.AbstractProjectsUsagesCollector
import org.jetbrains.kotlin.idea.util.compat.statistic.getEnumUsage
class KotlinFormatterUsageCollector : AbstractProjectsUsagesCollector() {
override fun getGroupId(): GroupDescriptor = GroupDescriptor.create(GROUP_ID)
override fun getProjectUsages(project: Project): Set<UsageDescriptor> {
val usedFormatter = getKotlinFormatterKind(project)
val settings = CodeStyleSettingsManager.getSettings(project)
val kotlinCommonSettings = settings.kotlinCommonSettings
val kotlinCustomSettings = settings.kotlinCustomSettings
return setOf(
getEnumUsage("kotlin.formatter.kind", usedFormatter),
getEnumStringPropertyUsage(
"kotlin.formatter.defaults",
kotlinCustomSettings.CODE_STYLE_DEFAULTS ?: kotlinCommonSettings.CODE_STYLE_DEFAULTS
)
)
}
private fun getEnumStringPropertyUsage(key: String, value: String?): UsageDescriptor {
return UsageDescriptor(key + "." + value.toString().toLowerCase(java.util.Locale.ENGLISH), 1)
}
companion object {
private const val GROUP_ID = "kotlin.formatter"
private val KOTLIN_DEFAULT_COMMON = KotlinLanguageCodeStyleSettingsProvider().defaultCommonSettings
.also { KotlinStyleGuideCodeStyle.applyToCommonSettings(it) }
private val KOTLIN_DEFAULT_CUSTOM = KotlinCodeStyleSettings.DEFAULT.clone()
.also { KotlinStyleGuideCodeStyle.applyToKotlinCustomSettings(it as KotlinCodeStyleSettings) }
fun getKotlinFormatterKind(project: Project): KotlinFormatterKind {
val isProject = CodeStyleSettingsManager.getInstance(project).USE_PER_PROJECT_SETTINGS
val settings = CodeStyleSettingsManager.getSettings(project)
val kotlinCommonSettings = settings.kotlinCommonSettings
val kotlinCustomSettings = settings.kotlinCustomSettings
val isDefaultKotlinCommonSettings = kotlinCommonSettings == KotlinLanguageCodeStyleSettingsProvider().defaultCommonSettings
val isDefaultKotlinCustomSettings = kotlinCustomSettings == KotlinCodeStyleSettings.DEFAULT
if (isDefaultKotlinCommonSettings && isDefaultKotlinCustomSettings) {
return if (isProject) KotlinFormatterKind.PROJECT_DEFAULT else KotlinFormatterKind.IDEA_DEFAULT
}
val isOnlyKotlinStyle = kotlinCommonSettings == KOTLIN_DEFAULT_COMMON && kotlinCustomSettings == KOTLIN_DEFAULT_CUSTOM
if (isOnlyKotlinStyle) {
return if (isProject) KotlinFormatterKind.PROJECT_KOTLIN else KotlinFormatterKind.IDEA_KOTLIN
}
val isKotlinLikeSettings = settings == settings.clone().also {
KotlinStyleGuideCodeStyle.apply(it)
}
if (isKotlinLikeSettings) {
return if (isProject) KotlinFormatterKind.PROJECT_KOTLIN_WITH_CUSTOM else KotlinFormatterKind.IDEA_KOTLIN_WITH_CUSTOM
}
return if (isProject) KotlinFormatterKind.PROJECT_CUSTOM else KotlinFormatterKind.IDEA_CUSTOM
}
}
enum class KotlinFormatterKind {
IDEA_DEFAULT,
IDEA_CUSTOM,
IDEA_KOTLIN_WITH_CUSTOM,
IDEA_KOTLIN,
PROJECT_DEFAULT,
PROJECT_CUSTOM,
PROJECT_KOTLIN_WITH_CUSTOM,
PROJECT_KOTLIN;
}
}
@@ -9,8 +9,8 @@ import com.intellij.codeInsight.hints.InlayParameterHintsExtension
import com.intellij.internal.statistic.UsagesCollector
import com.intellij.internal.statistic.beans.GroupDescriptor
import com.intellij.internal.statistic.beans.UsageDescriptor
import com.intellij.internal.statistic.utils.getBooleanUsage
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.util.compat.statistic.getBooleanUsage
class KotlinInlayParameterHintsUsageCollector : UsagesCollector() {
override fun getGroupId(): GroupDescriptor = GroupDescriptor.create(GROUP_ID)
@@ -1,29 +0,0 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.parameterInfo
import com.intellij.codeInsight.hints.InlayParameterHintsExtension
import com.intellij.internal.statistic.UsagesCollector
import com.intellij.internal.statistic.beans.GroupDescriptor
import com.intellij.internal.statistic.beans.UsageDescriptor
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.util.compat.statistic.getBooleanUsage
class KotlinInlayParameterHintsUsageCollector : UsagesCollector() {
override fun getGroupId(): GroupDescriptor = GroupDescriptor.create(GROUP_ID)
override fun getUsages(): Set<UsageDescriptor> {
val provider = InlayParameterHintsExtension.forLanguage(KotlinLanguage.INSTANCE) ?: return emptySet()
return provider.supportedOptions.mapTo(LinkedHashSet()) {
getBooleanUsage(it.id, it.get())
}
}
companion object {
private const val GROUP_ID = "kotlin.hints.inlay"
}
}
@@ -0,0 +1,26 @@
/*
* Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
@file:Suppress("IncompatibleAPI")
package org.jetbrains.kotlin.idea.util.compat.statistic
/**
* Should be dropped after abandoning 172.
* BUNCH: 173
*/
typealias AbstractProjectsUsagesCollector = com.intellij.internal.statistic.AbstractProjectsUsagesCollector
/**
* Should be dropped after abandoning 172.
* BUNCH: 173
*/
fun getEnumUsage(key: String, value: Enum<*>?) = com.intellij.internal.statistic.utils.getEnumUsage(key, value)
/**
* Should be dropped after abandoning 172.
* BUNCH: 173
*/
fun getBooleanUsage(key: String, value: Boolean) = com.intellij.internal.statistic.utils.getBooleanUsage(key, value)
@@ -3,10 +3,24 @@
* that can be found in the license/LICENSE.txt file.
*/
@file:Suppress("IncompatibleAPI")
package org.jetbrains.kotlin.idea.util.compat.statistic
/**
* Should be dropped after abandoning 172.
* BUNCH: 173
*/
typealias AbstractProjectsUsagesCollector = com.intellij.internal.statistic.AbstractApplicationUsagesCollector
/**
* Should be dropped after abandoning 172.
* BUNCH: 173
*/
fun getEnumUsage(key: String, value: Enum<*>?) = com.intellij.internal.statistic.getEnumUsage(key, value)
/**
* Should be dropped after abandoning 172.
* BUNCH: 173
*/
fun getBooleanUsage(key: String, value: Boolean) = com.intellij.internal.statistic.getBooleanUsage(key, value)