[fleet] Move rhizomedb compiler plugin to community/fleet/compiler-plugins/rhizomedb/ (IJI-2964)

GitOrigin-RevId: 54109895446c5902cbef1251a595708d15af8004
This commit is contained in:
Ilia Kirianovskii
2025-08-10 22:56:56 +00:00
committed by intellij-monorepo-bot
parent e5276e975c
commit 473bd70a4b
15 changed files with 917 additions and 0 deletions
@@ -0,0 +1,4 @@
out/
build/
.idea/
.gradle/
@@ -0,0 +1,88 @@
plugins {
kotlin("jvm")
`maven-publish`
`java-gradle-plugin`
}
val pluginVersion = run {
val pluginVersionOverride = System.getProperty("fleet.plugin.version.override")
if (pluginVersionOverride != null) {
return@run pluginVersionOverride
}
val versionRegex = Regex("const val VERSION = \"(.+)\"")
project.file("src/main/kotlin/com/jetbrains/rhizomedb/plugin/gradle/RhizomeGradlePlugin.kt").readLines().firstNotNullOfOrNull { line ->
versionRegex.find(line)?.let { match ->
match.groupValues[1]
}
} ?: error("Cannot find `const val VERSION = \"...\"` in RhizomeGradlePlugin.kt")
}
// the compiler plugin will be used together with this Kotlin compiler
val KOTLIN_VERSION = "2.2.0"
// the compiler plugin will be built with these Kotlin LV/APIV
val KOTLIN_LANGUAGE_VERSION = "2.2"
val KOTLIN_API_VERSION = "2.2"
group = "jetbrains.fleet"
version = pluginVersion
repositories {
mavenCentral()
if ("SNAPSHOT" in KOTLIN_VERSION || "dev" in KOTLIN_VERSION) {
mavenLocal()
}
}
dependencies {
compileOnly("org.jetbrains.kotlin:kotlin-compiler-embeddable:$KOTLIN_VERSION")
implementation("org.jetbrains.kotlin:kotlin-gradle-plugin-api:$KOTLIN_VERSION")
}
java {
withSourcesJar()
targetCompatibility = JavaVersion.VERSION_17
}
kotlin {
compilerOptions {
jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
apiVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.fromVersion(KOTLIN_LANGUAGE_VERSION))
languageVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.fromVersion(KOTLIN_API_VERSION))
// FREE COMPILER ARGS PLACEHOLDER PLEASE DO NOT CHANGE IT BEFORE DISCUSS IN #ij-monorepo-kotlin
}
}
gradlePlugin {
plugins {
create("rhizomedbGradle") {
id = "rhizomedb"
implementationClass = "com.jetbrains.rhizomedb.plugin.gradle.RhizomeGradlePlugin"
displayName = "Rhizomedb compiler plugin"
description = "Use this plugin for modules, which use rhizomedb"
}
}
}
publishing {
repositories {
maven {
url = uri("https://packages.jetbrains.team/maven/p/ij/intellij-dependencies")
credentials {
username = prop("publishingUsername")
password = prop("publishingPassword")
}
}
}
publications {
create<MavenPublication>("rhizomedbPlugin") {
groupId = "jetbrains.fleet"
artifactId = "rhizomedb-compiler-plugin"
version = pluginVersion
from(components["java"])
}
}
}
fun prop(name: String): String? =
extra.properties[name] as? String
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
+251
View File
@@ -0,0 +1,251 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# 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
#
# https://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.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
+94
View File
@@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
@@ -0,0 +1,26 @@
rootProject.name = "rhizomedb-compiler-plugin"
pluginManagement {
// the compiler plugin will be built by this Kotlin compiler
val KOTLIN_VERSION = "2.2.0"
plugins {
kotlin("jvm") version KOTLIN_VERSION
}
resolutionStrategy {
eachPlugin {
repositories {
gradlePluginPortal()
if ("SNAPSHOT" in KOTLIN_VERSION || "dev" in KOTLIN_VERSION) {
mavenLocal()
}
}
}
}
repositories {
gradlePluginPortal()
if ("SNAPSHOT" in KOTLIN_VERSION || "dev" in KOTLIN_VERSION) {
mavenLocal()
}
}
}
@@ -0,0 +1,75 @@
package com.jetbrains.rhizomedb.plugin
import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext
import org.jetbrains.kotlin.ir.IrElement
import org.jetbrains.kotlin.ir.declarations.IrClass
import org.jetbrains.kotlin.ir.declarations.IrDeclaration
import org.jetbrains.kotlin.ir.declarations.IrModuleFragment
import org.jetbrains.kotlin.ir.symbols.IrClassSymbol
import org.jetbrains.kotlin.ir.symbols.IrSimpleFunctionSymbol
import org.jetbrains.kotlin.ir.util.kotlinFqName
import org.jetbrains.kotlin.ir.visitors.IrVisitorVoid
import org.jetbrains.kotlin.name.CallableId
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.platform.jvm.JvmPlatform
abstract class DeclarationBasedExtension(
protected val pluginContext: IrPluginContext,
protected val moduleFragment: IrModuleFragment
) {
private val cacheFun = mutableMapOf<CallableId, IrSimpleFunctionSymbol>()
private val cacheClass = mutableMapOf<ClassId, IrClassSymbol>()
protected fun funByName(name: String, prefix: FqName): IrSimpleFunctionSymbol {
val callableId = CallableId(prefix, Name.identifier(name))
return cacheFun.computeIfAbsent(callableId) {
pluginContext.referenceFunctions(it).singleOrNull() ?: throw SymbolNotFoundException(it.toString(), moduleFragment)
}
}
protected fun classByName(name: String, prefix: FqName): IrClassSymbol {
val classId = ClassId.topLevel(prefix.child(Name.identifier(name)))
return cacheClass.computeIfAbsent(classId) {
pluginContext.referenceClass(it) ?: throw SymbolNotFoundException(it.asString(), moduleFragment)
}
}
/**
* Return a list of all IrDeclaration in the module.
*/
protected val declarations by lazy {
val declarations = mutableListOf<IrDeclaration>()
moduleFragment.accept(object : IrVisitorVoid() {
override fun visitElement(element: IrElement) {
if (element is IrDeclaration) {
declarations += element
}
element.acceptChildren(this, null)
}
}, null)
declarations
}
/**
* This returns true if the current target includes any JVM specific code.
*/
protected fun includesJvmTarget() = pluginContext.platform?.any { it is JvmPlatform } == true
/**
* This returns true if the current target includes any non-JVM specific code.
*/
protected fun includesNonJvmTarget() = pluginContext.platform?.any { it !is JvmPlatform } == true
protected fun IrClass.jvmLikeName(): String {
return when (val thisParent = parent) {
is IrClass -> "${thisParent.jvmLikeName()}\$${name}"
else -> kotlinFqName.toString()
}
}
}
class SymbolNotFoundException(fqn: String, module: IrModuleFragment) :
RuntimeException("$fqn cannot be resolved from module `${module.name.asString()}`.")
@@ -0,0 +1,229 @@
package com.jetbrains.rhizomedb.plugin
import org.jetbrains.kotlin.backend.common.extensions.IrGenerationExtension
import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext
import org.jetbrains.kotlin.backend.common.lower.DeclarationIrBuilder
import org.jetbrains.kotlin.backend.jvm.codegen.AnnotationCodegen.Companion.annotationClass
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.descriptors.DescriptorVisibilities
import org.jetbrains.kotlin.ir.backend.js.utils.nameWithoutExtension
import org.jetbrains.kotlin.ir.builders.*
import org.jetbrains.kotlin.ir.builders.declarations.*
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.expressions.IrConstructorCall
import org.jetbrains.kotlin.ir.types.typeWith
import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.name.CallableId
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import kotlin.io.path.Path
import kotlin.io.path.pathString
internal val RHIZOMEDB_FQN = FqName.fromSegments(listOf("com", "jetbrains", "rhizomedb"))
internal val RHIZOMEDB_FQN_IMPL = RHIZOMEDB_FQN.child(Name.identifier("impl"))
class EntityTypeRegistrationGenerator(
val jvmOutputDir: String?,
val readProvider: ((String) -> List<String>)? = null,
val writeProvider: ((String, Collection<String>) -> Unit)? = null
) : IrGenerationExtension {
override fun generate(moduleFragment: IrModuleFragment, pluginContext: IrPluginContext) {
EntityTypeRegistrationGeneratorImpl(
jvmOutputDir,
pluginContext,
moduleFragment,
readProvider,
writeProvider
).generate()
}
}
private class EntityTypeRegistrationGeneratorImpl(
val jvmOutputDir: String?,
pluginContext: IrPluginContext,
moduleFragment: IrModuleFragment,
val readProvider: ((String) -> List<String>)? = null,
val writeProvider: ((String, Collection<String>) -> Unit)? = null
) : DeclarationBasedExtension(pluginContext, moduleFragment) {
val entityType = classByName("EntityType", RHIZOMEDB_FQN).owner
val entityTypeProvider = classByName("EntityTypeProvider", RHIZOMEDB_FQN_IMPL).owner
val listOfFn =
pluginContext.referenceFunctions(CallableId(FqName("kotlin.collections"), Name.identifier("listOf"))).first {
it.owner.parameters.singleOrNull()?.varargElementType != null
}
/**
* Generate [META_INF_FILE] and [META_INF_CACHE_FILE]
*
* First one contains FQN for the entity type provider classes and can be used to load them on runtime.
* Each file with an entity type has such provider.
* The second one stores meta-information required for consistency during IC.
*
* [META_INF_CACHE_FILE] stores tuples `<fqn_provider>;<kind_of_ref>;<ref>`.
* <ref> using to detect file deletion to remove FQN from [META_INF_FILE].
* It can be a class or a property.
*/
// TODO: support properties like
// val MyEntityType = object : EntityType<...>(...) { }
fun generate() {
val files = moduleFragment.files.toSet()
// Process declarations and generate files
val res = declarations
.filterIsInstance<IrClass>()
.filter { it.isObject && it.isSubclassOf(entityType) }
.groupBy { it.file }
.toSortedMap { a, b -> a.fileEntry.name.compareTo(b.fileEntry.name) }
.map { (file, decls) ->
val providerClass = addEntityProviderClass(file, decls)
// Non-jvm handling: @EagerInitialization properties that populate a list of providers
if (includesNonJvmTarget()) {
addEagerInitializedProperty(moduleFragment.name.asStringStripSpecialMarkers(), file, providerClass)
}
// Return generated class + name for META-INF cache
providerClass to decls.first().classIdOrFail.asString()
}
// Jvm handling: META-INF files loaded with reflection
if (includesJvmTarget() && jvmOutputDir != null) {
val newEntries = res.map { (providerClass, firstEntityClassName) ->
val fqn = providerClass.jvmLikeName()
"$fqn;C;${firstEntityClassName}"
}
// Step 1: cache file
val cacheFilePath = Path("$jvmOutputDir/META-INF/$META_INF_CACHE_FILE").normalize().pathString
val cacheProcessor = if (readProvider != null && writeProvider != null) {
MetaInfListProcessor(cacheFilePath, readProvider, writeProvider)
} else {
MetaInfListProcessor(cacheFilePath)
}
val result = cacheProcessor.readAndUpdate(newEntries) { row ->
val (_, kind, fqn) = row.split(';')
when (kind) {
"P" -> false // TODO: support properties
"C" -> pluginContext.referenceClass(ClassId.fromString(fqn)).let { refClass ->
// 1. Failed to find ref - it is removed, file changed. We will regenerate the provider for file
// 2. The ref file is null - file not changed
// 3. The ref file is not in IC files set - file not changed
refClass != null && refClass.owner.fileOrNull !in files
}
else -> error("Unknown ref kind $kind")
}
}
// Step 2: actual list of providers dumped from the previous result
val metaInfFilePath = Path("$jvmOutputDir/META-INF/$META_INF_FILE").normalize().pathString
val metaInfProcessor = if (readProvider != null && writeProvider != null) {
MetaInfListProcessor(metaInfFilePath, readProvider, writeProvider)
} else {
MetaInfListProcessor(metaInfFilePath)
}
metaInfProcessor.writeOrDelete(result.map { it.substringBefore(';') })
}
}
private fun addEntityProviderClass(file: IrFile, decls: List<IrClass>): IrClass {
val apiStatusAnnotations = decls.map { it.extractApiStatusAnnotations() }.flatten().distinctBy { it.annotationClass.kotlinFqName.asString() }
return file.addClass {
name = Name.identifier("${file.nameWithoutExtension}EntityTypeProvider")
kind = ClassKind.OBJECT
}.apply {
// TODO: it is not entirely correct, but for IJ it should work, and shouldn't affect Fleet at all
// if any of the declarations contain ApiStatus annotation, EntityTypeProvider class also will have this annotation
annotations = annotations + apiStatusAnnotations
superTypes = listOf(entityTypeProvider.defaultType)
addSimpleDelegatingConstructor(
pluginContext.irBuiltIns.anyClass.owner.primaryConstructor!!,
pluginContext.irBuiltIns, true
)
addProperty {
name = Name.identifier("entityTypes")
}.apply {
val listOfEntityTypes = pluginContext.irBuiltIns.listClass.typeWith(entityType.defaultType)
addGetter { returnType = listOfEntityTypes }.apply {
parameters = listOf(createDispatchReceiverParameterWithClassParent()) + parameters
setBody {
+irReturn(
irCall(listOfFn).apply {
arguments[0] = irVararg(entityType.defaultType, decls.map { irGetObject(it.symbol) })
}
)
}
}
}
}
}
fun IrFunction.setBody(builder: IrBlockBodyBuilder.() -> Unit) {
body = DeclarationIrBuilder(pluginContext, symbol).irBlockBody { builder() }
}
/**
* Add field marked with @EagerInitialization, which will initialize its value on startup for non-jvm targets,
* effectively populating a list of entity types to register.
*
* Should not be used on JVM-only targets (EagerInitialization annotation is absent there).
*/
private fun addEagerInitializedProperty(moduleName: String, file: IrFile, targetClass: IrClass) {
val registerProviderFunction = funByName("registerEntityTypeProvider", RHIZOMEDB_FQN_IMPL)
val eagerAnnotation = classByName("EagerInitialization", FqName("kotlin"))
with(pluginContext.irFactory) {
// private val MyEntityTypeRegisterToken
buildProperty {
name = Name.identifier("${file.nameWithoutExtension}EntityTypeRegisterToken")
isVar = false
visibility = DescriptorVisibilities.PRIVATE
}.apply {
// @EagerInitialization
annotations += with(DeclarationIrBuilder(pluginContext, symbol)) {
irCall(eagerAnnotation.owner.primaryConstructor!!.symbol)
}
// Needs to be called before addBackingField
file.addChild(this)
// = markForRegistration(MyEntityTypeProvider)
addBackingField {
name = Name.identifier("_${file.nameWithoutExtension}EntityTypeRegisterToken")
type = pluginContext.irBuiltIns.booleanType
isFinal = true
isStatic = true
visibility = DescriptorVisibilities.PRIVATE
origin = IrDeclarationOrigin.PROPERTY_BACKING_FIELD
}.let {
it.initializer = createExpressionBody(with(DeclarationIrBuilder(pluginContext, symbol)) {
irCall(registerProviderFunction).apply {
arguments[0] = irString(moduleName)
arguments[1] = irGetObject(targetClass.symbol)
}
})
}
}
}
}
private fun IrDeclarationParent.addClass(builder: IrClassBuilder.() -> Unit) =
pluginContext.irFactory.buildClass(builder).apply {
parent = this@addClass
(this@addClass as IrDeclarationContainer).declarations += this
createThisReceiverParameter()
}
}
internal fun IrAnnotationContainer.extractApiStatusAnnotations(): List<IrConstructorCall> {
return annotations.filter { it.annotationClass.kotlinFqName.startsWith(FqName.fromSegments(listOf("org", "jetbrains", "annotations", "ApiStatus"))) }
}
private const val META_INF_FILE = "com.jetbrains.rhizomedb.impl.EntityTypeProvider.txt"
private const val META_INF_CACHE_FILE = "com.jetbrains.rhizomedb.impl.EntityTypeProvider.cache"
@@ -0,0 +1,72 @@
package com.jetbrains.rhizomedb.plugin
import java.io.File
import java.io.IOException
class MetaInfListProcessor(
private val pathName: String,
private val readProvider: ((String) -> List<String>)? = null,
private val writeProvider: ((String, Collection<String>) -> Unit)? = null
) {
private val file = File(pathName)
fun read(filterOutdated: (String) -> Boolean = { true }): List<String> {
val lines = try {
if (readProvider != null) {
readProvider.invoke(pathName)
} else {
if (file.exists()) file.readLines() else emptyList()
}
}
catch (e: IOException) {
throw IOException("Cannot read file $file to update registrars list", e)
}
return lines.filter { row -> filterOutdated(row) }
}
/**
* Process previous cache and merge with newly generated content.
*
* @param newContent new content to merge, will not be filtered by [checkPreviousContent]
* @param checkPreviousContent filter to apply on content that is already in cache file, if it returns true, the row will be kept in the new version
* @return merged content, without duplicates that was written to file
*/
fun readAndUpdate(newContent: List<String>, checkPreviousContent: (String) -> Boolean = { true }): Set<String> {
return (newContent + read(checkPreviousContent)).toSet()
.also {
writeOrDelete(it)
}
}
fun writeOrDelete(dump: Collection<String>) {
if (writeProvider != null) {
writeProvider.invoke(pathName, dump)
return
}
if (dump.isNotEmpty()) {
try {
file.parentFile.mkdirs()
file.createNewFile()
file.printWriter().use { out ->
dump.forEach { entry ->
out.print(entry)
out.print("\n")
}
}
}
catch (e: IOException) {
throw IOException("Cannot write into $file file", e)
}
}
else {
try {
file.delete()
}
catch (e: IOException) {
throw IOException("Cannot delete $file file with", e)
}
}
}
}
@@ -0,0 +1,18 @@
package com.jetbrains.rhizomedb.plugin
import org.jetbrains.kotlin.compiler.plugin.AbstractCliOption
import org.jetbrains.kotlin.compiler.plugin.CommandLineProcessor
import org.jetbrains.kotlin.compiler.plugin.ExperimentalCompilerApi
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.config.JVMConfigurationKeys
@OptIn(ExperimentalCompilerApi::class)
class RhizomedbCommandLineProcessor : CommandLineProcessor {
override val pluginId: String = "rhizomedb"
override val pluginOptions: Collection<AbstractCliOption> = emptyList()
}
// todo - support list of modules??
fun getJvmOutputDir(configuration: CompilerConfiguration) =
configuration[JVMConfigurationKeys.MODULES]?.singleOrNull()?.getOutputDirectory()
?: configuration.get(JVMConfigurationKeys.OUTPUT_DIRECTORY)?.absolutePath
@@ -0,0 +1,24 @@
package com.jetbrains.rhizomedb.plugin
import org.jetbrains.kotlin.backend.common.extensions.IrGenerationExtension
import org.jetbrains.kotlin.compiler.plugin.CompilerPluginRegistrar
import org.jetbrains.kotlin.compiler.plugin.ExperimentalCompilerApi
import org.jetbrains.kotlin.config.CompilerConfiguration
@OptIn(ExperimentalCompilerApi::class)
class RhizomedbComponentRegistrar(
private val readProvider: ((String) -> List<String>)? = null,
private val writeProvider: ((String, Collection<String>) -> Unit)? = null
) : CompilerPluginRegistrar() {
override val supportsK2: Boolean = true
override fun ExtensionStorage.registerExtensions(configuration: CompilerConfiguration) {
val output = getJvmOutputDir(configuration)
IrGenerationExtension.registerExtension(
EntityTypeRegistrationGenerator(
jvmOutputDir = output,
readProvider = readProvider,
writeProvider = writeProvider
)
)
}
}
@@ -0,0 +1,27 @@
package com.jetbrains.rhizomedb.plugin.gradle
import org.gradle.api.provider.Provider
import org.jetbrains.kotlin.gradle.plugin.KotlinCompilation
import org.jetbrains.kotlin.gradle.plugin.KotlinCompilerPluginSupportPlugin
import org.jetbrains.kotlin.gradle.plugin.SubpluginArtifact
import org.jetbrains.kotlin.gradle.plugin.SubpluginOption
private const val VERSION = "2.2.0-0.2"
class RhizomeGradlePlugin : KotlinCompilerPluginSupportPlugin {
override fun isApplicable(kotlinCompilation: KotlinCompilation<*>): Boolean = true
override fun getCompilerPluginId(): String = "rhizomedb"
override fun getPluginArtifact(): SubpluginArtifact = SubpluginArtifact(
groupId = "jetbrains.fleet",
artifactId = "rhizomedb-compiler-plugin", //it's name of gradle module
version = VERSION
)
override fun applyToCompilation(
kotlinCompilation: KotlinCompilation<*>
): Provider<List<SubpluginOption>> {
return kotlinCompilation.target.project.provider { emptyList() }
}
}
@@ -0,0 +1 @@
com.jetbrains.rhizomedb.plugin.RhizomedbCommandLineProcessor
@@ -0,0 +1 @@
com.jetbrains.rhizomedb.plugin.RhizomedbComponentRegistrar