diff --git a/fleet/compiler-plugins/rhizomedb/.gitignore b/fleet/compiler-plugins/rhizomedb/.gitignore new file mode 100644 index 000000000000..01d8fb504537 --- /dev/null +++ b/fleet/compiler-plugins/rhizomedb/.gitignore @@ -0,0 +1,4 @@ +out/ +build/ +.idea/ +.gradle/ \ No newline at end of file diff --git a/fleet/compiler-plugins/rhizomedb/build.gradle.kts b/fleet/compiler-plugins/rhizomedb/build.gradle.kts new file mode 100644 index 000000000000..4825dff36c84 --- /dev/null +++ b/fleet/compiler-plugins/rhizomedb/build.gradle.kts @@ -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("rhizomedbPlugin") { + groupId = "jetbrains.fleet" + artifactId = "rhizomedb-compiler-plugin" + version = pluginVersion + from(components["java"]) + } + } +} + +fun prop(name: String): String? = + extra.properties[name] as? String diff --git a/fleet/compiler-plugins/rhizomedb/gradle/wrapper/gradle-wrapper.jar b/fleet/compiler-plugins/rhizomedb/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000000..9bbc975c742b Binary files /dev/null and b/fleet/compiler-plugins/rhizomedb/gradle/wrapper/gradle-wrapper.jar differ diff --git a/fleet/compiler-plugins/rhizomedb/gradle/wrapper/gradle-wrapper.properties b/fleet/compiler-plugins/rhizomedb/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000000..37f853b1c84d --- /dev/null +++ b/fleet/compiler-plugins/rhizomedb/gradle/wrapper/gradle-wrapper.properties @@ -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 diff --git a/fleet/compiler-plugins/rhizomedb/gradlew b/fleet/compiler-plugins/rhizomedb/gradlew new file mode 100755 index 000000000000..faf93008b77e --- /dev/null +++ b/fleet/compiler-plugins/rhizomedb/gradlew @@ -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" "$@" diff --git a/fleet/compiler-plugins/rhizomedb/gradlew.bat b/fleet/compiler-plugins/rhizomedb/gradlew.bat new file mode 100644 index 000000000000..9d21a21834d5 --- /dev/null +++ b/fleet/compiler-plugins/rhizomedb/gradlew.bat @@ -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 diff --git a/fleet/compiler-plugins/rhizomedb/settings.gradle.kts b/fleet/compiler-plugins/rhizomedb/settings.gradle.kts new file mode 100644 index 000000000000..19ededc9571b --- /dev/null +++ b/fleet/compiler-plugins/rhizomedb/settings.gradle.kts @@ -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() + } + } +} diff --git a/fleet/compiler-plugins/rhizomedb/src/main/kotlin/com/jetbrains/rhizomedb/plugin/DeclarationBasedExtension.kt b/fleet/compiler-plugins/rhizomedb/src/main/kotlin/com/jetbrains/rhizomedb/plugin/DeclarationBasedExtension.kt new file mode 100644 index 000000000000..a18b649a8286 --- /dev/null +++ b/fleet/compiler-plugins/rhizomedb/src/main/kotlin/com/jetbrains/rhizomedb/plugin/DeclarationBasedExtension.kt @@ -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() + private val cacheClass = mutableMapOf() + + 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() + 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()}`.") diff --git a/fleet/compiler-plugins/rhizomedb/src/main/kotlin/com/jetbrains/rhizomedb/plugin/EntityTypeRegistrationGenerator.kt b/fleet/compiler-plugins/rhizomedb/src/main/kotlin/com/jetbrains/rhizomedb/plugin/EntityTypeRegistrationGenerator.kt new file mode 100644 index 000000000000..5f3dd884ead4 --- /dev/null +++ b/fleet/compiler-plugins/rhizomedb/src/main/kotlin/com/jetbrains/rhizomedb/plugin/EntityTypeRegistrationGenerator.kt @@ -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)? = null, + val writeProvider: ((String, Collection) -> 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)? = null, + val writeProvider: ((String, Collection) -> 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 `;;`. + * 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() + .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 { + 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 { + 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" diff --git a/fleet/compiler-plugins/rhizomedb/src/main/kotlin/com/jetbrains/rhizomedb/plugin/MetaInfListProcessor.kt b/fleet/compiler-plugins/rhizomedb/src/main/kotlin/com/jetbrains/rhizomedb/plugin/MetaInfListProcessor.kt new file mode 100644 index 000000000000..b99ed6c4f20b --- /dev/null +++ b/fleet/compiler-plugins/rhizomedb/src/main/kotlin/com/jetbrains/rhizomedb/plugin/MetaInfListProcessor.kt @@ -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)? = null, + private val writeProvider: ((String, Collection) -> Unit)? = null +) { + private val file = File(pathName) + + fun read(filterOutdated: (String) -> Boolean = { true }): List { + 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, checkPreviousContent: (String) -> Boolean = { true }): Set { + return (newContent + read(checkPreviousContent)).toSet() + .also { + writeOrDelete(it) + } + } + + fun writeOrDelete(dump: Collection) { + 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) + } + } + } +} diff --git a/fleet/compiler-plugins/rhizomedb/src/main/kotlin/com/jetbrains/rhizomedb/plugin/RhizomedbCommandLineProcessor.kt b/fleet/compiler-plugins/rhizomedb/src/main/kotlin/com/jetbrains/rhizomedb/plugin/RhizomedbCommandLineProcessor.kt new file mode 100644 index 000000000000..8edd4765730d --- /dev/null +++ b/fleet/compiler-plugins/rhizomedb/src/main/kotlin/com/jetbrains/rhizomedb/plugin/RhizomedbCommandLineProcessor.kt @@ -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 = emptyList() +} + +// todo - support list of modules?? +fun getJvmOutputDir(configuration: CompilerConfiguration) = + configuration[JVMConfigurationKeys.MODULES]?.singleOrNull()?.getOutputDirectory() + ?: configuration.get(JVMConfigurationKeys.OUTPUT_DIRECTORY)?.absolutePath diff --git a/fleet/compiler-plugins/rhizomedb/src/main/kotlin/com/jetbrains/rhizomedb/plugin/RhizomedbComponentRegistrar.kt b/fleet/compiler-plugins/rhizomedb/src/main/kotlin/com/jetbrains/rhizomedb/plugin/RhizomedbComponentRegistrar.kt new file mode 100644 index 000000000000..25f76460673d --- /dev/null +++ b/fleet/compiler-plugins/rhizomedb/src/main/kotlin/com/jetbrains/rhizomedb/plugin/RhizomedbComponentRegistrar.kt @@ -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)? = null, + private val writeProvider: ((String, Collection) -> 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 + ) + ) + } +} diff --git a/fleet/compiler-plugins/rhizomedb/src/main/kotlin/com/jetbrains/rhizomedb/plugin/gradle/RhizomeGradlePlugin.kt b/fleet/compiler-plugins/rhizomedb/src/main/kotlin/com/jetbrains/rhizomedb/plugin/gradle/RhizomeGradlePlugin.kt new file mode 100644 index 000000000000..421f82b6a8e2 --- /dev/null +++ b/fleet/compiler-plugins/rhizomedb/src/main/kotlin/com/jetbrains/rhizomedb/plugin/gradle/RhizomeGradlePlugin.kt @@ -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> { + return kotlinCompilation.target.project.provider { emptyList() } + } +} diff --git a/fleet/compiler-plugins/rhizomedb/src/main/resources/META-INF/services/org.jetbrains.kotlin.compiler.plugin.CommandLineProcessor b/fleet/compiler-plugins/rhizomedb/src/main/resources/META-INF/services/org.jetbrains.kotlin.compiler.plugin.CommandLineProcessor new file mode 100644 index 000000000000..c76d59e0791a --- /dev/null +++ b/fleet/compiler-plugins/rhizomedb/src/main/resources/META-INF/services/org.jetbrains.kotlin.compiler.plugin.CommandLineProcessor @@ -0,0 +1 @@ +com.jetbrains.rhizomedb.plugin.RhizomedbCommandLineProcessor \ No newline at end of file diff --git a/fleet/compiler-plugins/rhizomedb/src/main/resources/META-INF/services/org.jetbrains.kotlin.compiler.plugin.CompilerPluginRegistrar b/fleet/compiler-plugins/rhizomedb/src/main/resources/META-INF/services/org.jetbrains.kotlin.compiler.plugin.CompilerPluginRegistrar new file mode 100644 index 000000000000..3ed203961875 --- /dev/null +++ b/fleet/compiler-plugins/rhizomedb/src/main/resources/META-INF/services/org.jetbrains.kotlin.compiler.plugin.CompilerPluginRegistrar @@ -0,0 +1 @@ +com.jetbrains.rhizomedb.plugin.RhizomedbComponentRegistrar \ No newline at end of file