summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJoel Klinghed <the_jk@spawned.biz>2026-11-15 13:22:39 +0100
committerJoel Klinghed <the_jk@spawned.biz>2026-11-15 13:22:39 +0100
commit1d6d1a8ee90f407fc6461c18db2811ac672bd1c5 (patch)
tree75eb5114f9e9f1a753a4bc548d72072cf7d472f5
parent5df7cb16a9e2a38014deafda99e0b3256acc0040 (diff)
Generate argument handling from kotlin-compiler-arguments-description
-rw-r--r--.gitignore4
-rw-r--r--CLAUDE.md68
-rw-r--r--Makefile43
-rw-r--r--stubs/src/kotlin/proxy/KotlinProxyOverrides.java35
-rw-r--r--tools/ArgProbe.java161
-rw-r--r--tools/gen_arg_table.py309
6 files changed, 593 insertions, 27 deletions
diff --git a/.gitignore b/.gitignore
index 889fe2d..e9c8436 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,2 +1,6 @@
dist/
.stamp
+vendor/
+stubs/.compiled
+stubs/gen/
+tools/__pycache__/
diff --git a/CLAUDE.md b/CLAUDE.md
index f4d1d92..63fa5d8 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -9,9 +9,11 @@ ABI-identical **stub** of `org.jetbrains.kotlin.cli.jvm.K2JVMCompiler` that live
on the **Kotlin daemon's** classpath. The stub logs every call (and the
compiler arguments it receives) and returns JVM defaults / reflectively-built
real return objects — it does **not** actually compile. This is **pure
-replacement**: no passthrough, no fallback. The build is *supposed* to go red;
-the point is to observe exactly what AGP/KGP hands the compiler before
-implementing an alternative compile inside the stub.
+replacement**: no passthrough, no fallback. With no overrides implemented
+the build is *supposed* to go red; the point is to observe exactly what
+AGP/KGP hands the compiler before implementing an alternative compile inside
+the stub (the current `doExecutePhased` implementation does exactly that —
+it drives a native-image kotlinc — so the test build is green; see Testing).
`README.md` is the deep reference (bytecode format, log format, full option
table). Read it before changing generation behavior.
@@ -23,6 +25,18 @@ table). Read it before changing generation behavior.
erased structure verbatim.
- `tools/gen_jar_lists.py` — regenerates the `jars/*.txt` lists from the local
Gradle cache (see Building).
+- `tools/gen_arg_table.py` + `tools/ArgProbe.java` — generate the CLI
+ argument table (`stubs/gen/kotlin/proxy/GeneratedJvmArguments.java`):
+ translates the daemon-populated `K2JVMCompilerArguments` into kotlinc CLI
+ tokens for the alternative compile. The probe (reflection, no bytecode
+ parsing) reads the `@Argument` annotations off the real class — flag
+ names, delimiters, deprecated/removed markers, and the defaults the no-arg
+ constructor leaves behind — because the flag names are *not* derivable
+ from the descriptions (e.g. `-Xdebug` → `enableDebugMode`). The
+ `kotlin-compiler-arguments.json` from the
+ `kotlin-compiler-arguments-description` Maven artifact (fetched into
+ `vendor/` by a curl make target, pinned to `KOTLIN_VERSION`) is only
+ cross-checked for coverage.
- `docs/opcodes.html` — JVM bytecode opcode reference. **Consult it whenever
hand-rolling bytecode in `gen_class.py`** — opcodes like `putstatic` (0xb3)
and stack peaks are easy to get wrong, and the JVM only complains with an
@@ -31,6 +45,10 @@ table). Read it before changing generation behavior.
stub calls into.
- `stubs/src/kotlin/proxy/KotlinProxyOverrides.java` — per-method custom return
values: the extension point for actually *implementing* stub methods.
+- `stubs/gen/kotlin/proxy/GeneratedJvmArguments.java` — generated CLI
+ argument table (gitignored, see `tools/gen_arg_table.py`).
+- `vendor/kotlin-compiler-arguments-description-<v>.jar` — the Maven
+ artifact the generator cross-checks against (gitignored, curl-fetched).
- `stubs/src/kotlin/proxy/ProxyPerformanceManager.java` — override support
class (per-compiler-instance perf manager) returned by the overrides.
- `jars/defs.txt`, `jars/scan.txt`, `jars/fallback.txt`, `jars/.stamp` —
@@ -47,22 +65,31 @@ table). Read it before changing generation behavior.
make
```
-The Makefile runs the 3 real steps in order:
+The Makefile runs the 5 real steps in order:
-1. Regenerate `jars/*.txt` via `tools/gen_jar_lists.py` when the pinned
+1. Fetch `vendor/kotlin-compiler-arguments-description-<v>.jar` from Maven
+ Central via curl when missing (pinned to `KOTLIN_VERSION`; needs network).
+2. Regenerate the CLI argument table
+ `stubs/gen/kotlin/proxy/GeneratedJvmArguments.java` when the
+ tool/probe/vendor-jar/defs list changed (`tools/gen_arg_table.py`; it
+ prints a coverage report both directions — JSON args with no class field
+ and vice versa — to stderr).
+3. Regenerate `jars/*.txt` via `tools/gen_jar_lists.py` when the pinned
versions (Makefile vars `KOTLIN_VERSION` / `AGP_VERSION`, kept in sync with
`test_project/gradle/libs.versions.toml`) drift from `jars/.stamp`. The
Gradle cache must already hold those versions — run the test_project once
first (even a red build resolves everything).
-2. Generate the stub classes (`tools/gen_class.py`, **wipes** `stubs/classes_min`
+4. Generate the stub classes (`tools/gen_class.py`, **wipes** `stubs/classes_min`
first — put nothing you need there):
`--seed-only --no-closure --seed '…K2JVMCompiler,…K2JVMCompiler$Companion,…K2JVMCompilerKt'`.
-3. Compile the `kotlin.proxy.*` classes into the same tree (the `-cp` lets
- `KotlinProxyOverrides` import real compiler types), then package the jar.
+5. Compile the `kotlin.proxy.*` classes **and the generated argument table**
+ into the same tree (the `-cp` lets `KotlinProxyOverrides` import real
+ compiler types), then package the jar.
-The result is 7 class files + manifest: the three seeded stubs plus
+The result is 8 class files + manifest: the three seeded stubs plus
`kotlin/proxy/KotlinProxyLog`, `kotlin/proxy/KotlinProxyOverrides`
-(+ inner `$Compiler`), and `kotlin/proxy/ProxyPerformanceManager`. The
+(+ inner `$Compiler`), `kotlin/proxy/ProxyPerformanceManager`, and
+`kotlin/proxy/GeneratedJvmArguments`. The
seed trio are **the only** classes stubbed (the "trio" mode); their
superclasses/interfaces (`CLICompiler`, `K2JVMCompilerArguments`, …) are
*not* stubbed and resolve from the real jars on the daemon classpath.
@@ -75,10 +102,15 @@ The "test" is the test project. From `test_project/`:
./gradlew :app:compileDebugKotlin
```
-Expected outcome: **red** (`compileDebugKotlin FAILED`, "Internal compiler
-error" — the stub returns defaults, so the real compiler machinery fails
-after calling into the stub). That is the intended state. To confirm the stub
-actually ran *inside the out-of-process daemon*, read the marker file
+Expected outcome depends on which overrides are implemented: with none, the
+build is **red** (`compileDebugKotlin FAILED`, "Internal compiler error" —
+the stub returns defaults, so the real compiler machinery fails after
+calling into the stub). With the current `doExecutePhased` implementation
+(it hands the generated CLI table to a native-image kotlinc), the build is
+**green** and the compiled output lands in
+`test_project/app/build/intermediates/built_in_kotlinc/…/classes` (e.g.
+`…/org/the_jk/testproject/Hello.class`). To confirm the stub actually ran
+*inside the out-of-process daemon*, read the marker file
`/tmp/kotlin-proxy-marker.txt` — a daemon run shows thread names
`RMI TCP Connection(N)` and `LOAD …/dist/kotlin-proxy-compiler-stubs.jar`
lines (the trio's `<clinit>`s also `LOAD` `…$Companion`). An
@@ -160,6 +192,8 @@ re-verifying, and `rm /tmp/kotlin-proxy-marker.txt` for a fresh marker.
jar). The default mode is a full transitive closure from the AGP scan jars +
KGP plugin entry points — a much larger jar; only use it when you actually
want to stub a broader surface.
-- **Build artifacts are gitignored:** `dist/` (whole dir) and
- `stubs/classes_min/` are not tracked. If you need the jar and it's missing,
- run `make`.
+- **Build artifacts are gitignored:** `dist/` (whole dir),
+ `stubs/classes_min/`, `stubs/gen/` (generated argument table) and
+ `vendor/` (curl-fetched Maven artifact) are not tracked. If you need the
+ jar and it's missing, run `make` (the arg table and vendor jar are
+ regenerated/fetched as needed; the fetch needs network).
diff --git a/Makefile b/Makefile
index d80c617..4d596bb 100644
--- a/Makefile
+++ b/Makefile
@@ -1,13 +1,39 @@
.PHONY: all clean compileStubs jars
+# Stamp for the javac step (kept OUT of stubs/classes_min so it is not
+# packaged into the jar; gen_class.py wipes that tree anyway).
+STUBS_STAMP = stubs/.compiled
+
# Versions the jar lists (jars/*.txt) are generated for — see
# tools/gen_jar_lists.py. Keep in sync with test_project/gradle/
# libs.versions.toml (agp / kotlin).
KOTLIN_VERSION ?= 2.4.21
AGP_VERSION ?= 9.4.1
+# The kotlin-compiler-arguments-description artifact of the same version the
+# arguments class is probed from - fetched from Maven Central when missing.
+ARGS_DESCRIPTION = vendor/kotlin-compiler-arguments-description-$(KOTLIN_VERSION).jar
+
+# CLI argument table generated from @Argument annotations (see
+# tools/gen_arg_table.py / tools/ArgProbe.java).
+GEN_ARGS_JAVA = stubs/gen/kotlin/proxy/GeneratedJvmArguments.java
+
all: dist/kotlin-proxy-compiler-stubs.jar
+# Plain curl: the artifact is not a build dependency of anything else, so
+# there is no Gradle/dependency machinery involved.
+$(ARGS_DESCRIPTION):
+ mkdir -p vendor
+ curl -fL --retry 3 -o $@ \
+ https://repo1.maven.org/maven2/org/jetbrains/kotlin/kotlin-compiler-arguments-description/$(KOTLIN_VERSION)/kotlin-compiler-arguments-description-$(KOTLIN_VERSION).jar
+
+$(GEN_ARGS_JAVA): tools/gen_arg_table.py tools/ArgProbe.java \
+ $(ARGS_DESCRIPTION) jars/defs.txt
+ python3 tools/gen_arg_table.py \
+ --args-description $(ARGS_DESCRIPTION) \
+ --defs jars/defs.txt \
+ --out $@
+
# Regenerate jars/defs.txt + scan.txt + fallback.txt + .stamp from the
# Gradle cache (the cache must already hold these versions - run the
# test_project once first, even a red build resolves everything).
@@ -22,7 +48,10 @@ jars/.stamp: tools/gen_jar_lists.py Makefile
clean:
rm -f dist/kotlin-proxy-compiler-stubs.jar
+ rm -f $(STUBS_STAMP)
rm -rf stubs/classes_min/*
+ rm -rf stubs/gen
+ rm -rf vendor
rm -f jars/.stamp
stubs/classes_min/org/jetbrains/kotlin/cli/jvm/K2JVMCompiler.class: \
@@ -36,15 +65,21 @@ stubs/classes_min/org/jetbrains/kotlin/cli/jvm/K2JVMCompiler.class: \
--seed 'org/jetbrains/kotlin/cli/jvm/K2JVMCompiler,org/jetbrains/kotlin/cli/jvm/K2JVMCompiler$$Companion,org/jetbrains/kotlin/cli/jvm/K2JVMCompilerKt' \
--out stubs/classes_min
-compileStubs: stubs/classes_min/org/jetbrains/kotlin/cli/jvm/K2JVMCompiler.class \
- jars/defs.txt stubs/src/kotlin/proxy/*.java
+# javac is driven by a stamp file (not .PHONY) so `make` is a no-op when
+# nothing changed - the stubs/src and stubs/gen sources, the generated stub
+# classes and defs.txt are the real inputs.
+$(STUBS_STAMP): stubs/classes_min/org/jetbrains/kotlin/cli/jvm/K2JVMCompiler.class \
+ stubs/src/kotlin/proxy/*.java $(GEN_ARGS_JAVA)
# DEFS is computed at recipe time: defs.txt may have been rewritten
# earlier in this same make run (via jars/.stamp), and a $(shell)
# variable would still hold the pre-rewrite contents.
DEFS=$$(grep -v '^[[:space:]]*#' jars/defs.txt | tr '\n' ':'); \
javac -nowarn -proc:none -d stubs/classes_min \
-cp "$$DEFS" \
- stubs/src/kotlin/proxy/*.java
+ stubs/src/kotlin/proxy/*.java stubs/gen/kotlin/proxy/*.java; \
+ touch $@
+
+compileStubs: $(STUBS_STAMP)
-dist/kotlin-proxy-compiler-stubs.jar: compileStubs
+dist/kotlin-proxy-compiler-stubs.jar: $(STUBS_STAMP)
jar cf $@ -C stubs/classes_min .
diff --git a/stubs/src/kotlin/proxy/KotlinProxyOverrides.java b/stubs/src/kotlin/proxy/KotlinProxyOverrides.java
index eebc423..c52db80 100644
--- a/stubs/src/kotlin/proxy/KotlinProxyOverrides.java
+++ b/stubs/src/kotlin/proxy/KotlinProxyOverrides.java
@@ -4,13 +4,12 @@ import org.jetbrains.kotlin.cli.common.ExitCode;
import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments;
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity;
import org.jetbrains.kotlin.cli.common.messages.MessageCollector;
-import org.jetbrains.kotlin.com.intellij.openapi.Disposable;
-import org.jetbrains.kotlin.config.CompilerConfiguration;
import org.jetbrains.kotlin.config.JvmTarget;
import org.jetbrains.kotlin.config.Services;
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms;
-import org.jetbrains.kotlin.utils.KotlinPaths;
+import org.jetbrains.kotlin.progress.CompilationCanceledStatus;
+import java.util.ArrayList;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.Map;
@@ -65,10 +64,34 @@ public final class KotlinProxyOverrides {
}
if ("doExecutePhased".equals(member)) {
K2JVMCompilerArguments arguments = (K2JVMCompilerArguments) args[0];
- // Services services = (Services) args[1];
+ Services services = (Services) args[1];
MessageCollector messageCollector = (MessageCollector) args[2];
- messageCollector.report(CompilerMessageSeverity.ERROR, "Shit is broken, yo!", null);
- return ExitCode.COMPILATION_ERROR;
+ CompilationCanceledStatus canceledStatus = services.get(CompilationCanceledStatus.class);
+
+ ArrayList<String> cmd = new ArrayList<String>();
+ cmd.add("/home/the_jk/source/kotlin_proxy/img/kotlin-native-image-linux-x86_64-2.4.21/bin/kotlinc-native-image.sh");
+ cmd.addAll(GeneratedJvmArguments.buildCommandArgs(arguments));
+ cmd.addAll(arguments.getFreeArgs());
+ ProcessBuilder builder = new ProcessBuilder(cmd);
+ builder.environment().put("JAVA_HOME", arguments.getJdkHome());
+ try {
+ Process process = builder.start();
+ int exitvalue = process.waitFor();
+ /*
+ BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
+
+String s = null;
+while ((s = stdInput.readLine()) != null) {
+ System.out.println(s);
+ */
+ if (exitvalue == 0) {
+ return ExitCode.OK;
+ }
+ messageCollector.report(CompilerMessageSeverity.ERROR, "Shit is broken, yo!", null);
+ return ExitCode.COMPILATION_ERROR;
+ } catch (Throwable t) {
+ throw new RuntimeException(t);
+ }
}
}
return NO_VALUE;
diff --git a/tools/ArgProbe.java b/tools/ArgProbe.java
new file mode 100644
index 0000000..751ad50
--- /dev/null
+++ b/tools/ArgProbe.java
@@ -0,0 +1,161 @@
+package tools;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.util.Arrays;
+import java.util.stream.Collectors;
+
+import org.jetbrains.kotlin.cli.common.arguments.Argument;
+
+/**
+ * Reflection probe run by tools/gen_arg_table.py (compiled on the fly against
+ * the defs jars): walks the class hierarchy of a compiler-arguments class
+ * and prints one JSON object per line, per @Argument-annotated field:
+ *
+ * {"class":"...","field":"classpath","type":"stringArray",
+ * "value":"classpath","shortName":"cp","deprecatedName":"",
+ * "delimiter":"...","description":"...",
+ * "default":[]}
+ *
+ * value/shortName/deprecatedName/delimiter/description come straight from the
+ * @Argument annotation (the same source the compiler's own CLI parser reads).
+ * default is the value the no-arg constructor leaves in the field, rendered
+ * as JSON (null | true/false | "str" | [...] | {"class","constant"} for
+ * enums | {"opaque":"..."} for anything else).
+ * type is one of bool | Boolean | string | stringArray | enum | other.
+ */
+public final class ArgProbe {
+
+ private ArgProbe() {
+ }
+
+ public static void main(String[] args) throws Exception {
+ String clsName = args.length > 0
+ ? args[0]
+ : "org.jetbrains.kotlin.cli.common.arguments."
+ + "K2JVMCompilerArguments";
+ Class<?> cls = Class.forName(clsName);
+ Object inst = cls.getDeclaredConstructor().newInstance();
+ for (Class<?> c = cls; c != null && c != Object.class;
+ c = c.getSuperclass()) {
+ for (Field f : c.getDeclaredFields()) {
+ Argument ann = f.getAnnotation(Argument.class);
+ if (ann == null) {
+ continue;
+ }
+ String getterName = "get"
+ + Character.toUpperCase(f.getName().charAt(0))
+ + f.getName().substring(1);
+ Method getter = findGetter(cls, getterName);
+ if (getter == null) {
+ System.err.println(
+ "warn: no getter " + getterName
+ + " for field " + f.getName());
+ continue;
+ }
+ StringBuilder out = new StringBuilder();
+ out.append("{\"class\":").append(quote(c.getName()))
+ .append(",\"field\":").append(quote(f.getName()))
+ .append(",\"type\":").append(quote(typeOf(f.getType())))
+ .append(",\"value\":").append(quote(ann.value()))
+ .append(",\"shortName\":").append(quote(ann.shortName()))
+ .append(",\"deprecatedName\":")
+ .append(quote(ann.deprecatedName()))
+ .append(",\"deprecatedVersion\":")
+ .append(quote(ann.deprecatedVersion()))
+ .append(",\"removedVersion\":")
+ .append(quote(ann.removedVersion()))
+ .append(",\"delimiter\":").append(quote(ann.delimiter()))
+ .append(",\"description\":").append(quote(ann.description()))
+ .append(",\"default\":")
+ .append(jsonOf(getter.invoke(inst)))
+ .append('}');
+ System.out.println(out);
+ }
+ }
+ }
+
+ private static Method findGetter(Class<?> cls, String name) {
+ for (Class<?> c = cls; c != null; c = c.getSuperclass()) {
+ try {
+ return c.getMethod(name);
+ } catch (NoSuchMethodException e) {
+ // keep walking
+ }
+ }
+ return null;
+ }
+
+ private static String typeOf(Class<?> t) {
+ if (t == boolean.class) {
+ return "bool";
+ }
+ if (t == Boolean.class) {
+ return "Boolean";
+ }
+ if (t == String.class) {
+ return "string";
+ }
+ if (t == String[].class) {
+ return "stringArray";
+ }
+ if (t.isEnum()) {
+ return "enum";
+ }
+ return "other";
+ }
+
+ private static String quote(String s) {
+ StringBuilder b = new StringBuilder("\"");
+ for (int i = 0; i < s.length(); i++) {
+ char ch = s.charAt(i);
+ switch (ch) {
+ case '\\':
+ b.append("\\\\");
+ break;
+ case '"':
+ b.append("\\\"");
+ break;
+ case '\n':
+ b.append("\\n");
+ break;
+ case '\r':
+ b.append("\\r");
+ break;
+ case '\t':
+ b.append("\\t");
+ break;
+ default:
+ if (ch < 0x20) {
+ b.append(String.format("\\u%04x", (int) ch));
+ } else {
+ b.append(ch);
+ }
+ }
+ }
+ return b.append('"').toString();
+ }
+
+ private static String jsonOf(Object v) {
+ if (v == null) {
+ return "null";
+ }
+ if (v instanceof Boolean) {
+ return v.toString();
+ }
+ if (v instanceof String) {
+ return quote((String) v);
+ }
+ if (v instanceof Object[]) {
+ return Arrays.stream((Object[]) v)
+ .map(ArgProbe::jsonOf)
+ .collect(Collectors.joining(",", "[", "]"));
+ }
+ if (v instanceof Enum<?>) {
+ Enum<?> e = (Enum<?>) v;
+ return "{\"class\":\"" + e.getDeclaringClass().getName()
+ + "\",\"constant\":\"" + e.name() + "\"}";
+ }
+ return "{\"opaque\":\"" + v.getClass().getName() + "\"}";
+ }
+}
diff --git a/tools/gen_arg_table.py b/tools/gen_arg_table.py
new file mode 100644
index 0000000..d074ead
--- /dev/null
+++ b/tools/gen_arg_table.py
@@ -0,0 +1,309 @@
+#!/usr/bin/env python3
+"""
+kotlin-proxy CLI argument table generator.
+
+KGP hands the compiler a populated K2JVMCompilerArguments object; to drive a
+real (native-image) kotlinc from it we must translate that object back into
+CLI tokens. Hand-maintaining that table is tedious and breaks on every
+Kotlin bump, so this generates it.
+
+Sources:
+ - The arguments class itself, read by tools/ArgProbe.java (compiled on the
+ fly against the defs jars and run once): one JSON object per
+ @Argument-annotated field - the CLI flag (with dash, exactly as the
+ compiler's own CLI parser reads it), the getter, the element delimiter,
+ and the default left by the no-arg constructor. The class files are
+ never parsed by this tool; the class involvement is one small reflection
+ probe, because the flag names are NOT derivable from the descriptions
+ below (e.g. -Xdebug -> enableDebugMode, -Xadd-modules ->
+ additionalJavaModules).
+ - kotlin-compiler-arguments.json, shipped inside the
+ `kotlin-compiler-arguments-description` Maven artifact of the same
+ version: used only for a coverage cross-check - every argument in the
+ commonToolArguments/commonCompilerArguments/jvmCompilerArguments levels
+ should map onto a field, and vice versa.
+
+Rendering: only values differing from the field defaults are emitted - the
+native-image compiler shares kotlinc's defaults, so a default value needs no
+token. Booleans are flags (present means true); a boolean whose default is
+TRUE cannot spell false on the CLI and is reported (the token is omitted -
+the script's default then applies, as with kotlinc itself). List elements
+are joined into one token only when the annotation delimiter is
+<path_separator> (classpath and friends); any other list renders one token
+per element.
+
+Usage:
+ python3 tools/gen_arg_table.py \
+ --args-description vendor/kotlin-compiler-arguments-description-2.4.21.jar \
+ --defs jars/defs.txt \
+ --out stubs/gen/kotlin/proxy/GeneratedJvmArguments.java
+"""
+
+import argparse
+import json
+import os
+import subprocess
+import sys
+import tempfile
+import zipfile
+
+JSON_RESOURCE = "kotlin-compiler-arguments.json"
+DEFAULT_GROUPS = ["commonToolArguments", "commonCompilerArguments",
+ "jvmCompilerArguments"]
+PROBE = os.path.join(os.path.dirname(os.path.abspath(__file__)),
+ "ArgProbe.java")
+KIND_ORDER = {"bool": 0, "string": 1, "list": 2, "enum": 3}
+
+
+# ----------------------------------------------------------------------
+# probe
+# ----------------------------------------------------------------------
+def run_probe(def_jars, cls):
+ """Compile and run tools/ArgProbe against the defs jars.
+ Returns ({field: record}, probe_stderr_lines)."""
+ cp = os.pathsep.join(def_jars)
+ with tempfile.TemporaryDirectory() as td:
+ r = subprocess.run(["javac", "-nowarn", "-proc:none", "-cp", cp,
+ "-d", td, PROBE],
+ capture_output=True, text=True)
+ if r.returncode != 0:
+ sys.exit(f"error: ArgProbe does not compile:\n{r.stderr}")
+ r = subprocess.run(["java", "-cp", td + os.pathsep + cp,
+ "tools.ArgProbe", cls],
+ capture_output=True, text=True)
+ if r.returncode != 0:
+ sys.exit(f"error: ArgProbe failed:\n{r.stderr}")
+ out = {}
+ for line in r.stdout.splitlines():
+ if not line.strip():
+ continue
+ rec = json.loads(line)
+ out[rec["field"]] = rec
+ return out, [l for l in r.stderr.splitlines() if l.strip()]
+
+
+# ----------------------------------------------------------------------
+# arguments-description JSON (coverage cross-check only)
+# ----------------------------------------------------------------------
+def load_json(jar):
+ with zipfile.ZipFile(jar) as z:
+ with z.open(JSON_RESOURCE) as fh:
+ return json.load(fh)
+
+
+def group_args(data, group_names):
+ """All argument entries living in the named levels (recursive)."""
+ out = []
+
+ def walk(node):
+ if node.get("name") in group_names:
+ out.extend(node.get("arguments", []))
+ for c in node.get("nestedLevels", []):
+ walk(c)
+ walk(data["topLevel"])
+ return out
+
+
+# ----------------------------------------------------------------------
+# rendering
+# ----------------------------------------------------------------------
+def java_escape(s):
+ return s.replace("\\", "\\\\").replace('"', '\\"')
+
+
+def getter_name(field):
+ return "get" + field[0].upper() + field[1:]
+
+
+def join_notes(a, b):
+ return f"{a}; {b}" if a and b else (a or b)
+
+
+def render(records, notes):
+ """-> list of {'kind','flag','stmt','note'} in emission order."""
+ entries = []
+ for field, rec in records.items():
+ flag = rec["value"]
+ if rec["removedVersion"]:
+ notes.append(("skip", f"{flag} ({field}): removed in "
+ f"{rec['removedVersion']}"))
+ continue
+ dep_note = (f"deprecated since {rec['deprecatedVersion']}"
+ if rec["deprecatedVersion"] else None)
+ default = rec["default"]
+ g = f"a.{getter_name(field)}()"
+
+ if rec["type"] == "bool":
+ if default is True:
+ notes.append(("warn", f"{flag} ({field}): boolean default is "
+ f"true - a false value cannot be "
+ f"spelled on the CLI, token omitted"))
+ entries.append(dict(kind="bool", flag=flag,
+ stmt=f'if ({g}) cmd.add("{flag}");',
+ note=dep_note))
+ elif rec["type"] == "Boolean":
+ entries.append(dict(
+ kind="bool", flag=flag,
+ stmt=(f'{{\n'
+ f' Boolean v = {g};\n'
+ f' if (v != null && v) cmd.add("{flag}");\n'
+ f' }}'),
+ note=dep_note))
+ elif rec["type"] == "string":
+ if default is None:
+ stmt = f'if ({g} != null) cmd.add("{flag}=" + {g});'
+ elif isinstance(default, str):
+ stmt = (f'if (!java.util.Objects.equals({g}, '
+ f'"{java_escape(default)}")) '
+ f'cmd.add("{flag}=" + {g});')
+ else:
+ notes.append(("warn", f"{flag} ({field}): unexpected default "
+ f"{default!r}, rendering non-null"))
+ stmt = f'if ({g} != null) cmd.add("{flag}=" + {g});'
+ entries.append(dict(kind="string", flag=flag, stmt=stmt,
+ note=dep_note))
+ elif rec["type"] == "enum":
+ if default is None:
+ stmt = (f'if ({g} != null) '
+ f'cmd.add("{flag}=" + String.valueOf({g}));')
+ elif isinstance(default, dict) and "constant" in default:
+ stmt = (f'if (!java.util.Objects.equals({g}, '
+ f'{default["class"]}.{default["constant"]})) '
+ f'cmd.add("{flag}=" + String.valueOf({g}));')
+ else:
+ notes.append(("warn", f"{flag} ({field}): unrecognized enum "
+ f"default {default!r}, rendering "
+ f"non-null"))
+ stmt = (f'if ({g} != null) '
+ f'cmd.add("{flag}=" + String.valueOf({g}));')
+ entries.append(dict(
+ kind="enum", flag=flag, stmt=stmt,
+ note=join_notes(dep_note, "String.valueOf is the CLI spelling")))
+ elif rec["type"] == "stringArray":
+ if rec["delimiter"] == "<path_separator>":
+ stmt = (f'if ({g}.length > 0) cmd.add('
+ f'"{flag}=" + String.join(java.io.File.pathSeparator, '
+ f'{g}));')
+ note = "elements joined by File.pathSeparator"
+ else:
+ stmt = f'for (String v : {g}) cmd.add("{flag}=" + v);'
+ note = None
+ entries.append(dict(kind="list", flag=flag, stmt=stmt,
+ note=join_notes(dep_note, note)))
+ else:
+ notes.append(("skip", f"{flag} ({field}): non-renderable type "
+ f"{rec['type']}"))
+ entries.sort(key=lambda e: (KIND_ORDER[e["kind"]], e["flag"]))
+ return entries
+
+
+# ----------------------------------------------------------------------
+# driver
+# ----------------------------------------------------------------------
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--args-description", required=True,
+ help="kotlin-compiler-arguments-description-<v>.jar")
+ ap.add_argument("--defs", required=True,
+ help="definition jar list file (one path per line)")
+ ap.add_argument("--class", dest="cls", default=(
+ "org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments"))
+ ap.add_argument("--out", required=True)
+ ap.add_argument("--groups", default=",".join(DEFAULT_GROUPS),
+ help="JSON level names whose arguments should map onto "
+ "class fields (coverage cross-check)")
+ args = ap.parse_args()
+
+ def_jars = []
+ with open(args.defs) as fh:
+ for line in fh:
+ line = line.strip()
+ if line and not line.startswith("#"):
+ def_jars.append(line)
+
+ records, probe_notes = run_probe(def_jars, args.cls)
+ jdata = load_json(args.args_description)
+ groups = [g for g in args.groups.split(",") if g]
+ notes = []
+ entries = render(records, notes)
+
+ # coverage both directions (probe names incl. short/deprecated aliases)
+ probe_names = set()
+ for rec in records.values():
+ for k in ("value", "shortName", "deprecatedName"):
+ if rec[k]:
+ probe_names.add(rec[k].lstrip("-"))
+ jnames = {a["name"].lstrip("-")
+ for a in group_args(jdata, groups)}
+ missing = sorted(jnames - probe_names)
+ unlisted = sorted(probe_names - jnames)
+
+ d = os.path.dirname(args.out)
+ if d:
+ os.makedirs(d, exist_ok=True)
+ jar_name = os.path.basename(args.args_description)
+ counts = {}
+ for e in entries:
+ counts[e["kind"]] = counts.get(e["kind"], 0) + 1
+
+ L = []
+ L.append("// AUTO-GENERATED by tools/gen_arg_table.py - do not edit.")
+ L.append(f"// Sources: {args.cls} and its superclasses (defs jars),")
+ L.append("// read by tools/ArgProbe.java at build time, plus")
+ L.append(f"// {jar_name} ({JSON_RESOURCE}) for cross-checks.")
+ L.append("// Regenerate after a Kotlin bump; `make` rebuilds this.")
+ L.append("package kotlin.proxy;")
+ L.append("")
+ L.append("import java.util.ArrayList;")
+ L.append("import java.util.List;")
+ L.append("")
+ L.append(f"import {args.cls};")
+ L.append("")
+ L.append("/**")
+ L.append(" * Translates the daemon-populated arguments object into kotlinc")
+ L.append(" * CLI tokens. Only values differing from the field defaults are")
+ L.append(" * emitted: the native-image compiler shares kotlinc's defaults,")
+ L.append(" * so a default value needs no token. Booleans are flags (present")
+ L.append(" * means true); list elements are joined into one token only when")
+ L.append(" * the annotation delimiter is <path_separator> (classpath and")
+ L.append(" * friends), any other list renders one token per element.")
+ L.append(" */")
+ L.append("final class GeneratedJvmArguments {")
+ L.append("")
+ L.append(f" static List<String> buildCommandArgs({args.cls} a) {{")
+ L.append(" ArrayList<String> cmd = new ArrayList<String>();")
+ titles = {"bool": "// boolean flags (present means true)",
+ "string": "// single-value arguments",
+ "list": "// list arguments",
+ "enum": "// enum arguments (String.valueOf is the CLI spelling)"}
+ last_kind = None
+ for e in entries:
+ if e["kind"] != last_kind:
+ L.append("")
+ L.append(f" {titles[e['kind']]}")
+ last_kind = e["kind"]
+ note = f" // {e['note']}" if e.get("note") else ""
+ L.append(f" {e['stmt']}{note}")
+ L.append("")
+ L.append(" return cmd;")
+ L.append(" }")
+ L.append("}")
+ with open(args.out, "w") as fh:
+ fh.write("\n".join(L) + "\n")
+
+ print(f"arg table: {len(entries)} CLI arguments "
+ f"(bool {counts.get('bool', 0)}, string "
+ f"{counts.get('string', 0)}, list {counts.get('list', 0)}, "
+ f"enum {counts.get('enum', 0)}) -> {args.out}", file=sys.stderr)
+ for kind, text in probe_notes + notes:
+ print(f"{kind}: {text}", file=sys.stderr)
+ if missing:
+ print(f"JSON args in groups {groups} with no class field: {missing}",
+ file=sys.stderr)
+ if unlisted:
+ print(f"class fields not present in JSON: {unlisted}",
+ file=sys.stderr)
+
+
+if __name__ == "__main__":
+ main()