[K/JS] Prepare JS Plain Objects plugin to publication

This commit is contained in:
Artem Kobzar
2024-01-17 10:52:58 +00:00
committed by Space Team
parent 561be747c1
commit dfe2d8651e
53 changed files with 479 additions and 393 deletions
@@ -0,0 +1,92 @@
import org.jetbrains.kotlin.gradle.plugin.KotlinPlatformType
import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinUsages
import org.jetbrains.kotlin.gradle.targets.js.KotlinJsCompilerAttribute
description = "JavaScript Plain Objects Compiler Plugin"
plugins {
kotlin("jvm")
id("jps-compatible")
}
val jsoIrRuntimeForTests by configurations.creating {
attributes {
attribute(KotlinPlatformType.attribute, KotlinPlatformType.js)
attribute(KotlinJsCompilerAttribute.jsCompilerAttribute, KotlinJsCompilerAttribute.ir)
attribute(Usage.USAGE_ATTRIBUTE, objects.named(KotlinUsages.KOTLIN_RUNTIME))
}
}
dependencies {
embedded(project(":plugins:js-plain-objects:compiler-plugin:js-plain-objects.common")) { isTransitive = false }
embedded(project(":plugins:js-plain-objects:compiler-plugin:js-plain-objects.k2")) { isTransitive = false }
embedded(project(":plugins:js-plain-objects:compiler-plugin:js-plain-objects.backend")) { isTransitive = false }
embedded(project(":plugins:js-plain-objects:compiler-plugin:js-plain-objects.cli")) { isTransitive = false }
testApi(project(":compiler:backend"))
testApi(project(":compiler:cli"))
testApi(project(":plugins:js-plain-objects:compiler-plugin:js-plain-objects.cli"))
testApi(projectTests(":compiler:test-infrastructure"))
testApi(projectTests(":compiler:test-infrastructure-utils"))
testApi(projectTests(":compiler:tests-compiler-utils"))
testApi(projectTests(":compiler:tests-common-new"))
testImplementation(projectTests(":js:js.tests"))
testImplementation(projectTests(":generators:test-generator"))
testApi(platform(libs.junit.bom))
testImplementation(libs.junit.jupiter.api)
testRuntimeOnly(libs.junit.jupiter.engine)
if (!project.kotlinBuildProperties.isInJpsBuildIdeaSync) {
jsoIrRuntimeForTests(project(":plugins:js-plain-objects:runtime")) { isTransitive = false }
embedded(project(":plugins:js-plain-objects:runtime")) {
attributes {
attribute(KotlinPlatformType.attribute, KotlinPlatformType.js)
attribute(KotlinJsCompilerAttribute.jsCompilerAttribute, KotlinJsCompilerAttribute.ir)
attribute(Usage.USAGE_ATTRIBUTE, objects.named(KotlinUsages.KOTLIN_RUNTIME))
}
isTransitive = false
}
}
testRuntimeOnly(project(":core:descriptors.runtime"))
}
optInToExperimentalCompilerApi()
sourceSets {
"main" { none() }
"test" {
projectDefault()
generatedTestDir()
}
}
publish {
artifactId = "kotlinx-js-plain-objects-compiler-plugin"
}
runtimeJar()
sourcesJar()
javadocJar()
testsJar()
projectTest(parallel = true, jUnitMode = JUnitMode.JUnit5) {
useJUnitPlatform()
useJsIrBoxTests(version = version, buildDir = layout.buildDirectory)
workingDir = rootDir
dependsOn(jsoIrRuntimeForTests)
val localJsPlainObjectsIrRuntimePath: FileCollection = jsoIrRuntimeForTests
doFirst {
systemProperty("jso.runtime.path", localJsPlainObjectsIrRuntimePath.asPath)
}
}
val generateTests by generator("org.jetbrains.kotlinx.jspo.TestGeneratorKt")
@@ -0,0 +1,25 @@
description = "Kotlin JavaScript Plain Objects Compiler Plugin (Backend)"
plugins {
kotlin("jvm")
id("jps-compatible")
}
dependencies {
compileOnly(project(":compiler:backend"))
compileOnly(project(":compiler:ir.backend.common"))
compileOnly(project(":compiler:ir.tree"))
implementation(project(":plugins:js-plain-objects:compiler-plugin:js-plain-objects.common"))
compileOnly(intellijCore())
}
sourceSets {
"main" { projectDefault() }
"test" { none() }
}
runtimeJar()
sourcesJar()
javadocJar()
@@ -0,0 +1,73 @@
/*
* Copyright 2010-2023 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.kotlinx.jspo.compiler.backend
import org.jetbrains.kotlin.backend.common.DeclarationTransformer
import org.jetbrains.kotlin.backend.common.extensions.IrGenerationExtension
import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext
import org.jetbrains.kotlin.backend.common.lower
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.expressions.IrBlockBody
import org.jetbrains.kotlin.ir.expressions.impl.*
import org.jetbrains.kotlin.ir.symbols.UnsafeDuringIrConstructionAPI
import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.util.OperatorNameConventions
import org.jetbrains.kotlinx.jspo.compiler.resolve.JsPlainObjectsPluginKey
import org.jetbrains.kotlinx.jspo.compiler.resolve.StandardIds
private class MoveExternalInlineFunctionsWithBodiesOutsideLowering(private val context: IrPluginContext) : DeclarationTransformer {
private val jsFunction = context.referenceFunctions(StandardIds.JS_FUNCTION_ID).single()
private val EXPECTED_ORIGIN = IrDeclarationOrigin.GeneratedByPlugin(JsPlainObjectsPluginKey)
@OptIn(UnsafeDuringIrConstructionAPI::class)
override fun transformFlat(declaration: IrDeclaration): List<IrDeclaration>? {
val file = declaration.file
val parent = declaration.parentClassOrNull
if (parent == null || declaration !is IrSimpleFunction || declaration.origin != EXPECTED_ORIGIN) return null
file.declarations.add(declaration)
declaration.body = when (declaration.name) {
StandardNames.DATA_CLASS_COPY, OperatorNameConventions.INVOKE -> declaration.generateBodyForFactoryAndCopyFunction()
else -> error("Unexpected function with name `${declaration.name.identifier}`")
}
declaration.parent = file
declaration.isExternal = false
return emptyList()
}
private fun IrSimpleFunction.generateBodyForFactoryAndCopyFunction(): IrBlockBody {
val declaration = this
return context.irFactory.createBlockBody(startOffset, declaration.endOffset).apply {
statements += IrReturnImpl(
declaration.startOffset,
declaration.endOffset,
declaration.returnType,
declaration.symbol,
IrCallImpl(
declaration.startOffset,
declaration.endOffset,
declaration.returnType,
jsFunction,
0,
1,
).apply {
val jsObject = "{ ${declaration.valueParameters.joinToString(", ") { "${it.name.identifier}:${it.name.identifier}" }} }"
putValueArgument(0, jsObject.toIrConst(context.irBuiltIns.stringType))
}
)
}
}
}
open class JsPlainObjectsLoweringExtension : IrGenerationExtension {
override fun generate(moduleFragment: IrModuleFragment, pluginContext: IrPluginContext) {
MoveExternalInlineFunctionsWithBodiesOutsideLowering(pluginContext).lower(moduleFragment)
}
}
@@ -0,0 +1,31 @@
description = "Kotlin JavaScript Plain Objects Compiler Plugin (CLI)"
plugins {
kotlin("jvm")
id("jps-compatible")
}
dependencies {
compileOnly(project(":compiler:util"))
compileOnly(project(":compiler:cli"))
compileOnly(project(":compiler:plugin-api"))
compileOnly(project(":compiler:fir:entrypoint"))
compileOnly(project(":compiler:ir.backend.common"))
implementation(project(":plugins:js-plain-objects:compiler-plugin:js-plain-objects.common"))
implementation(project(":plugins:js-plain-objects:compiler-plugin:js-plain-objects.backend"))
implementation(project(":plugins:js-plain-objects:compiler-plugin:js-plain-objects.k2"))
compileOnly(intellijCore())
}
optInToExperimentalCompilerApi()
sourceSets {
"main" { projectDefault() }
"test" { none() }
}
runtimeJar()
sourcesJar()
javadocJar()
@@ -0,0 +1,17 @@
#
# Copyright 2010-2023 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.
#
org.jetbrains.kotlinx.jspo.compiler.cli.JsPlainObjectsComponentRegistrar
@@ -0,0 +1,28 @@
/*
* Copyright 2010-2023 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.kotlinx.jspo.compiler.cli
import org.jetbrains.kotlin.backend.common.extensions.IrGenerationExtension
import org.jetbrains.kotlin.compiler.plugin.CompilerPluginRegistrar
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.fir.extensions.FirExtensionRegistrarAdapter
import org.jetbrains.kotlinx.jspo.compiler.backend.JsPlainObjectsLoweringExtension
import org.jetbrains.kotlinx.jspo.compiler.fir.JsPlainObjectsExtensionRegistrar
class JsPlainObjectsComponentRegistrar : CompilerPluginRegistrar() {
override val supportsK2: Boolean get() = true
override fun ExtensionStorage.registerExtensions(configuration: CompilerConfiguration) {
Companion.registerExtensions(this)
}
companion object {
fun registerExtensions(extensionStorage: ExtensionStorage) = with(extensionStorage) {
FirExtensionRegistrarAdapter.registerExtension(JsPlainObjectsExtensionRegistrar())
IrGenerationExtension.registerExtension(JsPlainObjectsLoweringExtension())
}
}
}
@@ -0,0 +1,21 @@
description = "Kotlin JavaScript Plain Objects Compiler Plugin (Common)"
plugins {
kotlin("jvm")
id("jps-compatible")
}
dependencies {
compileOnly(project(":compiler:util"))
compileOnly(project(":core:compiler.common"))
compileOnly(intellijCore())
}
sourceSets {
"main" { projectDefault() }
"test" { none() }
}
runtimeJar()
sourcesJar()
javadocJar()
@@ -0,0 +1,14 @@
/*
* Copyright 2010-2023 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.kotlinx.jspo.compiler.resolve
import org.jetbrains.kotlin.GeneratedDeclarationKey
object JsPlainObjectsPluginKey : GeneratedDeclarationKey() {
override fun toString(): String {
return "KotlinxJsPlainObjectsPlugin"
}
}
@@ -0,0 +1,21 @@
/*
* Copyright 2010-2023 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.kotlinx.jspo.compiler.resolve;
import org.jetbrains.kotlin.name.CallableId
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
object StandardIds {
val KOTLIN_JS_FQN = FqName("kotlin.js")
val JS_FUNCTION_ID = CallableId(KOTLIN_JS_FQN, Name.identifier("js"))
}
object JsPlainObjectsAnnotations {
val jsPlainObjectAnnotationClassId = ClassId(FqName("kotlinx.js"), Name.identifier("JsPlainObject"))
val jsPlainObjectAnnotationFqName = jsPlainObjectAnnotationClassId.asSingleFqName()
}
@@ -0,0 +1,34 @@
description = "Kotlin JavaScript Plain Objects Compiler Plugin (K2)"
plugins {
kotlin("jvm")
id("jps-compatible")
}
dependencies {
compileOnly(project(":compiler:fir:cones"))
compileOnly(project(":compiler:fir:tree"))
compileOnly(project(":compiler:fir:resolve"))
compileOnly(project(":compiler:fir:plugin-utils"))
compileOnly(project(":compiler:fir:entrypoint"))
compileOnly(project(":compiler:cli-common"))
implementation(project(":plugins:js-plain-objects:compiler-plugin:js-plain-objects.common"))
compileOnly(intellijCore())
testApi(project(":compiler:fir:plugin-utils"))
}
sourceSets {
"main" { projectDefault() }
"test" { none() }
}
runtimeJar()
sourcesJar()
javadocJar()
tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile>().configureEach {
compilerOptions.freeCompilerArgs.add("-Xcontext-receivers")
}
@@ -0,0 +1,19 @@
/*
* Copyright 2010-2023 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.kotlinx.jspo.compiler.fir
import org.jetbrains.kotlin.fir.extensions.FirExtensionRegistrar
import org.jetbrains.kotlinx.jspo.compiler.fir.checkers.FirJsPlainObjectsCheckersComponent
import org.jetbrains.kotlinx.jspo.compiler.fir.services.JsPlainObjectsPropertiesProvider
class JsPlainObjectsExtensionRegistrar : FirExtensionRegistrar() {
override fun ExtensionRegistrarContext.configurePlugin() {
+::FirJsPlainObjectsCheckersComponent
+::JsPlainObjectsFunctionsGenerator
// services
+::JsPlainObjectsPropertiesProvider
}
}
@@ -0,0 +1,249 @@
/*
* Copyright 2010-2023 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.kotlinx.jspo.compiler.fir
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.descriptors.Visibilities
import org.jetbrains.kotlin.fir.FirFunctionTarget
import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.analysis.checkers.getContainingClassSymbol
import org.jetbrains.kotlin.fir.declarations.FirResolvePhase
import org.jetbrains.kotlin.fir.declarations.FirSimpleFunction
import org.jetbrains.kotlin.fir.declarations.builder.buildRegularClass
import org.jetbrains.kotlin.fir.declarations.builder.buildSimpleFunction
import org.jetbrains.kotlin.fir.declarations.builder.buildValueParameter
import org.jetbrains.kotlin.fir.declarations.impl.FirResolvedDeclarationStatusImpl
import org.jetbrains.kotlin.fir.declarations.origin
import org.jetbrains.kotlin.fir.declarations.utils.isCompanion
import org.jetbrains.kotlin.fir.declarations.utils.visibility
import org.jetbrains.kotlin.fir.expressions.FirExpression
import org.jetbrains.kotlin.fir.expressions.builder.*
import org.jetbrains.kotlin.fir.extensions.FirDeclarationGenerationExtension
import org.jetbrains.kotlin.fir.extensions.MemberGenerationContext
import org.jetbrains.kotlin.fir.extensions.NestedClassGenerationContext
import org.jetbrains.kotlin.fir.extensions.predicateBasedProvider
import org.jetbrains.kotlin.fir.moduleData
import org.jetbrains.kotlin.fir.references.builder.buildImplicitThisReference
import org.jetbrains.kotlin.fir.references.builder.buildResolvedNamedReference
import org.jetbrains.kotlin.fir.resolve.defaultType
import org.jetbrains.kotlin.fir.scopes.kotlinScopeProvider
import org.jetbrains.kotlin.fir.symbols.SymbolInternals
import org.jetbrains.kotlin.fir.symbols.impl.*
import org.jetbrains.kotlin.fir.toEffectiveVisibility
import org.jetbrains.kotlin.fir.types.isNullable
import org.jetbrains.kotlin.fir.types.toFirResolvedTypeRef
import org.jetbrains.kotlin.name.CallableId
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.name.SpecialNames
import org.jetbrains.kotlin.types.ConstantValueKind
import org.jetbrains.kotlin.util.OperatorNameConventions
import org.jetbrains.kotlin.utils.addToStdlib.runIf
import org.jetbrains.kotlinx.jspo.compiler.fir.services.jsPlainObjectPropertiesProvider
import org.jetbrains.kotlinx.jspo.compiler.resolve.JsPlainObjectsPluginKey
/**
* The extension generate a synthetic factory and copy-method for an `external interface` annotated with @JsPlainObjects
* Imagine the next interfaces:
* ```
* external interface User {
* val name: String
* }
* @JsPlainObjects
* external interface Admin {
* val chat: Chat
* }
* ```
*
* For the interface `Admin` this function should generate the companion inline function:
* ```
* external interface Admin {
* val chat: Chat
*
* inline fun copy(chat: Chat = this.chat, name: String = this.name): Admin =
* Admin.Companion.invoke(chat, name)
*
* companion object {
* inline operator fun invoke(chat: Chat, name: String): Admin =
* js("{ chat: chat, name: name }")
* }
* }
* ```
*/
class JsPlainObjectsFunctionsGenerator(session: FirSession) : FirDeclarationGenerationExtension(session) {
private val predicateBasedProvider = session.predicateBasedProvider
private val matchedInterfaces by lazy {
predicateBasedProvider.getSymbolsByPredicate(JsPlainObjectsPredicates.AnnotatedWithJsPlainObject.LOOKUP)
.filterIsInstance<FirRegularClassSymbol>()
.toSet()
}
private val factoryFqNamesToJsPlainObjectsInterface by lazy {
matchedInterfaces.associateBy { it.classId.asSingleFqName() }
}
private val FirClassLikeSymbol<*>.isJsPlainObject: Boolean
get() = this is FirRegularClassSymbol && this in matchedInterfaces
override fun getNestedClassifiersNames(classSymbol: FirClassSymbol<*>, context: NestedClassGenerationContext): Set<Name> {
return if (classSymbol.isJsPlainObject) setOf(SpecialNames.DEFAULT_NAME_FOR_COMPANION_OBJECT) else emptySet()
}
override fun generateNestedClassLikeDeclaration(
owner: FirClassSymbol<*>,
name: Name,
context: NestedClassGenerationContext
): FirClassLikeSymbol<*>? {
return if (
owner is FirRegularClassSymbol &&
owner.isJsPlainObject &&
name == org.jetbrains.kotlin.name.SpecialNames.DEFAULT_NAME_FOR_COMPANION_OBJECT
) generateCompanionDeclaration(owner)
else null
}
private fun generateCompanionDeclaration(owner: FirRegularClassSymbol): FirRegularClassSymbol? {
if (owner.companionObjectSymbol != null) return null
val classId = owner.classId.createNestedClassId(SpecialNames.DEFAULT_NAME_FOR_COMPANION_OBJECT)
return buildRegularClass {
resolvePhase = FirResolvePhase.BODY_RESOLVE
moduleData = session.moduleData
origin = JsPlainObjectsPluginKey.origin
classKind = ClassKind.OBJECT
scopeProvider = session.kotlinScopeProvider
status = FirResolvedDeclarationStatusImpl(
Visibilities.Public,
Modality.FINAL,
Visibilities.Public.toEffectiveVisibility(owner, forClass = true)
).apply {
isExternal = true
isCompanion = true
}
name = classId.shortClassName
symbol = FirRegularClassSymbol(classId)
}.symbol
}
override fun getCallableNamesForClass(classSymbol: FirClassSymbol<*>, context: MemberGenerationContext): Set<Name> {
val outerClass = classSymbol.getContainingClassSymbol(session)
return when {
classSymbol.isCompanion && outerClass?.isJsPlainObject == true -> setOf(OperatorNameConventions.INVOKE)
classSymbol.isJsPlainObject -> setOf(StandardNames.DATA_CLASS_COPY)
else -> emptySet()
}
}
override fun generateFunctions(callableId: CallableId, context: MemberGenerationContext?): List<FirNamedFunctionSymbol> {
if (context == null) return emptyList()
val containingClass = callableId.classId
val possibleInterface = containingClass?.outerClassId
return when (callableId.callableName) {
StandardNames.DATA_CLASS_COPY -> {
containingClass
?.let { factoryFqNamesToJsPlainObjectsInterface[it.asSingleFqName()] }
?.let { listOf(createJsPlainObjectCopyFunction(callableId, context.owner, it).symbol) } ?: emptyList()
}
OperatorNameConventions.INVOKE -> {
possibleInterface
?.takeIf { context.owner.isCompanion }
?.let { factoryFqNamesToJsPlainObjectsInterface[it.asSingleFqName()] }
?.let { listOf(createJsPlainObjectFactoryFunction(callableId, context.owner, it).symbol) } ?: emptyList()
}
else -> emptyList()
}
}
private fun createJsPlainObjectFactoryFunction(
callableId: CallableId,
parent: FirClassSymbol<*>,
jsPlainObjectInterface: FirRegularClassSymbol,
): FirSimpleFunction {
return createJsPlainObjectsFunction(callableId, parent, jsPlainObjectInterface) {
runIf(resolvedReturnTypeRef.type.isNullable) {
buildConstExpression(
source = null,
value = null,
kind = ConstantValueKind.Null,
setType = true
)
}
}
}
private fun createJsPlainObjectCopyFunction(
callableId: CallableId,
parent: FirClassSymbol<*>,
jsPlainObjectInterface: FirRegularClassSymbol,
): FirSimpleFunction {
val interfaceType = jsPlainObjectInterface.defaultType()
return createJsPlainObjectsFunction(callableId, parent, jsPlainObjectInterface) {
buildPropertyAccessExpression {
dispatchReceiver = buildThisReceiverExpression {
calleeReference = buildImplicitThisReference { boundSymbol = jsPlainObjectInterface }
coneTypeOrNull = interfaceType
}
calleeReference = buildResolvedNamedReference {
name = this@createJsPlainObjectsFunction.name
resolvedSymbol = this@createJsPlainObjectsFunction
}
coneTypeOrNull = resolvedReturnType
}
}
}
@OptIn(SymbolInternals::class)
private fun createJsPlainObjectsFunction(
callableId: CallableId,
parent: FirClassSymbol<*>,
jsPlainObjectInterface: FirRegularClassSymbol,
getParameterDefaultValueFromProperty: FirPropertySymbol.() -> FirExpression?
): FirSimpleFunction {
val jsPlainObjectProperties = session.jsPlainObjectPropertiesProvider.getJsPlainObjectsPropertiesForClass(jsPlainObjectInterface)
val functionTarget = FirFunctionTarget(null, isLambda = false)
val jsPlainObjectInterfaceDefaultType = jsPlainObjectInterface.defaultType()
return buildSimpleFunction {
moduleData = jsPlainObjectInterface.moduleData
resolvePhase = FirResolvePhase.BODY_RESOLVE
origin = JsPlainObjectsPluginKey.origin
symbol = FirNamedFunctionSymbol(callableId)
name = callableId.callableName
returnTypeRef = jsPlainObjectInterfaceDefaultType.toFirResolvedTypeRef()
status = FirResolvedDeclarationStatusImpl(
jsPlainObjectInterface.visibility,
Modality.FINAL,
jsPlainObjectInterface.visibility.toEffectiveVisibility(parent, forClass = true)
).apply {
isInline = true
isOperator = true
}
dispatchReceiverType = parent.defaultType()
jsPlainObjectInterface.typeParameterSymbols.mapTo(typeParameters) { it.fir }
jsPlainObjectProperties.mapTo(valueParameters) {
val typeRef = it.resolvedReturnTypeRef
buildValueParameter {
moduleData = session.moduleData
origin = JsPlainObjectsPluginKey.origin
returnTypeRef = typeRef
name = it.name
symbol = FirValueParameterSymbol(it.name)
isCrossinline = false
isNoinline = true
isVararg = false
resolvePhase = FirResolvePhase.BODY_RESOLVE
containingFunctionSymbol = this@buildSimpleFunction.symbol
defaultValue = it.getParameterDefaultValueFromProperty()
}
}
}.also(functionTarget::bind)
}
}
@@ -0,0 +1,17 @@
/*
* Copyright 2010-2023 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.kotlinx.jspo.compiler.fir
import org.jetbrains.kotlin.fir.extensions.predicate.DeclarationPredicate
import org.jetbrains.kotlin.fir.extensions.predicate.LookupPredicate
import org.jetbrains.kotlinx.jspo.compiler.resolve.JsPlainObjectsAnnotations
object JsPlainObjectsPredicates {
internal object AnnotatedWithJsPlainObject {
private val jsPlainObjectAnnotation = setOf(JsPlainObjectsAnnotations.jsPlainObjectAnnotationFqName)
internal val LOOKUP = LookupPredicate.create { annotated(jsPlainObjectAnnotation) }
internal val DECLARATION = DeclarationPredicate.create { annotated(jsPlainObjectAnnotation) }
}
}
@@ -0,0 +1,17 @@
/*
* Copyright 2010-2023 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.kotlinx.jspo.compiler.fir.checkers
import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.analysis.checkers.declaration.DeclarationCheckers
import org.jetbrains.kotlin.fir.analysis.checkers.declaration.FirClassChecker
import org.jetbrains.kotlin.fir.analysis.extensions.FirAdditionalCheckersExtension
class FirJsPlainObjectsCheckersComponent(session: FirSession) : FirAdditionalCheckersExtension(session) {
override val declarationCheckers: DeclarationCheckers = object : DeclarationCheckers() {
override val classCheckers: Set<FirClassChecker> = setOf(FirJsPlainObjectsPluginClassChecker)
}
}
@@ -0,0 +1,22 @@
/*
* Copyright 2010-2023 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.kotlinx.jspo.compiler.fir.checkers
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.diagnostics.*
import org.jetbrains.kotlin.diagnostics.rendering.RootDiagnosticRendererFactory
object FirJsPlainObjectsErrors {
val NON_EXTERNAL_DECLARATIONS_NOT_SUPPORTED by error1<PsiElement, String>()
val ONLY_INTERFACES_ARE_SUPPORTED by error1<PsiElement, String>()
val IMPLEMENTING_OF_JS_PLAIN_OBJECT_IS_NOT_SUPPORTED by error1<PsiElement, String>()
val METHODS_ARE_NOT_ALLOWED_INSIDE_JS_PLAIN_OBJECT by error0<PsiElement>()
val JS_PLAIN_OBJECT_CAN_EXTEND_ONLY_OTHER_JS_PLAIN_OBJECTS by error1<PsiElement, String>()
init {
RootDiagnosticRendererFactory.registerFactory(KtDefaultErrorMessagesJsPlainObjects)
}
}
@@ -0,0 +1,105 @@
/*
* Copyright 2010-2023 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.kotlinx.jspo.compiler.fir.checkers
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.diagnostics.DiagnosticReporter
import org.jetbrains.kotlin.diagnostics.reportOn
import org.jetbrains.kotlin.fir.analysis.checkers.context.CheckerContext
import org.jetbrains.kotlin.fir.analysis.checkers.declaration.FirClassChecker
import org.jetbrains.kotlin.fir.declarations.FirClass
import org.jetbrains.kotlin.fir.declarations.hasAnnotation
import org.jetbrains.kotlin.fir.declarations.utils.isEffectivelyExternal
import org.jetbrains.kotlin.fir.declarations.utils.isInline
import org.jetbrains.kotlin.fir.declarations.utils.isInterface
import org.jetbrains.kotlin.fir.declarations.utils.isMethodOfAny
import org.jetbrains.kotlin.fir.resolve.fullyExpandedType
import org.jetbrains.kotlin.fir.scopes.impl.declaredMemberScope
import org.jetbrains.kotlin.fir.scopes.processAllFunctions
import org.jetbrains.kotlin.fir.symbols.impl.FirClassSymbol
import org.jetbrains.kotlin.fir.symbols.impl.FirRegularClassSymbol
import org.jetbrains.kotlin.fir.types.coneType
import org.jetbrains.kotlin.fir.types.isAny
import org.jetbrains.kotlin.fir.types.toRegularClassSymbol
import org.jetbrains.kotlinx.jspo.compiler.resolve.JsPlainObjectsAnnotations
object FirJsPlainObjectsPluginClassChecker : FirClassChecker() {
override fun check(declaration: FirClass, context: CheckerContext, reporter: DiagnosticReporter) {
with(context) {
val classSymbol = declaration.symbol as? FirRegularClassSymbol ?: return
if (classSymbol.hasAnnotation(JsPlainObjectsAnnotations.jsPlainObjectAnnotationClassId, session)) {
checkJsPlainObjectAnnotationTargets(classSymbol, reporter)
checkJsPlainObjectSuperTypes(classSymbol, reporter)
checkJsPlainObjectMembers(classSymbol, reporter)
} else {
checkJsPlainObjectAsSuperInterface(classSymbol, reporter)
}
}
}
context(CheckerContext)
private fun checkJsPlainObjectAnnotationTargets(classSymbol: FirClassSymbol<out FirClass>, reporter: DiagnosticReporter) {
val classKind = classSymbol.classKind.codeRepresentation ?: error("Unexpected enum entry")
if (!classSymbol.isEffectivelyExternal(session)) {
reporter.reportOn(classSymbol.source, FirJsPlainObjectsErrors.NON_EXTERNAL_DECLARATIONS_NOT_SUPPORTED, classKind)
return
}
if (!classSymbol.isInterface) {
reporter.reportOn(classSymbol.source, FirJsPlainObjectsErrors.ONLY_INTERFACES_ARE_SUPPORTED, classKind)
return
}
}
context(CheckerContext)
private fun checkJsPlainObjectMembers(classSymbol: FirClassSymbol<out FirClass>, reporter: DiagnosticReporter) {
if (!classSymbol.isEffectivelyExternal(session) || !classSymbol.isInterface) return
classSymbol
.declaredMemberScope(session, null)
.processAllFunctions {
if (!it.isMethodOfAny && !it.isInline) {
reporter.reportOn(it.source, FirJsPlainObjectsErrors.METHODS_ARE_NOT_ALLOWED_INSIDE_JS_PLAIN_OBJECT)
}
}
}
context(CheckerContext)
private fun checkJsPlainObjectSuperTypes(classSymbol: FirClassSymbol<out FirClass>, reporter: DiagnosticReporter) {
if (!classSymbol.isEffectivelyExternal(session) || !classSymbol.isInterface) return
classSymbol.resolvedSuperTypeRefs.forEach { superType ->
val superInterface = superType.coneType
.takeIf { !it.isAny }
?.fullyExpandedType(session)
?.toRegularClassSymbol(session) ?: return@forEach
if (!superInterface.hasAnnotation(JsPlainObjectsAnnotations.jsPlainObjectAnnotationClassId, session)) {
reporter.reportOn(
superType.source,
FirJsPlainObjectsErrors.JS_PLAIN_OBJECT_CAN_EXTEND_ONLY_OTHER_JS_PLAIN_OBJECTS,
classSymbol.classId.asFqNameString()
)
}
}
}
context(CheckerContext)
private fun checkJsPlainObjectAsSuperInterface(classSymbol: FirClassSymbol<out FirClass>, reporter: DiagnosticReporter) {
classSymbol.resolvedSuperTypeRefs.forEach {
val superInterface = it.coneType.fullyExpandedType(session)
.toRegularClassSymbol(session)
?.takeIf { it.classKind == ClassKind.INTERFACE } ?: return@forEach
if (superInterface.hasAnnotation(JsPlainObjectsAnnotations.jsPlainObjectAnnotationClassId, session)) {
reporter.reportOn(
it.source,
FirJsPlainObjectsErrors.IMPLEMENTING_OF_JS_PLAIN_OBJECT_IS_NOT_SUPPORTED,
classSymbol.classId.asFqNameString()
)
}
}
}
}
@@ -0,0 +1,30 @@
/*
* Copyright 2010-2023 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.kotlinx.jspo.compiler.fir.checkers
import org.jetbrains.kotlin.diagnostics.KtDiagnosticFactoryToRendererMap
import org.jetbrains.kotlin.diagnostics.rendering.BaseDiagnosticRendererFactory
import org.jetbrains.kotlin.diagnostics.rendering.CommonRenderers
object KtDefaultErrorMessagesJsPlainObjects : BaseDiagnosticRendererFactory() {
override val MAP = KtDiagnosticFactoryToRendererMap("JsPlainObjects").apply {
put(
FirJsPlainObjectsErrors.NON_EXTERNAL_DECLARATIONS_NOT_SUPPORTED,
"Non-external {0} can not be annotated with JsPlainObjects. Only external interfaces are supported.",
CommonRenderers.STRING
)
put(
FirJsPlainObjectsErrors.ONLY_INTERFACES_ARE_SUPPORTED,
"External {0} can not be annotated with JsPlainObjects. Only external interfaces are supported.",
CommonRenderers.STRING
)
put(
FirJsPlainObjectsErrors.IMPLEMENTING_OF_JS_PLAIN_OBJECT_IS_NOT_SUPPORTED,
"[{0}] is marked as JsPlainObjects, so, it can not be used as a super-type for non-JsPlainObjects declarations",
CommonRenderers.STRING
)
}
}
@@ -0,0 +1,64 @@
/*
* Copyright 2010-2023 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.kotlinx.jspo.compiler.fir.services
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.descriptors.Visibilities
import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.caches.FirCache
import org.jetbrains.kotlin.fir.caches.createCache
import org.jetbrains.kotlin.fir.caches.firCachesFactory
import org.jetbrains.kotlin.fir.caches.getValue
import org.jetbrains.kotlin.fir.declarations.hasAnnotation
import org.jetbrains.kotlin.fir.declarations.utils.visibility
import org.jetbrains.kotlin.fir.extensions.FirDeclarationPredicateRegistrar
import org.jetbrains.kotlin.fir.extensions.FirExtensionSessionComponent
import org.jetbrains.kotlin.fir.resolve.fullyExpandedType
import org.jetbrains.kotlin.fir.scopes.impl.declaredMemberScope
import org.jetbrains.kotlin.fir.scopes.processAllProperties
import org.jetbrains.kotlin.fir.symbols.impl.FirClassSymbol
import org.jetbrains.kotlin.fir.symbols.impl.FirPropertySymbol
import org.jetbrains.kotlin.fir.types.toRegularClassSymbol
import org.jetbrains.kotlin.utils.addIfNotNull
import org.jetbrains.kotlinx.jspo.compiler.fir.JsPlainObjectsPredicates
import org.jetbrains.kotlinx.jspo.compiler.resolve.JsPlainObjectsAnnotations
class JsPlainObjectsPropertiesProvider(session: FirSession) : FirExtensionSessionComponent(session) {
private val cache: FirCache<FirClassSymbol<*>, List<FirPropertySymbol>, Nothing?> =
session.firCachesFactory.createCache(this::createJsPlainObjectProperties)
override fun FirDeclarationPredicateRegistrar.registerPredicates() {
register(JsPlainObjectsPredicates.AnnotatedWithJsPlainObject.DECLARATION)
}
fun getJsPlainObjectsPropertiesForClass(classSymbol: FirClassSymbol<*>): List<FirPropertySymbol> {
return cache.getValue(classSymbol)
}
private fun createJsPlainObjectProperties(classSymbol: FirClassSymbol<*>): List<FirPropertySymbol> =
if (!classSymbol.hasAnnotation(JsPlainObjectsAnnotations.jsPlainObjectAnnotationClassId, session)) {
emptyList()
} else {
buildList {
classSymbol.resolvedSuperTypes.forEach {
val superInterface = it.fullyExpandedType(session)
.toRegularClassSymbol(session)
?.takeIf { it.classKind == ClassKind.INTERFACE } ?: return@forEach
val superInterfaceSimpleObjectProperties = createJsPlainObjectProperties(superInterface)
superInterfaceSimpleObjectProperties.forEach(::addIfNotNull)
}
classSymbol
.declaredMemberScope(session, null)
.processAllProperties {
addIfNotNull(it.takeIf { it.visibility == Visibilities.Public } as? FirPropertySymbol)
}
}
}
}
val FirSession.jsPlainObjectPropertiesProvider: JsPlainObjectsPropertiesProvider by FirSession.sessionComponentAccessor()
@@ -0,0 +1,25 @@
package foo
import kotlinx.js.JsPlainObject
@JsPlainObject
external interface User {
var name: String
val age: Int
}
fun box(): String {
val user = User(name = "Name", age = 10)
val copy = user.copy(age = 11)
if (copy === user) return "Fail: mutation instead of immutable copy"
val json = js("JSON.stringify(copy)")
if (copy.name != "Name") return "Fail: problem with copied `name` property"
if (copy.age != 11) return "Fail: problem with copied `age` property"
if (json != "{\"age\":11,\"name\":\"Name\"}") return "Fail: got the next json for the copy: $json"
return "OK"
}
@@ -0,0 +1,31 @@
package foo
import kotlinx.js.JsPlainObject
@JsPlainObject
external interface User {
var name: String
val age: Int
val email: String?
}
fun box(): String {
val user = User(name = "Name", age = 10)
if (user.name != "Name") return "Fail: problem with `name` property"
if (user.age != 10) return "Fail: problem with `age` property"
val json = js("JSON.stringify(user)")
if (json != "{\"email\":null,\"age\":10,\"name\":\"Name\"}") return "Fail: got the next json: $json"
val withEmail = User(name = "Name", age = 10, email = "test@test")
if (withEmail.name != "Name") return "Fail: problem with emailed `name` property"
if (withEmail.age != 10) return "Fail: problem with emailed `age` property"
if (withEmail.email != "test@test") return "Fail: problem with emailed `email` property"
val jsonWithEmail = js("JSON.stringify(withEmail)")
if (jsonWithEmail != "{\"email\":\"test@test\",\"age\":10,\"name\":\"Name\"}") return "Fail: got the next emailed json: $jsonWithEmail"
return "OK"
}
@@ -0,0 +1,21 @@
package foo
import kotlinx.js.JsPlainObject
@JsPlainObject
external interface User {
var name: String
val age: Int
}
fun box(): String {
val user = User(name = "Name", age = 10)
if (user.name != "Name") return "Fail: problem with `name` property"
if (user.age != 10) return "Fail: problem with `age` property"
val json = js("JSON.stringify(user)")
if (json != "{\"age\":10,\"name\":\"Name\"}") return "Fail: got the next json: $json"
return "OK"
}
@@ -0,0 +1,28 @@
package foo
import kotlinx.js.JsPlainObject
@JsPlainObject
external interface User {
var name: String
val age: Int
}
@JsPlainObject
external interface ExtendedUser : User {
val email: String
}
fun box(): String {
val user = ExtendedUser(name = "Name", age = 10, email = "test@test")
if (user.name != "Name") return "Fail: problem with `name` property"
if (user.age != 10) return "Fail: problem with `age` property"
if (user.email != "test@test") return "Fail: problem with `email` property"
val json = js("JSON.stringify(user)")
if (json != "{\"age\":10,\"name\":\"Name\",\"email\":\"test@test\"}") return "Fail: got the next json: $json"
return "OK"
}
@@ -0,0 +1,33 @@
package foo
import kotlinx.js.JsPlainObject
@JsPlainObject
external interface User {
var name: String
val age: Int
}
@JsPlainObject
external interface Role {
val role: String
}
@JsPlainObject
external interface ExtendedUser : User, Role {
val email: String
}
fun box(): String {
val user = ExtendedUser(name = "Name", age = 10, email = "test@test", role = "Admin")
if (user.name != "Name") return "Fail: problem with `name` property"
if (user.age != 10) return "Fail: problem with `age` property"
if (user.email != "test@test") return "Fail: problem with `email` property"
if (user.role != "Admin") return "Fail: problem with `role` property"
val json = js("JSON.stringify(user)")
if (json != "{\"age\":10,\"name\":\"Name\",\"role\":\"Admin\",\"email\":\"test@test\"}") return "Fail: got the next json: $json"
return "OK"
}
@@ -0,0 +1,27 @@
// FIR_IDENTICAL
// SKIP_TXT
// FILE: test.kt
import kotlinx.js.JsPlainObject
external interface A
external interface B
external interface C
@JsPlainObject
external interface D : <!JS_PLAIN_OBJECT_CAN_EXTEND_ONLY_OTHER_JS_PLAIN_OBJECTS!>A<!>, <!JS_PLAIN_OBJECT_CAN_EXTEND_ONLY_OTHER_JS_PLAIN_OBJECTS!>B<!>, <!JS_PLAIN_OBJECT_CAN_EXTEND_ONLY_OTHER_JS_PLAIN_OBJECTS!>C<!>
@JsPlainObject
external interface E
@JsPlainObject
external interface F
@JsPlainObject
external interface DEF: D, E, F
external interface G: A, C, <!IMPLEMENTING_OF_JS_PLAIN_OBJECT_IS_NOT_SUPPORTED!>E<!>
class Foo : A, <!IMPLEMENTING_OF_JS_PLAIN_OBJECT_IS_NOT_SUPPORTED!>D<!>, B
@@ -0,0 +1,15 @@
// FIR_IDENTICAL
// SKIP_TXT
// FILE: test.kt
import kotlinx.js.JsPlainObject
@JsPlainObject
external interface Foo {
val foo: String
val bar: Int?
val fn: () -> String
val fnOptional: (() -> String)?
<!METHODS_ARE_NOT_ALLOWED_INSIDE_JS_PLAIN_OBJECT!>fun test(): String<!>
}
@@ -0,0 +1,28 @@
// FIR_IDENTICAL
// SKIP_TXT
// FILE: test.kt
import kotlinx.js.JsPlainObject
<!NON_EXTERNAL_DECLARATIONS_NOT_SUPPORTED("class")!>@JsPlainObject
class Regular1<!>
@JsPlainObject
<!NON_EXTERNAL_DECLARATIONS_NOT_SUPPORTED("object")!>object Regular2<!>
<!NON_EXTERNAL_DECLARATIONS_NOT_SUPPORTED("enum class")!>@JsPlainObject
enum class Regular3<!>
<!ONLY_INTERFACES_ARE_SUPPORTED("class")!>@JsPlainObject
external class External1<!>
@JsPlainObject
external <!ONLY_INTERFACES_ARE_SUPPORTED("object")!>object External2<!>
@JsPlainObject
external interface External3
external class Nested {
@JsPlainObject
interface Inner
}
@@ -0,0 +1,57 @@
/*
* Copyright 2010-2024 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.kotlinx.jspo.runners;
import com.intellij.testFramework.TestDataPath;
import org.jetbrains.kotlin.test.util.KtTestUtil;
import org.jetbrains.kotlin.test.TargetBackend;
import org.jetbrains.kotlin.test.TestMetadata;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.util.regex.Pattern;
/** This class is generated by {@link org.jetbrains.kotlinx.jspo.TestGeneratorKt}. DO NOT MODIFY MANUALLY */
@SuppressWarnings("all")
@TestMetadata("plugins/js-plain-objects/compiler-plugin/testData/box")
@TestDataPath("$PROJECT_ROOT")
public class FirJsPlainObjectsIrJsBoxTestGenerated extends AbstractFirJsPlainObjectsIrJsBoxTest {
@Test
public void testAllFilesPresentInBox() throws Exception {
KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("plugins/js-plain-objects/compiler-plugin/testData/box"), Pattern.compile("^(.+)\\.kt$"), null, TargetBackend.JS_IR, true);
}
@Test
@TestMetadata("copy.kt")
public void testCopy() throws Exception {
runTest("plugins/js-plain-objects/compiler-plugin/testData/box/copy.kt");
}
@Test
@TestMetadata("optional.kt")
public void testOptional() throws Exception {
runTest("plugins/js-plain-objects/compiler-plugin/testData/box/optional.kt");
}
@Test
@TestMetadata("simple.kt")
public void testSimple() throws Exception {
runTest("plugins/js-plain-objects/compiler-plugin/testData/box/simple.kt");
}
@Test
@TestMetadata("with-inheritance.kt")
public void testWith_inheritance() throws Exception {
runTest("plugins/js-plain-objects/compiler-plugin/testData/box/with-inheritance.kt");
}
@Test
@TestMetadata("with-multiple-inheritance.kt")
public void testWith_multiple_inheritance() throws Exception {
runTest("plugins/js-plain-objects/compiler-plugin/testData/box/with-multiple-inheritance.kt");
}
}
@@ -0,0 +1,44 @@
/*
* Copyright 2010-2024 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.kotlinx.jspo.runners;
import com.intellij.testFramework.TestDataPath;
import org.jetbrains.kotlin.test.util.KtTestUtil;
import org.jetbrains.kotlin.test.TestMetadata;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.util.regex.Pattern;
/** This class is generated by {@link org.jetbrains.kotlinx.jspo.TestGeneratorKt}. DO NOT MODIFY MANUALLY */
@SuppressWarnings("all")
@TestMetadata("plugins/js-plain-objects/compiler-plugin/testData/diagnostics")
@TestDataPath("$PROJECT_ROOT")
public class FirJsPlainObjectsPluginDiagnosticTestGenerated extends AbstractFirJsPlainObjectsPluginDiagnosticTest {
@Test
public void testAllFilesPresentInDiagnostics() throws Exception {
KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("plugins/js-plain-objects/compiler-plugin/testData/diagnostics"), Pattern.compile("^(.+)\\.kt$"), null, true);
}
@Test
@TestMetadata("inheritance.kt")
public void testInheritance() throws Exception {
runTest("plugins/js-plain-objects/compiler-plugin/testData/diagnostics/inheritance.kt");
}
@Test
@TestMetadata("only-properties.kt")
public void testOnly_properties() throws Exception {
runTest("plugins/js-plain-objects/compiler-plugin/testData/diagnostics/only-properties.kt");
}
@Test
@TestMetadata("wrongAnnotationTarget.kt")
public void testWrongAnnotationTarget() throws Exception {
runTest("plugins/js-plain-objects/compiler-plugin/testData/diagnostics/wrongAnnotationTarget.kt");
}
}
@@ -0,0 +1,30 @@
/*
* Copyright 2010-2021 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.kotlinx.jspo
import org.jetbrains.kotlin.generators.generateTestGroupSuiteWithJUnit5
import org.jetbrains.kotlinx.jspo.runners.AbstractFirJsPlainObjectsIrJsBoxTest
import org.jetbrains.kotlinx.jspo.runners.AbstractFirJsPlainObjectsPluginDiagnosticTest
fun main(args: Array<String>) {
generateTestGroupSuiteWithJUnit5(args) {
testGroup(
"plugins/js-plain-objects/compiler-plugin/tests-gen",
"plugins/js-plain-objects/compiler-plugin/testData"
) {
// ------------------------------- diagnostics -------------------------------
testClass<AbstractFirJsPlainObjectsPluginDiagnosticTest>() {
model("diagnostics")
}
// ------------------------------- box -------------------------------
testClass<AbstractFirJsPlainObjectsIrJsBoxTest> {
model("box")
}
}
}
}
@@ -0,0 +1,36 @@
/*
* Copyright 2010-2022 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.kotlinx.jspo.runners
import org.jetbrains.kotlin.compiler.plugin.CompilerPluginRegistrar
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.test.builders.TestConfigurationBuilder
import org.jetbrains.kotlin.test.model.TestModule
import org.jetbrains.kotlin.test.services.EnvironmentConfigurator
import org.jetbrains.kotlin.test.services.RuntimeClasspathProvider
import org.jetbrains.kotlin.test.services.TestServices
import org.jetbrains.kotlinx.jspo.compiler.cli.JsPlainObjectsComponentRegistrar
import java.io.File
class JsPlainObjectsEnvironmentConfigurator(testServices: TestServices) : EnvironmentConfigurator(testServices) {
override fun CompilerPluginRegistrar.ExtensionStorage.registerCompilerExtensions(
module: TestModule,
configuration: CompilerConfiguration
) {
JsPlainObjectsComponentRegistrar.registerExtensions(this)
}
}
class JsPlainObjectsRuntimeClasspathProvider(testServices: TestServices) : RuntimeClasspathProvider(testServices) {
override fun runtimeClassPaths(module: TestModule): List<File> {
return listOf(File(System.getProperty("jso.runtime.path")))
}
}
fun TestConfigurationBuilder.configureForKotlinxJsPlainObjects() {
useConfigurators(::JsPlainObjectsEnvironmentConfigurator)
useCustomRuntimeClasspathProviders(::JsPlainObjectsRuntimeClasspathProvider)
}
@@ -0,0 +1,19 @@
/*
* Copyright 2010-2022 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.kotlinx.jspo.runners
import org.jetbrains.kotlin.js.test.fir.AbstractFirJsTest
import org.jetbrains.kotlin.test.builders.TestConfigurationBuilder
open class AbstractFirJsPlainObjectsIrJsBoxTest : AbstractFirJsTest(
pathToTestDir = "plugins/kotlinx-serialization/testData/boxIr/",
testGroupOutputDirPrefix = "codegen/serializationBoxIr/"
) {
override fun configure(builder: TestConfigurationBuilder) {
super.configure(builder)
builder.configureForKotlinxJsPlainObjects()
}
}
@@ -0,0 +1,35 @@
/*
* Copyright 2010-2022 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.kotlinx.jspo.runners
import org.jetbrains.kotlin.platform.js.JsPlatforms
import org.jetbrains.kotlin.test.TargetBackend
import org.jetbrains.kotlin.test.builders.TestConfigurationBuilder
import org.jetbrains.kotlin.test.directives.DiagnosticsDirectives.DIAGNOSTICS
import org.jetbrains.kotlin.test.model.DependencyKind
import org.jetbrains.kotlin.test.runners.AbstractFirPsiDiagnosticTest
abstract class AbstractFirJsPlainObjectsPluginDiagnosticTest : AbstractFirPsiDiagnosticTest() {
override fun configure(builder: TestConfigurationBuilder) {
super.configure(builder)
with(builder) {
globalDefaults {
targetPlatform = JsPlatforms.defaultJsPlatform
targetBackend = TargetBackend.JS_IR
dependencyKind = DependencyKind.Source
}
configureForKotlinxJsPlainObjects()
disableOptInErrors()
}
}
}
private fun TestConfigurationBuilder.disableOptInErrors() {
defaultDirectives {
DIAGNOSTICS with listOf("-OPT_IN_USAGE", "-OPT_IN_USAGE_ERROR")
}
}