diff options
Diffstat (limited to 'tools')
| -rw-r--r-- | tools/ArgProbe.java | 161 | ||||
| -rw-r--r-- | tools/gen_arg_table.py | 309 |
2 files changed, 470 insertions, 0 deletions
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() |
