Compare commits

...

70 Commits

Author SHA1 Message Date
Ilya Goncharov
0a64fdc40f [Gradle, JS] Not consider mocha default arguments 2019-10-11 17:52:51 +03:00
Ilya Goncharov
2d7936c98b [Gradle, JS] Deprecate useNodeJs for compatibility 2019-10-11 17:52:51 +03:00
Ilya Goncharov
c715b42961 [Gradle, JS] Remove redundant NodeJs runner 2019-10-11 17:52:51 +03:00
Ilya Goncharov
aa2f552f02 [Gradle, JS] Detect adapter automatically, not depends on JasmineLike 2019-10-11 17:52:51 +03:00
Ilya Goncharov
d2f5d87d41 [Gradle, JS] Remove copypaste for karma and nodejs test adapters 2019-10-11 17:52:51 +03:00
Ilya Goncharov
9d9f3f17aa [Gradle, JS] useMocha by default 2019-10-11 17:52:51 +03:00
Ilya Goncharov
55150bfacc [Gradle, JS] Return result of testing function
- It is useful for async testing (Promise returning)
2019-10-11 17:52:51 +03:00
Ilya Goncharov
1e5050e5f3 [Gradle, JS] Remove redundant related with JS test run 2019-10-11 17:52:50 +03:00
Ilya Goncharov
07ab3b89b7 [Gradle, JS] Only one sender of team city stdOut messages
- NodeJS and Browser tests should use one code to send TeamCity messages
2019-10-11 17:52:50 +03:00
Ilya Goncharov
253077bdf4 Use team city messages for mocha test output 2019-10-11 17:52:50 +03:00
Ilya Goncharov
9f15055b0e Migrate filtering adapter on mocha's initial adapter 2019-10-11 17:52:50 +03:00
Ilya Matveev
e7a794b814 Gradle, native: Add a DSL shortcut for iOS, watchsOS and tvOS
This patch adds a group of shortcut DSL methods allowing a user to
create simulator and device targets for Apple platforms along with
corresponding common source set(s) in one command. iOS, tvOS and
watchOS targets are supported.

Issue #KT-33856 fixed
2019-10-11 17:43:47 +03:00
Leonid Startsev
1005f1f473 Do not add synthetic deserialization constructor if .deserialize method is customized
Otherwise, there was an added descriptor without generated IR on Native

(cherry picked from commit d8ad0ec43a)
2019-10-11 14:36:57 +03:00
Leonid Startsev
4866c7ccfe Fix failing tests after 6d905157 2019-10-11 14:36:40 +03:00
Leonid Startsev
efcf136813 Don't skip LazyIR declarations during serialization
Skipping it would break kotlinx-serialization compiler plugin, because it emits lazy ir for now.

This commit is intended for 1.3.60 branch. In master, compiler plugins would be rewritten to emit correct IR.
2019-10-11 14:27:08 +03:00
Ilya Goncharov
2437a8e43a Fix license information for js modules
(cherry picked from commit 18b287def5)
2019-10-11 12:25:27 +03:00
Ilya Chernikov
2f42c88180 Fix filename pattern building under Windows
(cherry picked from commit 9bf46cf435)
2019-10-11 08:15:10 +02:00
Ilya Chernikov
7a7c7c5f6e Add a property for resolving via classloader in JSR-223 2019-10-10 17:39:01 +02:00
Ilya Chernikov
47bf4d3474 Add resolving from classloader to REPL pipeline 2019-10-10 17:38:59 +02:00
Ilya Chernikov
a8599875b5 Implement resolve top-level functions and props from classloader
#KT-33892 fixed
2019-10-10 17:38:58 +02:00
Ilya Chernikov
0f78a45008 Use default scripting host configuration if not provided 2019-10-10 17:38:57 +02:00
Ilya Goncharov
b230cdbcb0 Commonization of condition for linking node packages
(cherry picked from commit bf0b4f6878)
2019-10-10 12:25:13 +03:00
Ilya Goncharov
3f1927887f Remove NpmSimpleLinker
- Now only Yarn is responsible to link modules

(cherry picked from commit bcbc408892)
2019-10-10 12:25:12 +03:00
Ilya Goncharov
bf8ccbc396 Remain only license files
(cherry picked from commit 48e2e1f0c1)
2019-10-10 11:45:50 +03:00
Ilya Goncharov
e5c0d4440a Migrate on copyfiles
(cherry picked from commit 8c2ae4f91a)
2019-10-10 11:45:50 +03:00
Ilya Goncharov
ba1e0c8c50 Add similarity with kotlin-test-js-runner
(cherry picked from commit 896271cd87)
2019-10-10 11:45:50 +03:00
Ilya Goncharov
ef46414012 Remove webpack protocol for processing stacktrace
(cherry picked from commit 8ef28446cc)
2019-10-10 11:45:50 +03:00
Ilya Goncharov
02c522db47 Simplify progress procentage
(cherry picked from commit f4ba132327)
2019-10-10 11:45:50 +03:00
Ilya Goncharov
afaa730d7f Windows source-map-loading with absolute paths
(cherry picked from commit 7e5c51e6aa)
2019-10-10 11:45:50 +03:00
Ilya Goncharov
a4899235f0 Temp ignore tests on missing source file
#KT-32319 fixed

(cherry picked from commit b2fb81e9cc)
2019-10-10 11:45:50 +03:00
Ilya Goncharov
8561ff4f83 Fix webpack delimiter and add test on short path in stack trace
(cherry picked from commit 6688df8f6a)
2019-10-10 11:45:49 +03:00
Ilya Goncharov
81f3106918 Source-map-loader resolves relative paths into absolute even
- Now event sources with content in source map should be resolved with absolute path

(cherry picked from commit f7ba1c56e2)
2019-10-10 11:45:49 +03:00
Ilya Goncharov
fc0b7b16e1 Add tests for source-map-loader
(cherry picked from commit f3db846bce)
2019-10-10 11:45:49 +03:00
Ilya Goncharov
e8617a154c Add patched kotlin-source-map-loader
(cherry picked from commit e8efe5407d)
2019-10-10 11:45:49 +03:00
Ilya Goncharov
5f4c2405cc Fix test logging for Windows
(cherry picked from commit d2c2128aad)
2019-10-10 11:45:49 +03:00
Ilya Goncharov
2c1ab9fc0b Add typings field for DtsResolver
#KT-33549 fixed

(cherry picked from commit 1f5a760ac8)
2019-10-10 11:45:49 +03:00
Ilya Goncharov
e8239aece9 Add tests for processing karma stack traces
(cherry picked from commit 58e9b756f1)
2019-10-10 11:45:49 +03:00
Pavel Kirpichenkov
456a03cb5b Fix capturing of outer type parameters for classes declared inside init block 2019-10-10 11:13:40 +03:00
Abduqodiri Qurbonzoda
a8effec213 Fix Iterable, Sequence and String index overflow in windowed
(cherry picked from commit e54b405fe4)
2019-10-10 04:36:28 +03:00
Pavel Kirpichenkov
46fef9d71c Minor: fix typo in diagnostic message 2019-10-09 20:33:29 +03:00
Leonid Startsev
6d905157b3 Supply JVM and JS platforms when compile from CLI
To be able to check descriptor's platform in frontend during plugin processing.

This is needed for serialization plugin because some synthesized descriptors (annotation interface implementation) must be JVM-only (or the Native compilation fails).

(cherry picked from commit 395d595b22)
2019-10-09 14:20:32 +03:00
victor.petukhov
5f12ba992f Use new -Xinline-classes compiler flag in the corresponding IDEA intention 2019-10-09 12:23:37 +03:00
Kirill Shmakov
cc8eec91fd Advance 193 bunch to 193.4099
(cherry picked from commit 2a99687a95)
2019-10-09 12:06:39 +03:00
Ilya Chernikov
5e4bfe09db Drop TestCaseWithTempDir usage from scripting compiler plugin tests
fighting with flaky tests
2019-10-09 10:40:34 +02:00
Ilya Chernikov
574715616e [minor] Fix URL conversion to the file
possibly fixes the exception from https://stackoverflow.com/questions/57727150/kotlin-script-engine-with-spring-boot-self-running-war
2019-10-09 10:40:33 +02:00
Ilya Chernikov
f1f6963607 [minor] fix source root creation from imported scripts:
make the usages of KotlinSourceRoot consistent everywhere
2019-10-09 10:40:32 +02:00
Dmitry Gridin
cfc8721cde CreateExpect: shouldn't generate expect declaration from actual function with private, lateinit or const
#KT-33930 Fixed

(cherry picked from commit eaa07dac17)
2019-10-09 13:57:05 +07:00
Dmitry Gridin
d5d3e9a58b DescriptorRenderer: shouldn't render private modifier by default
#KT-31587 Fixed

(cherry picked from commit 9da6dcf840)
2019-10-09 13:57:04 +07:00
Dmitry Gridin
8a8e42a1fe CreateExpect: shouldn't generate expect declaration from actual function with default implementation from interface
#KT-32737 Fixed

(cherry picked from commit 847295bf1c)
2019-10-09 13:57:04 +07:00
Toshiaki Kameyama
e17f3edd3c Add quickfix to change object to class
#KT-33586 Fixed

(cherry picked from commit d86e87d35e)
2019-10-09 13:56:29 +07:00
Toshiaki Kameyama
b3ccda2f8d Convert to anonymous object: fix wrong replacement when SAM is nested interface
#KT-33660 Fixed

(cherry picked from commit 6a329210cb)
2019-10-09 13:56:28 +07:00
Toshiaki Kameyama
759141545a Change parameter type quick fix: don't use qualified name
#KT-32012 Fixed

(cherry picked from commit ac7e955d3e)
2019-10-09 13:55:49 +07:00
Toshiaki Kameyama
6c71264718 Add "Remove redundant label" quick fix for REDUNDANT_LABEL_WARNING
#KT-26431 Fixed

(cherry picked from commit b2d2165342)
2019-10-09 13:55:09 +07:00
nikita.movshin
f4c170f156 Add changelog for 1.3.60 EAP1 2019-10-08 17:21:24 +03:00
nikita.movshin
2597ac278d Update K/N 2019-10-08 10:46:28 +03:00
Alexander Gorshenev
ae4d8447c6 Use MessageCollector.NONE as a dummy logger collector for js library resolver 2019-10-07 18:28:08 +03:00
Alexander Gorshenev
77a325b664 Attached library resolver to messge collector 2019-10-07 18:28:07 +03:00
Alexander Gorshenev
1fa392cdcd A couple of fixes for js library resolver 2019-10-07 18:28:07 +03:00
Alexander Gorshenev
03896b1a02 Commonized FileRegistry with SourceFileMap for klib metadata 2019-10-07 18:28:06 +03:00
Alexander Gorshenev
5f397e27f8 The friend module identification has regressed recently 2019-10-07 18:28:06 +03:00
Vyacheslav Gerasimov
10a1d10100 Build: Fix maven dependencies for compiler daemon and util-klib-metadata artifacts 2019-10-07 15:14:46 +02:00
Nikolay Krasko
ca8cd19bff Move 193 version to the one we build against 2019-10-07 14:29:52 +03:00
Nikolay Krasko
8320337b05 Separate versions for 192 and 193 2019-10-07 14:19:16 +03:00
Anton Yalyshev
995b4637b8 Return older android.tools.build version, as we have problems with newer one 2019-10-07 12:51:55 +03:00
Anton Yalyshev
7bbe89fd60 Set JVM 1.8 for test source set as well #KT-34154 Fixed 2019-10-07 12:51:42 +03:00
Dmitriy Dolovov
ed2ca98e01 Fix KNPE after calling completion in native targeted filesIssue KT-34158 Fixed 2019-10-04 19:02:16 +03:00
Natalia Selezneva
7f403dc87f Add support for settings.gradle.kts configuring kotlin in project (KT-34114)
^KT-34114 Fixed
2019-10-03 16:04:33 +03:00
Igor Yakovlev
9fdd516582 Remove unnecessary fallback LigthClasses from UL 2019-10-03 15:35:00 +03:00
Igor Yakovlev
1f2df0f018 Revert commit and additional workaround to diagnostics problem
Another workaround of testClassObjectCopiedFieldObject test fix

Revert "Fix testClassObjectCopiedFieldObject test"

This reverts commit 8def1f07aa.
2019-10-03 15:34:53 +03:00
nikita.movshin
087ada6b4e Update K/N 2019-10-03 02:55:06 +03:00
290 changed files with 5880 additions and 11450 deletions

1
.gitignore vendored
View File

@@ -52,4 +52,5 @@ kotlin-ultimate/
node_modules/
.rpt2_cache/
libraries/tools/kotlin-test-js-runner/lib/
libraries/tools/kotlin-source-map-loader/lib/
local.properties

File diff suppressed because it is too large Load Diff

View File

