#!/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 (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"] == "": 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-.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 (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 buildCommandArgs({args.cls} a) {{") L.append(" ArrayList cmd = new ArrayList();") 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()