1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
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()
|