diff options
22 files changed, 1051 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5b33b62 --- /dev/null +++ b/.gitignore @@ -0,0 +1,42 @@ +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Kotlin ### +.kotlin + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store
\ No newline at end of file diff --git a/annotations/build.gradle.kts b/annotations/build.gradle.kts new file mode 100644 index 0000000..d4febab --- /dev/null +++ b/annotations/build.gradle.kts @@ -0,0 +1,8 @@ +plugins { + kotlin("jvm") + `maven-publish` +} + +dependencies { +} + diff --git a/annotations/src/main/java/moe/nea/mcautotranslations/annotations/GatheredTranslation.java b/annotations/src/main/java/moe/nea/mcautotranslations/annotations/GatheredTranslation.java new file mode 100644 index 0000000..18054fd --- /dev/null +++ b/annotations/src/main/java/moe/nea/mcautotranslations/annotations/GatheredTranslation.java @@ -0,0 +1,16 @@ +package moe.nea.mcautotranslations.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Repeatable; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.CLASS) +@Target(ElementType.TYPE) +@Repeatable(GatheredTranslations.class) +public @interface GatheredTranslation { + String key(); + + String value(); +} diff --git a/annotations/src/main/java/moe/nea/mcautotranslations/annotations/GatheredTranslations.java b/annotations/src/main/java/moe/nea/mcautotranslations/annotations/GatheredTranslations.java new file mode 100644 index 0000000..e2456cc --- /dev/null +++ b/annotations/src/main/java/moe/nea/mcautotranslations/annotations/GatheredTranslations.java @@ -0,0 +1,13 @@ +package moe.nea.mcautotranslations.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.CLASS) +@Target(ElementType.TYPE) +public @interface GatheredTranslations { + GatheredTranslation[] value(); +} + diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..04628d9 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,39 @@ +import com.github.gmazzo.buildconfig.BuildConfigExtension +import org.jetbrains.kotlin.gradle.dsl.JvmTarget +import org.jetbrains.kotlin.gradle.tasks.KotlinCompile + +plugins { + kotlin("jvm") version "2.0.20" apply false + id("com.google.devtools.ksp") version "2.0.20-1.0.25" apply false + id("com.gradle.plugin-publish") version "1.1.0" apply false + id("com.github.gmazzo.buildconfig") version "5.5.0" apply false +} + +allprojects { + group = "moe.nea.mcautotranslations" + version = "1.0-SNAPSHOT" + + repositories { + mavenCentral() + } + tasks.withType<JavaCompile> { + sourceCompatibility = "1.8" + targetCompatibility = "1.8" + } + tasks.withType<KotlinCompile> { + compilerOptions.jvmTarget.set(JvmTarget.JVM_1_8) + } + tasks.withType<Test> { + useJUnitPlatform() + } +} +subprojects { + apply(plugin = "com.github.gmazzo.buildconfig") + configure<BuildConfigExtension> { + packageName("moe.nea.mcautotranslation.${project.name}") + buildConfigField<String>("KOTLIN_PLUGIN_ID", "moe.nea.mcautotranslations") + buildConfigField<String>("KOTLIN_PLUGIN_GROUP", project(":kotlin-plugin").group.toString()) + buildConfigField<String>("KOTLIN_PLUGIN_ARTIFACT", project(":kotlin-plugin").name) + buildConfigField<String>("KOTLIN_PLUGIN_VERSION", project(":kotlin-plugin").version.toString()) + } +}
\ No newline at end of file diff --git a/gradle-plugin/build.gradle.kts b/gradle-plugin/build.gradle.kts new file mode 100644 index 0000000..caef680 --- /dev/null +++ b/gradle-plugin/build.gradle.kts @@ -0,0 +1,23 @@ +plugins { + kotlin("jvm") + id("java-gradle-plugin") +} + +dependencies { + implementation(kotlin("gradle-plugin-api")) + implementation(kotlin("stdlib")) + implementation("com.google.code.gson:gson:2.11.0") + implementation("org.ow2.asm:asm:9.7.1") + implementation(project(":annotations")) +} + +gradlePlugin { + plugins { + create("mcAutoTranslations") { + id = "moe.nea.mc-auto-translations" + displayName = "MC Auto Translation File Generation" + implementationClass = "moe.nea.mcautotranslations.gradle.MCAutoTranslationsGradlePlugin" + } + } + +} diff --git a/gradle-plugin/src/main/kotlin/moe/nea/mcautotranslations/gradle/MCAutoTranslationsExtension.kt b/gradle-plugin/src/main/kotlin/moe/nea/mcautotranslations/gradle/MCAutoTranslationsExtension.kt new file mode 100644 index 0000000..7367056 --- /dev/null +++ b/gradle-plugin/src/main/kotlin/moe/nea/mcautotranslations/gradle/MCAutoTranslationsExtension.kt @@ -0,0 +1,7 @@ +package moe.nea.mcautotranslations.gradle + +abstract class MCAutoTranslationsExtension { + + fun translationFunction(name: String) {} // TODO: actual config + +} diff --git a/gradle-plugin/src/main/kotlin/moe/nea/mcautotranslations/gradle/MCAutoTranslationsGradlePlugin.kt b/gradle-plugin/src/main/kotlin/moe/nea/mcautotranslations/gradle/MCAutoTranslationsGradlePlugin.kt new file mode 100644 index 0000000..d954e64 --- /dev/null +++ b/gradle-plugin/src/main/kotlin/moe/nea/mcautotranslations/gradle/MCAutoTranslationsGradlePlugin.kt @@ -0,0 +1,37 @@ +package moe.nea.mcautotranslations.gradle + +import moe.nea.mcautotranslation.`gradle-plugin`.BuildConfig +import org.gradle.api.Project +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 + +class MCAutoTranslationsGradlePlugin : KotlinCompilerPluginSupportPlugin { + override fun apply(target: Project) { + target.extensions.create("mcAutoTranslations", MCAutoTranslationsExtension::class.java) + } + + override fun applyToCompilation(kotlinCompilation: KotlinCompilation<*>): Provider<List<SubpluginOption>> { + val project = kotlinCompilation.target.project + val extension = project.extensions.getByType(MCAutoTranslationsExtension::class.java) + return project.provider { + listOf() // TODO: add plugin options from extension in here + } + } + + override fun getCompilerPluginId(): String { + return BuildConfig.KOTLIN_PLUGIN_ID + } + + override fun getPluginArtifact(): SubpluginArtifact = SubpluginArtifact( + groupId = BuildConfig.KOTLIN_PLUGIN_GROUP, + artifactId = BuildConfig.KOTLIN_PLUGIN_ARTIFACT, + version = BuildConfig.KOTLIN_PLUGIN_VERSION, + ) + + override fun isApplicable(kotlinCompilation: KotlinCompilation<*>): Boolean { + return true + } +}
\ No newline at end of file diff --git a/gradle-plugin/src/main/kotlin/moe/nea/mcautotranslations/gradle/MergeTranslations.kt b/gradle-plugin/src/main/kotlin/moe/nea/mcautotranslations/gradle/MergeTranslations.kt new file mode 100644 index 0000000..44cea35 --- /dev/null +++ b/gradle-plugin/src/main/kotlin/moe/nea/mcautotranslations/gradle/MergeTranslations.kt @@ -0,0 +1,181 @@ +package moe.nea.mcautotranslations.gradle + +import com.google.gson.Gson +import com.google.gson.reflect.TypeToken +import moe.nea.mcautotranslations.annotations.GatheredTranslation +import org.gradle.api.DefaultTask +import org.gradle.api.file.ConfigurableFileCollection +import org.gradle.api.file.RegularFileProperty +import org.gradle.api.tasks.InputFiles +import org.gradle.api.tasks.OutputFile +import org.gradle.api.tasks.PathSensitive +import org.gradle.api.tasks.PathSensitivity +import org.gradle.api.tasks.TaskAction +import org.gradle.work.Incremental +import org.gradle.work.InputChanges +import org.objectweb.asm.AnnotationVisitor +import org.objectweb.asm.ClassReader +import org.objectweb.asm.ClassVisitor +import org.objectweb.asm.Opcodes +import org.objectweb.asm.Type +import java.io.File + +abstract class CollectTranslations : DefaultTask() { + @get:InputFiles + @get:Incremental + abstract val baseTranslations: ConfigurableFileCollection + + @get:InputFiles + @get:Incremental + @get:PathSensitive(PathSensitivity.RELATIVE) + abstract val classes: ConfigurableFileCollection + + @get:OutputFile + abstract val outputFile: RegularFileProperty + + class Translations { + var baseTranslation: HashMap<String, HashMap<String, String>> = HashMap() + var inlineTranslations: HashMap<String, HashMap<String, String>> = HashMap() + } + + companion object { + val gson = Gson() + val mapType: TypeToken<HashMap<String, String>> = object : TypeToken<HashMap<String, String>>() {} + } + + @TaskAction + fun execute(inputs: InputChanges) { + val baseTranslationsDirty = inputs.getFileChanges(baseTranslations).any() + val outFile = outputFile.get().asFile + val outputExists = outFile.exists() + val canBeIncremental = outputExists && !baseTranslationsDirty + val baseTranslations: Translations = if (canBeIncremental) { + gson.fromJson(outFile.readText(), Translations::class.java) + } else { + val t = Translations() + baseTranslations.associateTo(t.baseTranslation) { + it.toString() to gson.fromJson(outFile.readText(), mapType) + } + t + } + val files: List<FileChange> = if (canBeIncremental) { + inputs.getFileChanges(classes).map { FileChange(it.file, it.normalizedPath) } + } else { + buildList { + classes.asFileTree.visit { + add(FileChange(it.file, it.path)) + } + } + } + files + .asSequence() + .filter { checkFile(it.file) } + .forEach { + val className = getClassName(it.relativePath) + if (it.file.exists()) { + parseClassAnnotations(it.file) + } else { + baseTranslations.inlineTranslations.remove(className) + } + } + outFile.writeText(gson.toJson(baseTranslations)) + } + + + private class KVVisitor(val map: MutableMap<String, String>) : AnnotationVisitor(Opcodes.ASM9) { + var value: String? = null + var key: String? = null + override fun visit(name: String, value: Any) { + when (name) { + "key" -> this.key = value as String + "value" -> this.value = value as String + else -> error("Unknown annotation element $name") + } + } + + override fun visitAnnotation(name: String?, descriptor: String?): AnnotationVisitor { + error("Unknown annotation element $name") + } + + override fun visitArray(name: String?): AnnotationVisitor { + error("Unknown annotation element $name") + } + + override fun visitEnum(name: String?, descriptor: String?, value: String?) { + error("Unknown annotation element $name") + } + + override fun visitEnd() { + map[key ?: error("Missing key")] = value ?: error("Missing value") + } + } + + private class RepeatableVisitor(val map: MutableMap<String, String>) : AnnotationVisitor(Opcodes.ASM9) { + override fun visitArray(name: String?): AnnotationVisitor { + require(name == "value") { "Unknown annotation element $name" } + foundArray = true + return KVVisitor(map) + } + + var foundArray = false + + override fun visitEnd() { + require(foundArray) { "Missing array" } + } + + override fun visitAnnotation(name: String?, descriptor: String?): AnnotationVisitor { + error("Unknown annotation element $name") + } + + override fun visit(name: String?, value: Any?) { + error("Unknown annotation element $name") + } + + override fun visitEnum(name: String?, descriptor: String?, value: String?) { + error("Unknown annotation element $name") + } + } + + private class AnnotationCollector(val map: MutableMap<String, String>) : ClassVisitor(Opcodes.ASM9) { + override fun visitAnnotation(descriptor: String, visible: Boolean): AnnotationVisitor? { + // TODO: inject our own annotations into the classpath + if (Type.getType(GatheredTranslation::class.java).descriptor.equals(descriptor)) { + return KVVisitor(map) + } + if (Type.getType(GatheredTranslation.Repeatable::class.java).descriptor.equals(descriptor)) { + return RepeatableVisitor(map) + } + // TODO: remove print log + println("Ignoring descriptor $descriptor") + return null + } + } + + private fun parseClassAnnotations(file: File): HashMap<String, String> { + val map = HashMap<String, String>() + kotlin.runCatching { + ClassReader(file.readBytes()) + .accept(AnnotationCollector(map), + ClassReader.SKIP_CODE or ClassReader.SKIP_DEBUG or ClassReader.SKIP_FRAMES) + }.onFailure { + throw RuntimeException("Could not parse annotations in $file", it) + } + return map + } + + private fun getClassName(relativePath: String): String { + return relativePath.replace("/", ".").removeSuffix(".class") + } + + data class FileChange(val file: File, val relativePath: String) + + private fun checkFile(file: File): Boolean { + if (file.isDirectory) return false + val extension = file.extension + if (extension == "kt" || extension == "java") + error("Cannot collect translations from source files. Please attach the CollectTranslations task to a compile output") + if (extension != "class") return false + return true + } + +}
\ No newline at end of file diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..7fc6f1f --- /dev/null +++ b/gradle.properties @@ -0,0 +1 @@ +kotlin.code.style=official diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar Binary files differnew file mode 100644 index 0000000..249e583 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.jar diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..461ea5b --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Mon Oct 14 11:39:31 CEST 2024 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists @@ -0,0 +1,234 @@ +#!/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. +# + +############################################################################## +# +# 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/master/subprojects/plugins/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 + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# 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"' + +# 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 + which java >/dev/null 2>&1 || 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 + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + 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 + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# 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/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@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 + +@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=. +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%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +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%"=="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! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/kotlin-plugin/build.gradle.kts b/kotlin-plugin/build.gradle.kts new file mode 100644 index 0000000..9cf4d36 --- /dev/null +++ b/kotlin-plugin/build.gradle.kts @@ -0,0 +1,20 @@ +plugins { + kotlin("jvm") + id("com.google.devtools.ksp") + `maven-publish` +} + +dependencies { + compileOnly("org.jetbrains.kotlin:kotlin-compiler-embeddable") + implementation("com.google.devtools.ksp:symbol-processing-api:1.9.23-1.0.20") + implementation(project(":annotations")) + + ksp("dev.zacsweers.autoservice:auto-service-ksp:1.2.0") + compileOnly("com.google.auto.service:auto-service-annotations:1.0.1") + + testImplementation(kotlin("test-junit5")) + testImplementation("org.jetbrains.kotlin:kotlin-compiler-embeddable") + testImplementation("dev.zacsweers.kctfork:core:0.5.1") + testImplementation("dev.zacsweers.kctfork:ksp:0.5.1") +} + diff --git a/kotlin-plugin/src/main/kotlin/moe/nea/mcautotranslations/kotlin/MCAutoTranslationsCallTransformerAndCollector.kt b/kotlin-plugin/src/main/kotlin/moe/nea/mcautotranslations/kotlin/MCAutoTranslationsCallTransformerAndCollector.kt new file mode 100644 index 0000000..cc38b57 --- /dev/null +++ b/kotlin-plugin/src/main/kotlin/moe/nea/mcautotranslations/kotlin/MCAutoTranslationsCallTransformerAndCollector.kt @@ -0,0 +1,166 @@ +package moe.nea.mcautotranslations.kotlin + +import moe.nea.mcautotranslations.annotations.GatheredTranslation +import org.jetbrains.kotlin.backend.common.IrElementTransformerVoidWithContext +import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext +import org.jetbrains.kotlin.backend.common.getCompilerMessageLocation +import org.jetbrains.kotlin.backend.common.lower.DeclarationIrBuilder +import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity +import org.jetbrains.kotlin.cli.common.messages.MessageCollector +import org.jetbrains.kotlin.ir.builders.irCall +import org.jetbrains.kotlin.ir.builders.irCallConstructor +import org.jetbrains.kotlin.ir.builders.irVararg +import org.jetbrains.kotlin.ir.declarations.IrFile +import org.jetbrains.kotlin.ir.expressions.IrCall +import org.jetbrains.kotlin.ir.expressions.IrConst +import org.jetbrains.kotlin.ir.expressions.IrConstKind +import org.jetbrains.kotlin.ir.expressions.IrExpression +import org.jetbrains.kotlin.ir.expressions.IrStringConcatenation +import org.jetbrains.kotlin.ir.types.makeNullable +import org.jetbrains.kotlin.ir.util.SYNTHETIC_OFFSET +import org.jetbrains.kotlin.ir.util.kotlinFqName +import org.jetbrains.kotlin.ir.util.toIrConst +import org.jetbrains.kotlin.name.CallableId +import org.jetbrains.kotlin.name.ClassId +import org.jetbrains.kotlin.name.FqName +import org.jetbrains.kotlin.name.Name + +class MCAutoTranslationsCallTransformerAndCollector( + val file: IrFile, + val irPluginContext: IrPluginContext, + val messageCollector: MessageCollector, + val translationNames: Map<FqName, CallableId>, +) : IrElementTransformerVoidWithContext() { + + override fun visitCall(expression: IrCall): IrExpression { + val function = expression.symbol.owner + val fqFunctionName = function.kotlinFqName + val translatedFunctionName = translationNames[fqFunctionName] + ?: return super.visitCall(expression) + if (expression.valueArgumentsCount != 2) { + messageCollector.report( + CompilerMessageSeverity.ERROR, + "Translation calls need to have exactly two arguments. Use $fqFunctionName(\"translation.key\", \"some \$template string\")", + expression.getCompilerMessageLocation(file) + ) + return super.visitCall(expression) + } + val translationKey = expression.getValueArgument(0).asStringConst() + if (translationKey == null) { + messageCollector.report( + CompilerMessageSeverity.ERROR, + "The key of a translation call needs to be a constant string. Use $fqFunctionName(\"translation.key\", \"some \$template string\")", + (expression.getValueArgument(0) ?: expression).getCompilerMessageLocation(file) + ) + return super.visitCall(expression) + } + val translationDefault = expression.getValueArgument(1).asStringDyn() + if (translationDefault == null) { + messageCollector.report( + CompilerMessageSeverity.ERROR, + "The default of a translation call needs to be a string template or constant. Use $fqFunctionName(\"translation.key\", \"some \$template string\")", + (expression.getValueArgument(1) ?: expression).getCompilerMessageLocation(file) + ) + return super.visitCall(expression) + + } + val symbol = currentScope!!.scope.scopeOwnerSymbol + val builder = DeclarationIrBuilder(irPluginContext, symbol, expression.startOffset, expression.endOffset) + return builder.generateTemplate( + translatedFunctionName, translationKey, + expression.getValueArgument(0)!!, translationDefault) + } + + fun DeclarationIrBuilder.generateTemplate( + translationName: CallableId, + key: String, + keySource: IrExpression, + template: StringTemplate, + ): IrExpression { + val replacementFunction = irPluginContext.referenceFunctions(translationName) + .single() // TODO: find proper overload + val arguments = splitTemplate(key, template) + val varArgs = irVararg(context.irBuiltIns.anyType.makeNullable(), arguments) + + return irCall( + replacementFunction, replacementFunction.owner.returnType, + valueArgumentsCount = 2, + ).apply { + putValueArgument(0, + constString(key, keySource.startOffset, keySource.endOffset)) + putValueArgument(1, varArgs) + } + } + + fun splitTemplate(key: String, template: StringTemplate): List<IrExpression> { + var templateString = "" + val arguments = mutableListOf<IrExpression>() + for (segment in template.segments) { + val const = segment.asStringConst() + if (const != null) { + templateString += const.replace("%", "%%") + } else { + templateString += "%s" + arguments.add(segment) + } + } + + messageCollector.report( + CompilerMessageSeverity.INFO, + "Generated template: $templateString" + ) + templates[key] = templateString + return arguments + } + + val templates: MutableMap<String, String> = mutableMapOf() + + + fun finish() { + val builder = DeclarationIrBuilder(irPluginContext, file.symbol, SYNTHETIC_OFFSET, SYNTHETIC_OFFSET) + val annotationCons = irPluginContext + .referenceConstructors(GatheredTranslation::class.java.toClassId()).single() + val annotations = templates.map { + builder.irCallConstructor(annotationCons, listOf()).apply { + putValueArgument(0, constString(it.key)) + putValueArgument(1, constString(it.value)) + } + } + file.annotations = annotations + file.annotations + } + + + fun constString( + text: String, + startOffset: Int = SYNTHETIC_OFFSET, + endOffset: Int = SYNTHETIC_OFFSET + ): IrConst<String> = + text.toIrConst(irPluginContext.irBuiltIns.stringType, startOffset, endOffset) as IrConst<String> +} + +data class StringTemplate( + val segments: List<IrExpression>, +) { + constructor(vararg segments: IrExpression) : this(segments.toList()) +} + +fun IrExpression?.asStringDyn(): StringTemplate? = when (this) { + is IrConst<*> -> if (kind == IrConstKind.String) StringTemplate(this) else null + is IrStringConcatenation -> StringTemplate(this.arguments) + else -> null +} + +fun IrExpression?.asStringConst(): String? = when (this) { + is IrConst<*> -> if (kind == IrConstKind.String) value as String else null + is IrStringConcatenation -> this.arguments.singleOrNull().asStringConst() + else -> null +} + + +fun Class<*>.toClassId(): ClassId { + require(!this.isArray) + require("." in this.name) + return ClassId( + FqName(this.name.substringBeforeLast(".")), + Name.identifier(this.name.substringAfterLast(".").replace("$", "."))) +} diff --git a/kotlin-plugin/src/main/kotlin/moe/nea/mcautotranslations/kotlin/MCAutoTranslationsCommandLineProcessor.kt b/kotlin-plugin/src/main/kotlin/moe/nea/mcautotranslations/kotlin/MCAutoTranslationsCommandLineProcessor.kt new file mode 100644 index 0000000..31088cf --- /dev/null +++ b/kotlin-plugin/src/main/kotlin/moe/nea/mcautotranslations/kotlin/MCAutoTranslationsCommandLineProcessor.kt @@ -0,0 +1,23 @@ +@file:OptIn(ExperimentalCompilerApi::class) + +package moe.nea.mcautotranslations.kotlin + +import com.google.auto.service.AutoService +import moe.nea.mcautotranslation.`kotlin-plugin`.BuildConfig +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 + + +@AutoService(CommandLineProcessor::class) +class MCAutoTranslationsCommandLineProcessor : CommandLineProcessor { + override val pluginId: String + get() = BuildConfig.KOTLIN_PLUGIN_ID + override val pluginOptions: Collection<AbstractCliOption> + get() = listOf() + + override fun processOption(option: AbstractCliOption, value: String, configuration: CompilerConfiguration) { + // TODO: process options + } +}
\ No newline at end of file diff --git a/kotlin-plugin/src/main/kotlin/moe/nea/mcautotranslations/kotlin/MCAutoTranslationsComponentRegistrar.kt b/kotlin-plugin/src/main/kotlin/moe/nea/mcautotranslations/kotlin/MCAutoTranslationsComponentRegistrar.kt new file mode 100644 index 0000000..e1e22dd --- /dev/null +++ b/kotlin-plugin/src/main/kotlin/moe/nea/mcautotranslations/kotlin/MCAutoTranslationsComponentRegistrar.kt @@ -0,0 +1,37 @@ +@file:OptIn(ExperimentalCompilerApi::class) + +package moe.nea.mcautotranslations.kotlin + +import com.google.auto.service.AutoService +import org.jetbrains.kotlin.backend.common.extensions.IrGenerationExtension +import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity +import org.jetbrains.kotlin.compiler.plugin.CompilerPluginRegistrar +import org.jetbrains.kotlin.compiler.plugin.ExperimentalCompilerApi +import org.jetbrains.kotlin.config.CompilerConfiguration +import org.jetbrains.kotlin.config.messageCollector +import org.jetbrains.kotlin.extensions.ProjectExtensionDescriptor +import kotlin.collections.getOrPut + +@AutoService(CompilerPluginRegistrar::class) +class MCAutoTranslationsComponentRegistrar : CompilerPluginRegistrar() { + override val supportsK2: Boolean + get() = true + + override fun ExtensionStorage.registerExtensions(configuration: CompilerConfiguration) { + val messageCollector = configuration.messageCollector + IrGenerationExtension.registerExtension( + extension = MCAutoTranslationsIrGenerationExtension(messageCollector)) + + messageCollector.report(CompilerMessageSeverity.INFO, "Registering stuff") + } + + fun <T : Any> ExtensionStorage.registerExtensionFirst( + descriptor: ProjectExtensionDescriptor<T>, + extension: T + ) { + val extensions = (registeredExtensions as MutableMap<Any, Any>) + .getOrPut(descriptor, { mutableListOf<Any>() }) as MutableList<T> + extensions.add(0, extension) + } + +}
\ No newline at end of file diff --git a/kotlin-plugin/src/main/kotlin/moe/nea/mcautotranslations/kotlin/MCAutoTranslationsIrGenerationExtension.kt b/kotlin-plugin/src/main/kotlin/moe/nea/mcautotranslations/kotlin/MCAutoTranslationsIrGenerationExtension.kt new file mode 100644 index 0000000..3b17e68 --- /dev/null +++ b/kotlin-plugin/src/main/kotlin/moe/nea/mcautotranslations/kotlin/MCAutoTranslationsIrGenerationExtension.kt @@ -0,0 +1,29 @@ +package moe.nea.mcautotranslations.kotlin + +import org.jetbrains.kotlin.backend.common.extensions.IrGenerationExtension +import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext +import org.jetbrains.kotlin.cli.common.messages.MessageCollector +import org.jetbrains.kotlin.ir.declarations.IrModuleFragment +import org.jetbrains.kotlin.name.CallableId +import org.jetbrains.kotlin.name.FqName + +class MCAutoTranslationsIrGenerationExtension( + private val messageCollector: MessageCollector, +) : IrGenerationExtension { + override fun generate(moduleFragment: IrModuleFragment, pluginContext: IrPluginContext) { + val translationNames: MutableMap<FqName, CallableId> = mutableMapOf() + val target = FqName("moe.nea.translatetest.tr") + val resolved = FqName("moe.nea.translatetest.trResolved") // TODO: make these names configurable + translationNames[target] = CallableId(resolved.parent(), resolved.shortName()) + moduleFragment.files.forEach { + val visitor = MCAutoTranslationsCallTransformerAndCollector( + it, + pluginContext, + messageCollector, + translationNames + ) + it.accept(visitor, null) + visitor.finish() + } + } +} diff --git a/kotlin-plugin/src/test/kotlin/moe/nea/mcautotranslations/TestTemplateReplacement.kt b/kotlin-plugin/src/test/kotlin/moe/nea/mcautotranslations/TestTemplateReplacement.kt new file mode 100644 index 0000000..b4a7f18 --- /dev/null +++ b/kotlin-plugin/src/test/kotlin/moe/nea/mcautotranslations/TestTemplateReplacement.kt @@ -0,0 +1,40 @@ +@file:OptIn(ExperimentalCompilerApi::class) + +package moe.nea.mcautotranslations + +import com.tschuchort.compiletesting.SourceFile +import org.jetbrains.kotlin.compiler.plugin.ExperimentalCompilerApi +import kotlin.test.Test + +class TestTemplateReplacement { + @Test + fun testX() { + val dollar = '$' + compile(listOf( + SourceFile.kotlin( + "test.kt", + """ + package moe.nea.translatetest + + data class Text(val text: String) + fun tr(key: String, value: String): Text { + error("This should not be executed at runtime. Compiler plugin did not run.") + } + + fun trResolved(key: String, vararg templateArgs: Any?): Text { + return Text("TODO: do a lookup here for $dollar{key} and make use of $dollar{templateArgs.toList()}") + } + + fun main() { + val test = 20 + val othertest = "test2" + + println(tr("hi", "aaa$dollar{test}rest$dollar{othertest}end")) + println(tr("hello", "just a regular strnig")) + println(trResolved("hi", test, othertest)) + } + """.trimIndent() + ) + )) + } +}
\ No newline at end of file diff --git a/kotlin-plugin/src/test/kotlin/moe/nea/mcautotranslations/compile_utils.kt b/kotlin-plugin/src/test/kotlin/moe/nea/mcautotranslations/compile_utils.kt new file mode 100644 index 0000000..48d9c6e --- /dev/null +++ b/kotlin-plugin/src/test/kotlin/moe/nea/mcautotranslations/compile_utils.kt @@ -0,0 +1,33 @@ +@file:OptIn(ExperimentalCompilerApi::class) + +package moe.nea.mcautotranslations + +import com.tschuchort.compiletesting.JvmCompilationResult +import com.tschuchort.compiletesting.KotlinCompilation +import com.tschuchort.compiletesting.SourceFile +import com.tschuchort.compiletesting.configureKsp +import moe.nea.mcautotranslations.kotlin.MCAutoTranslationsComponentRegistrar +import org.jetbrains.kotlin.compiler.plugin.CompilerPluginRegistrar +import org.jetbrains.kotlin.compiler.plugin.ExperimentalCompilerApi + +private val DEFAULT_PLUGINS = arrayOf( + MCAutoTranslationsComponentRegistrar() +) + + +fun compile( + list: List<SourceFile>, + vararg plugins: CompilerPluginRegistrar = DEFAULT_PLUGINS +): JvmCompilationResult { + return KotlinCompilation().apply { + sources = list + compilerPluginRegistrars = plugins.toList() + inheritClassPath = true + messageOutputStream = System.out // TODO: capture this output somehow for testing + }.compile() +} + + + + + diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..bdab325 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,7 @@ +plugins { + id("org.gradle.toolchains.foojay-resolver-convention") version "0.8.0" +} +rootProject.name = "mcautotranslations" +include(":kotlin-plugin") +include(":gradle-plugin") +include(":annotations") |