ruby-anything 0.2.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,510 +1,510 @@
1
- """Java support for the polyglot adapter (lang_kotlin.py reuses the driver generator below).
2
-
3
- Analysis: methods of top-level classes. `public static` methods are recordable functions; other
4
- non-private methods are listed with owner=<class> (kind=method, not recordable).
5
- Driver: all .java files of the target are compiled with javac into `work/classes` together with a
6
- generated `PpDriver` (default package) that carries a tiny JSON parser/encoder, decodes args by
7
- declared parameter type, calls the method directly and maps Throwable to a raise outcome.
8
- Spring Boot / Maven / Gradle projects: only the target file and the project files it references
9
- (transitively) are compiled, test sources are skipped, and dependency jars found in the project
10
- (target/dependency, build/dependency, lib, libs) go on the classpath. Without jars, framework
11
- imports and annotations (@Service, @Autowired, @Transactional, ...) are blanked in the /tmp copy
12
- (offsets and line numbers kept), so plain business logic inside Spring classes still compiles.
13
- Public methods of classes with no instance fields and no constructor arguments (typical
14
- stateless @Service/@Component helpers) are recorded via `new Cls().method(...)`.
15
- """
16
- import os
17
- import re
18
- import subprocess
19
-
20
- from harness import match_brace, unit_record
21
-
22
- EXTS = {".java"}
23
- THROW = r"\bthrow\b"
24
- JVM_FLAGS = ["-Xshare:off", "-Xmx512m", "-XX:+UseSerialGC", "-XX:-UsePerfData"]
25
- JAVAC_FLAGS = ["-J-Xmx512m", "-J-XX:+UseSerialGC", "-J-Xshare:off", "-encoding", "UTF-8", "-proc:none", "-nowarn", "-Xlint:none"]
26
- KEYWORDS = {"if", "else", "for", "while", "switch", "catch", "return", "new", "throw", "synchronized", "do", "try", "case"}
27
-
28
-
29
- def runtime():
30
- err = subprocess.run(["java", "-version"], capture_output=True, text=True).stderr
31
- return err.split("\n")[0].replace('"', "").strip() or "java"
32
-
33
-
34
- def blank(text):
35
- """Copy of text with comment and string/char contents replaced by spaces (same offsets and newlines)."""
36
- out, i, n = list(text), 0, len(text)
37
-
38
- def wipe(a, b):
39
- for k in range(a, min(b, n)):
40
- if out[k] != "\n":
41
- out[k] = " "
42
- while i < n:
43
- if text.startswith("//", i):
44
- j = text.find("\n", i)
45
- j = n if j < 0 else j
46
- wipe(i, j)
47
- i = j
48
- elif text.startswith("/*", i):
49
- j = text.find("*/", i + 2)
50
- j = n if j < 0 else j + 2
51
- wipe(i, j)
52
- i = j
53
- elif text.startswith('"""', i):
54
- j = text.find('"""', i + 3)
55
- j = n if j < 0 else j
56
- wipe(i + 3, j)
57
- i = j + 3
58
- elif text[i] in "\"'":
59
- q, j = text[i], i + 1
60
- while j < n and text[j] != q and text[j] != "\n":
61
- j += 2 if text[j] == "\\" else 1
62
- wipe(i + 1, j)
63
- i = j + 1
64
- else:
65
- i += 1
66
- return "".join(out)
67
-
68
-
69
- def split_top(raw, sep=","):
70
- parts, depth, cur = [], 0, ""
71
- for c in raw:
72
- depth += c in "<(["
73
- depth -= c in ">)]"
74
- if c == sep and depth == 0:
75
- parts.append(cur)
76
- cur = ""
77
- else:
78
- cur += c
79
- return [p.strip() for p in parts + [cur] if p.strip()]
80
-
81
-
82
- def parse_params(raw):
83
- params = []
84
- for part in split_top(raw):
85
- part = re.sub(r"@\w+(\([^)]*\))?\s*", "", part)
86
- part = re.sub(r"\bfinal\s+", "", part).strip()
87
- m = re.match(r"(.+?)\s+(\w+)$", part, re.S)
88
- if not m:
89
- continue
90
- typ = re.sub(r"\s+", " ", m.group(1)).strip()
91
- params.append({"name": m.group(2), "annotation": typ, "default": None,
92
- "kind": "varargs" if typ.endswith("...") else "positional"})
93
- return params
94
-
95
-
96
- METH_RE = re.compile(r"((?:@\w+(?:\([^)]*\))?\s+)*)((?:(?:public|protected|private|static|final|synchronized|abstract|native|strictfp|default)\s+)*)"
97
- r"(<[^>]*>\s*)?([\w.]+(?:<[^;{}()]*?>)?(?:\s*\[\s*\])*)\s+(\w+)\s*\(([^()]*)\)\s*(?:throws\s+[\w.,\s]+)?\{")
98
- CLASS_RE = re.compile(r"\b(?:class|interface|enum|record)\s+(\w+)[^{;]*\{")
99
-
100
-
101
- def analyze_file(rel, text):
102
- clean = blank(text)
103
- units = []
104
- for cm in CLASS_RE.finditer(clean):
105
- # only top-level classes: brace depth 0 before the keyword
106
- if clean.count("{", 0, cm.start()) != clean.count("}", 0, cm.start()):
107
- continue
108
- cls, body_open = cm.group(1), cm.end() - 1
109
- body_end = match_brace(text, body_open)
110
- body = clean[body_open + 1:body_end]
111
- newable = constructible(cm.group(0), body, cls)
112
- for m in METH_RE.finditer(body):
113
- mods = m.group(2).split()
114
- if m.group(5) in KEYWORDS or m.group(3) or "private" in mods:
115
- continue # control flow, generic methods, private methods
116
- if body.count("{", 0, m.start()) != body.count("}", 0, m.start()):
117
- continue # not directly inside the class body
118
- params = parse_params(m.group(6))
119
- if any(p["kind"] == "varargs" for p in params):
120
- continue
121
- open_brace = body_open + 1 + m.end() - 1
122
- static = "static" in mods
123
- instance = not static and newable and "public" in mods and "abstract" not in mods
124
- unit = unit_record(rel, cls, m.group(5), body_open + 1 + m.start(), match_brace(text, open_brace), text,
125
- params, re.sub(r"\s+", "", m.group(4)), THROW,
126
- owner=None if static or instance else cls)
127
- if instance:
128
- unit["instance"] = True
129
- units.append(unit)
130
- return units
131
-
132
-
133
- def constructible(decl, body, cls):
134
- """Plain class, no instance fields, only a no-arg (or implicit) public constructor."""
135
- if not re.search(r"\bclass\b", decl) or re.search(r"\babstract\b", decl):
136
- return False
137
- depth, top = 0, []
138
- for c in body: # text directly inside the class body
139
- if c == "{":
140
- depth += 1
141
- top.append(";")
142
- elif c == "}":
143
- depth -= 1
144
- elif depth == 0:
145
- top.append(c)
146
- for stmt in "".join(top).split(";"):
147
- stmt = re.sub(r"@\w+(\([^)]*\))?", "", stmt).strip()
148
- head = stmt.split("=", 1)[0]
149
- if "(" in head or not head or re.search(r"\bstatic\b", head):
150
- continue
151
- if re.fullmatch(r"((public|protected|private|final|transient|volatile)\s+)*[\w.<>,\[\]?\s]+\s+\w+\s*", head):
152
- return False # instance field (e.g. an injected repository)
153
- for ctor in re.finditer(r"((?:public|protected|private)\s+)?\b" + cls + r"\s*\(([^()]*)\)\s*(?:throws[^{]*)?\{", body):
154
- if ctor.group(2).strip() or (ctor.group(1) or "").strip() != "public":
155
- return False
156
- return True
157
-
158
-
159
- # ------------------------------------------------------------------ generated driver (shared with Kotlin)
160
- PRIMS = {"int": "ppInt({x})", "long": "ppLong({x})", "short": "(short)ppInt({x})", "byte": "(byte)ppInt({x})",
161
- "float": "(float)ppDouble({x})", "double": "ppDouble({x})", "boolean": "ppBool({x})", "char": "ppChar({x})"}
162
- BOXES = {"Integer": "int", "Long": "long", "Short": "short", "Byte": "byte", "Float": "float", "Double": "double",
163
- "Boolean": "boolean", "Character": "char"}
164
-
165
-
166
- def dec(t, x, helpers):
167
- """Java expression decoding the parsed-JSON Object expression `x` into declared type `t`."""
168
- t = re.sub(r"\s+", "", t).replace("java.lang.", "")
169
- if t in PRIMS:
170
- return PRIMS[t].format(x=x)
171
- if t in BOXES:
172
- return f"({x}==null?null:({t})({PRIMS[BOXES[t]].format(x=x)}))"
173
- if t == "String":
174
- return f"ppStr({x})"
175
- if t in helpers:
176
- return f"{helpers[t][0]}({x})"
177
- if t.endswith("[]"):
178
- elem = t[:-2]
179
- inner = dec(elem, "l.get(i)", helpers)
180
- base, dims = elem.split("[]")[0], "[]" * elem.count("[]")
181
- name = f"d{len(helpers)}"
182
- helpers[t] = (name, f"static {t} {name}(Object o){{ if(o==null) return null; List<Object> l=ppList(o); "
183
- f"{t} r=new {base}[l.size()]{dims}; for(int i=0;i<r.length;i++) r[i]={inner}; return r; }}")
184
- return f"{name}({x})"
185
- m = re.fullmatch(r"(?:java\.util\.)?(List|ArrayList|Collection)<(.+)>", t)
186
- if m:
187
- elem = m.group(2)
188
- inner = dec(elem, "e", helpers)
189
- name = f"d{len(helpers)}"
190
- helpers[t] = (name, f"static {t} {name}(Object o){{ if(o==null) return null; {t} r=new java.util.ArrayList<{elem}>(); "
191
- f"for(Object e: ppList(o)) r.add({inner}); return r; }}")
192
- return f"{name}({x})"
193
- raise SystemExit(f"unsupported parameter type {t!r}: only primitives, boxed types, String, arrays and lists of those can be recorded")
194
-
195
-
196
- DRIVER = r'''import java.io.*;
197
- import java.nio.charset.StandardCharsets;
198
- import java.nio.file.*;
199
- import java.util.*;
200
-
201
- @SuppressWarnings("unchecked")
202
- public class PpDriver {
203
- static String S; static int P;
204
- static void ws() { while (P < S.length() && Character.isWhitespace(S.charAt(P))) P++; }
205
- static Object parse() {
206
- ws(); char c = S.charAt(P);
207
- if (c == '{') {
208
- P++; Map<String, Object> m = new LinkedHashMap<>(); ws();
209
- if (S.charAt(P) == '}') { P++; return m; }
210
- while (true) { ws(); String k = (String) parse(); ws(); P++; m.put(k, parse()); ws(); if (S.charAt(P++) == '}') return m; }
211
- }
212
- if (c == '[') {
213
- P++; List<Object> l = new ArrayList<>(); ws();
214
- if (S.charAt(P) == ']') { P++; return l; }
215
- while (true) { l.add(parse()); ws(); if (S.charAt(P++) == ']') return l; }
216
- }
217
- if (c == '"') {
218
- P++; StringBuilder b = new StringBuilder();
219
- while (true) {
220
- char d = S.charAt(P++);
221
- if (d == '"') return b.toString();
222
- if (d != '\\') { b.append(d); continue; }
223
- char e = S.charAt(P++);
224
- switch (e) {
225
- case 'n': b.append('\n'); break;
226
- case 't': b.append('\t'); break;
227
- case 'r': b.append('\r'); break;
228
- case 'b': b.append('\b'); break;
229
- case 'f': b.append('\f'); break;
230
- case 'u': b.append((char) Integer.parseInt(S.substring(P, P + 4), 16)); P += 4; break;
231
- default: b.append(e);
232
- }
233
- }
234
- }
235
- if (S.startsWith("true", P)) { P += 4; return Boolean.TRUE; }
236
- if (S.startsWith("false", P)) { P += 5; return Boolean.FALSE; }
237
- if (S.startsWith("null", P)) { P += 4; return null; }
238
- int st = P;
239
- while (P < S.length() && "+-0123456789.eE".indexOf(S.charAt(P)) >= 0) P++;
240
- String n = S.substring(st, P);
241
- if (n.matches("-?\\d+")) { try { return Long.parseLong(n); } catch (NumberFormatException e) { return Double.parseDouble(n); } }
242
- return Double.parseDouble(n);
243
- }
244
-
245
- static int ppInt(Object o) { if (o instanceof Number) return ((Number) o).intValue(); throw new ClassCastException("expected int, got " + o); }
246
- static long ppLong(Object o) { if (o instanceof Number) return ((Number) o).longValue(); throw new ClassCastException("expected long, got " + o); }
247
- static boolean ppBool(Object o) { if (o instanceof Boolean) return (Boolean) o; throw new ClassCastException("expected boolean, got " + o); }
248
- static char ppChar(Object o) { if (o instanceof String && ((String) o).length() == 1) return ((String) o).charAt(0); throw new ClassCastException("expected char, got " + o); }
249
- static String ppStr(Object o) { if (o == null || o instanceof String) return (String) o; throw new ClassCastException("expected String, got " + o); }
250
- static List<Object> ppList(Object o) { if (o instanceof List) return (List<Object>) o; throw new ClassCastException("expected array, got " + o); }
251
- static double ppDouble(Object o) {
252
- if (o instanceof Number) return ((Number) o).doubleValue();
253
- if (o instanceof Map && ((Map<String, Object>) o).get("$float") instanceof String) {
254
- String s = (String) ((Map<String, Object>) o).get("$float");
255
- switch (s) {
256
- case "nan": return Double.NaN;
257
- case "inf": return Double.POSITIVE_INFINITY;
258
- case "-inf": return Double.NEGATIVE_INFINITY;
259
- case "-0.0": return -0.0;
260
- default: return Double.parseDouble(s);
261
- }
262
- }
263
- throw new ClassCastException("expected double, got " + o);
264
- }
265
-
266
- static void quote(String s, StringBuilder b) {
267
- b.append('"');
268
- for (int i = 0; i < s.length(); i++) {
269
- char c = s.charAt(i);
270
- if (c == '"') b.append("\\\"");
271
- else if (c == '\\') b.append("\\\\");
272
- else if (c == '\n') b.append("\\n");
273
- else if (c == '\r') b.append("\\r");
274
- else if (c == '\t') b.append("\\t");
275
- else if (c < 0x20) b.append(String.format("\\u%04x", (int) c));
276
- else b.append(c);
277
- }
278
- b.append('"');
279
- }
280
- static void enc(Object v, StringBuilder b) {
281
- if (v == null) { b.append("null"); }
282
- else if (v instanceof Double || v instanceof Float) {
283
- double d = v instanceof Float ? Double.parseDouble(v.toString()) : (Double) v;
284
- if (Double.isNaN(d)) b.append("{\"$float\":\"nan\"}");
285
- else if (Double.isInfinite(d)) b.append(d > 0 ? "{\"$float\":\"inf\"}" : "{\"$float\":\"-inf\"}");
286
- else if (d == 0 && 1 / d < 0) b.append("{\"$float\":\"-0.0\"}");
287
- else if (d == Math.rint(d) && Math.abs(d) > 9007199254740992.0) b.append("{\"$float\":\"").append(Double.toString(d)).append("\"}");
288
- else b.append(Double.toString(d));
289
- }
290
- else if (v instanceof Number || v instanceof Boolean) b.append(v.toString());
291
- else if (v instanceof String || v instanceof Character) quote(v.toString(), b);
292
- else if (v instanceof Map) {
293
- b.append('{'); boolean first = true;
294
- for (Map.Entry<?, ?> e : ((Map<?, ?>) v).entrySet()) { if (!first) b.append(','); first = false; quote(String.valueOf(e.getKey()), b); b.append(':'); enc(e.getValue(), b); }
295
- b.append('}');
296
- }
297
- else if (v instanceof Collection) {
298
- b.append('['); boolean first = true;
299
- for (Object o : (Collection<?>) v) { if (!first) b.append(','); first = false; enc(o, b); }
300
- b.append(']');
301
- }
302
- else if (v.getClass().isArray()) {
303
- b.append('['); int n = java.lang.reflect.Array.getLength(v);
304
- for (int i = 0; i < n; i++) { if (i > 0) b.append(','); enc(java.lang.reflect.Array.get(v, i), b); }
305
- b.append(']');
306
- }
307
- else quote(v.toString(), b);
308
- }
309
-
310
- static final String FILE = "__FILE__";
311
- __HELPERS__
312
- __FIELDS__
313
- static Object call() throws Throwable {
314
- __CALL__
315
- }
316
-
317
- static Map<String, Object> raise(String type, String msg, int line) {
318
- Map<String, Object> o = new LinkedHashMap<>();
319
- o.put("kind", "raise"); o.put("type", type); o.put("message", msg == null ? "" : msg);
320
- if (line > 0) o.put("raise_line", line);
321
- return o;
322
- }
323
- static Map<String, Object> run() {
324
- try {
325
- Map<String, Object> o = new LinkedHashMap<>();
326
- o.put("kind", "return"); o.put("value", call());
327
- return o;
328
- } catch (Throwable t) {
329
- int line = 0;
330
- for (StackTraceElement f : t.getStackTrace()) { if (FILE.equals(f.getFileName())) { line = f.getLineNumber(); break; } }
331
- return raise(t.getClass().getSimpleName(), t.getMessage(), line);
332
- }
333
- }
334
- static void write(Object v) throws IOException {
335
- StringBuilder b = new StringBuilder(); enc(v, b);
336
- Files.write(Paths.get(System.getenv("PP_RESULT")), b.toString().getBytes(StandardCharsets.UTF_8));
337
- }
338
-
339
- public static void main(String[] argv) throws Exception {
340
- S = new String(System.in.readAllBytes(), StandardCharsets.UTF_8); P = 0;
341
- Map<String, Object> req = (Map<String, Object>) parse();
342
- List<Object> args = (List<Object>) req.get("args");
343
- try {
344
- __DECODE__
345
- } catch (Throwable t) {
346
- Map<String, Object> o = new LinkedHashMap<>(); o.put("outcome", raise("TypeError", String.valueOf(t.getMessage()), 0));
347
- write(o); return;
348
- }
349
- Map<String, Object> out = new LinkedHashMap<>();
350
- if ("bench".equals(req.get("mode"))) {
351
- int n = ((Number) req.get("iterations")).intValue(); List<Object> samples = new ArrayList<>();
352
- for (int i = 0; i < n; i++) { long t0 = System.nanoTime(); run(); samples.add(System.nanoTime() - t0); }
353
- out.put("samples_ns", samples);
354
- } else out.put("outcome", run());
355
- write(out);
356
- System.out.flush(); System.err.flush();
357
- System.exit(0);
358
- }
359
- }
360
- '''
361
-
362
-
363
- def driver_source(jtypes, call, void, file_name):
364
- helpers = {}
365
- decode = [f"a{i} = {dec(t, f'(args.size() > {i} ? args.get({i}) : null)', helpers)};" for i, t in enumerate(jtypes)]
366
- fields = [f" static {t} a{i};" for i, t in enumerate(jtypes)]
367
- body = f" {call};\n return null;" if void else f" return {call};"
368
- return DRIVER.replace("__HELPERS__", "\n".join(" " + h[1] for h in helpers.values())) \
369
- .replace("__FIELDS__", "\n".join(fields)).replace("__DECODE__", "\n".join(" " + d for d in decode)) \
370
- .replace("__CALL__", body).replace("__FILE__", file_name)
371
-
372
-
373
- def source_files(root, ext):
374
- out = []
375
- for base, dirs, names in os.walk(root):
376
- dirs[:] = sorted(d for d in dirs if d not in {".git", "build", "target", "out", "bin", "node_modules"}
377
- and not d.startswith(".") and not (d == "test" and os.path.basename(base) == "src"))
378
- out += [os.path.join(base, n) for n in sorted(names) if n.endswith(ext) and not re.search(r"Tests?\.(java|kt)$", n)]
379
- return out
380
-
381
-
382
- JDK_JAVAX = ("javax.crypto", "javax.net", "javax.security", "javax.xml", "javax.naming", "javax.sql", "javax.script",
383
- "javax.management", "javax.annotation.processing", "javax.lang", "javax.tools", "javax.imageio", "javax.sound")
384
- JDK_ANNOTATIONS = {"Override", "Deprecated", "SuppressWarnings", "FunctionalInterface", "SafeVarargs"}
385
- JAR_DIRS = ("target/dependency", "build/dependency", "lib", "libs")
386
-
387
-
388
- def project_jars(src):
389
- jars = []
390
- for d in JAR_DIRS:
391
- base = os.path.join(src, d)
392
- if os.path.isdir(base):
393
- jars += sorted(os.path.join(base, n) for n in os.listdir(base) if n.endswith(".jar"))
394
- return os.pathsep.join(jars)
395
-
396
-
397
- def top_types(clean):
398
- found = {m.group(1) for m in CLASS_RE.finditer(clean)
399
- if clean.count("{", 0, m.start()) == clean.count("}", 0, m.start())}
400
- return found | set(re.findall(r"@interface\s+(\w+)", clean))
401
-
402
-
403
- def closure(files, target):
404
- """target plus the project files it references by type name, transitively."""
405
- clean = {f: blank(open(f, encoding="utf-8", errors="replace").read()) for f in files}
406
- owner = {}
407
- for f, c in clean.items():
408
- for t in top_types(c) | {os.path.splitext(os.path.basename(f))[0]}:
409
- owner.setdefault(t, set()).add(f)
410
- seen, todo = set(), [target]
411
- while todo:
412
- f = todo.pop()
413
- if f in seen or f not in clean:
414
- continue
415
- seen.add(f)
416
- for tok in set(re.findall(r"\b[A-Z]\w*\b", clean[f])):
417
- todo += owner.get(tok, ())
418
- return sorted(seen)
419
-
420
-
421
- def strip_framework(text, project_pkgs, project_types):
422
- """Blank imports and annotations the JDK can't resolve (offsets and newlines preserved)."""
423
- clean, out = blank(text), list(text)
424
-
425
- def wipe(a, b):
426
- for k in range(a, b):
427
- if out[k] != "\n":
428
- out[k] = " "
429
- for m in re.finditer(r"^[ \t]*import\s+(static\s+)?([\w.]+?)(\.\*)?\s*;", clean, re.M):
430
- name = m.group(2)
431
- pkg = name if m.group(3) else name.rsplit(".", 1)[0]
432
- if m.group(1) and not m.group(3):
433
- pkg = pkg.rsplit(".", 1)[0]
434
- if name.startswith("java.") or name.startswith(JDK_JAVAX) or pkg in project_pkgs \
435
- or any(pkg.startswith(p + ".") for p in project_pkgs):
436
- continue
437
- wipe(m.start(), m.end())
438
- for m in re.finditer(r"@(?!interface\b)([\w.]+)", clean):
439
- simple = m.group(1).rsplit(".", 1)[-1]
440
- if simple in JDK_ANNOTATIONS or simple in project_types:
441
- continue
442
- end = m.end()
443
- rest = re.match(r"\s*\(", clean[end:])
444
- if rest:
445
- depth, j = 0, end + rest.end() - 1
446
- while j < len(clean):
447
- depth += clean[j] == "("
448
- depth -= clean[j] == ")"
449
- j += 1
450
- if depth == 0:
451
- break
452
- end = j
453
- wipe(m.start(), end)
454
- return "".join(out)
455
-
456
-
457
- def stage_sources(src, rel, work):
458
- """(files to compile, classpath). Without dependency jars the files are rewritten into work/srcs."""
459
- needed = closure([os.path.normpath(f) for f in source_files(src, ".java")], os.path.normpath(os.path.join(src, rel)))
460
- jars = project_jars(src)
461
- if jars:
462
- return needed, jars
463
- texts = {f: open(f, encoding="utf-8", errors="replace").read() for f in needed}
464
- pkgs = set()
465
- for t in texts.values():
466
- m = re.search(r"^\s*package\s+([\w.]+)\s*;", blank(t), re.M)
467
- if m:
468
- pkgs.add(m.group(1))
469
- types = {t for x in texts.values() for t in top_types(blank(x))}
470
- out = []
471
- for i, (f, t) in enumerate(texts.items()):
472
- d = os.path.join(work, "srcs", str(i))
473
- os.makedirs(d, exist_ok=True)
474
- path = os.path.join(d, os.path.basename(f))
475
- open(path, "w", encoding="utf-8").write(strip_framework(t, pkgs, types))
476
- out.append(path)
477
- return out, ""
478
-
479
-
480
- def compile_driver(work, driver, classpath, java_files):
481
- """javac the generated driver (plus java_files) into work/classes; return the java argv."""
482
- os.makedirs(os.path.join(work, "drv"), exist_ok=True)
483
- path = os.path.join(work, "drv", "PpDriver.java")
484
- open(path, "w", encoding="utf-8").write(driver)
485
- classes = os.path.join(work, "classes")
486
- os.makedirs(classes, exist_ok=True)
487
- cp = ["-cp", os.pathsep.join(x for x in (classes, classpath) if x)]
488
- done = subprocess.run(["javac"] + JAVAC_FLAGS + cp + ["-d", classes] + java_files + [path],
489
- capture_output=True, text=True, cwd=work, env=dict(os.environ, HOME=work))
490
- if done.returncode:
491
- raise SystemExit("javac failed. Framework types used outside annotations need their jars in "
492
- "target/dependency (mvn dependency:copy-dependencies):\n" + (done.stderr or done.stdout)[-1500:])
493
- return ["java"] + JVM_FLAGS + ["-cp", os.pathsep.join(x for x in (classes, classpath) if x), "PpDriver"]
494
-
495
-
496
- def prepare(src, rel, unit, work):
497
- header = re.sub(r"@[\w.]+(\s*\([^)]*\))?", "", blank(unit["source"])).split("(", 1)[0]
498
- instance = unit.get("instance")
499
- if unit["kind"] != "function" or not re.search(r"\bpublic\b", header) \
500
- or not (instance or re.search(r"\bstatic\b", header)):
501
- raise SystemExit("only public static methods, or public methods of stateless classes, can be recorded")
502
- text = open(os.path.join(src, rel), encoding="utf-8", errors="replace").read()
503
- pkg = re.search(r"^\s*package\s+([\w.]+)\s*;", text, re.M)
504
- cls = (pkg.group(1) + "." if pkg else "") + unit["module"]
505
- args = ", ".join(f"a{i}" for i in range(len(unit["params"])))
506
- target = f"new {cls}()" if instance else cls
507
- driver = driver_source([p["annotation"] for p in unit["params"]], f"{target}.{unit['name']}({args})",
508
- unit["returns"] == "void", os.path.basename(rel))
509
- files, classpath = stage_sources(src, rel, work)
510
- return compile_driver(work, driver, classpath, files)
1
+ """Java support for the polyglot adapter (lang_kotlin.py reuses the driver generator below).
2
+
3
+ Analysis: methods of top-level classes. `public static` methods are recordable functions; other
4
+ non-private methods are listed with owner=<class> (kind=method, not recordable).
5
+ Driver: all .java files of the target are compiled with javac into `work/classes` together with a
6
+ generated `PpDriver` (default package) that carries a tiny JSON parser/encoder, decodes args by
7
+ declared parameter type, calls the method directly and maps Throwable to a raise outcome.
8
+ Spring Boot / Maven / Gradle projects: only the target file and the project files it references
9
+ (transitively) are compiled, test sources are skipped, and dependency jars found in the project
10
+ (target/dependency, build/dependency, lib, libs) go on the classpath. Without jars, framework
11
+ imports and annotations (@Service, @Autowired, @Transactional, ...) are blanked in the /tmp copy
12
+ (offsets and line numbers kept), so plain business logic inside Spring classes still compiles.
13
+ Public methods of classes with no instance fields and no constructor arguments (typical
14
+ stateless @Service/@Component helpers) are recorded via `new Cls().method(...)`.
15
+ """
16
+ import os
17
+ import re
18
+ import subprocess
19
+
20
+ from harness import match_brace, unit_record
21
+
22
+ EXTS = {".java"}
23
+ THROW = r"\bthrow\b"
24
+ JVM_FLAGS = ["-Xshare:off", "-Xmx512m", "-XX:+UseSerialGC", "-XX:-UsePerfData"]
25
+ JAVAC_FLAGS = ["-J-Xmx512m", "-J-XX:+UseSerialGC", "-J-Xshare:off", "-encoding", "UTF-8", "-proc:none", "-nowarn", "-Xlint:none"]
26
+ KEYWORDS = {"if", "else", "for", "while", "switch", "catch", "return", "new", "throw", "synchronized", "do", "try", "case"}
27
+
28
+
29
+ def runtime():
30
+ err = subprocess.run(["java", "-version"], capture_output=True, text=True).stderr
31
+ return err.split("\n")[0].replace('"', "").strip() or "java"
32
+
33
+
34
+ def blank(text):
35
+ """Copy of text with comment and string/char contents replaced by spaces (same offsets and newlines)."""
36
+ out, i, n = list(text), 0, len(text)
37
+
38
+ def wipe(a, b):
39
+ for k in range(a, min(b, n)):
40
+ if out[k] != "\n":
41
+ out[k] = " "
42
+ while i < n:
43
+ if text.startswith("//", i):
44
+ j = text.find("\n", i)
45
+ j = n if j < 0 else j
46
+ wipe(i, j)
47
+ i = j
48
+ elif text.startswith("/*", i):
49
+ j = text.find("*/", i + 2)
50
+ j = n if j < 0 else j + 2
51
+ wipe(i, j)
52
+ i = j
53
+ elif text.startswith('"""', i):
54
+ j = text.find('"""', i + 3)
55
+ j = n if j < 0 else j
56
+ wipe(i + 3, j)
57
+ i = j + 3
58
+ elif text[i] in "\"'":
59
+ q, j = text[i], i + 1
60
+ while j < n and text[j] != q and text[j] != "\n":
61
+ j += 2 if text[j] == "\\" else 1
62
+ wipe(i + 1, j)
63
+ i = j + 1
64
+ else:
65
+ i += 1
66
+ return "".join(out)
67
+
68
+
69
+ def split_top(raw, sep=","):
70
+ parts, depth, cur = [], 0, ""
71
+ for c in raw:
72
+ depth += c in "<(["
73
+ depth -= c in ">)]"
74
+ if c == sep and depth == 0:
75
+ parts.append(cur)
76
+ cur = ""
77
+ else:
78
+ cur += c
79
+ return [p.strip() for p in parts + [cur] if p.strip()]
80
+
81
+
82
+ def parse_params(raw):
83
+ params = []
84
+ for part in split_top(raw):
85
+ part = re.sub(r"@\w+(\([^)]*\))?\s*", "", part)
86
+ part = re.sub(r"\bfinal\s+", "", part).strip()
87
+ m = re.match(r"(.+?)\s+(\w+)$", part, re.S)
88
+ if not m:
89
+ continue
90
+ typ = re.sub(r"\s+", " ", m.group(1)).strip()
91
+ params.append({"name": m.group(2), "annotation": typ, "default": None,
92
+ "kind": "varargs" if typ.endswith("...") else "positional"})
93
+ return params
94
+
95
+
96
+ METH_RE = re.compile(r"((?:@\w+(?:\([^)]*\))?\s+)*)((?:(?:public|protected|private|static|final|synchronized|abstract|native|strictfp|default)\s+)*)"
97
+ r"(<[^>]*>\s*)?([\w.]+(?:<[^;{}()]*?>)?(?:\s*\[\s*\])*)\s+(\w+)\s*\(([^()]*)\)\s*(?:throws\s+[\w.,\s]+)?\{")
98
+ CLASS_RE = re.compile(r"\b(?:class|interface|enum|record)\s+(\w+)[^{;]*\{")
99
+
100
+
101
+ def analyze_file(rel, text):
102
+ clean = blank(text)
103
+ units = []
104
+ for cm in CLASS_RE.finditer(clean):
105
+ # only top-level classes: brace depth 0 before the keyword
106
+ if clean.count("{", 0, cm.start()) != clean.count("}", 0, cm.start()):
107
+ continue
108
+ cls, body_open = cm.group(1), cm.end() - 1
109
+ body_end = match_brace(text, body_open)
110
+ body = clean[body_open + 1:body_end]
111
+ newable = constructible(cm.group(0), body, cls)
112
+ for m in METH_RE.finditer(body):
113
+ mods = m.group(2).split()
114
+ if m.group(5) in KEYWORDS or m.group(3) or "private" in mods:
115
+ continue # control flow, generic methods, private methods
116
+ if body.count("{", 0, m.start()) != body.count("}", 0, m.start()):
117
+ continue # not directly inside the class body
118
+ params = parse_params(m.group(6))
119
+ if any(p["kind"] == "varargs" for p in params):
120
+ continue
121
+ open_brace = body_open + 1 + m.end() - 1
122
+ static = "static" in mods
123
+ instance = not static and newable and "public" in mods and "abstract" not in mods
124
+ unit = unit_record(rel, cls, m.group(5), body_open + 1 + m.start(), match_brace(text, open_brace), text,
125
+ params, re.sub(r"\s+", "", m.group(4)), THROW,
126
+ owner=None if static or instance else cls)
127
+ if instance:
128
+ unit["instance"] = True
129
+ units.append(unit)
130
+ return units
131
+
132
+
133
+ def constructible(decl, body, cls):
134
+ """Plain class, no instance fields, only a no-arg (or implicit) public constructor."""
135
+ if not re.search(r"\bclass\b", decl) or re.search(r"\babstract\b", decl):
136
+ return False
137
+ depth, top = 0, []
138
+ for c in body: # text directly inside the class body
139
+ if c == "{":
140
+ depth += 1
141
+ top.append(";")
142
+ elif c == "}":
143
+ depth -= 1
144
+ elif depth == 0:
145
+ top.append(c)
146
+ for stmt in "".join(top).split(";"):
147
+ stmt = re.sub(r"@\w+(\([^)]*\))?", "", stmt).strip()
148
+ head = stmt.split("=", 1)[0]
149
+ if "(" in head or not head or re.search(r"\bstatic\b", head):
150
+ continue
151
+ if re.fullmatch(r"((public|protected|private|final|transient|volatile)\s+)*[\w.<>,\[\]?\s]+\s+\w+\s*", head):
152
+ return False # instance field (e.g. an injected repository)
153
+ for ctor in re.finditer(r"((?:public|protected|private)\s+)?\b" + cls + r"\s*\(([^()]*)\)\s*(?:throws[^{]*)?\{", body):
154
+ if ctor.group(2).strip() or (ctor.group(1) or "").strip() != "public":
155
+ return False
156
+ return True
157
+
158
+
159
+ # ------------------------------------------------------------------ generated driver (shared with Kotlin)
160
+ PRIMS = {"int": "ppInt({x})", "long": "ppLong({x})", "short": "(short)ppInt({x})", "byte": "(byte)ppInt({x})",
161
+ "float": "(float)ppDouble({x})", "double": "ppDouble({x})", "boolean": "ppBool({x})", "char": "ppChar({x})"}
162
+ BOXES = {"Integer": "int", "Long": "long", "Short": "short", "Byte": "byte", "Float": "float", "Double": "double",
163
+ "Boolean": "boolean", "Character": "char"}
164
+
165
+
166
+ def dec(t, x, helpers):
167
+ """Java expression decoding the parsed-JSON Object expression `x` into declared type `t`."""
168
+ t = re.sub(r"\s+", "", t).replace("java.lang.", "")
169
+ if t in PRIMS:
170
+ return PRIMS[t].format(x=x)
171
+ if t in BOXES:
172
+ return f"({x}==null?null:({t})({PRIMS[BOXES[t]].format(x=x)}))"
173
+ if t == "String":
174
+ return f"ppStr({x})"
175
+ if t in helpers:
176
+ return f"{helpers[t][0]}({x})"
177
+ if t.endswith("[]"):
178
+ elem = t[:-2]
179
+ inner = dec(elem, "l.get(i)", helpers)
180
+ base, dims = elem.split("[]")[0], "[]" * elem.count("[]")
181
+ name = f"d{len(helpers)}"
182
+ helpers[t] = (name, f"static {t} {name}(Object o){{ if(o==null) return null; List<Object> l=ppList(o); "
183
+ f"{t} r=new {base}[l.size()]{dims}; for(int i=0;i<r.length;i++) r[i]={inner}; return r; }}")
184
+ return f"{name}({x})"
185
+ m = re.fullmatch(r"(?:java\.util\.)?(List|ArrayList|Collection)<(.+)>", t)
186
+ if m:
187
+ elem = m.group(2)
188
+ inner = dec(elem, "e", helpers)
189
+ name = f"d{len(helpers)}"
190
+ helpers[t] = (name, f"static {t} {name}(Object o){{ if(o==null) return null; {t} r=new java.util.ArrayList<{elem}>(); "
191
+ f"for(Object e: ppList(o)) r.add({inner}); return r; }}")
192
+ return f"{name}({x})"
193
+ raise SystemExit(f"unsupported parameter type {t!r}: only primitives, boxed types, String, arrays and lists of those can be recorded")
194
+
195
+
196
+ DRIVER = r'''import java.io.*;
197
+ import java.nio.charset.StandardCharsets;
198
+ import java.nio.file.*;
199
+ import java.util.*;
200
+
201
+ @SuppressWarnings("unchecked")
202
+ public class PpDriver {
203
+ static String S; static int P;
204
+ static void ws() { while (P < S.length() && Character.isWhitespace(S.charAt(P))) P++; }
205
+ static Object parse() {
206
+ ws(); char c = S.charAt(P);
207
+ if (c == '{') {
208
+ P++; Map<String, Object> m = new LinkedHashMap<>(); ws();
209
+ if (S.charAt(P) == '}') { P++; return m; }
210
+ while (true) { ws(); String k = (String) parse(); ws(); P++; m.put(k, parse()); ws(); if (S.charAt(P++) == '}') return m; }
211
+ }
212
+ if (c == '[') {
213
+ P++; List<Object> l = new ArrayList<>(); ws();
214
+ if (S.charAt(P) == ']') { P++; return l; }
215
+ while (true) { l.add(parse()); ws(); if (S.charAt(P++) == ']') return l; }
216
+ }
217
+ if (c == '"') {
218
+ P++; StringBuilder b = new StringBuilder();
219
+ while (true) {
220
+ char d = S.charAt(P++);
221
+ if (d == '"') return b.toString();
222
+ if (d != '\\') { b.append(d); continue; }
223
+ char e = S.charAt(P++);
224
+ switch (e) {
225
+ case 'n': b.append('\n'); break;
226
+ case 't': b.append('\t'); break;
227
+ case 'r': b.append('\r'); break;
228
+ case 'b': b.append('\b'); break;
229
+ case 'f': b.append('\f'); break;
230
+ case 'u': b.append((char) Integer.parseInt(S.substring(P, P + 4), 16)); P += 4; break;
231
+ default: b.append(e);
232
+ }
233
+ }
234
+ }
235
+ if (S.startsWith("true", P)) { P += 4; return Boolean.TRUE; }
236
+ if (S.startsWith("false", P)) { P += 5; return Boolean.FALSE; }
237
+ if (S.startsWith("null", P)) { P += 4; return null; }
238
+ int st = P;
239
+ while (P < S.length() && "+-0123456789.eE".indexOf(S.charAt(P)) >= 0) P++;
240
+ String n = S.substring(st, P);
241
+ if (n.matches("-?\\d+")) { try { return Long.parseLong(n); } catch (NumberFormatException e) { return Double.parseDouble(n); } }
242
+ return Double.parseDouble(n);
243
+ }
244
+
245
+ static int ppInt(Object o) { if (o instanceof Number) return ((Number) o).intValue(); throw new ClassCastException("expected int, got " + o); }
246
+ static long ppLong(Object o) { if (o instanceof Number) return ((Number) o).longValue(); throw new ClassCastException("expected long, got " + o); }
247
+ static boolean ppBool(Object o) { if (o instanceof Boolean) return (Boolean) o; throw new ClassCastException("expected boolean, got " + o); }
248
+ static char ppChar(Object o) { if (o instanceof String && ((String) o).length() == 1) return ((String) o).charAt(0); throw new ClassCastException("expected char, got " + o); }
249
+ static String ppStr(Object o) { if (o == null || o instanceof String) return (String) o; throw new ClassCastException("expected String, got " + o); }
250
+ static List<Object> ppList(Object o) { if (o instanceof List) return (List<Object>) o; throw new ClassCastException("expected array, got " + o); }
251
+ static double ppDouble(Object o) {
252
+ if (o instanceof Number) return ((Number) o).doubleValue();
253
+ if (o instanceof Map && ((Map<String, Object>) o).get("$float") instanceof String) {
254
+ String s = (String) ((Map<String, Object>) o).get("$float");
255
+ switch (s) {
256
+ case "nan": return Double.NaN;
257
+ case "inf": return Double.POSITIVE_INFINITY;
258
+ case "-inf": return Double.NEGATIVE_INFINITY;
259
+ case "-0.0": return -0.0;
260
+ default: return Double.parseDouble(s);
261
+ }
262
+ }
263
+ throw new ClassCastException("expected double, got " + o);
264
+ }
265
+
266
+ static void quote(String s, StringBuilder b) {
267
+ b.append('"');
268
+ for (int i = 0; i < s.length(); i++) {
269
+ char c = s.charAt(i);
270
+ if (c == '"') b.append("\\\"");
271
+ else if (c == '\\') b.append("\\\\");
272
+ else if (c == '\n') b.append("\\n");
273
+ else if (c == '\r') b.append("\\r");
274
+ else if (c == '\t') b.append("\\t");
275
+ else if (c < 0x20) b.append(String.format("\\u%04x", (int) c));
276
+ else b.append(c);
277
+ }
278
+ b.append('"');
279
+ }
280
+ static void enc(Object v, StringBuilder b) {
281
+ if (v == null) { b.append("null"); }
282
+ else if (v instanceof Double || v instanceof Float) {
283
+ double d = v instanceof Float ? Double.parseDouble(v.toString()) : (Double) v;
284
+ if (Double.isNaN(d)) b.append("{\"$float\":\"nan\"}");
285
+ else if (Double.isInfinite(d)) b.append(d > 0 ? "{\"$float\":\"inf\"}" : "{\"$float\":\"-inf\"}");
286
+ else if (d == 0 && 1 / d < 0) b.append("{\"$float\":\"-0.0\"}");
287
+ else if (d == Math.rint(d) && Math.abs(d) > 9007199254740992.0) b.append("{\"$float\":\"").append(Double.toString(d)).append("\"}");
288
+ else b.append(Double.toString(d));
289
+ }
290
+ else if (v instanceof Number || v instanceof Boolean) b.append(v.toString());
291
+ else if (v instanceof String || v instanceof Character) quote(v.toString(), b);
292
+ else if (v instanceof Map) {
293
+ b.append('{'); boolean first = true;
294
+ for (Map.Entry<?, ?> e : ((Map<?, ?>) v).entrySet()) { if (!first) b.append(','); first = false; quote(String.valueOf(e.getKey()), b); b.append(':'); enc(e.getValue(), b); }
295
+ b.append('}');
296
+ }
297
+ else if (v instanceof Collection) {
298
+ b.append('['); boolean first = true;
299
+ for (Object o : (Collection<?>) v) { if (!first) b.append(','); first = false; enc(o, b); }
300
+ b.append(']');
301
+ }
302
+ else if (v.getClass().isArray()) {
303
+ b.append('['); int n = java.lang.reflect.Array.getLength(v);
304
+ for (int i = 0; i < n; i++) { if (i > 0) b.append(','); enc(java.lang.reflect.Array.get(v, i), b); }
305
+ b.append(']');
306
+ }
307
+ else quote(v.toString(), b);
308
+ }
309
+
310
+ static final String FILE = "__FILE__";
311
+ __HELPERS__
312
+ __FIELDS__
313
+ static Object call() throws Throwable {
314
+ __CALL__
315
+ }
316
+
317
+ static Map<String, Object> raise(String type, String msg, int line) {
318
+ Map<String, Object> o = new LinkedHashMap<>();
319
+ o.put("kind", "raise"); o.put("type", type); o.put("message", msg == null ? "" : msg);
320
+ if (line > 0) o.put("raise_line", line);
321
+ return o;
322
+ }
323
+ static Map<String, Object> run() {
324
+ try {
325
+ Map<String, Object> o = new LinkedHashMap<>();
326
+ o.put("kind", "return"); o.put("value", call());
327
+ return o;
328
+ } catch (Throwable t) {
329
+ int line = 0;
330
+ for (StackTraceElement f : t.getStackTrace()) { if (FILE.equals(f.getFileName())) { line = f.getLineNumber(); break; } }
331
+ return raise(t.getClass().getSimpleName(), t.getMessage(), line);
332
+ }
333
+ }
334
+ static void write(Object v) throws IOException {
335
+ StringBuilder b = new StringBuilder(); enc(v, b);
336
+ Files.write(Paths.get(System.getenv("PP_RESULT")), b.toString().getBytes(StandardCharsets.UTF_8));
337
+ }
338
+
339
+ public static void main(String[] argv) throws Exception {
340
+ S = new String(System.in.readAllBytes(), StandardCharsets.UTF_8); P = 0;
341
+ Map<String, Object> req = (Map<String, Object>) parse();
342
+ List<Object> args = (List<Object>) req.get("args");
343
+ try {
344
+ __DECODE__
345
+ } catch (Throwable t) {
346
+ Map<String, Object> o = new LinkedHashMap<>(); o.put("outcome", raise("TypeError", String.valueOf(t.getMessage()), 0));
347
+ write(o); return;
348
+ }
349
+ Map<String, Object> out = new LinkedHashMap<>();
350
+ if ("bench".equals(req.get("mode"))) {
351
+ int n = ((Number) req.get("iterations")).intValue(); List<Object> samples = new ArrayList<>();
352
+ for (int i = 0; i < n; i++) { long t0 = System.nanoTime(); run(); samples.add(System.nanoTime() - t0); }
353
+ out.put("samples_ns", samples);
354
+ } else out.put("outcome", run());
355
+ write(out);
356
+ System.out.flush(); System.err.flush();
357
+ System.exit(0);
358
+ }
359
+ }
360
+ '''
361
+
362
+
363
+ def driver_source(jtypes, call, void, file_name):
364
+ helpers = {}
365
+ decode = [f"a{i} = {dec(t, f'(args.size() > {i} ? args.get({i}) : null)', helpers)};" for i, t in enumerate(jtypes)]
366
+ fields = [f" static {t} a{i};" for i, t in enumerate(jtypes)]
367
+ body = f" {call};\n return null;" if void else f" return {call};"
368
+ return DRIVER.replace("__HELPERS__", "\n".join(" " + h[1] for h in helpers.values())) \
369
+ .replace("__FIELDS__", "\n".join(fields)).replace("__DECODE__", "\n".join(" " + d for d in decode)) \
370
+ .replace("__CALL__", body).replace("__FILE__", file_name)
371
+
372
+
373
+ def source_files(root, ext):
374
+ out = []
375
+ for base, dirs, names in os.walk(root):
376
+ dirs[:] = sorted(d for d in dirs if d not in {".git", "build", "target", "out", "bin", "node_modules"}
377
+ and not d.startswith(".") and not (d == "test" and os.path.basename(base) == "src"))
378
+ out += [os.path.join(base, n) for n in sorted(names) if n.endswith(ext) and not re.search(r"Tests?\.(java|kt)$", n)]
379
+ return out
380
+
381
+
382
+ JDK_JAVAX = ("javax.crypto", "javax.net", "javax.security", "javax.xml", "javax.naming", "javax.sql", "javax.script",
383
+ "javax.management", "javax.annotation.processing", "javax.lang", "javax.tools", "javax.imageio", "javax.sound")
384
+ JDK_ANNOTATIONS = {"Override", "Deprecated", "SuppressWarnings", "FunctionalInterface", "SafeVarargs"}
385
+ JAR_DIRS = ("target/dependency", "build/dependency", "lib", "libs")
386
+
387
+
388
+ def project_jars(src):
389
+ jars = []
390
+ for d in JAR_DIRS:
391
+ base = os.path.join(src, d)
392
+ if os.path.isdir(base):
393
+ jars += sorted(os.path.join(base, n) for n in os.listdir(base) if n.endswith(".jar"))
394
+ return os.pathsep.join(jars)
395
+
396
+
397
+ def top_types(clean):
398
+ found = {m.group(1) for m in CLASS_RE.finditer(clean)
399
+ if clean.count("{", 0, m.start()) == clean.count("}", 0, m.start())}
400
+ return found | set(re.findall(r"@interface\s+(\w+)", clean))
401
+
402
+
403
+ def closure(files, target):
404
+ """target plus the project files it references by type name, transitively."""
405
+ clean = {f: blank(open(f, encoding="utf-8", errors="replace").read()) for f in files}
406
+ owner = {}
407
+ for f, c in clean.items():
408
+ for t in top_types(c) | {os.path.splitext(os.path.basename(f))[0]}:
409
+ owner.setdefault(t, set()).add(f)
410
+ seen, todo = set(), [target]
411
+ while todo:
412
+ f = todo.pop()
413
+ if f in seen or f not in clean:
414
+ continue
415
+ seen.add(f)
416
+ for tok in set(re.findall(r"\b[A-Z]\w*\b", clean[f])):
417
+ todo += owner.get(tok, ())
418
+ return sorted(seen)
419
+
420
+
421
+ def strip_framework(text, project_pkgs, project_types):
422
+ """Blank imports and annotations the JDK can't resolve (offsets and newlines preserved)."""
423
+ clean, out = blank(text), list(text)
424
+
425
+ def wipe(a, b):
426
+ for k in range(a, b):
427
+ if out[k] != "\n":
428
+ out[k] = " "
429
+ for m in re.finditer(r"^[ \t]*import\s+(static\s+)?([\w.]+?)(\.\*)?\s*;", clean, re.M):
430
+ name = m.group(2)
431
+ pkg = name if m.group(3) else name.rsplit(".", 1)[0]
432
+ if m.group(1) and not m.group(3):
433
+ pkg = pkg.rsplit(".", 1)[0]
434
+ if name.startswith("java.") or name.startswith(JDK_JAVAX) or pkg in project_pkgs \
435
+ or any(pkg.startswith(p + ".") for p in project_pkgs):
436
+ continue
437
+ wipe(m.start(), m.end())
438
+ for m in re.finditer(r"@(?!interface\b)([\w.]+)", clean):
439
+ simple = m.group(1).rsplit(".", 1)[-1]
440
+ if simple in JDK_ANNOTATIONS or simple in project_types:
441
+ continue
442
+ end = m.end()
443
+ rest = re.match(r"\s*\(", clean[end:])
444
+ if rest:
445
+ depth, j = 0, end + rest.end() - 1
446
+ while j < len(clean):
447
+ depth += clean[j] == "("
448
+ depth -= clean[j] == ")"
449
+ j += 1
450
+ if depth == 0:
451
+ break
452
+ end = j
453
+ wipe(m.start(), end)
454
+ return "".join(out)
455
+
456
+
457
+ def stage_sources(src, rel, work):
458
+ """(files to compile, classpath). Without dependency jars the files are rewritten into work/srcs."""
459
+ needed = closure([os.path.normpath(f) for f in source_files(src, ".java")], os.path.normpath(os.path.join(src, rel)))
460
+ jars = project_jars(src)
461
+ if jars:
462
+ return needed, jars
463
+ texts = {f: open(f, encoding="utf-8", errors="replace").read() for f in needed}
464
+ pkgs = set()
465
+ for t in texts.values():
466
+ m = re.search(r"^\s*package\s+([\w.]+)\s*;", blank(t), re.M)
467
+ if m:
468
+ pkgs.add(m.group(1))
469
+ types = {t for x in texts.values() for t in top_types(blank(x))}
470
+ out = []
471
+ for i, (f, t) in enumerate(texts.items()):
472
+ d = os.path.join(work, "srcs", str(i))
473
+ os.makedirs(d, exist_ok=True)
474
+ path = os.path.join(d, os.path.basename(f))
475
+ open(path, "w", encoding="utf-8").write(strip_framework(t, pkgs, types))
476
+ out.append(path)
477
+ return out, ""
478
+
479
+
480
+ def compile_driver(work, driver, classpath, java_files):
481
+ """javac the generated driver (plus java_files) into work/classes; return the java argv."""
482
+ os.makedirs(os.path.join(work, "drv"), exist_ok=True)
483
+ path = os.path.join(work, "drv", "PpDriver.java")
484
+ open(path, "w", encoding="utf-8").write(driver)
485
+ classes = os.path.join(work, "classes")
486
+ os.makedirs(classes, exist_ok=True)
487
+ cp = ["-cp", os.pathsep.join(x for x in (classes, classpath) if x)]
488
+ done = subprocess.run(["javac"] + JAVAC_FLAGS + cp + ["-d", classes] + java_files + [path],
489
+ capture_output=True, text=True, cwd=work, env=dict(os.environ, HOME=work))
490
+ if done.returncode:
491
+ raise SystemExit("javac failed. Framework types used outside annotations need their jars in "
492
+ "target/dependency (mvn dependency:copy-dependencies):\n" + (done.stderr or done.stdout)[-1500:])
493
+ return ["java"] + JVM_FLAGS + ["-cp", os.pathsep.join(x for x in (classes, classpath) if x), "PpDriver"]
494
+
495
+
496
+ def prepare(src, rel, unit, work):
497
+ header = re.sub(r"@[\w.]+(\s*\([^)]*\))?", "", blank(unit["source"])).split("(", 1)[0]
498
+ instance = unit.get("instance")
499
+ if unit["kind"] != "function" or not re.search(r"\bpublic\b", header) \
500
+ or not (instance or re.search(r"\bstatic\b", header)):
501
+ raise SystemExit("only public static methods, or public methods of stateless classes, can be recorded")
502
+ text = open(os.path.join(src, rel), encoding="utf-8", errors="replace").read()
503
+ pkg = re.search(r"^\s*package\s+([\w.]+)\s*;", text, re.M)
504
+ cls = (pkg.group(1) + "." if pkg else "") + unit["module"]
505
+ args = ", ".join(f"a{i}" for i in range(len(unit["params"])))
506
+ target = f"new {cls}()" if instance else cls
507
+ driver = driver_source([p["annotation"] for p in unit["params"]], f"{target}.{unit['name']}({args})",
508
+ unit["returns"] == "void", os.path.basename(rel))
509
+ files, classpath = stage_sources(src, rel, work)
510
+ return compile_driver(work, driver, classpath, files)