@@ -169,7 +169,7 @@ extra["versions.trove4j"] = "1.0.20181211"
extra["versions.ktor-network"] = "1.0.1"
if (!project.hasProperty("versions.kotlin-native")) {
extra["versions.kotlin-native"] = "1.3.60-dev-12485"
extra["versions.kotlin-native"] = "1.3.60-eap-12915"
}
val isTeamcityBuild = project.kotlinBuildProperties.isTeamcityBuild
@@ -527,6 +527,7 @@ tasks {
dependsOn(":kotlin-script-util:test")
dependsOn(":kotlin-scripting-compiler:test")
dependsOn(":kotlin-scripting-common:test")
dependsOn(":kotlin-scripting-jvm:test")
dependsOn(":kotlin-scripting-jvm-host-test:test")
dependsOn(":kotlin-scripting-jsr223-test:test")
dependsOn(":kotlin-scripting-jvm-host-test:embeddableTest")

View File

@@ -15,6 +15,7 @@ import org.jetbrains.kotlin.cli.common.arguments.K2JSCompilerArguments
import org.jetbrains.kotlin.cli.common.arguments.K2JsArgumentConstants
import org.jetbrains.kotlin.cli.common.config.addKotlinSourceRoot
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.*
import org.jetbrains.kotlin.cli.common.messages.GroupingMessageCollector
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.cli.common.messages.MessageUtil
import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles
@@ -28,19 +29,18 @@ import org.jetbrains.kotlin.incremental.components.ExpectActualTracker
import org.jetbrains.kotlin.incremental.components.LookupTracker
import org.jetbrains.kotlin.incremental.js.IncrementalDataProvider
import org.jetbrains.kotlin.incremental.js.IncrementalResultsConsumer
import org.jetbrains.kotlin.ir.backend.js.*
import org.jetbrains.kotlin.ir.backend.js.compile
import org.jetbrains.kotlin.ir.backend.js.generateKLib
import org.jetbrains.kotlin.ir.backend.js.jsPhases
import org.jetbrains.kotlin.ir.backend.js.jsResolveLibraries
import org.jetbrains.kotlin.js.config.EcmaVersion
import org.jetbrains.kotlin.js.config.JSConfigurationKeys
import org.jetbrains.kotlin.js.config.JsConfig
import org.jetbrains.kotlin.js.config.SourceMapSourceEmbedding
import org.jetbrains.kotlin.library.resolver.impl.libraryResolver
import org.jetbrains.kotlin.library.KotlinLibrary
import org.jetbrains.kotlin.library.KotlinLibrarySearchPathResolver
import org.jetbrains.kotlin.library.UnresolvedLibrary
import org.jetbrains.kotlin.library.toUnresolvedLibraries
import org.jetbrains.kotlin.metadata.deserialization.BinaryVersion
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.serialization.js.ModuleKind
import org.jetbrains.kotlin.util.Logger
import org.jetbrains.kotlin.utils.JsMetadataVersion
import org.jetbrains.kotlin.utils.KotlinPaths
import org.jetbrains.kotlin.utils.join
@@ -142,21 +142,15 @@ class K2JsIrCompiler : CLICompiler<K2JSCompilerArguments>() {
// TODO: Handle non-empty main call arguments
val mainCallArguments = if (K2JsArgumentConstants.NO_CALL == arguments.main) null else emptyList<String>()
val unresolvedLibraries = libraries.toUnresolvedLibraries
// Configure resolver to only understands absolute path libraries.
val libraryResolver = KotlinLibrarySearchPathResolver<KotlinLibrary>(
repositories = emptyList(),
directLibs = libraries,
distributionKlib = null,
localKotlinDir = null,
skipCurrentDir = true
// TODO: pass logger attached to message collector here.
).libraryResolver()
val resolvedLibraries = libraryResolver.resolveWithDependencies(unresolvedLibraries, true, true, true)
val friendDependencies = resolvedLibraries.getFullList()
.filter {
it.moduleName in friendLibraries
}
val resolvedLibraries = jsResolveLibraries(
libraries,
messageCollectorLogger(configuration[CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY] ?: error("Could not find message collector"))
)
val friendAbsolutePaths = friendLibraries.map { File(it).absolutePath }
val friendDependencies = resolvedLibraries.getFullList().filter {
it.libraryFile.absolutePath in friendAbsolutePaths
}
val produceKind = produceMap[arguments.irProduceOnly]
if (produceKind == null) {
@@ -345,3 +339,14 @@ class K2JsIrCompiler : CLICompiler<K2JSCompilerArguments>() {
}
}
}
fun messageCollectorLogger(collector: MessageCollector) = object : Logger {
override fun warning(message: String)= collector.report(STRONG_WARNING, message)
override fun error(message: String) = collector.report(ERROR, message)
override fun log(message: String) = collector.report(LOGGING, message)
override fun fatal(message: String): Nothing {
collector.report(ERROR, message)
(collector as? GroupingMessageCollector)?.flush()
kotlin.error(message)
}
}

View File

@@ -25,14 +25,11 @@ import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.LOGGING
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.cli.jvm.index.JavaRoot
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.load.kotlin.PackagePartProvider
import org.jetbrains.kotlin.load.kotlin.JvmPackagePartProviderBase
import org.jetbrains.kotlin.load.kotlin.loadModuleMapping
import org.jetbrains.kotlin.metadata.jvm.deserialization.JvmMetadataVersion
import org.jetbrains.kotlin.metadata.jvm.deserialization.ModuleMapping
import org.jetbrains.kotlin.metadata.jvm.deserialization.PackageParts
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.resolve.CompilerDeserializationConfiguration
import org.jetbrains.kotlin.serialization.deserialization.MetadataPartProvider
import java.io.ByteArrayOutputStream
import java.io.EOFException
import java.io.PrintStream
@@ -40,49 +37,10 @@ import java.io.PrintStream
class JvmPackagePartProvider(
languageVersionSettings: LanguageVersionSettings,
private val scope: GlobalSearchScope
) : PackagePartProvider, MetadataPartProvider {
private data class ModuleMappingInfo(val root: VirtualFile, val mapping: ModuleMapping, val name: String)
) : JvmPackagePartProviderBase<VirtualFile>() {
private val deserializationConfiguration = CompilerDeserializationConfiguration(languageVersionSettings)
private val loadedModules: MutableList<ModuleMappingInfo> = SmartList()
override fun findPackageParts(packageFqName: String): List<String> {
val rootToPackageParts = getPackageParts(packageFqName)
if (rootToPackageParts.isEmpty()) return emptyList()
val result = linkedSetOf<String>()
val visitedMultifileFacades = linkedSetOf<String>()
for ((_, packageParts) in rootToPackageParts) {
for (name in packageParts.parts) {
val facadeName = packageParts.getMultifileFacadeName(name)
if (facadeName == null || facadeName !in visitedMultifileFacades) {
result.add(name)
}
}
packageParts.parts.mapNotNullTo(visitedMultifileFacades, packageParts::getMultifileFacadeName)
}
return result.toList()
}
override fun findMetadataPackageParts(packageFqName: String): List<String> =
getPackageParts(packageFqName).values.flatMap(PackageParts::metadataParts).distinct()
@Synchronized
private fun getPackageParts(packageFqName: String): Map<VirtualFile, PackageParts> {
val result = mutableMapOf<VirtualFile, PackageParts>()
for ((root, mapping) in loadedModules) {
val newParts = mapping.findPackageParts(packageFqName) ?: continue
result[root]?.let { parts -> parts += newParts } ?: result.put(root, newParts)
}
return result
}
override fun getAnnotationsOnBinaryModule(moduleName: String): List<ClassId> {
return loadedModules.mapNotNull { (_, mapping, name) ->
if (name == moduleName) mapping.moduleData.annotations.map(ClassId::fromString) else null
}.flatten()
}
override val loadedModules: MutableList<ModuleMappingInfo<VirtualFile>> = SmartList()
fun addRoots(roots: List<JavaRoot>, messageCollector: MessageCollector) {
for ((root, type) in roots) {
@@ -93,29 +51,40 @@ class JvmPackagePartProvider(
for (moduleFile in metaInf.children) {
if (!moduleFile.name.endsWith(ModuleMapping.MAPPING_FILE_EXT)) continue
try {
val mapping = ModuleMapping.loadModuleMapping(
moduleFile.contentsToByteArray(), moduleFile.toString(), deserializationConfiguration
) { incompatibleVersion ->
messageCollector.report(
ERROR,
"Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is " +
"$incompatibleVersion, expected version is ${JvmMetadataVersion.INSTANCE}.",
CompilerMessageLocation.create(moduleFile.path)
)
}
loadedModules.add(ModuleMappingInfo(root, mapping, moduleFile.nameWithoutExtension))
} catch (e: EOFException) {
messageCollector.report(
ERROR, "Error occurred when reading the module: ${e.message}", CompilerMessageLocation.create(moduleFile.path)
)
messageCollector.report(
LOGGING,
String(ByteArrayOutputStream().also { e.printStackTrace(PrintStream(it)) }.toByteArray()),
CompilerMessageLocation.create(moduleFile.path)
)
tryLoadModuleMapping(
{ moduleFile.contentsToByteArray() }, moduleFile.toString(), moduleFile.path,
deserializationConfiguration, messageCollector
)?.let {
loadedModules.add(ModuleMappingInfo(root, it, moduleFile.nameWithoutExtension))
}
}
}
}
}
fun tryLoadModuleMapping(
getModuleBytes: () -> ByteArray,
debugName: String,
modulePath: String,
deserializationConfiguration: CompilerDeserializationConfiguration,
messageCollector: MessageCollector
): ModuleMapping? = try {
ModuleMapping.loadModuleMapping(getModuleBytes(), debugName, deserializationConfiguration) { incompatibleVersion ->
messageCollector.report(
ERROR,
"Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is " +
"$incompatibleVersion, expected version is ${JvmMetadataVersion.INSTANCE}.",
CompilerMessageLocation.create(modulePath)
)
}
} catch (e: EOFException) {
messageCollector.report(
ERROR, "Error occurred when reading the module: ${e.message}", CompilerMessageLocation.create(modulePath)
)
messageCollector.report(
LOGGING,
String(ByteArrayOutputStream().also { e.printStackTrace(PrintStream(it)) }.toByteArray()),
CompilerMessageLocation.create(modulePath)
)
null
}

View File

@@ -55,6 +55,7 @@ import org.jetbrains.kotlin.load.kotlin.incremental.IncrementalPackageFragmentPr
import org.jetbrains.kotlin.load.kotlin.incremental.IncrementalPackagePartProvider
import org.jetbrains.kotlin.modules.TargetId
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.*
@@ -125,7 +126,11 @@ object TopDownAnalyzerFacadeForJVM {
targetEnvironment: TargetEnvironment = CompilerEnvironment,
sourceModuleSearchScope: GlobalSearchScope = newModuleSearchScope(project, files)
): ComponentProvider {
val moduleContext = createModuleContext(project, configuration)
val jvmTarget = configuration.get(JVMConfigurationKeys.JVM_TARGET, JvmTarget.DEFAULT)
val languageVersionSettings = configuration.languageVersionSettings
val jvmPlatform = JvmPlatforms.jvmPlatformByTargetVersion(jvmTarget)
val moduleContext = createModuleContext(project, configuration, jvmPlatform)
val storageManager = moduleContext.storageManager
val module = moduleContext.module
@@ -140,9 +145,6 @@ object TopDownAnalyzerFacadeForJVM {
val sourceScope = if (separateModules) sourceModuleSearchScope else GlobalSearchScope.allScope(project)
val moduleClassResolver = SourceOrBinaryModuleClassResolver(sourceScope)
val jvmTarget = configuration.get(JVMConfigurationKeys.JVM_TARGET, JvmTarget.DEFAULT)
val languageVersionSettings = configuration.languageVersionSettings
val fallbackBuiltIns = JvmBuiltIns(storageManager, JvmBuiltIns.Kind.FALLBACK).apply {
initialize(builtInsModule, languageVersionSettings)
}.builtInsModule
@@ -161,14 +163,14 @@ object TopDownAnalyzerFacadeForJVM {
val dependencyModule = if (separateModules) {
val dependenciesContext = ContextForNewModule(
moduleContext, Name.special("<dependencies of ${configuration.getNotNull(CommonConfigurationKeys.MODULE_NAME)}>"),
module.builtIns, null
module.builtIns, jvmPlatform
)
// Scope for the dependency module contains everything except files present in the scope for the source module
val dependencyScope = GlobalSearchScope.notScope(sourceScope)
val dependenciesContainer = createContainerForLazyResolveWithJava(
JvmPlatforms.jvmPlatformByTargetVersion(jvmTarget),
jvmPlatform,
dependenciesContext, trace, DeclarationProviderFactory.EMPTY, dependencyScope, moduleClassResolver,
targetEnvironment, lookupTracker, expectActualTracker,
packagePartProvider(dependencyScope), languageVersionSettings,
@@ -200,7 +202,7 @@ object TopDownAnalyzerFacadeForJVM {
// to be stored in CliLightClassGenerationSupport, and it better be the source one (otherwise light classes would not be found)
// TODO: get rid of duplicate invocation of CodeAnalyzerInitializer#initialize, or refactor CliLightClassGenerationSupport
val container = createContainerForLazyResolveWithJava(
JvmPlatforms.jvmPlatformByTargetVersion(jvmTarget),
jvmPlatform,
moduleContext, trace, declarationProviderFactory(storageManager, files), sourceScope, moduleClassResolver,
targetEnvironment, lookupTracker, expectActualTracker,
partProvider, languageVersionSettings,
@@ -275,11 +277,11 @@ object TopDownAnalyzerFacadeForJVM {
}
}
private fun createModuleContext(project: Project, configuration: CompilerConfiguration): MutableModuleContext {
private fun createModuleContext(project: Project, configuration: CompilerConfiguration, platform: TargetPlatform?): MutableModuleContext {
val projectContext = ProjectContext(project, "TopDownAnalyzer for JVM")
val builtIns = JvmBuiltIns(projectContext.storageManager, JvmBuiltIns.Kind.FROM_DEPENDENCIES)
return ContextForNewModule(
projectContext, Name.special("<${configuration.getNotNull(CommonConfigurationKeys.MODULE_NAME)}>"), builtIns, null
projectContext, Name.special("<${configuration.getNotNull(CommonConfigurationKeys.MODULE_NAME)}>"), builtIns, platform
).apply {
builtIns.builtInsModule = module
}

View File

@@ -17,13 +17,14 @@ jvmTarget = "1.8"
val ktorExcludesForDaemon : List<Pair<String, String>> by rootProject.extra
dependencies {
compile(project(":compiler:cli"))
compile(project(":compiler:cli-js"))
compile(project(":daemon-common-new"))
compile(project(":compiler:incremental-compilation-impl"))
compile(commonDep("org.fusesource.jansi", "jansi"))
compile(commonDep("org.jline", "jline"))
compileOnly(project(":compiler:cli"))
compileOnly(project(":compiler:cli-js"))
compileOnly(project(":compiler:incremental-compilation-impl"))
compileOnly(project(":daemon-common-new"))
compileOnly(intellijCoreDep()) { includeJars("intellij-core") }
compileOnly(intellijDep()) { includeJars("trove4j") }

View File

@@ -203,7 +203,7 @@ public class DefaultErrorMessages {
MAP.put(SPREAD_OF_LAMBDA_OR_CALLABLE_REFERENCE, "The spread operator (*foo) cannot be applied to lambda argument or callable reference");
MAP.put(MANY_LAMBDA_EXPRESSION_ARGUMENTS, "Only one lambda expression is allowed outside a parenthesized argument list");
MAP.put(UNEXPECTED_TRAILING_LAMBDA_ON_A_NEW_LINE, "Expression is treated a trailing lambda argument; consider separating it from call with semicolon");
MAP.put(UNEXPECTED_TRAILING_LAMBDA_ON_A_NEW_LINE, "Expression is treated as a trailing lambda argument; consider separating it from call with semicolon");
MAP.put(PROPERTY_WITH_NO_TYPE_NO_INITIALIZER, "This property must either have a type annotation, be initialized or be delegated");
MAP.put(VARIABLE_WITH_NO_TYPE_NO_INITIALIZER, "This variable must either have a type annotation or be initialized");

View File

@@ -105,7 +105,10 @@ class DeclarationTable(
}
}
if (this is IrLazyDeclarationBase) return false
// Currently this check is skipped because LazyIr
// can be generated by kotlinx-serialization compiler plugin
// if (this is IrLazyDeclarationBase) return false
if (parent is IrPackageFragment) return true

View File

@@ -12,8 +12,13 @@ import org.jetbrains.kotlin.descriptors.MemberDescriptor
import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor
import org.jetbrains.kotlin.resolve.checkers.ExpectedActualDeclarationChecker
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.library.KotlinLibrary
import org.jetbrains.kotlin.library.metadata.KlibMetadataPackageFragment
import org.jetbrains.kotlin.library.metadata.KlibMetadataProtoBuf
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.OverridingUtil
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedPropertyDescriptor
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedSimpleFunctionDescriptor
internal val DeclarationDescriptor.isExpectMember: Boolean
get() = this is MemberDescriptor && this.isExpect
@@ -49,3 +54,23 @@ internal fun <T : CallableMemberDescriptor> T.resolveFakeOverrideMaybeAbstract()
// This is Native specific. Try to eliminate.
val ModuleDescriptor.isForwardDeclarationModule get() =
name == Name.special("<forward declarations>")
private fun sourceByIndex(descriptor: CallableMemberDescriptor, index: Int): SourceFile {
val fragment = descriptor.findPackage() as KlibMetadataPackageFragment
return fragment.fileRegistry.sourceFile(index)
}
fun CallableMemberDescriptor.findSourceFile(): SourceFile {
val source = this.source.containingFile
if (source != SourceFile.NO_SOURCE_FILE)
return source
return when {
this is DeserializedSimpleFunctionDescriptor && proto.hasExtension(KlibMetadataProtoBuf.functionFile) ->
sourceByIndex(
this, proto.getExtension(KlibMetadataProtoBuf.functionFile))
this is DeserializedPropertyDescriptor && proto.hasExtension(KlibMetadataProtoBuf.propertyFile) ->
sourceByIndex(
this, proto.getExtension(KlibMetadataProtoBuf.propertyFile))
else -> TODO()
}
}

View File

@@ -3,7 +3,7 @@
* 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.ir.backend.js.lower.serialization.metadata
package org.jetbrains.kotlin.backend.common.serialization.metadata
import org.jetbrains.kotlin.library.metadata.KlibMetadataPackageFragment
import org.jetbrains.kotlin.psi.KtFile

View File

@@ -1,41 +0,0 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.ir.backend.js.lower.serialization.metadata
import org.jetbrains.kotlin.backend.common.serialization.metadata.extractFileId
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptorWithSource
import org.jetbrains.kotlin.library.metadata.KlibMetadataPackageFragment
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.source.PsiSourceFile
class KlibMetadataFileRegistry {
private val fileIdsImpl = mutableMapOf<KlibFileMetadata, Int>()
fun lookup(file: KlibFileMetadata) = fileIdsImpl.getOrPut(file) { fileIdsImpl.size }
val fileIds: Map<KlibFileMetadata, Int>
get() = fileIdsImpl
fun getFileId(descriptor: DeclarationDescriptor): Int? {
if (!DescriptorUtils.isTopLevelDeclaration(descriptor) || descriptor !is DeclarationDescriptorWithSource) return null
val fileId = descriptor.extractFileId()
if (fileId != null) {
(descriptor.containingDeclaration as? KlibMetadataPackageFragment)?.let { packageFragment ->
return this.lookup(KotlinDeserializedFileMetadata(packageFragment, fileId))
}
}
val file = descriptor.source.containingFile as? PsiSourceFile ?: return null
val psiFile = file.psiFile
return (psiFile as? KtFile)?.let { this.lookup(KotlinPsiFileMetadata(it)) }
}
}

View File

@@ -11,8 +11,7 @@ import org.jetbrains.kotlin.config.AnalysisFlags
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.ir.backend.js.lower.serialization.metadata.KlibMetadataFileRegistry
import org.jetbrains.kotlin.ir.backend.js.lower.serialization.metadata.KotlinPsiFileMetadata
import org.jetbrains.kotlin.library.metadata.KlibMetadataFileRegistry
import org.jetbrains.kotlin.library.metadata.KlibMetadataProtoBuf
import org.jetbrains.kotlin.metadata.ProtoBuf
import org.jetbrains.kotlin.metadata.deserialization.BinaryVersion
@@ -35,7 +34,6 @@ abstract class KlibMetadataSerializer(
val metadataVersion: BinaryVersion,
val descriptorTable: DescriptorTable
) {
val fileRegistry = KlibMetadataFileRegistry()
lateinit var serializerContext: SerializerContext
@@ -57,7 +55,7 @@ abstract class KlibMetadataSerializer(
languageVersionSettings,
metadataVersion,
::declarationTableHandler,
{descriptor -> fileRegistry.getFileId(descriptor) } ,
{descriptor: DeclarationDescriptorWithSource -> fileRegistry.assign(descriptor.source.containingFile) } ,
KlibMetadataStringTable()
)
return SerializerContext(
@@ -82,10 +80,6 @@ abstract class KlibMetadataSerializer(
val (stringTableProto, nameTableProto) = serializerExtension.stringTable.buildProto()
// TODO: we place files table to each and every fragment.
// Need to refactor it out sonehow.
val files = serializeFiles(fileRegistry, bindingContext, AnnotationSerializer(serializerExtension.stringTable))
return ProtoBuf.PackageFragment.newBuilder()
.setPackage(packageProto)
.addAllClass_(classesProto.map { it.first })
@@ -95,7 +89,6 @@ abstract class KlibMetadataSerializer(
classesProto.forEach {
packageFragment.addExtension(KlibMetadataProtoBuf.className, it.second )
}
packageFragment.setExtension(KlibMetadataProtoBuf.packageFragmentFiles, files)
packageFragment.setExtension(KlibMetadataProtoBuf.isEmpty, isEmpty)
packageFragment.setExtension(KlibMetadataProtoBuf.fqName, fqName.asString())
}
@@ -224,32 +217,17 @@ abstract class KlibMetadataSerializer(
}
private fun serializeFiles(
fileRegistry: KlibMetadataFileRegistry,
bindingContext: BindingContext,
serializer: AnnotationSerializer
): KlibMetadataProtoBuf.Files {
val filesProto = KlibMetadataProtoBuf.Files.newBuilder()
for ((file, id) in fileRegistry.fileIds.entries.sortedBy { it.value }) {
header: KlibMetadataProtoBuf.Header.Builder,
fileRegistry: KlibMetadataFileRegistry
) {
fileRegistry.filesAndClear().map { it.name ?: "" }.forEach {
val fileProto = KlibMetadataProtoBuf.File.newBuilder()
if (id != filesProto.fileCount) {
fileProto.id = id
}
val annotations = when (file) {
is KotlinPsiFileMetadata -> file.ktFile.annotationEntries.map { bindingContext[BindingContext.ANNOTATION, it]!! }
//is KotlinDeserializedFileMetadata -> file.packageFragment.fileMap[file.fileId]!!.annotations
else -> TODO("support other file types")
}
for (annotation in annotations.filterOutSourceAnnotations()) {
fileProto.addAnnotation(serializer.serializeAnnotation(annotation))
}
val name = when (file) {
is KotlinPsiFileMetadata -> file.ktFile.getName()
else -> TODO("support other file types")
}
fileProto.name = name
filesProto.addFile(fileProto)
.setName(it)
.build()
header.addFile(fileProto)
}
return filesProto.build()
}
protected fun getPackagesFqNames(module: ModuleDescriptor): Set<FqName> {
@@ -296,6 +274,9 @@ abstract class KlibMetadataSerializer(
emptyPackages.forEach {
header.addEmptyPackage(it)
}
serializeFiles(header, fileRegistry)
return header.build()
}

View File

@@ -22,7 +22,7 @@ class KlibMetadataSerializerExtension(
private val languageVersionSettings: LanguageVersionSettings,
override val metadataVersion: BinaryVersion,
val declarationTableHandler: (DeclarationDescriptor) -> KlibMetadataProtoBuf.DescriptorUniqId?,
val descriptorFileId: (DeclarationDescriptor) -> Int?,
val descriptorFileId: (DeclarationDescriptorWithSource) -> Int?,
override val stringTable: StringTableImpl
) : KotlinSerializerExtensionBase(KlibMetadataSerializerProtocol) {
override fun shouldUseTypeTable(): Boolean = true

View File

@@ -12,7 +12,7 @@ dependencies {
testCompile(intellijCoreDep()) { includeJars("intellij-core") }
testCompile(project(":compiler:frontend"))
testCompile(project(":compiler:cli"))
testCompile(project(":compiler:cli-js"))
testCompile(project(":compiler:util"))
testRuntime(project(":kotlin-reflect"))

View File

@@ -41,6 +41,7 @@ import org.jetbrains.kotlin.library.impl.buildKoltinLibrary
import org.jetbrains.kotlin.library.impl.createKotlinLibrary
import org.jetbrains.kotlin.library.resolver.KotlinLibraryResolveResult
import org.jetbrains.kotlin.library.resolver.TopologicalLibraryOrder
import org.jetbrains.kotlin.library.resolver.impl.libraryResolver
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.progress.ProgressIndicatorAndCompilationCanceledStatus
import org.jetbrains.kotlin.psi.KtFile
@@ -51,6 +52,7 @@ import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.BindingContextUtils
import org.jetbrains.kotlin.storage.LockBasedStorageManager
import org.jetbrains.kotlin.storage.StorageManager
import org.jetbrains.kotlin.util.Logger
import org.jetbrains.kotlin.utils.DFS
import java.io.File
import org.jetbrains.kotlin.konan.file.File as KFile
@@ -80,6 +82,29 @@ private val CompilerConfiguration.metadataVersion
class KotlinFileSerializedData(val metadata: ByteArray, val irData: SerializedIrFile)
// TODO: This is a temporary set of library resolver policies for js compiler.
fun jsResolveLibraries(libraries: List<String>, logger: Logger): KotlinLibraryResolveResult {
val unresolvedLibraries = libraries.map { UnresolvedLibrary(it ,null) }
val libraryAbsolutePaths = libraries.map{ File(it).absolutePath }
// Configure the resolver to only work with absolute paths for now.
val libraryResolver = KotlinLibrarySearchPathResolver<KotlinLibrary>(
repositories = emptyList(),
directLibs = libraryAbsolutePaths,
distributionKlib = null,
localKotlinDir = null,
skipCurrentDir = false,
logger = logger
).libraryResolver()
val resolvedLibraries =
libraryResolver.resolveWithDependencies(
unresolvedLibraries = unresolvedLibraries,
noStdLib = true,
noDefaultLibs = true,
noEndorsedLibs = true
)
return resolvedLibraries
}
fun generateKLib(
project: Project,
files: List<KtFile>,

View File

@@ -1,76 +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.ir.backend.js.lower.serialization.metadata
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.SourceFile
import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor
import org.jetbrains.kotlin.library.metadata.KlibMetadataProtoBuf
import org.jetbrains.kotlin.metadata.ProtoBuf
import org.jetbrains.kotlin.metadata.deserialization.NameResolverImpl
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.serialization.deserialization.*
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedContainerSource
import org.jetbrains.kotlin.storage.StorageManager
import org.jetbrains.kotlin.storage.getValue
class JsKlibMetadataPackageFragment(
fqName: FqName,
storageManager: StorageManager,
module: ModuleDescriptor,
proto: ProtoBuf.PackageFragment,
header: KlibMetadataProtoBuf.Header,
metadataVersion: JsKlibMetadataVersion,
configuration: DeserializationConfiguration
) : DeserializedPackageFragmentImpl(
fqName, storageManager, module, proto, metadataVersion, JsContainerSource(fqName, header, configuration)
) {
val fileMap: Map<Int, FileHolder> =
proto.getExtension(KlibMetadataProtoBuf.packageFragmentFiles).fileList.withIndex().associate { (index, file) ->
(if (file.hasId()) file.id else index) to FileHolder(file.annotationList)
}
private lateinit var annotationDeserializer: AnnotationDeserializer
override fun initialize(components: DeserializationComponents) {
super.initialize(components)
this.annotationDeserializer = AnnotationDeserializer(components.moduleDescriptor, components.notFoundClasses)
}
inner class FileHolder(private val annotationsProto: List<ProtoBuf.Annotation>) {
val annotations: List<AnnotationDescriptor> by storageManager.createLazyValue {
annotationsProto.map { annotationDeserializer.deserializeAnnotation(it, nameResolver) }
}
}
class JsContainerSource(
private val fqName: FqName,
header: KlibMetadataProtoBuf.Header,
configuration: DeserializationConfiguration
) : DeserializedContainerSource {
val annotations: List<ClassId> =
if (header.annotationCount == 0) emptyList()
else NameResolverImpl(header.strings, header.qualifiedNames).let { nameResolver ->
// TODO: read arguments of module annotations
header.annotationList.map { annotation -> nameResolver.getClassId(annotation.id) }
}
// TODO
override fun getContainingFile(): SourceFile = SourceFile.NO_SOURCE_FILE
// This is null because we look for incompatible libraries in dependencies in the beginning of the compilation anyway,
// and refuse to compile against them completely
override val incompatibility: IncompatibleVersionErrorData<*>?
get() = null
override val isPreReleaseInvisible: Boolean =
configuration.reportErrorsOnPreReleaseDependencies && (header.flags and 1) != 0
override val presentableString: String
get() = "Package '$fqName'"
}
}

View File

@@ -9,15 +9,13 @@ import com.intellij.openapi.Disposable
import com.intellij.openapi.vfs.StandardFileSystems
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.psi.PsiManager
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.cli.js.messageCollectorLogger
import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
import org.jetbrains.kotlin.config.*
import org.jetbrains.kotlin.js.config.JSConfigurationKeys
import org.jetbrains.kotlin.library.KotlinLibrary
import org.jetbrains.kotlin.library.KotlinLibrarySearchPathResolver
import org.jetbrains.kotlin.library.UnresolvedLibrary
import org.jetbrains.kotlin.library.resolver.KotlinLibraryResolveResult
import org.jetbrains.kotlin.library.resolver.impl.libraryResolver
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.multiplatform.isCommonSource
import org.jetbrains.kotlin.serialization.js.ModuleKind
@@ -117,18 +115,9 @@ fun main(args: Array<String>) {
error("Please set path to .klm file: `-o some/dir/module-name.klm`")
}
val dependencyAbsolutePaths = dependencies.map{ File(it).absolutePath }
val unresolvedLibraries = dependencies.map { UnresolvedLibrary(it, null) }
// Configure the resolver to only understand absolute path libraries.
val libraryResolver = KotlinLibrarySearchPathResolver<KotlinLibrary>(
repositories = emptyList(),
directLibs = dependencyAbsolutePaths,
distributionKlib = null,
localKotlinDir = null,
skipCurrentDir = true
// TODO: pass logger attached to message collector here.
).libraryResolver()
val resolvedLibraries = libraryResolver.resolveWithDependencies(unresolvedLibraries, true, true, true)
val resolvedLibraries = jsResolveLibraries(
dependencies, messageCollectorLogger(MessageCollector.NONE)
)
buildKLib(File(outputPath).absolutePath, listOfKtFilesFrom(inputFiles), outputPath, resolvedLibraries, listOfKtFilesFrom(commonSources))
}

View File

@@ -170,7 +170,7 @@ private class ClassFilterForClassOrObject(private val classOrObject: KtClassOrOb
if (classOrObject === processingClassOrObject) return true
// process all children
if (classOrObject.isAncestor(processingClassOrObject, true) || processingClassOrObject.isAncestor(classOrObject, true)) {
if (classOrObject.isAncestor(processingClassOrObject, true)) {
return true
}
@@ -196,8 +196,9 @@ private class ClassFilterForClassOrObject(private val classOrObject: KtClassOrOb
return false
}
override fun shouldGenerateClass(processingClassOrObject: KtClassOrObject) =
shouldGenerateClassMembers(processingClassOrObject)
override fun shouldGenerateClass(processingClassOrObject: KtClassOrObject)
// generate outer classes but not their members
= shouldGenerateClassMembers(processingClassOrObject) || processingClassOrObject.isAncestor(classOrObject, true)
override fun shouldGenerateScript(script: KtScript) = PsiTreeUtil.isAncestor(script, classOrObject, false)
override fun shouldGenerateCodeFragment(script: KtCodeFragment) = false

View File

@@ -23,6 +23,7 @@ import org.jetbrains.kotlin.asJava.builder.InvalidLightClassDataHolder
import org.jetbrains.kotlin.asJava.builder.LightClassDataProviderForFileFacade
import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade
import org.jetbrains.kotlin.asJava.classes.KtLightClassForSourceDeclaration
import org.jetbrains.kotlin.asJava.classes.getOutermostClassOrObject
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory.cast
@@ -49,7 +50,8 @@ fun getJvmSignatureDiagnostics(element: PsiElement, otherDiagnostics: Diagnostic
}
fun getDiagnosticsForClass(ktClassOrObject: KtClassOrObject): Diagnostics {
val lightClassDataHolder = KtLightClassForSourceDeclaration.getLightClassDataHolder(ktClassOrObject)
val outermostClass = getOutermostClassOrObject(ktClassOrObject)
val lightClassDataHolder = KtLightClassForSourceDeclaration.getLightClassDataHolder(outermostClass)
if (lightClassDataHolder is InvalidLightClassDataHolder) {
return Diagnostics.EMPTY
}

View File

@@ -472,6 +472,8 @@ class KtPsiFactory @JvmOverloads constructor(private val project: Project, val m
return file.importDirectives
}
fun createClassKeyword(): PsiElement = createClass("class A").getClassKeyword()!!
fun createPrimaryConstructor(text: String = ""): KtPrimaryConstructor {
return createClass(if (text.isNotEmpty()) "class A $text" else "class A()").primaryConstructor!!
}

View File

@@ -0,0 +1,18 @@
// !DIAGNOSTICS: -UNUSED_VARIABLE
class Outer<T> (val v: T) {
val prop: Any?
init {
class Inner(val v: T) {
override fun toString() = v.toString()
}
val value: Inner = Inner(v)
prop = value
}
}
fun box(): String {
return Outer("OK").prop.toString()
}

View File

@@ -5,73 +5,73 @@ Output:
-- JVM --
Exit code: COMPILATION_ERROR
Output:
compiler/testData/multiplatform/incompatibleCallables/common.kt:1:12: error: expected function 'f1' has no actual declaration in module
compiler/testData/multiplatform/incompatibleCallables/common.kt:1:12: error: expected function 'f1' has no actual declaration in module for JVM
The following declaration is incompatible because return type is different:
public actual fun f1(): String
expect fun f1()
^
compiler/testData/multiplatform/incompatibleCallables/common.kt:5:14: error: expected function 'f3' has no actual declaration in module
compiler/testData/multiplatform/incompatibleCallables/common.kt:5:14: error: expected function 'f3' has no actual declaration in module for JVM
The following declaration is incompatible because parameter types are different:
public actual fun f3(name: Double): Unit
expect fun f3(name: String)
^
compiler/testData/multiplatform/incompatibleCallables/common.kt:6:24: error: expected function 'f3ext' has no actual declaration in module
compiler/testData/multiplatform/incompatibleCallables/common.kt:6:24: error: expected function 'f3ext' has no actual declaration in module for JVM
The following declaration is incompatible because parameter types are different:
public actual fun Double.f3ext(): Unit
expect fun String.f3ext()
^
compiler/testData/multiplatform/incompatibleCallables/common.kt:8:14: error: expected function 'f4' has no actual declaration in module
compiler/testData/multiplatform/incompatibleCallables/common.kt:8:14: error: expected function 'f4' has no actual declaration in module for JVM
The following declaration is incompatible because parameter shapes are different (extension vs non-extension):
public actual fun String.f4(): Unit
expect fun f4(name: String)
^
compiler/testData/multiplatform/incompatibleCallables/common.kt:10:12: error: expected function 'f5' has no actual declaration in module
compiler/testData/multiplatform/incompatibleCallables/common.kt:10:12: error: expected function 'f5' has no actual declaration in module for JVM
The following declaration is incompatible because parameter shapes are different (extension vs non-extension):
public actual fun f5(name: String): Unit
expect fun String.f5()
^
compiler/testData/multiplatform/incompatibleCallables/common.kt:12:14: error: expected function 'f6' has no actual declaration in module
compiler/testData/multiplatform/incompatibleCallables/common.kt:12:14: error: expected function 'f6' has no actual declaration in module for JVM
The following declaration is incompatible because number of value parameters is different:
public actual fun f6(p2: Int): Unit
expect fun f6(p1: String, p2: Int)
^
compiler/testData/multiplatform/incompatibleCallables/common.kt:14:12: error: expected function 'f7' has no actual declaration in module
compiler/testData/multiplatform/incompatibleCallables/common.kt:14:12: error: expected function 'f7' has no actual declaration in module for JVM
The following declaration is incompatible because number of type parameters is different:
public actual fun <K, V> f7(): Unit
expect fun <T> f7()
^
compiler/testData/multiplatform/incompatibleCallables/common.kt:19:12: error: expected function 'f11' has no actual declaration in module
compiler/testData/multiplatform/incompatibleCallables/common.kt:19:12: error: expected function 'f11' has no actual declaration in module for JVM
The following declaration is incompatible because upper bounds of type parameters are different:
public actual fun <T : Annotation> f11(): Unit
expect fun <T : Number> f11()
^
compiler/testData/multiplatform/incompatibleCallables/common.kt:20:12: error: expected function 'f12' has no actual declaration in module
compiler/testData/multiplatform/incompatibleCallables/common.kt:20:12: error: expected function 'f12' has no actual declaration in module for JVM
The following declaration is incompatible because upper bounds of type parameters are different:
public actual fun <U : MutableList<out String>> f12(): Unit
expect fun <U : MutableList<String>> f12()
^
compiler/testData/multiplatform/incompatibleCallables/common.kt:21:12: error: expected function 'f13' has no actual declaration in module
compiler/testData/multiplatform/incompatibleCallables/common.kt:21:12: error: expected function 'f13' has no actual declaration in module for JVM
The following declaration is incompatible because upper bounds of type parameters are different:
public actual fun <A, B : Comparable<B>> f13(): Unit
expect fun <A, B : Comparable<A>> f13()
^
compiler/testData/multiplatform/incompatibleCallables/common.kt:32:15: error: expected function 'f21' has no actual declaration in module
compiler/testData/multiplatform/incompatibleCallables/common.kt:32:15: error: expected function 'f21' has no actual declaration in module for JVM
The following declaration is incompatible because parameter types are different:
public actual fun f21(c: Unit.() -> Unit): Unit
expect fun f21(c: suspend Unit.() -> Unit)
^
compiler/testData/multiplatform/incompatibleCallables/common.kt:33:15: error: expected function 'f22' has no actual declaration in module
compiler/testData/multiplatform/incompatibleCallables/common.kt:33:15: error: expected function 'f22' has no actual declaration in module for JVM
The following declaration is incompatible because parameter types are different:
public actual fun f22(c: suspend Unit.() -> Unit): Unit

View File

@@ -5,19 +5,19 @@ Output:
-- JVM --
Exit code: COMPILATION_ERROR
Output:
compiler/testData/multiplatform/incompatibleClasses/common.kt:14:16: error: expected class 'C1' has no actual declaration in module
compiler/testData/multiplatform/incompatibleClasses/common.kt:14:16: error: expected class 'C1' has no actual declaration in module for JVM
The following declaration is incompatible because number of type parameters is different:
public final actual class C1<A, Extra>
expect class C1<A>
^
compiler/testData/multiplatform/incompatibleClasses/common.kt:16:16: error: expected class 'C3' has no actual declaration in module
compiler/testData/multiplatform/incompatibleClasses/common.kt:16:16: error: expected class 'C3' has no actual declaration in module for JVM
The following declaration is incompatible because upper bounds of type parameters are different:
public final actual class C3<D, E : D?>
expect class C3<D, E : D>
^
compiler/testData/multiplatform/incompatibleClasses/common.kt:18:16: error: expected class 'C4' has no actual declaration in module
compiler/testData/multiplatform/incompatibleClasses/common.kt:18:16: error: expected class 'C4' has no actual declaration in module for JVM
The following declaration is incompatible because upper bounds of type parameters are different:
public actual typealias C4<F> = C4Impl<F>

View File

@@ -5,7 +5,7 @@ Output:
-- JVM --
Exit code: COMPILATION_ERROR
Output:
compiler/testData/multiplatform/missingOverload/common.kt:7:13: error: expected function 'g' has no actual declaration in module
compiler/testData/multiplatform/missingOverload/common.kt:7:13: error: expected function 'g' has no actual declaration in module for JVM
The following declaration is incompatible because parameter types are different:
public actual fun g(a: Any): Unit

View File

@@ -26,7 +26,7 @@ fun useInSignature(a: A) = a.toString()
compiler/testData/multiplatform/optionalExpectationIncorrectUse/common.kt:9:1: error: this annotation is not applicable to target 'class'
@OptionalExpectation
^
compiler/testData/multiplatform/optionalExpectationIncorrectUse/common.kt:10:14: error: expected class 'NotAnAnnotationClass' has no actual declaration in module
compiler/testData/multiplatform/optionalExpectationIncorrectUse/common.kt:10:14: error: expected class 'NotAnAnnotationClass' has no actual declaration in module for JVM
expect class NotAnAnnotationClass
^
compiler/testData/multiplatform/optionalExpectationIncorrectUse/common.kt:12:1: error: '@OptionalExpectation' can only be used on an expected annotation class

View File

@@ -22997,6 +22997,11 @@ public class BlackBoxCodegenTestGenerated extends AbstractBlackBoxCodegenTest {
runTest("compiler/testData/codegen/box/regressions/kt2318.kt");
}
@TestMetadata("kt24913.kt")
public void testKt24913() throws Exception {
runTest("compiler/testData/codegen/box/regressions/kt24913.kt");
}
@TestMetadata("Kt2495Test.kt")
public void testKt2495Test() throws Exception {
runTest("compiler/testData/codegen/box/regressions/Kt2495Test.kt");

View File

@@ -22997,6 +22997,11 @@ public class LightAnalysisModeTestGenerated extends AbstractLightAnalysisModeTes
runTest("compiler/testData/codegen/box/regressions/kt2318.kt");
}
@TestMetadata("kt24913.kt")
public void testKt24913() throws Exception {
runTest("compiler/testData/codegen/box/regressions/kt24913.kt");
}
@TestMetadata("Kt2495Test.kt")
public void testKt2495Test() throws Exception {
runTest("compiler/testData/codegen/box/regressions/Kt2495Test.kt");

View File

@@ -21897,6 +21897,11 @@ public class IrBlackBoxCodegenTestGenerated extends AbstractIrBlackBoxCodegenTes
runTest("compiler/testData/codegen/box/regressions/kt2318.kt");
}
@TestMetadata("kt24913.kt")
public void testKt24913() throws Exception {
runTest("compiler/testData/codegen/box/regressions/kt24913.kt");
}
@TestMetadata("Kt2495Test.kt")
public void testKt2495Test() throws Exception {
runTest("compiler/testData/codegen/box/regressions/Kt2495Test.kt");

View File

@@ -24,6 +24,7 @@ import org.jetbrains.kotlin.js.facade.MainCallParameters
import org.jetbrains.kotlin.js.facade.TranslationResult
import org.jetbrains.kotlin.js.resolve.JsPlatformAnalyzerServices
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.platform.js.JsPlatforms
import org.jetbrains.kotlin.resolve.BindingTraceContext
import org.jetbrains.kotlin.serialization.AbstractVersionRequirementTest
import org.jetbrains.kotlin.test.ConfigurationKind
@@ -78,7 +79,7 @@ class JsVersionRequirementTest : AbstractVersionRequirementTest() {
val config = JsConfig(environment.project, environment.configuration)
return ContextForNewModule(
ProjectContext(environment.project, "ProjectContext"),
Name.special("<test>"), JsPlatformAnalyzerServices.builtIns, null
Name.special("<test>"), JsPlatformAnalyzerServices.builtIns, JsPlatforms.defaultJsPlatform
).apply {
setDependencies(listOf(module) + config.moduleDescriptors + module.builtIns.builtInsModule)
}

View File

@@ -6,10 +6,11 @@ plugins {
description = "Common klib metadata reader and writer"
dependencies {
compileOnly(project(":compiler:frontend"))
compileOnly(project(":core:deserialization"))
compileOnly(project(":compiler:serialization"))
compile(kotlinStdlib())
compile(project(":compiler:frontend"))
compile(project(":core:deserialization"))
compile(project(":compiler:serialization"))
compile(project(":kotlin-util-io"))
compile(project(":kotlin-util-klib"))
}

View File

@@ -33,6 +33,7 @@ message Header {
repeated org.jetbrains.kotlin.metadata.Annotation annotation = 6;
repeated string package_fragment_name = 7;
repeated string empty_package = 8;
repeated File file = 9;
// TODO: Unused.
// TODO: We need to have backend specific extension for versionings.
@@ -42,14 +43,7 @@ message Header {
}
message File {
// If absent, id is the index of the file in the Files.file list
optional int32 id = 1;
required string name = 2;
repeated org.jetbrains.kotlin.metadata.Annotation annotation = 3;
}
message Files {
repeated File file = 1;
required string name = 1;
}
message DescriptorUniqId {
@@ -92,6 +86,10 @@ extend org.jetbrains.kotlin.metadata.EnumEntry {
optional DescriptorUniqId enum_entry_uniq_id = 172;
}
extend org.jetbrains.kotlin.metadata.ValueParameter {
repeated org.jetbrains.kotlin.metadata.Annotation parameter_annotation = 170;
}
extend org.jetbrains.kotlin.metadata.Type {
repeated org.jetbrains.kotlin.metadata.Annotation type_annotation = 170;
}
@@ -102,7 +100,7 @@ extend org.jetbrains.kotlin.metadata.TypeParameter {
}
extend org.jetbrains.kotlin.metadata.PackageFragment {
optional Files package_fragment_files = 170;
repeated int32 package_fragment_files = 170;
optional bool is_empty = 172;
optional string fq_name = 173;
// id in StringTable

View File

@@ -1,26 +1,13 @@
/*
* 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 file.
* 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.backend.common.serialization.metadata
package org.jetbrains.kotlin.library.metadata
import org.jetbrains.kotlin.descriptors.SourceFile
import org.jetbrains.kotlin.library.KotlinLibrary
private class DeserializedSourceFile(
val name_: String, val index: Int, val library: KotlinLibrary) : SourceFile {
override fun getName(): String? = name_
override fun equals(other: Any?): Boolean {
return other is DeserializedSourceFile && library == other.library && index == other.index
}
override fun hashCode(): Int {
return library.hashCode() xor index
}
}
class SourceFileMap {
class KlibMetadataFileRegistry {
private val sourceToIndex = mutableMapOf<SourceFile, Int>()
private val indexToSource = mutableMapOf<Int, SourceFile>()
@@ -37,7 +24,7 @@ class SourceFileMap {
}
fun sourceFile(index: Int): SourceFile =
indexToSource[index] ?: throw Error("Unknown file for $index")
indexToSource[index] ?: throw Error("Unknown file for $index")
fun filesAndClear() =
sourceToIndex.keys.sortedBy {
@@ -51,4 +38,18 @@ class SourceFileMap {
sourceToIndex.clear()
indexToSource.clear()
}
}
class DeserializedSourceFile(
val name_: String, val index: Int, val library: KotlinLibrary
) : SourceFile {
override fun getName(): String? = name_
override fun equals(other: Any?): Boolean {
return other is DeserializedSourceFile && library == other.library && index == other.index
}
override fun hashCode(): Int {
return library.hashCode() xor index
}
}

View File

@@ -19,6 +19,16 @@ import org.jetbrains.kotlin.serialization.deserialization.getClassId
import org.jetbrains.kotlin.serialization.deserialization.getName
import org.jetbrains.kotlin.storage.StorageManager
private val KotlinLibrary.fileSources: KlibMetadataFileRegistry get() {
val result = KlibMetadataFileRegistry()
val proto = parseModuleHeader(moduleHeaderData)
proto.fileList.forEachIndexed { index, it ->
result.provide(it.name, index, this)
}
return result
}
class KlibMetadataPackageFragment(
fqName: FqName,
private val library: KotlinLibrary,
@@ -28,6 +38,10 @@ class KlibMetadataPackageFragment(
private val partName: String
) : DeserializedPackageFragment(fqName, storageManager, module) {
val fileRegistry: KlibMetadataFileRegistry by lazy {
library.fileSources
}
lateinit var components: DeserializationComponents
override fun initialize(components: DeserializationComponents) {

View File

@@ -5,7 +5,8 @@
package org.jetbrains.kotlin.serialization.konan.impl
import org.jetbrains.kotlin.backend.common.serialization.metadata.*
import org.jetbrains.kotlin.backend.common.serialization.metadata.KlibMetadataDeserializedPackageFragmentsFactory
import org.jetbrains.kotlin.backend.common.serialization.metadata.KlibMetadataModuleDescriptorFactory
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.builtins.functions.functionInterfacePackageFragmentProvider
import org.jetbrains.kotlin.config.LanguageVersionSettings
@@ -28,15 +29,14 @@ import org.jetbrains.kotlin.resolve.CompilerDeserializationConfiguration
import org.jetbrains.kotlin.serialization.deserialization.*
import org.jetbrains.kotlin.storage.StorageManager
val ModuleDescriptorImpl.isStdlibModule
get() = (this.klibModuleOrigin as? DeserializedKlibModuleOrigin)
?.library?.unresolvedDependencies?.isEmpty() ?: false
private val ModuleDescriptorImpl.isStdlibModule
get() = (this.klibModuleOrigin as? DeserializedKlibModuleOrigin)?.library?.unresolvedDependencies?.isEmpty() ?: false
class KlibMetadataModuleDescriptorFactoryImpl(
override val descriptorFactory: KlibModuleDescriptorFactory,
override val packageFragmentsFactory: KlibMetadataDeserializedPackageFragmentsFactory,
override val flexibleTypeDeserializer: FlexibleTypeDeserializer
): KlibMetadataModuleDescriptorFactory {
) : KlibMetadataModuleDescriptorFactory {
override fun createDescriptorOptionalBuiltIns(
library: KotlinLibrary,
@@ -89,11 +89,13 @@ class KlibMetadataModuleDescriptorFactoryImpl(
): PackageFragmentProvider {
val deserializedPackageFragments = packageFragmentsFactory.createDeserializedPackageFragments(
library, packageFragmentNames, moduleDescriptor, packageAccessHandler, storageManager)
library, packageFragmentNames, moduleDescriptor, packageAccessHandler, storageManager
)
// TODO: this is native specific. Move to a child class.
val syntheticPackageFragments = packageFragmentsFactory.createSyntheticPackageFragments(
library, deserializedPackageFragments, moduleDescriptor)
library, deserializedPackageFragments, moduleDescriptor
)
val provider = PackageFragmentProviderImpl(deserializedPackageFragments + syntheticPackageFragments)
@@ -119,21 +121,22 @@ class KlibMetadataModuleDescriptorFactoryImpl(
emptyList(),
notFoundClasses,
ContractDeserializerImpl(configuration, storageManager),
extensionRegistryLite = KlibMetadataSerializerProtocol.extensionRegistry)
extensionRegistryLite = KlibMetadataSerializerProtocol.extensionRegistry
)
for (packageFragment in deserializedPackageFragments) {
packageFragment.initialize(components)
}
return compositePackageFragmentAddend ?.let {
return compositePackageFragmentAddend?.let {
CompositePackageFragmentProvider(listOf(it, provider))
} ?: provider
}
fun createForwardDeclarationHackPackagePartProvider(
storageManager: StorageManager,
module: ModuleDescriptorImpl
): PackageFragmentProviderImpl {
storageManager: StorageManager,
module: ModuleDescriptorImpl
): PackageFragmentProviderImpl {
fun createPackage(fqName: FqName, supertypeName: String, classKind: ClassKind) =
ForwardDeclarationsPackageFragmentDescriptor(
storageManager,

View File

@@ -22,7 +22,7 @@ fun String.parseKonanAbiVersion(): KotlinAbiVersion {
data class KotlinAbiVersion(val version: Int) {
companion object {
val CURRENT = KotlinAbiVersion(16)
val CURRENT = KotlinAbiVersion(17)
}
override fun toString() = "$version"
}

View File

@@ -0,0 +1,54 @@
/*
* 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.load.kotlin
import org.jetbrains.kotlin.metadata.jvm.deserialization.ModuleMapping
import org.jetbrains.kotlin.metadata.jvm.deserialization.PackageParts
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.serialization.deserialization.MetadataPartProvider
abstract class JvmPackagePartProviderBase<MappingsKey> : PackagePartProvider, MetadataPartProvider {
protected data class ModuleMappingInfo<MappingsKey>(val key: MappingsKey, val mapping: ModuleMapping, val name: String)
protected abstract val loadedModules: MutableList<ModuleMappingInfo<MappingsKey>>
override fun findPackageParts(packageFqName: String): List<String> {
val rootToPackageParts: Collection<PackageParts> = getPackageParts(packageFqName)
if (rootToPackageParts.isEmpty()) return emptyList()
val result = linkedSetOf<String>()
val visitedMultifileFacades = linkedSetOf<String>()
for (packageParts in rootToPackageParts) {
for (name in packageParts.parts) {
val facadeName = packageParts.getMultifileFacadeName(name)
if (facadeName == null || facadeName !in visitedMultifileFacades) {
result.add(name)
}
}
packageParts.parts.mapNotNullTo(visitedMultifileFacades, packageParts::getMultifileFacadeName)
}
return result.toList()
}
override fun findMetadataPackageParts(packageFqName: String): List<String> =
getPackageParts(packageFqName).flatMap(PackageParts::metadataParts).distinct()
private fun getPackageParts(packageFqName: String): Collection<PackageParts> {
val result = mutableMapOf<MappingsKey, PackageParts>()
for ((root, mapping) in loadedModules) {
val newParts = mapping.findPackageParts(packageFqName) ?: continue
result[root]?.let { parts -> parts += newParts } ?: result.put(root, newParts)
}
return result.values
}
override fun getAnnotationsOnBinaryModule(moduleName: String): List<ClassId> {
return loadedModules.mapNotNull { (_, mapping, name) ->
if (name == moduleName) mapping.moduleData.annotations.map(ClassId::fromString) else null
}.flatten()
}
}

View File

@@ -106,14 +106,15 @@ fun makeLazyJavaPackageFragmentFromClassLoaderProvider(
notFoundClasses: NotFoundClasses,
reflectKotlinClassFinder: KotlinClassFinder,
deserializedDescriptorResolver: DeserializedDescriptorResolver,
singleModuleClassResolver: ModuleClassResolver
singleModuleClassResolver: ModuleClassResolver,
packagePartProvider: PackagePartProvider = PackagePartProvider.Empty
): LazyJavaPackageFragmentProvider {
val annotationTypeQualifierResolver = AnnotationTypeQualifierResolver(storageManager, Jsr305State.DISABLED)
val javaResolverComponents = JavaResolverComponents(
storageManager, ReflectJavaClassFinder(classLoader), reflectKotlinClassFinder, deserializedDescriptorResolver,
SignaturePropagator.DO_NOTHING, RuntimeErrorReporter, JavaResolverCache.EMPTY,
JavaPropertyInitializerEvaluator.DoNothing, SamConversionResolver.Empty, RuntimeSourceElementFactory,
singleModuleClassResolver, PackagePartProvider.Empty, SupertypeLoopChecker.EMPTY, LookupTracker.DO_NOTHING, module,
singleModuleClassResolver, packagePartProvider, SupertypeLoopChecker.EMPTY, LookupTracker.DO_NOTHING, module,
ReflectionTypes(module, notFoundClasses), annotationTypeQualifierResolver,
SignatureEnhancement(annotationTypeQualifierResolver, Jsr305State.DISABLED),
JavaClassesTracker.Default, JavaResolverSettings.Default, NewKotlinTypeChecker.Default

View File

@@ -30,7 +30,9 @@ fun ClassifierDescriptorWithTypeParameters.computeConstructorTypeParameters(): L
val parametersFromContainingFunctions =
parents.takeWhile { it is CallableDescriptor }
.flatMap { (it as CallableDescriptor).typeParameters.asSequence() }.toList()
.filter { it !is ConstructorDescriptor }
.flatMap { (it as CallableDescriptor).typeParameters.asSequence() }
.toList()
val containingClassTypeConstructorParameters = parents.firstIsInstanceOrNull<ClassDescriptor>()?.typeConstructor?.parameters.orEmpty()
if (parametersFromContainingFunctions.isEmpty() && containingClassTypeConstructorParameters.isEmpty()) return declaredTypeParameters

View File

@@ -723,7 +723,8 @@ internal class DescriptorRendererImpl(
private fun renderConstructor(constructor: ConstructorDescriptor, builder: StringBuilder) {
builder.renderAnnotations(constructor)
val visibilityRendered = renderVisibility(constructor.visibility, builder)
val visibilityRendered = (options.renderDefaultVisibility || constructor.constructedClass.modality != Modality.SEALED)
&& renderVisibility(constructor.visibility, builder)
renderMemberKind(constructor, builder)
val constructorKeywordRendered = renderConstructorKeyword || !constructor.isPrimary || visibilityRendered

View File

@@ -1,4 +1,4 @@
versions.intellijSdk=193.3793.14-EAP-SNAPSHOT
versions.intellijSdk=193.4099.13-EAP-SNAPSHOT
versions.androidBuildTools=r23.0.1
versions.idea.NodeJS=181.3494.12
versions.jar.asm-all=7.0.1

View File

@@ -62,16 +62,20 @@ import java.util.concurrent.ConcurrentMap
class IDELightClassGenerationSupport(private val project: Project) : LightClassGenerationSupport() {
private inner class KtUltraLightSupportImpl(private val element: KtElement, private val module: Module) : KtUltraLightSupport {
private inner class KtUltraLightSupportImpl(private val element: KtElement) : KtUltraLightSupport {
private val module = ModuleUtilCore.findModuleForPsiElement(element)
override val isReleasedCoroutine
get() = module.languageVersionSettings.supportsFeature(LanguageFeature.ReleaseCoroutines)
get() = module?.languageVersionSettings?.supportsFeature(LanguageFeature.ReleaseCoroutines) ?: true
private fun KtDeclaration.mayBeModifiedByCompilerPlugins(): Boolean {
val facet = KotlinFacet.get(module)
val pluginClasspaths = facet?.configuration?.settings?.compilerArguments?.pluginClasspaths
if (pluginClasspaths.isNullOrEmpty()) return false
module?.let {
val facet = KotlinFacet.get(it)
val pluginClasspaths = facet?.configuration?.settings?.compilerArguments?.pluginClasspaths
if (pluginClasspaths.isNullOrEmpty()) return false
}
val resolvedDescriptor = lazy(LazyThreadSafetyMode.NONE) {
resolveToDescriptorIfAny(
@@ -157,8 +161,7 @@ class IDELightClassGenerationSupport(private val project: Project) : LightClassG
if (files.any { it.isScript() }) return null
val filesToSupports: List<Pair<KtFile, KtUltraLightSupport>> = files.map {
val module = ModuleUtilCore.findModuleForPsiElement(it) ?: return null
it to KtUltraLightSupportImpl(it, module)
it to KtUltraLightSupportImpl(it)
}
return KtUltraLightClassForFacade(
@@ -178,9 +181,7 @@ class IDELightClassGenerationSupport(private val project: Project) : LightClassG
return null
}
val module = ModuleUtilCore.findModuleForPsiElement(element) ?: return null
return KtUltraLightSupportImpl(element, module).let { support ->
return KtUltraLightSupportImpl(element).let { support ->
when {
element is KtObjectDeclaration && element.isObjectLiteral() ->
KtUltraLightClassForAnonymousDeclaration(element, support)

View File

@@ -27,6 +27,7 @@ import com.intellij.openapi.roots.ModifiableModelsProvider
import com.intellij.openapi.roots.ModifiableRootModel
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtil.createDirectoryIfMissing
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.idea.KotlinIcons
import org.jetbrains.kotlin.idea.formatter.KotlinStyleGuideCodeStyle
import org.jetbrains.kotlin.idea.formatter.ProjectCodeStyleImporter
@@ -156,7 +157,7 @@ abstract class GradleKotlinFrameworkSupportProvider(
KotlinFUSLogger.log(FUSEventGroups.NPWizards, this.javaClass.simpleName)
}
protected open fun updateSettingsScript(settingsBuilder: SettingsScriptBuilder, specifyPluginVersionIfNeeded: Boolean) {}
protected open fun updateSettingsScript(settingsBuilder: SettingsScriptBuilder<out PsiFile>, specifyPluginVersionIfNeeded: Boolean) {}
protected abstract fun getDependencies(sdk: Sdk?): List<String>
protected open fun getTestDependencies(): List<String> = listOf()

View File

@@ -16,6 +16,7 @@ import org.jetbrains.kotlin.cli.common.arguments.CliArgumentStringBuilder.buildA
import org.jetbrains.kotlin.cli.common.arguments.CliArgumentStringBuilder.replaceLanguageFeature
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.idea.configuration.KotlinWithGradleConfigurator.Companion.getBuildScriptSettingsPsiFile
import org.jetbrains.kotlin.idea.inspections.gradle.DifferentKotlinGradleVersionInspection
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.idea.util.module
import org.jetbrains.kotlin.psi.psiUtil.getChildrenOfType
@@ -164,7 +165,8 @@ class GroovyBuildScriptManipulator(
return allBlock.statements.lastOrNull()
}
val featureArgumentString = feature.buildArgumentString(state)
val kotlinVersion = DifferentKotlinGradleVersionInspection.getKotlinPluginVersion(scriptFile)
val featureArgumentString = feature.buildArgumentString(state, kotlinVersion)
val parameterName = "freeCompilerArgs"
return addOrReplaceKotlinTaskParameter(
scriptFile,
@@ -173,7 +175,13 @@ class GroovyBuildScriptManipulator(
forTests
) { insideKotlinOptions ->
val prefix = if (insideKotlinOptions) "kotlinOptions." else ""
val newText = text.replaceLanguageFeature(feature, state, prefix = "$prefix$parameterName = [", postfix = "]")
val newText = text.replaceLanguageFeature(
feature,
state,
kotlinVersion,
prefix = "$prefix$parameterName = [",
postfix = "]"
)
replaceWithStatementFromText(newText)
}
}

View File

@@ -229,6 +229,55 @@ class KotlinBuildScriptManipulator(
}
}
private fun KtBlockExpression.findClassPathDependencyVersion(pluginName: String): String? {
return PsiTreeUtil.getChildrenOfAnyType(this, KtCallExpression::class.java).mapNotNull {
if (it?.calleeExpression?.text == "classpath") {
val dependencyName = it.valueArguments.firstOrNull()?.text?.removeSurrounding("\"")
if (dependencyName?.startsWith(pluginName) == true) dependencyName.substringAfter("$pluginName:") else null
} else null
}.singleOrNull()
}
private fun getPluginInfoFromBuildScript(
operatorName: String?,
pluginVersion: KtExpression?,
receiverCalleeExpression: KtCallExpression?
): Pair<String, String>? {
val receiverCalleeExpressionText = receiverCalleeExpression?.calleeExpression?.text?.trim()
val receivedPluginName = when {
receiverCalleeExpressionText == "id" ->
receiverCalleeExpression.valueArguments.firstOrNull()?.text?.trim()?.removeSurrounding("\"")
operatorName == "version" -> receiverCalleeExpressionText
else -> null
}
val pluginVersionText = pluginVersion?.text?.trim()?.removeSurrounding("\"") ?: return null
return receivedPluginName?.to(pluginVersionText)
}
private fun KtBlockExpression.findPluginVersionInPluginGroup(pluginName: String): String? {
val versionsToPluginNames =
PsiTreeUtil.getChildrenOfAnyType(this, KtBinaryExpression::class.java, KtDotQualifiedExpression::class.java).mapNotNull {
when (it) {
is KtBinaryExpression -> getPluginInfoFromBuildScript(
it.operationReference.text,
it.right,
it.left as? KtCallExpression
)
is KtDotQualifiedExpression ->
(it.selectorExpression as? KtCallExpression)?.run {
getPluginInfoFromBuildScript(
calleeExpression?.text,
valueArguments.firstOrNull()?.getArgumentExpression(),
it.receiverExpression as? KtCallExpression
)
}
else -> null
}
}.toMap()
return versionsToPluginNames.getOrDefault(pluginName, null)
}
private fun KtBlockExpression.findPluginInPluginsGroup(pluginName: String): KtCallExpression? {
return PsiTreeUtil.getChildrenOfAnyType(
this,
@@ -354,14 +403,24 @@ class KotlinBuildScriptManipulator(
?.addExpressionIfMissing("languageSettings.enableLanguageFeature(\"${feature.name}\")")
}
val featureArgumentString = feature.buildArgumentString(state)
val pluginsBlock = findScriptInitializer("plugins")?.getBlock()
val kotlinVersion = pluginsBlock?.findPluginVersionInPluginGroup("kotlin")
?: pluginsBlock?.findPluginVersionInPluginGroup("org.jetbrains.kotlin.jvm")
?: findScriptInitializer("buildscript")?.getBlock()?.findBlock("dependencies")?.findClassPathDependencyVersion("org.jetbrains.kotlin:kotlin-gradle-plugin")
val featureArgumentString = feature.buildArgumentString(state, kotlinVersion)
val parameterName = "freeCompilerArgs"
return addOrReplaceKotlinTaskParameter(
parameterName,
"listOf(\"$featureArgumentString\")",
forTests
) {
val newText = text.replaceLanguageFeature(feature, state, prefix = "$parameterName = listOf(", postfix = ")")
val newText = text.replaceLanguageFeature(
feature,
state,
kotlinVersion,
prefix = "$parameterName = listOf(",
postfix = ")"
)
replace(psiFactory.createExpression(newText))
}
}

View File

@@ -153,9 +153,10 @@ class KotlinDslGradleKotlinJavaFrameworkSupportProvider :
.addOther("""
tasks {
compileKotlin {
kotlinOptions {
jvmTarget = "1.8"
}
kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}
}""".trimIndent()
)

View File

@@ -35,7 +35,7 @@ class KotlinGradleMobileMultiplatformModuleBuilder :
"Multiplatform Gradle project allowing reuse of the same Kotlin code between Android and iOS mobile platforms"
override fun BuildScriptDataBuilder.setupAdditionalDependencies() {
addBuildscriptDependencyNotation("classpath 'com.android.tools.build:gradle:3.5.0'")
addBuildscriptDependencyNotation("classpath 'com.android.tools.build:gradle:3.2.1'")
addBuildscriptRepositoriesDefinition("google()")
addBuildscriptRepositoriesDefinition("jcenter()")
addRepositoriesDefinition("google()")

View File

@@ -9,6 +9,7 @@ import com.intellij.framework.addSupport.FrameworkSupportInModuleConfigurable
import com.intellij.ide.util.frameworkSupport.FrameworkSupportModel
import com.intellij.openapi.externalSystem.model.project.ProjectId
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectCoreUtil
import com.intellij.openapi.roots.ModifiableModelsProvider
import com.intellij.openapi.roots.ModifiableRootModel
@@ -16,8 +17,11 @@ import com.intellij.openapi.util.Key
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiFile
import com.intellij.psi.codeStyle.CodeStyleManager
import org.jetbrains.kotlin.idea.core.util.toPsiFile
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.UserDataProperty
import org.jetbrains.plugins.gradle.frameworkSupport.GradleFrameworkSupportProvider
import org.jetbrains.plugins.gradle.service.project.wizard.GradleModuleBuilder
@@ -27,7 +31,7 @@ import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory
import java.io.File
internal var Module.gradleModuleBuilder: GradleModuleBuilder? by UserDataProperty(Key.create("GRADLE_MODULE_BUILDER"))
private var Module.settingsScriptBuilder: SettingsScriptBuilder? by UserDataProperty(Key.create("SETTINGS_SCRIPT_BUILDER"))
private var Module.settingsScriptBuilder: SettingsScriptBuilder<out PsiFile>? by UserDataProperty(Key.create("SETTINGS_SCRIPT_BUILDER"))
internal fun findSettingsGradleFile(module: Module): VirtualFile? {
val contentEntryPath = module.gradleModuleBuilder?.contentEntryPath ?: return null
@@ -35,10 +39,12 @@ internal fun findSettingsGradleFile(module: Module): VirtualFile? {
val contentRootDir = File(contentEntryPath)
val modelContentRootDir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(contentRootDir) ?: return null
return modelContentRootDir.findChild(GradleConstants.SETTINGS_FILE_NAME)
?: module.project.baseDir.findChild(GradleConstants.SETTINGS_FILE_NAME)
?: modelContentRootDir.findChild(GradleConstants.KOTLIN_DSL_SETTINGS_FILE_NAME)
?: module.project.baseDir.findChild(GradleConstants.SETTINGS_FILE_NAME)
?: module.project.baseDir.findChild(GradleConstants.KOTLIN_DSL_SETTINGS_FILE_NAME)
}
class SettingsScriptBuilder(scriptFile: GroovyFile) {
abstract class SettingsScriptBuilder<T: PsiFile>(val scriptFile: T) {
private val builder = StringBuilder(scriptFile.text)
private fun findBlockBody(blockName: String, startFrom: Int = 0): Int {
@@ -81,7 +87,7 @@ class SettingsScriptBuilder(scriptFile: GroovyFile) {
private fun getOrCreatePluginManagementBody() = getOrPrependTopLevelBlockBody("pluginManagement")
private fun addPluginRepositoryExpression(expression: String) {
protected fun addPluginRepositoryExpression(expression: String) {
val repositoriesBody = getOrAppendInnerBlockBody("repositories", getOrCreatePluginManagementBody())
appendExpressionToBlockIfAbsent(expression, repositoriesBody)
}
@@ -90,9 +96,7 @@ class SettingsScriptBuilder(scriptFile: GroovyFile) {
addPluginRepositoryExpression("mavenCentral()")
}
fun addPluginRepository(repository: RepositoryDescription) {
addPluginRepositoryExpression(repository.toGroovyRepositorySnippet())
}
abstract fun addPluginRepository(repository: RepositoryDescription)
fun addResolutionStrategy(pluginId: String) {
val resolutionStrategyBody = getOrAppendInnerBlockBody("resolutionStrategy", getOrCreatePluginManagementBody())
@@ -112,16 +116,48 @@ class SettingsScriptBuilder(scriptFile: GroovyFile) {
}
fun build() = builder.toString()
abstract fun buildPsiFile(project: Project): T
}
class GroovySettingsScriptBuilder(scriptFile: GroovyFile): SettingsScriptBuilder<GroovyFile>(scriptFile) {
override fun addPluginRepository(repository: RepositoryDescription) {
addPluginRepositoryExpression(repository.toGroovyRepositorySnippet())
}
override fun buildPsiFile(project: Project): GroovyFile {
return GroovyPsiElementFactory
.getInstance(project)
.createGroovyFile(build(), false, null)
}
}
class KotlinSettingsScriptBuilder(scriptFile: KtFile): SettingsScriptBuilder<KtFile>(scriptFile) {
override fun addPluginRepository(repository: RepositoryDescription) {
addPluginRepositoryExpression(repository.toKotlinRepositorySnippet())
}
override fun buildPsiFile(project: Project): KtFile {
return KtPsiFactory(project).createFile(build())
}
}
// Circumvent write actions and modify the file directly
// TODO: Get rid of this hack when IDEA API allows manipulation of settings script similarly to the main script itself
internal fun updateSettingsScript(module: Module, updater: (SettingsScriptBuilder) -> Unit) {
internal fun updateSettingsScript(module: Module, updater: (SettingsScriptBuilder<out PsiFile>) -> Unit) {
val storedSettingsBuilder = module.settingsScriptBuilder
val settingsBuilder =
storedSettingsBuilder
?: (findSettingsGradleFile(module)?.toPsiFile(module.project) as? GroovyFile)?.let { SettingsScriptBuilder(it) }
?: return
?: (findSettingsGradleFile(module)?.toPsiFile(module.project))?.let {
if (it is KtFile) {
KotlinSettingsScriptBuilder(it)
} else if (it is GroovyFile) {
GroovySettingsScriptBuilder(it)
} else {
null
}
}
?: return
if (storedSettingsBuilder == null) {
module.settingsScriptBuilder = settingsBuilder
}
@@ -140,10 +176,7 @@ internal fun flushSettingsGradleCopy(module: Module) {
// and we will get KT-29333 problem).
// TODO: get rid of file manipulations until project is opened
val project = ProjectCoreUtil.theOnlyOpenProject() ?: module.project
val tmpFile =
GroovyPsiElementFactory
.getInstance(project)
.createGroovyFile(settingsScriptBuilder.build(), false, null)
val tmpFile = settingsScriptBuilder.buildPsiFile(project)
CodeStyleManager.getInstance(project).reformat(tmpFile)
VfsUtil.saveText(settingsFile, tmpFile.text)
}

View File

@@ -32,6 +32,10 @@ class GradleConfiguratorPlatformSpecificTest : GradleImportingTestCase() {
}
}
@TargetVersions("4.7+")
@Test
fun testEnableFeatureSupportMultiplatformWithXFlag() = testEnableFeatureSupportMultiplatform()
@TargetVersions("4.7+")
@Test
fun testEnableFeatureSupportMultiplatform2() {

View File

@@ -569,6 +569,10 @@ class GradleConfiguratorTest : GradleImportingTestCase() {
}
}
@TargetVersions("4.7+")
@Test
fun testChangeFeatureSupportWithXFlag() = testChangeFeatureSupport()
@Test
fun testDisableFeatureSupport() {
val files = importProjectFromTestData()
@@ -584,6 +588,10 @@ class GradleConfiguratorTest : GradleImportingTestCase() {
}
}
@TargetVersions("4.7+")
@Test
fun testDisableFeatureSupportWithXFlag() = testDisableFeatureSupport()
@Test
fun testEnableFeatureSupport() {
val files = importProjectFromTestData()
@@ -599,6 +607,11 @@ class GradleConfiguratorTest : GradleImportingTestCase() {
}
}
@TargetVersions("4.7+")
@Test
@JvmName("testEnableFeatureSupportWithXFlag")
fun testEnableFeatureSupportWithXFlag() = testEnableFeatureSupport()
@Test
fun testEnableFeatureSupportToExistentArguments() {
val files = importProjectFromTestData()
@@ -614,6 +627,10 @@ class GradleConfiguratorTest : GradleImportingTestCase() {
}
}
@TargetVersions("4.7+")
@Test
fun testEnableFeatureSupportToExistentArgumentsWithXFlag() = testEnableFeatureSupportToExistentArguments()
@Test
fun testChangeFeatureSupportGSK() {
val files = importProjectFromTestData()
@@ -629,6 +646,10 @@ class GradleConfiguratorTest : GradleImportingTestCase() {
}
}
@TargetVersions("4.7+")
@Test
fun testChangeFeatureSupportGSKWithXFlag() = testChangeFeatureSupportGSK()
@Test
fun testDisableFeatureSupportGSK() {
val files = importProjectFromTestData()
@@ -644,6 +665,10 @@ class GradleConfiguratorTest : GradleImportingTestCase() {
}
}
@TargetVersions("4.7+")
@Test
fun testDisableFeatureSupportGSKWithXFlag() = testDisableFeatureSupportGSK()
@Test
fun testEnableFeatureSupportGSK() {
val files = importProjectFromTestData()
@@ -659,6 +684,18 @@ class GradleConfiguratorTest : GradleImportingTestCase() {
}
}
@TargetVersions("4.7+")
@Test
fun testEnableFeatureSupportGSKWithXFlag() = testEnableFeatureSupportGSK()
@TargetVersions("4.7+")
@Test
fun testEnableFeatureSupportGSKWithNotInfixVersionCallAndXFlag() = testEnableFeatureSupportGSK()
@TargetVersions("4.7+")
@Test
fun testEnableFeatureSupportGSKWithSpecifyingPluginThroughIdAndXFlag() = testEnableFeatureSupportGSK()
override fun testDataDirName(): String {
return "configurator"
}

View File

@@ -5,10 +5,20 @@
package org.jetbrains.kotlin.cli.common.arguments
import com.intellij.openapi.util.text.StringUtil.compareVersionNumbers
import org.jetbrains.kotlin.config.LanguageFeature
object CliArgumentStringBuilder {
private const val languagePrefix = "-XXLanguage:"
private const val LANGUAGE_FEATURE_FLAG_PREFIX = "-XXLanguage:"
private const val LANGUAGE_FEATURE_DEDICATED_FLAG_PREFIX = "-X"
private val versionRegex = Regex("""^(\d+)\.(\d+)\.(\d+)""")
private val LanguageFeature.dedicatedFlagInfo
get() = when (this) {
LanguageFeature.InlineClasses -> Pair("inline-classes", KotlinVersion(1, 3, 50))
else -> null
}
private val LanguageFeature.State.sign: String
get() = when (this) {
@@ -18,24 +28,50 @@ object CliArgumentStringBuilder {
LanguageFeature.State.ENABLED_WITH_ERROR -> "-" // not supported normally
}
fun LanguageFeature.buildArgumentString(state: LanguageFeature.State): String {
return "$languagePrefix${state.sign}$name"
private fun LanguageFeature.getFeatureMentionInCompilerArgsRegex(): Regex {
val basePattern = "$LANGUAGE_FEATURE_FLAG_PREFIX(?:-|\\+)$name"
val fullPattern =
if (dedicatedFlagInfo != null) "(?:$basePattern)|$LANGUAGE_FEATURE_DEDICATED_FLAG_PREFIX${dedicatedFlagInfo!!.first}" else basePattern
return Regex(fullPattern)
}
fun LanguageFeature.buildArgumentString(state: LanguageFeature.State, kotlinVersion: String?): String {
val shouldBeFeatureEnabled = state == LanguageFeature.State.ENABLED || state == LanguageFeature.State.ENABLED_WITH_WARNING
val dedicatedFlag = dedicatedFlagInfo?.run {
val (xFlag, xFlagSinceVersion) = this
// TODO: replace to returning xFlag in 1.4 (behaviour for fallback)
if (kotlinVersion == null) return@run null
val isAtLeastSpecifiedVersion = versionRegex.find(kotlinVersion)?.destructured?.let { (major, minor, patch) ->
KotlinVersion(major.toInt(), minor.toInt(), patch.toInt()) >= xFlagSinceVersion
} == true
if (isAtLeastSpecifiedVersion) xFlag else null
}
return if (shouldBeFeatureEnabled && dedicatedFlag != null) {
LANGUAGE_FEATURE_DEDICATED_FLAG_PREFIX + dedicatedFlag
} else {
"$LANGUAGE_FEATURE_FLAG_PREFIX${state.sign}$name"
}
}
fun String.replaceLanguageFeature(
feature: LanguageFeature,
state: LanguageFeature.State,
kotlinVersion: String?,
prefix: String = "",
postfix: String = "",
separator: String = ", ",
quoted: Boolean = true
): String {
val existingFeatureIndex = indexOf(feature.name)
val languagePrefixIndex = lastIndexOf(languagePrefix, existingFeatureIndex)
val featureArgumentString = feature.buildArgumentString(state)
val quote = if (quoted) "\"" else ""
return if (languagePrefixIndex != -1) {
replaceRange(languagePrefixIndex, existingFeatureIndex + feature.name.length, featureArgumentString)
val featureArgumentString = feature.buildArgumentString(state, kotlinVersion)
val existingFeatureMatchResult = feature.getFeatureMentionInCompilerArgsRegex().find(this)
return if (existingFeatureMatchResult != null) {
replace(existingFeatureMatchResult.value, featureArgumentString)
} else {
val splitText = if (postfix.isNotEmpty()) split(postfix) else listOf(this, "")
if (splitText.size != 2) {

View File

@@ -23,6 +23,7 @@ import org.jetbrains.kotlin.config.ApiVersion
import org.jetbrains.kotlin.config.KotlinFacetSettingsProvider
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.config.LanguageVersion
import org.jetbrains.kotlin.idea.facet.getCleanRuntimeLibraryVersion
import org.jetbrains.kotlin.idea.facet.getRuntimeLibraryVersion
import org.jetbrains.kotlin.idea.facet.toApiVersion
import org.jetbrains.kotlin.idea.framework.ui.CreateLibraryDialogWithModules
@@ -368,7 +369,13 @@ abstract class KotlinWithLibraryConfigurator protected constructor() : KotlinPro
facetSettings.apiLevel = feature.sinceVersion
facetSettings.languageLevel = feature.sinceVersion
facetSettings.compilerSettings?.apply {
additionalArguments = additionalArguments.replaceLanguageFeature(feature, state, separator = " ", quoted = false)
additionalArguments = additionalArguments.replaceLanguageFeature(
feature,
state,
getCleanRuntimeLibraryVersion(module),
separator = " ",
quoted = false
)
}
}
}

View File

@@ -20,7 +20,9 @@ import org.jetbrains.kotlin.idea.configuration.findApplicableConfigurator
import org.jetbrains.kotlin.idea.configuration.getBuildSystemType
import org.jetbrains.kotlin.idea.core.isInTestSourceContentKotlinAware
import org.jetbrains.kotlin.idea.facet.KotlinFacet
import org.jetbrains.kotlin.idea.facet.getCleanRuntimeLibraryVersion
import org.jetbrains.kotlin.idea.roots.invalidateProjectRoots
import org.jetbrains.kotlin.idea.util.module
import org.jetbrains.kotlin.psi.KtFile
sealed class ChangeGeneralLanguageFeatureSupportFix(
@@ -56,7 +58,13 @@ sealed class ChangeGeneralLanguageFeatureSupportFix(
if (!checkUpdateRuntime(project, feature.sinceApiVersion)) return
}
KotlinCompilerSettings.getInstance(project).update {
additionalArguments = additionalArguments.replaceLanguageFeature(feature, featureSupport, separator = " ", quoted = false)
additionalArguments = additionalArguments.replaceLanguageFeature(
feature,
featureSupport,
file.module?.let { getCleanRuntimeLibraryVersion(it) },
separator = " ",
quoted = false
)
}
project.invalidateProjectRoots()
}

View File

@@ -711,7 +711,7 @@ fun PomFile.changeFeatureConfiguration(
}
argsSubTag.findSubTags("arg").filter { feature.name in it.value.text }.forEach { it.deleteCascade() }
val featureArgumentString = feature.buildArgumentString(state)
val featureArgumentString = feature.buildArgumentString(state, kotlinPlugin.version.stringValue)
val childTag = argsSubTag.createChildTag("arg", featureArgumentString)
return argsSubTag.add(childTag)
}

View File

@@ -82,6 +82,11 @@ class MavenUpdateConfigurationQuickFixTest : MavenImportingTestCase() {
doTest("Enable inline classes support in the current module")
}
@Test
fun testEnableInlineClassesWithXFlag() {
doTest("Enable inline classes support in the current module")
}
@Test
fun testAddKotlinReflect() {
doTest("Add kotlin-reflect.jar to the classpath")

View File

@@ -0,0 +1,56 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>maventest</groupId>
<artifactId>maventest</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<kotlin.version>1.3.50</kotlin.version>
</properties>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jre8</artifactId>
<version>${kotlin.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-test</artifactId>
<version>${kotlin.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>${kotlin.version}</version>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>wrong-goal</goal>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>test-compile</id>
<phase>test-compile</phase>
<goals>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,61 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>maventest</groupId>
<artifactId>maventest</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<kotlin.version>1.3.50</kotlin.version>
</properties>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jre8</artifactId>
<version>${kotlin.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-test</artifactId>
<version>${kotlin.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>${kotlin.version}</version>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>wrong-goal</goal>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>test-compile</id>
<phase>test-compile</phase>
<goals>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
<configuration>
<args>
<arg>-Xinline-classes</arg>
</args>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1 @@
inline class My(val x: Int)

View File

@@ -18,6 +18,7 @@ import org.jetbrains.kotlin.analyzer.ResolverForModuleFactory
import org.jetbrains.kotlin.analyzer.getCapability
import org.jetbrains.kotlin.builtins.DefaultBuiltIns
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.builtins.functions.functionInterfacePackageFragmentProvider
import org.jetbrains.kotlin.caches.resolve.IdePlatformKindResolution
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.context.ProjectContext
@@ -167,6 +168,7 @@ private fun createKotlinNativeBuiltIns(moduleInfo: ModuleInfo, projectContext: P
CompositePackageFragmentProvider(
listOf(
stdlibFragmentProvider,
functionInterfacePackageFragmentProvider(storageManager, builtInsModule),
(KonanFactories.DefaultDeserializedDescriptorFactory as KlibMetadataModuleDescriptorFactoryImpl)
.createForwardDeclarationHackPackagePartProvider(storageManager, builtInsModule)
)

View File

@@ -0,0 +1,318 @@
/*
* Copyright 2000-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.test
import com.intellij.codeInsight.daemon.impl.EditorTracker
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.ide.startup.impl.StartupManagerImpl
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.actionSystem.ex.ActionManagerEx
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProviderImpl
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.StartupManager
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.newvfs.impl.VfsRootAccess
import com.intellij.psi.PsiClassOwner
import com.intellij.psi.PsiJavaFile
import com.intellij.psi.PsiManager
import com.intellij.psi.search.FileTypeIndex
import com.intellij.psi.search.ProjectScope
import com.intellij.testFramework.LightProjectDescriptor
import com.intellij.testFramework.LoggedErrorProcessor
import com.sun.tools.corba.se.idl.toJavaPortable.Util.fileName
import org.apache.log4j.Logger
import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments
import org.jetbrains.kotlin.config.CompilerSettings
import org.jetbrains.kotlin.config.CompilerSettings.Companion.DEFAULT_ADDITIONAL_ARGUMENTS
import org.jetbrains.kotlin.config.JvmTarget
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.config.LanguageVersion
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinCommonCompilerArgumentsHolder
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinCompilerSettings
import org.jetbrains.kotlin.idea.facet.KotlinFacet
import org.jetbrains.kotlin.idea.facet.configureFacet
import org.jetbrains.kotlin.idea.facet.getOrCreateFacet
import org.jetbrains.kotlin.idea.inspections.UnusedSymbolInspection
import org.jetbrains.kotlin.idea.test.CompilerTestDirectives.COMPILER_ARGUMENTS_DIRECTIVE
import org.jetbrains.kotlin.idea.test.CompilerTestDirectives.JVM_TARGET_DIRECTIVE
import org.jetbrains.kotlin.idea.test.CompilerTestDirectives.LANGUAGE_VERSION_DIRECTIVE
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.test.InTextDirectivesUtils
import org.jetbrains.kotlin.test.KotlinTestUtils
import org.jetbrains.kotlin.test.TestMetadata
import org.jetbrains.kotlin.utils.addIfNotNull
import org.jetbrains.kotlin.utils.rethrow
import java.io.File
import java.io.IOException
import java.util.*
import kotlin.reflect.full.findAnnotation
abstract class KotlinLightCodeInsightFixtureTestCase : KotlinLightCodeInsightFixtureTestCaseBase() {
private val exceptions = ArrayList<Throwable>()
protected open val captureExceptions = true
protected fun testDataFile(): File = File(testDataPath, fileName())
protected fun testPath(): String = testDataFile().toString()
protected open fun fileName(): String = KotlinTestUtils.getTestDataFileName(this::class.java, this.name) ?: (getTestName(false) + ".kt")
override fun getTestDataPath(): String {
return this::class.findAnnotation<TestMetadata>()?.value ?: super.getTestDataPath()
}
override fun setUp() {
super.setUp()
// We do it here to avoid possible initialization problems
// UnusedSymbolInspection() calls IDEA UnusedDeclarationInspection() in static initializer,
// which in turn registers some extensions provoking "modifications aren't allowed during highlighting"
// when done lazily
UnusedSymbolInspection()
(StartupManager.getInstance(project) as StartupManagerImpl).runPostStartupActivities()
VfsRootAccess.allowRootAccess(KotlinTestUtils.getHomeDirectory())
EditorTracker.getInstance(project)
invalidateLibraryCache(project)
if (captureExceptions) {
LoggedErrorProcessor.setNewInstance(object : LoggedErrorProcessor() {
override fun processError(message: String?, t: Throwable?, details: Array<out String>?, logger: Logger) {
exceptions.addIfNotNull(t)
super.processError(message, t, details, logger)
}
})
}
}
override fun tearDown() {
LoggedErrorProcessor.restoreDefaultProcessor()
VfsRootAccess.disallowRootAccess(KotlinTestUtils.getHomeDirectory())
super.tearDown()
if (exceptions.isNotEmpty()) {
exceptions.forEach { it.printStackTrace() }
throw AssertionError("Exceptions in other threads happened")
}
}
override fun getProjectDescriptor(): LightProjectDescriptor = getProjectDescriptorFromFileDirective()
protected fun getProjectDescriptorFromAnnotation(): LightProjectDescriptor {
val testMethod = this::class.java.getDeclaredMethod(name)
val platformId = testMethod.getAnnotation(ProjectDescriptorKind::class.java)?.value
return when (platformId) {
JDK_AND_MULTIPLATFORM_STDLIB_WITH_SOURCES -> KotlinJdkAndMultiplatformStdlibDescriptor.JDK_AND_MULTIPLATFORM_STDLIB_WITH_SOURCES
KOTLIN_JVM_WITH_STDLIB_SOURCES -> ProjectDescriptorWithStdlibSources.INSTANCE
KOTLIN_JAVASCRIPT -> KotlinStdJSProjectDescriptor
KOTLIN_JVM_WITH_STDLIB_SOURCES_WITH_ADDITIONAL_JS -> {
KotlinMultiModuleProjectDescriptor(
KOTLIN_JVM_WITH_STDLIB_SOURCES_WITH_ADDITIONAL_JS,
mainModuleDescriptor = ProjectDescriptorWithStdlibSources.INSTANCE,
additionalModuleDescriptor = KotlinStdJSProjectDescriptor
)
}
KOTLIN_JAVASCRIPT_WITH_ADDITIONAL_JVM_WITH_STDLIB -> {
KotlinMultiModuleProjectDescriptor(
KOTLIN_JAVASCRIPT_WITH_ADDITIONAL_JVM_WITH_STDLIB,
mainModuleDescriptor = KotlinStdJSProjectDescriptor,
additionalModuleDescriptor = ProjectDescriptorWithStdlibSources.INSTANCE
)
}
else -> throw IllegalStateException("Unknown value for project descriptor kind")
}
}
protected fun getProjectDescriptorFromTestName(): LightProjectDescriptor {
val testName = StringUtil.toLowerCase(getTestName(false))
return when {
testName.endsWith("runtime") -> KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE
testName.endsWith("stdlib") -> ProjectDescriptorWithStdlibSources.INSTANCE
else -> KotlinLightProjectDescriptor.INSTANCE
}
}
private fun getProjectDescriptorFromFileDirective(): LightProjectDescriptor {
if (isAllFilesPresentInTest()) return KotlinLightProjectDescriptor.INSTANCE
try {
val fileText = FileUtil.loadFile(File(testDataPath, fileName()), true)
val withLibraryDirective = InTextDirectivesUtils.findLinesWithPrefixesRemoved(fileText, "WITH_LIBRARY:")
return when {
!withLibraryDirective.isEmpty() ->
SdkAndMockLibraryProjectDescriptor(
PluginTestCaseBase.getTestDataPathBase() + "/" + withLibraryDirective[0],
true
)
InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME_WITH_SOURCES") ->
ProjectDescriptorWithStdlibSources.INSTANCE
InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME_WITH_KOTLIN_TEST") ->
KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE_WITH_KOTLIN_TEST
InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME_WITH_FULL_JDK") ->
KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE_FULL_JDK
InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME_WITH_REFLECT") ->
KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE_WITH_REFLECT
InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME_WITH_SCRIPT_RUNTIME") ->
KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE_WITH_SCRIPT_RUNTIME
InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME") ||
InTextDirectivesUtils.isDirectiveDefined(fileText, "WITH_RUNTIME") ->
KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE
InTextDirectivesUtils.isDirectiveDefined(fileText, "JS") ->
KotlinStdJSProjectDescriptor
InTextDirectivesUtils.isDirectiveDefined(fileText, "ENABLE_MULTIPLATFORM") ->
KotlinProjectDescriptorWithFacet.KOTLIN_STABLE_WITH_MULTIPLATFORM
else -> KotlinLightProjectDescriptor.INSTANCE
}
} catch (e: IOException) {
throw rethrow(e)
}
}
protected fun isAllFilesPresentInTest(): Boolean = KotlinTestUtils.isAllFilesPresentTest(getTestName(false))
protected fun performNotWriteEditorAction(actionId: String): Boolean {
val dataContext = (myFixture.editor as EditorEx).dataContext
val managerEx = ActionManagerEx.getInstanceEx()
val action = managerEx.getAction(actionId)
val event = AnActionEvent(null, dataContext, ActionPlaces.UNKNOWN, Presentation(), managerEx, 0)
action.update(event)
if (!event.presentation.isEnabled) {
return false
}
managerEx.fireBeforeActionPerformed(action, dataContext, event)
action.actionPerformed(event)
managerEx.fireAfterActionPerformed(action, dataContext, event)
return true
}
}
object CompilerTestDirectives {
const val LANGUAGE_VERSION_DIRECTIVE = "LANGUAGE_VERSION:"
const val JVM_TARGET_DIRECTIVE = "JVM_TARGET:"
const val COMPILER_ARGUMENTS_DIRECTIVE = "COMPILER_ARGUMENTS:"
val ALL_COMPILER_TEST_DIRECTIVES = listOf(LANGUAGE_VERSION_DIRECTIVE, JVM_TARGET_DIRECTIVE, COMPILER_ARGUMENTS_DIRECTIVE)
}
fun configureCompilerOptions(fileText: String, project: Project, module: Module): Boolean {
val version = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// $LANGUAGE_VERSION_DIRECTIVE ")
val jvmTarget = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// $JVM_TARGET_DIRECTIVE ")
// We can have several such directives in quickFixMultiFile tests
// TODO: refactor such tests or add sophisticated check for the directive
val options = InTextDirectivesUtils.findListWithPrefixes(fileText, "// $COMPILER_ARGUMENTS_DIRECTIVE ").firstOrNull()
if (version != null || jvmTarget != null || options != null) {
configureLanguageAndApiVersion(project, module, version ?: LanguageVersion.LATEST_STABLE.versionString)
val facetSettings = KotlinFacet.get(module)!!.configuration.settings
if (jvmTarget != null) {
val compilerArguments = facetSettings.compilerArguments
require(compilerArguments is K2JVMCompilerArguments) { "Attempt to specify `$JVM_TARGET_DIRECTIVE` for non-JVM test" }
compilerArguments.jvmTarget = jvmTarget
}
if (options != null) {
val compilerSettings = facetSettings.compilerSettings ?: CompilerSettings().also {
facetSettings.compilerSettings = it
}
compilerSettings.additionalArguments = options
facetSettings.updateMergedArguments()
KotlinCompilerSettings.getInstance(project).update { this.additionalArguments = options }
}
return true
}
return false
}
fun rollbackCompilerOptions(project: Project, module: Module) {
configureLanguageAndApiVersion(project, module, LanguageVersion.LATEST_STABLE.versionString)
val facetSettings = KotlinFacet.get(module)!!.configuration.settings
(facetSettings.compilerArguments as? K2JVMCompilerArguments)?.jvmTarget = JvmTarget.DEFAULT.description
val compilerSettings = facetSettings.compilerSettings ?: CompilerSettings().also {
facetSettings.compilerSettings = it
}
compilerSettings.additionalArguments = DEFAULT_ADDITIONAL_ARGUMENTS
facetSettings.updateMergedArguments()
KotlinCompilerSettings.getInstance(project).update { this.additionalArguments = DEFAULT_ADDITIONAL_ARGUMENTS }
}
fun configureLanguageAndApiVersion(
project: Project,
module: Module,
languageVersion: String,
apiVersion: String? = null
) {
WriteAction.run<Throwable> {
val modelsProvider = IdeModifiableModelsProviderImpl(project)
val facet = module.getOrCreateFacet(modelsProvider, useProjectSettings = false)
facet.configureFacet(languageVersion, LanguageFeature.State.DISABLED, null, modelsProvider)
if (apiVersion != null) {
facet.configuration.settings.apiLevel = LanguageVersion.fromVersionString(apiVersion)
}
KotlinCommonCompilerArgumentsHolder.getInstance(project).update { this.languageVersion = languageVersion }
modelsProvider.commit()
}
}
fun Project.allKotlinFiles(): List<KtFile> {
val virtualFiles = FileTypeIndex.getFiles(KotlinFileType.INSTANCE, ProjectScope.getProjectScope(this))
return virtualFiles
.map { PsiManager.getInstance(this).findFile(it) }
.filterIsInstance<KtFile>()
}
fun Project.allJavaFiles(): List<PsiJavaFile> {
val virtualFiles = FileTypeIndex.getFiles(JavaFileType.INSTANCE, ProjectScope.getProjectScope(this))
return virtualFiles
.map { PsiManager.getInstance(this).findFile(it) }
.filterIsInstance<PsiJavaFile>()
}
fun Project.findFileWithCaret(): PsiClassOwner {
return (allKotlinFiles() + allJavaFiles()).single {
"<caret>" in VfsUtilCore.loadText(it.virtualFile) && !it.virtualFile.name.endsWith(".after")
}
}

View File

@@ -86,7 +86,7 @@ fun waitForAllEditorsFinallyLoaded(project: Project) {
}
fun replaceWithCustomHighlighter(parentDisposable: Disposable, fromImplementationClass: String, toImplementationClass: String) {
val pointName = ExtensionPointName.create<LanguageExtensionPoint<Annotator>>(LanguageAnnotators.EP_NAME)
val pointName = ExtensionPointName.create<LanguageExtensionPoint<Annotator>>(LanguageAnnotators.EP_NAME.name)
val extensionPoint = pointName.getPoint(null)
val point = LanguageExtensionPoint<Annotator>()

View File

@@ -13,7 +13,7 @@ The Kotlin plugin provides language support in IntelliJ IDEA and Android Studio.
<version>@snapshot@</version>
<vendor url="http://www.jetbrains.com">JetBrains</vendor>
<idea-version since-build="192.5118.30" until-build="193.*"/>
<idea-version since-build="192.5118.30" until-build="192.*"/>
<depends>com.intellij.modules.platform</depends>

View File

@@ -0,0 +1,85 @@
<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="193.3793.14" until-build="193.*"/>
<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="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/*)"/>
<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>
<extensions defaultExtensionNs="com.intellij">
<statistics.counterUsagesCollector groupId="kotlin.gradle.target" version="2"/>
<statistics.counterUsagesCollector groupId="kotlin.maven.target" version="2"/>
<statistics.counterUsagesCollector groupId="kotlin.jps.target" version="2"/>
<statistics.counterUsagesCollector groupId="kotlin.gradle.library" version="1"/>
<statistics.counterUsagesCollector groupId="kotlin.ide.action.refactoring" version="1"/>
<statistics.counterUsagesCollector groupId="kotlin.ide.newFileTempl" version="1"/>
<statistics.counterUsagesCollector groupId="kotlin.ide.npwizards" version="1"/>
<statistics.counterUsagesCollector groupId="kotlin.ide.debugger" version="1"/>
<statistics.counterUsagesCollector groupId="kotlin.ide.j2k" version="1"/>
<statistics.counterUsagesCollector groupId="kotlin.ide.editor" version="1"/>
<statistics.projectUsagesCollector implementation="org.jetbrains.kotlin.idea.statistics.IDESettingsFUSCollector"/>
<statistics.projectUsagesCollector implementation="org.jetbrains.kotlin.idea.statistics.ProjectConfigurationCollector"/>
<trafficLightRendererContributor implementation="org.jetbrains.kotlin.idea.core.script.ScriptTrafficLightRendererContributor"/>
<fileTypeUsageSchemaDescriptor schema="Gradle Script" implementationClass="org.jetbrains.kotlin.idea.core.script.KotlinGradleScriptFileTypeSchemaDetector"/>
</extensions>
</idea-plugin>

View File

@@ -0,0 +1,218 @@
/*
* 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.actions.internal.benchmark
import com.intellij.codeInsight.AutoPopupController
import com.intellij.codeInsight.completion.CompletionType
import com.intellij.codeInsight.navigation.NavigationUtil
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.ScrollType
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.MessageType
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.wm.WindowManager
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.search.DelegatingGlobalSearchScope
import com.intellij.psi.search.FileTypeIndex
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.ui.components.JBLabel
import com.intellij.ui.components.JBTextField
import com.intellij.uiDesigner.core.GridConstraints
import kotlinx.coroutines.*
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.caches.project.ModuleOrigin
import org.jetbrains.kotlin.idea.caches.project.getNullableModuleInfo
import org.jetbrains.kotlin.idea.completion.CompletionBenchmarkSink
import org.jetbrains.kotlin.idea.core.moveCaret
import org.jetbrains.kotlin.idea.core.util.EDT
import org.jetbrains.kotlin.idea.core.util.getLineCount
import org.jetbrains.kotlin.idea.core.util.toPsiFile
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.psi.KtFile
import java.util.*
import javax.swing.JFileChooser
import javax.swing.JPanel
abstract class AbstractCompletionBenchmarkAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
val benchmarkSink = CompletionBenchmarkSink.enableAndGet()
val scenario = createBenchmarkScenario(project, benchmarkSink) ?: return
GlobalScope.launch(EDT) {
scenario.doBenchmark()
CompletionBenchmarkSink.disable()
}
}
internal abstract fun createBenchmarkScenario(
project: Project,
benchmarkSink: CompletionBenchmarkSink.Impl
): AbstractCompletionBenchmarkScenario?
companion object {
fun showPopup(project: Project, text: String) {
val statusBar = WindowManager.getInstance().getStatusBar(project)
JBPopupFactory.getInstance()
.createHtmlTextBalloonBuilder(text, MessageType.ERROR, null)
.setFadeoutTime(5000)
.createBalloon().showInCenterOf(statusBar.component)
}
internal fun <T> List<T>.randomElement(random: Random): T? = if (this.isNotEmpty()) this[random.nextInt(this.size)] else null
internal fun <T : Any> List<T>.shuffledSequence(random: Random): Sequence<T> =
generateSequence { this.randomElement(random) }.distinct()
internal fun collectSuitableKotlinFiles(project: Project, filePredicate: (KtFile) -> Boolean): MutableList<KtFile> {
val scope = GlobalSearchScope.allScope(project)
fun KtFile.isUsableForBenchmark(): Boolean {
val moduleInfo = this.getNullableModuleInfo() ?: return false
if (this.isCompiled || !this.isWritable || this.isScript()) return false
return moduleInfo.moduleOrigin == ModuleOrigin.MODULE
}
val kotlinVFiles = FileTypeIndex.getFiles(KotlinFileType.INSTANCE, scope)
return kotlinVFiles
.asSequence()
.mapNotNull { vfile -> (vfile.toPsiFile(project) as? KtFile) }
.filterTo(mutableListOf()) { it.isUsableForBenchmark() && filePredicate(it) }
}
internal fun JPanel.addBoxWithLabel(tooltip: String, label: String = "$tooltip:", default: String, i: Int): JBTextField {
this.add(JBLabel(label), GridConstraints().apply { row = i; column = 0 })
val textField = JBTextField().apply {
text = default
toolTipText = tooltip
}
this.add(textField, GridConstraints().apply { row = i; column = 1; fill = GridConstraints.FILL_HORIZONTAL })
return textField
}
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = ApplicationManager.getApplication().isInternal
}
}
internal abstract class AbstractCompletionBenchmarkScenario(
val project: Project, private val benchmarkSink: CompletionBenchmarkSink.Impl,
val random: Random = Random(), private val timeout: Long = 15000
) {
sealed class Result {
abstract fun toCSV(stringBuilder: StringBuilder)
open class SuccessResult(val lines: Int, val filePath: String, val first: Long, val full: Long) : Result() {
override fun toCSV(stringBuilder: StringBuilder): Unit = with(stringBuilder) {
append(filePath)
append(", ")
append(lines)
append(", ")
append(first)
append(", ")
append(full)
}
}
class ErrorResult(val filePath: String) : Result() {
override fun toCSV(stringBuilder: StringBuilder): Unit = with(stringBuilder) {
append(filePath)
append(", ")
append(", ")
append(", ")
}
}
}
protected suspend fun typeAtOffsetAndGetResult(text: String, offset: Int, file: KtFile): Result {
NavigationUtil.openFileWithPsiElement(file.navigationElement, false, true)
val document =
PsiDocumentManager.getInstance(project).getDocument(file) ?: return Result.ErrorResult("${file.virtualFile.path}:O$offset")
val location = "${file.virtualFile.path}:${document.getLineNumber(offset)}"
val editor = EditorFactory.getInstance().getEditors(document, project).firstOrNull() ?: return Result.ErrorResult(location)
delay(500)
editor.moveCaret(offset, scrollType = ScrollType.CENTER)
delay(500)
CommandProcessor.getInstance().executeCommand(project, {
runWriteAction {
document.insertString(editor.caretModel.offset, "\n$text\n")
PsiDocumentManager.getInstance(project).commitDocument(document)
}
editor.moveCaret(editor.caretModel.offset + text.length + 1)
AutoPopupController.getInstance(project).scheduleAutoPopup(editor, CompletionType.BASIC, null)
}, "insertTextAndInvokeCompletion", "completionBenchmark")
val result = try {
withTimeout(timeout) { collectResult(file, location) }
} catch (_: CancellationException) {
Result.ErrorResult(location)
}
CommandProcessor.getInstance().executeCommand(project, {
runWriteAction {
document.deleteString(offset, offset + text.length + 2)
PsiDocumentManager.getInstance(project).commitDocument(document)
}
}, "revertToOriginal", "completionBenchmark")
delay(100)
return result
}
private suspend fun collectResult(file: KtFile, location: String): Result {
val results = benchmarkSink.channel.receive()
return Result.SuccessResult(file.getLineCount(), location, results.firstFlush, results.full)
}
protected fun saveResults(allResults: List<Result>) {
val jfc = JFileChooser()
val result = jfc.showSaveDialog(null)
if (result == JFileChooser.APPROVE_OPTION) {
val file = jfc.selectedFile
file.writeText(buildString {
appendln("n, file, lines, ff, full")
var i = 0
allResults.forEach {
append(i++)
append(", ")
it.toCSV(this)
appendln()
}
})
}
AbstractCompletionBenchmarkAction.showPopup(project, "Done")
}
abstract suspend fun doBenchmark()
}

View File

@@ -12,6 +12,7 @@ import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.diagnostics.Severity
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor
import org.jetbrains.kotlin.lexer.KtTokens
@@ -21,8 +22,10 @@ import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtLambdaExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.callUtil.getType
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf
@@ -84,7 +87,12 @@ class SamConversionToAnonymousObjectIntention : SelfTargetingRangeIntention<KtCa
functionDescriptor: FunctionDescriptor,
functionName: String
) {
val interfaceName = call.calleeExpression?.text ?: return
val parentOfCall = call.getQualifiedExpressionForSelector()
val interfaceName = if (parentOfCall != null) {
parentOfCall.resolveToCall()?.resultingDescriptor?.fqNameSafe?.asString()
} else {
call.calleeExpression?.text
} ?: return
val typeArguments = call.typeArguments.mapNotNull { it.typeReference }
val typeArgumentsText =
if (typeArguments.isEmpty()) "" else typeArguments.joinToString(prefix = "<", postfix = ">", separator = ", ") { it.text }
@@ -92,7 +100,9 @@ class SamConversionToAnonymousObjectIntention : SelfTargetingRangeIntention<KtCa
val typeParameters = classDescriptor?.declaredTypeParameters?.map { it.name.asString() }?.zip(typeArguments)?.toMap().orEmpty()
LambdaToAnonymousFunctionIntention.convertLambdaToFunction(lambda, functionDescriptor, functionName, typeParameters) {
it.addModifier(KtTokens.OVERRIDE_KEYWORD)
call.replaced(KtPsiFactory(it).createExpression("object : $interfaceName$typeArgumentsText { ${it.text} }"))
(parentOfCall ?: call).replaced(
KtPsiFactory(it).createExpression("object : $interfaceName$typeArgumentsText { ${it.text} }")
)
}
}

View File

@@ -0,0 +1,36 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.psi.KtConstructor
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtObjectDeclaration
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
class ChangeObjectToClassFix(element: KtObjectDeclaration) : KotlinQuickFixAction<KtObjectDeclaration>(element) {
override fun getText(): String = "Change object to class"
override fun getFamilyName(): String = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val objectDeclaration = element ?: return
val psiFactory = KtPsiFactory(objectDeclaration)
objectDeclaration.getObjectKeyword()?.replace(psiFactory.createClassKeyword())
objectDeclaration.replace(psiFactory.createClass(objectDeclaration.text))
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtObjectDeclaration>? {
val element = diagnostic.psiElement as? KtConstructor<*> ?: return null
val containingObject = element.containingClassOrObject as? KtObjectDeclaration ?: return null
return ChangeObjectToClassFix(containingObject)
}
}
}

View File

@@ -42,7 +42,7 @@ class ChangeParameterTypeFix(element: KtParameter, type: KotlinType) : KotlinQui
init {
val declaration = PsiTreeUtil.getParentOfType(element, KtNamedDeclaration::class.java)
this.containingDeclarationName = declaration?.fqName?.asString() ?: declaration?.name
this.containingDeclarationName = declaration?.name
this.isPrimaryConstructorParameter = declaration is KtPrimaryConstructor
}

View File

@@ -613,5 +613,9 @@ class QuickFixRegistrar : QuickFixContributor {
NO_VALUE_FOR_PARAMETER.registerFactory(AddConstructorParameterFromSuperTypeCallFix)
UNEXPECTED_TRAILING_LAMBDA_ON_A_NEW_LINE.registerFactory(AddSemicolonBeforeLambdaExpressionFix.Factory)
CONSTRUCTOR_IN_OBJECT.registerFactory(ChangeObjectToClassFix)
REDUNDANT_LABEL_WARNING.registerFactory(RemoveRedundantLabelFix)
}
}

View File

@@ -0,0 +1,34 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtLabelReferenceExpression
import org.jetbrains.kotlin.psi.KtLabeledExpression
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
class RemoveRedundantLabelFix(element: KtLabeledExpression) : KotlinQuickFixAction<KtLabeledExpression>(element) {
override fun getText(): String = "Remove redundant label"
override fun getFamilyName(): String = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val labeledExpression = element ?: return
val baseExpression = labeledExpression.baseExpression ?: return
labeledExpression.replace(baseExpression)
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtLabeledExpression>? {
val labelReference = diagnostic.psiElement as? KtLabelReferenceExpression ?: return null
val labeledExpression = labelReference.getStrictParentOfType<KtLabeledExpression>() ?: return null
return RemoveRedundantLabelFix(labeledExpression)
}
}
}

View File

@@ -32,7 +32,6 @@ import org.jetbrains.kotlin.idea.quickfix.TypeAccessibilityChecker
import org.jetbrains.kotlin.idea.util.actualsForExpected
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getSuperNames
import org.jetbrains.kotlin.psi.psiUtil.hasExpectModifier
sealed class CreateActualFix<D : KtNamedDeclaration>(
@@ -92,7 +91,7 @@ class CreateActualClassFix(
actualPlatform: TargetPlatform
) : CreateActualFix<KtClassOrObject>(klass, actualModule, actualPlatform, block@{ project, checker, element ->
checker.findAndApplyExistingClasses(element.collectDeclarationsForAddActualModifier().toList())
if (!checker.isCorrectAndHaveNonPrivateModifier(element, true)) return@block null
if (!checker.isCorrectAndHaveAccessibleModifiers(element, true)) return@block null
generateClassOrObject(project, false, element, checker = checker)
})
@@ -102,7 +101,7 @@ class CreateActualCallableMemberFix(
actualModule: Module,
actualPlatform: TargetPlatform
) : CreateActualFix<KtCallableDeclaration>(declaration, actualModule, actualPlatform, block@{ project, checker, element ->
if (!checker.isCorrectAndHaveNonPrivateModifier(element, true)) return@block null
if (!checker.isCorrectAndHaveAccessibleModifiers(element, true)) return@block null
val descriptor = element.toDescriptor() as? CallableMemberDescriptor
descriptor?.let { generateCallable(project, false, element, descriptor, checker = checker) }

View File

@@ -30,7 +30,6 @@ import org.jetbrains.kotlin.idea.refactoring.getExpressionShortText
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.idea.util.liftToExpected
import org.jetbrains.kotlin.idea.util.module
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer
@@ -115,10 +114,10 @@ class CreateExpectedClassFix(
) : CreateExpectedFix<KtClassOrObject>(klass, outerExpectedClass, commonModule, block@{ project, checker, element ->
val originalElements = element.collectDeclarationsForAddActualModifier(withSelf = false).toList()
val existingClasses = checker.findAndApplyExistingClasses(originalElements + klass)
if (!checker.isCorrectAndHaveNonPrivateModifier(element, true)) return@block null
if (!checker.isCorrectAndHaveAccessibleModifiers(element, true)) return@block null
val (members, declarationsWithNonExistentClasses) = originalElements.partition {
checker.isCorrectAndHaveNonPrivateModifier(it)
checker.isCorrectAndHaveAccessibleModifiers(it)
}
if (!showUnknownTypeInDeclarationDialog(project, declarationsWithNonExistentClasses)) return@block null
@@ -138,10 +137,10 @@ class CreateExpectedClassFix(
val selectedClasses = checker.findAndApplyExistingClasses(selectedElements)
val resultDeclarations = if (selectedClasses != existingClasses) {
if (!checker.isCorrectAndHaveNonPrivateModifier(element, true)) return@block null
if (!checker.isCorrectAndHaveAccessibleModifiers(element, true)) return@block null
val (resultDeclarations, withErrors) = selectedElements.partition {
checker.isCorrectAndHaveNonPrivateModifier(it)
checker.isCorrectAndHaveAccessibleModifiers(it)
}
if (!showUnknownTypeInDeclarationDialog(project, withErrors)) return@block null
resultDeclarations
@@ -179,7 +178,6 @@ private fun showUnknownTypeInDeclarationDialog(
private fun KtDeclaration.canAddActualModifier() = when (this) {
is KtEnumEntry, is KtClassInitializer -> false
is KtParameter -> hasValOrVar()
is KtProperty -> !hasModifier(KtTokens.LATEINIT_KEYWORD) && !hasModifier(KtTokens.CONST_KEYWORD)
else -> true
}
@@ -270,7 +268,7 @@ class CreateExpectedCallableMemberFix(
targetExpectedClass: KtClassOrObject?,
commonModule: Module
) : CreateExpectedFix<KtNamedDeclaration>(declaration, targetExpectedClass, commonModule, block@{ project, checker, element ->
if (!checker.isCorrectAndHaveNonPrivateModifier(element, true)) return@block null
if (!checker.isCorrectAndHaveAccessibleModifiers(element, true)) return@block null
val descriptor = element.toDescriptor() as? CallableMemberDescriptor
checker.existingTypeNames = targetExpectedClass?.getSuperNames()?.toSet().orEmpty()
descriptor?.let {

View File

@@ -10,6 +10,7 @@ import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.JavaDirectoryService
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor
import org.jetbrains.kotlin.descriptors.annotations.Annotations
@@ -30,11 +31,14 @@ import org.jetbrains.kotlin.idea.quickfix.TypeAccessibilityChecker
import org.jetbrains.kotlin.idea.refactoring.createKotlinFile
import org.jetbrains.kotlin.idea.refactoring.fqName.fqName
import org.jetbrains.kotlin.idea.refactoring.introduce.showErrorHint
import org.jetbrains.kotlin.idea.refactoring.isInterfaceClass
import org.jetbrains.kotlin.idea.util.*
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.lexer.KtModifierKeywordToken
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.hasActualModifier
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.checkers.ExpectedActualDeclarationChecker
@@ -383,9 +387,11 @@ fun KtNamedDeclaration.isAlwaysActual(): Boolean = safeAs<KtParameter>()?.parent
?.mustHaveValOrVar() ?: false
fun TypeAccessibilityChecker.isCorrectAndHaveNonPrivateModifier(declaration: KtNamedDeclaration, showErrorHint: Boolean = false): Boolean {
if (declaration.hasPrivateModifier()) {
if (showErrorHint) showInaccessibleDeclarationError(declaration, "The declaration has a private modifier")
fun TypeAccessibilityChecker.isCorrectAndHaveAccessibleModifiers(declaration: KtNamedDeclaration, showErrorHint: Boolean = false): Boolean {
if (declaration.anyInaccessibleModifier(INACCESSIBLE_MODIFIERS, showErrorHint)) return false
if (declaration is KtFunction && declaration.hasBody() && declaration.containingClassOrObject?.isInterfaceClass() == true) {
if (showErrorHint) showInaccessibleDeclarationError(declaration, "The function declaration shouldn't have a default implementation")
return false
}
@@ -402,7 +408,19 @@ fun TypeAccessibilityChecker.isCorrectAndHaveNonPrivateModifier(declaration: KtN
return false
}
fun showInaccessibleDeclarationError(element: KtNamedDeclaration, message: String, editor: Editor? = element.findExistingEditor()) {
private val INACCESSIBLE_MODIFIERS = listOf(KtTokens.PRIVATE_KEYWORD, KtTokens.CONST_KEYWORD, KtTokens.LATEINIT_KEYWORD)
private fun KtModifierListOwner.anyInaccessibleModifier(modifiers: Collection<KtModifierKeywordToken>, showErrorHint: Boolean): Boolean {
for (modifier in modifiers) {
if (hasModifier(modifier)) {
if (showErrorHint) showInaccessibleDeclarationError(this, "The declaration has `$modifier` modifier")
return true
}
}
return false
}
fun showInaccessibleDeclarationError(element: PsiElement, message: String, editor: Editor? = element.findExistingEditor()) {
editor?.let {
showErrorHint(element.project, editor, escapeXml(message), "Inaccessible declaration")
}
@@ -420,7 +438,7 @@ fun TypeAccessibilityChecker.findAndApplyExistingClasses(elements: Collection<Kt
val existingNames = classes.mapNotNull { it.fqName?.asString() }.toHashSet()
existingTypeNames = existingNames
val newExistingClasses = classes.filter { isCorrectAndHaveNonPrivateModifier(it) }
val newExistingClasses = classes.filter { isCorrectAndHaveAccessibleModifiers(it) }
if (classes.size == newExistingClasses.size) return existingNames
classes = newExistingClasses

View File

@@ -248,7 +248,7 @@ private fun smartSelectElement(
}
fun getExpressionShortText(element: KtElement): String {
val text = element.renderTrimmed()
val text = element.renderTrimmed().trimStart()
val firstNewLinePos = text.indexOf('\n')
var trimmedText = text.substring(0, if (firstNewLinePos != -1) firstNewLinePos else min(100, text.length))
if (trimmedText.length != text.length) trimmedText += " ..."

View File

@@ -0,0 +1,15 @@
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id("org.jetbrains.kotlin.jvm") version "1.3.50"
}
repositories {
mavenCentral()
maven { setUrl("https://dl.bintray.com/kotlin/kotlin-eap") }
}
val compileKotlin: KotlinCompile by tasks
compileKotlin.kotlinOptions {
freeCompilerArgs = listOf("-Xinline-classes")
}

View File

@@ -0,0 +1,15 @@
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id("org.jetbrains.kotlin.jvm") version "1.3.50"
}
repositories {
mavenCentral()
maven { setUrl("https://dl.bintray.com/kotlin/kotlin-eap") }
}
val compileKotlin: KotlinCompile by tasks
compileKotlin.kotlinOptions {
freeCompilerArgs = listOf("-XXLanguage:-InlineClasses")
}

View File

@@ -0,0 +1,8 @@
pluginManagement {
repositories {
maven("https://dl.bintray.com/kotlin/kotlin-dev")
gradlePluginPortal()
}
}
rootProject.name = "my-app"

View File

@@ -0,0 +1,24 @@
buildscript {
repositories {
jcenter()
mavenCentral()
maven { url 'https://dl.bintray.com/kotlin/kotlin-dev' }
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.60-dev-1951"
}
}
apply plugin: "kotlin"
repositories {
jcenter()
mavenCentral()
maven { url 'https://dl.bintray.com/kotlin/kotlin-dev' }
}
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib"
}
compileKotlin {
kotlinOptions {
freeCompilerArgs = ["-XXLanguage:-InlineClasses"]
}
}

View File

@@ -0,0 +1,24 @@
buildscript {
repositories {
jcenter()
mavenCentral()
maven { url 'https://dl.bintray.com/kotlin/kotlin-dev' }
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.60-dev-1951"
}
}
apply plugin: "kotlin"
repositories {
jcenter()
mavenCentral()
maven { url 'https://dl.bintray.com/kotlin/kotlin-dev' }
}
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib"
}
compileKotlin {
kotlinOptions {
freeCompilerArgs = ["-Xinline-classes"]
}
}

View File

@@ -0,0 +1,7 @@
plugins {
kotlin("jvm") version "1.3.50"
}
repositories {
maven { setUrl("https://dl.bintray.com/kotlin/kotlin-eap") }
}

View File

@@ -0,0 +1,13 @@
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
kotlin("jvm") version "1.3.50"
}
repositories {
maven { setUrl("https://dl.bintray.com/kotlin/kotlin-eap") }
}
val compileKotlin: KotlinCompile by tasks
compileKotlin.kotlinOptions {
freeCompilerArgs = listOf("-XXLanguage:-InlineClasses")
}

View File

@@ -0,0 +1,8 @@
pluginManagement {
repositories {
maven("https://dl.bintray.com/kotlin/kotlin-dev")
gradlePluginPortal()
}
}
rootProject.name = "my-app"

View File

@@ -0,0 +1,15 @@
buildscript {
repositories {
jcenter()
mavenCentral()
maven { setUrl("https://dl.bintray.com/kotlin/kotlin-dev") }
}
dependencies {
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.60-dev-1951")
}
}
apply(plugin="kotlin-multiplatform")
repositories {
jcenter()
mavenCentral()
}

View File

@@ -0,0 +1,21 @@
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
buildscript {
repositories {
jcenter()
mavenCentral()
maven { setUrl("https://dl.bintray.com/kotlin/kotlin-dev") }
}
dependencies {
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.50-eap-2")
}
}
apply(plugin="kotlin-multiplatform")
repositories {
jcenter()
mavenCentral()
}
val compileKotlin: KotlinCompile by tasks
compileKotlin.kotlinOptions {
freeCompilerArgs = listOf("-XXLanguage:-InlineClasses")
}

View File

@@ -0,0 +1,19 @@
buildscript {
repositories {
jcenter()
mavenCentral()
maven { url 'https://dl.bintray.com/kotlin/kotlin-dev' }
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.50"
}
}
apply plugin: "kotlin"
repositories {
jcenter()
mavenCentral()
maven { url 'https://dl.bintray.com/kotlin/kotlin-dev' }
}
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib"
}

View File

@@ -0,0 +1,24 @@
buildscript {
repositories {
jcenter()
mavenCentral()
maven { url 'https://dl.bintray.com/kotlin/kotlin-dev' }
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.50"
}
}
apply plugin: "kotlin"
repositories {
jcenter()
mavenCentral()
maven { url 'https://dl.bintray.com/kotlin/kotlin-dev' }
}
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib"
}
compileKotlin {
kotlinOptions {
freeCompilerArgs = ["-XXLanguage:-InlineClasses"]
}
}

View File

@@ -0,0 +1,8 @@
plugins {
id("org.jetbrains.kotlin.jvm").version("1.3.50")
}
repositories {
mavenCentral()
maven { setUrl("https://dl.bintray.com/kotlin/kotlin-eap") }
}

View File

@@ -0,0 +1,14 @@
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id("org.jetbrains.kotlin.jvm").version("1.3.50")
}
repositories {
mavenCentral()
maven { setUrl("https://dl.bintray.com/kotlin/kotlin-eap") }
}
val compileKotlin: KotlinCompile by tasks
compileKotlin.kotlinOptions {
freeCompilerArgs = listOf("-Xinline-classes")
}

View File

@@ -0,0 +1,8 @@
pluginManagement {
repositories {
maven("https://dl.bintray.com/kotlin/kotlin-dev")
gradlePluginPortal()
}
}
rootProject.name = "my-app"

View File

@@ -0,0 +1,8 @@
plugins {
id("org.jetbrains.kotlin.jvm") version "1.3.50"
}
repositories {
mavenCentral()
maven { setUrl("https://dl.bintray.com/kotlin/kotlin-eap") }
}

View File

@@ -0,0 +1,14 @@
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id("org.jetbrains.kotlin.jvm") version "1.3.50"
}
repositories {
mavenCentral()
maven { setUrl("https://dl.bintray.com/kotlin/kotlin-eap") }
}
val compileKotlin: KotlinCompile by tasks
compileKotlin.kotlinOptions {
freeCompilerArgs = listOf("-Xinline-classes")
}

View File

@@ -0,0 +1,8 @@
pluginManagement {
repositories {
maven("https://dl.bintray.com/kotlin/kotlin-dev")
gradlePluginPortal()
}
}
rootProject.name = "my-app"

View File

@@ -0,0 +1,12 @@
buildscript {
repositories {
jcenter()
mavenCentral()
maven { setUrl("https://dl.bintray.com/kotlin/kotlin-dev") }
}
dependencies {
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.60-dev-1951")
}
}
apply(plugin ="kotlin")

View File

@@ -0,0 +1,18 @@
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
buildscript {
repositories {
jcenter()
mavenCentral()
maven { setUrl("https://dl.bintray.com/kotlin/kotlin-dev") }
}
dependencies {
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.60-dev-1951")
}
}
apply(plugin ="kotlin")
val compileKotlin: KotlinCompile by tasks
compileKotlin.kotlinOptions {
freeCompilerArgs = listOf("-Xinline-classes")
}

View File

@@ -0,0 +1,29 @@
buildscript {
repositories {
jcenter()
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.50"
}
}
apply plugin: "kotlin-multiplatform"
repositories {
jcenter()
mavenCentral()
}
kotlin {
targets.fromPreset(presets.jvm, 'jvm')
sourceSets {
commonMain {
dependencies {
implementation 'org.jetbrains.kotlin:kotlin-stdlib-common'
}
}
jvmMain {
dependencies {
implementation 'org.jetbrains.kotlin:kotlin-stdlib'
}
}
}
}

View File

@@ -0,0 +1,36 @@
buildscript {
repositories {
jcenter()
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.50-eap-2"
}
}
apply plugin: "kotlin-multiplatform"
repositories {
jcenter()
mavenCentral()
}
kotlin {
targets.fromPreset(presets.jvm, 'jvm')
sourceSets {
commonMain {
dependencies {
implementation 'org.jetbrains.kotlin:kotlin-stdlib-common'
}
}
jvmMain {
dependencies {
implementation 'org.jetbrains.kotlin:kotlin-stdlib'
}
}
}
targets {
configure([jvm]) {
tasks.getByName(compilations.main.compileKotlinTaskName).kotlinOptions {
freeCompilerArgs = ["-Xinline-classes"]
}
}
}
}

View File

@@ -0,0 +1,32 @@
buildscript {
repositories {
jcenter()
mavenCentral()
maven { url "https://dl.bintray.com/kotlin/kotlin-eap" }
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.50-eap-5"
}
}
apply plugin: "kotlin-multiplatform"
repositories {
jcenter()
mavenCentral()
}
kotlin {
targets {
fromPreset(presets.jvm, 'jvm')
}
sourceSets {
commonMain {
dependencies {
implementation 'org.jetbrains.kotlin:kotlin-stdlib-common'
}
}
jvmMain {
dependencies {
implementation 'org.jetbrains.kotlin:kotlin-stdlib'
}
}
}
}

View File

@@ -0,0 +1,35 @@
buildscript {
repositories {
jcenter()
mavenCentral()
maven { url "https://dl.bintray.com/kotlin/kotlin-eap" }
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.50-eap-5"
}
}
apply plugin: "kotlin-multiplatform"
repositories {
jcenter()
mavenCentral()
}
kotlin {
targets {
fromPreset(presets.jvm, 'jvm')
}
sourceSets {
commonMain {
dependencies {
implementation 'org.jetbrains.kotlin:kotlin-stdlib-common'
}
}
jvmMain {
dependencies {
implementation 'org.jetbrains.kotlin:kotlin-stdlib'
}
}
all {
languageSettings.enableLanguageFeature("InlineClasses")
}
}
}

View File

@@ -0,0 +1,7 @@
pluginManagement {
repositories {
maven {
url 'http://dl.bintray.com/kotlin/kotlin-eap'
}
}
}

View File

@@ -0,0 +1,24 @@
buildscript {
repositories {
jcenter()
mavenCentral()
maven { url 'https://dl.bintray.com/kotlin/kotlin-dev' }
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.60-dev-1951"
}
}
apply plugin: "kotlin"
repositories {
jcenter()
mavenCentral()
maven { url 'https://dl.bintray.com/kotlin/kotlin-dev' }
}
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib"
}
compileKotlin {
kotlinOptions {
freeCompilerArgs = ["-XXLanguage:+SamConversionForKotlinFunctions"] // Free compiler arguments
}
}

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