gdp-wired 0.31.0 → 0.32.0

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.
Files changed (73) hide show
  1. package/README.md +82 -6
  2. package/dist/core/c/reader.d.ts +86 -0
  3. package/dist/core/c/reader.js +860 -0
  4. package/dist/core/cli.d.ts +66 -0
  5. package/dist/core/cli.js +582 -0
  6. package/dist/core/dsl.d.ts +4 -2
  7. package/dist/core/dsl.js +22 -12
  8. package/dist/core/effect.d.ts +6 -4
  9. package/dist/core/effect.js +48 -10
  10. package/dist/core/ex/harness.exs +177 -0
  11. package/dist/core/ex/json.exs +46 -0
  12. package/dist/core/ex/reader.exs +462 -0
  13. package/dist/core/exists.d.ts +3 -0
  14. package/dist/core/exists.js +3 -1
  15. package/dist/core/extract-c.d.ts +35 -0
  16. package/dist/core/extract-c.js +424 -0
  17. package/dist/core/extract-check.js +27 -6
  18. package/dist/core/extract-ex.d.ts +16 -0
  19. package/dist/core/extract-ex.js +33 -0
  20. package/dist/core/extract-go-check.d.ts +28 -0
  21. package/dist/core/extract-go-check.js +639 -0
  22. package/dist/core/extract-go.d.ts +231 -0
  23. package/dist/core/extract-go.js +1166 -0
  24. package/dist/core/extract-jvm.d.ts +23 -0
  25. package/dist/core/extract-jvm.js +220 -0
  26. package/dist/core/extract-print.js +17 -7
  27. package/dist/core/extract-py.d.ts +15 -0
  28. package/dist/core/extract-py.js +31 -0
  29. package/dist/core/extract-rb.d.ts +17 -0
  30. package/dist/core/extract-rb.js +31 -0
  31. package/dist/core/extract-read.d.ts +20 -0
  32. package/dist/core/extract-read.js +46 -6
  33. package/dist/core/extract-rs.d.ts +12 -0
  34. package/dist/core/extract-rs.js +306 -0
  35. package/dist/core/extract-shapes.d.ts +2 -0
  36. package/dist/core/extract-shapes.js +6 -5
  37. package/dist/core/extract-step.d.ts +806 -0
  38. package/dist/core/extract-step.js +4141 -0
  39. package/dist/core/extract-swift.d.ts +27 -0
  40. package/dist/core/extract-swift.js +484 -0
  41. package/dist/core/extract-xstate.d.ts +10 -3
  42. package/dist/core/extract-xstate.js +50 -4
  43. package/dist/core/extract.d.ts +22 -3
  44. package/dist/core/extract.js +107 -18
  45. package/dist/core/go/go.mod +3 -0
  46. package/dist/core/go/reader.go +901 -0
  47. package/dist/core/infer.js +1770 -52
  48. package/dist/core/jvm/Harness.java +361 -0
  49. package/dist/core/jvm/JavaReader.java +825 -0
  50. package/dist/core/jvm/Jvm.java +332 -0
  51. package/dist/core/jvm/KtReader.java +960 -0
  52. package/dist/core/jvm/Rt.java +10 -0
  53. package/dist/core/laws.d.ts +66 -0
  54. package/dist/core/laws.js +522 -0
  55. package/dist/core/py/harness.py +328 -0
  56. package/dist/core/py/reader.py +447 -0
  57. package/dist/core/rb/harness.rb +233 -0
  58. package/dist/core/rb/reader.rb +375 -0
  59. package/dist/core/rs/Cargo.lock +108 -0
  60. package/dist/core/rs/Cargo.toml +14 -0
  61. package/dist/core/rs/src/main.rs +681 -0
  62. package/dist/core/swift/Harness.swift +124 -0
  63. package/dist/core/swift/Main.swift +34 -0
  64. package/dist/core/swift/Package.swift +13 -0
  65. package/dist/core/swift/Sources/gdp-swiftreader/main.swift +1341 -0
  66. package/dist/kernel/cdcl.js +43 -18
  67. package/dist/kernel/epr.d.ts +35 -0
  68. package/dist/kernel/epr.js +1676 -0
  69. package/dist/kernel/prove.d.ts +44 -0
  70. package/dist/kernel/prove.js +668 -54
  71. package/dist/lean-kernel/emit.d.ts +1 -0
  72. package/dist/lean-kernel/emit.js +21 -4
  73. package/package.json +53 -6
@@ -0,0 +1,825 @@
1
+ // The extractor's Java reader (core/extract-jvm.ts): a class read through the JDK's own compiler (javac's tree API,
2
+ // com.sun.source, its types attributed by javac against the project's sources and classpath) and lowered into the
3
+ // shared step IR (core/extract-step.ts's SModule, as JSON on stdout). Nothing here decides what is in the subset beyond
4
+ // the syntax: a construct the IR has no node for becomes {"e": "no"} or {"s": "no"} with the reason, refused by the
5
+ // executor only where a step reaches it. Java's semantics are made explicit as the IR's operations: int and long
6
+ // arithmetic wraps at its width (binary promotion as `as` on the operands), Math's exact arithmetic traps, / and %
7
+ // truncate, a switch is a chain of ifs inside a block a break leaves, a compare-and-set loop is its first pass,
8
+ // synchronized and a ReentrantLock's lock()/finally unlock() make the step atomic, a throw is the step's failure.
9
+ //
10
+ // java -cp <tools> gdp.jvm.JavaReader '{"root": <dir>, "file": <file>, "names": ["Class"], "classpath": "<cp>"}'
11
+ package gdp.jvm;
12
+
13
+ import com.sun.source.tree.*;
14
+ import com.sun.source.util.*;
15
+ import java.io.*;
16
+ import java.nio.charset.StandardCharsets;
17
+ import java.util.*;
18
+ import javax.lang.model.element.*;
19
+ import javax.lang.model.type.*;
20
+ import javax.lang.model.util.*;
21
+ import javax.tools.*;
22
+ import static gdp.jvm.Jvm.*;
23
+
24
+ public final class JavaReader implements Jvm.Env {
25
+ Trees trees; Elements els; Types types; SourcePositions sp;
26
+ final Map<String, Object> recs = new LinkedHashMap<>(), funcs = new LinkedHashMap<>();
27
+ final List<Object> rewrites = new ArrayList<>();
28
+ final Map<String, Object> jvm = new LinkedHashMap<>();
29
+ final Set<String> reading = new HashSet<>();
30
+ // The class whose method is being lowered (its own calls are inlined), and the file's `// gdp:` tags.
31
+ TypeElement self;
32
+ final Map<CompilationUnitTree, TreeMap<Integer, String>> tagsOf = new HashMap<>();
33
+ int tmp = 0;
34
+
35
+ public static void main(String[] argv) throws Exception {
36
+ Map<?, ?> req = (Map<?, ?>) parse(argv[0]);
37
+ JavaReader r = new JavaReader();
38
+ System.out.println(json(r.read(req)));
39
+ }
40
+
41
+ Map<String, Object> read(Map<?, ?> req) throws IOException {
42
+ String root = (String) req.get("root"), file = (String) req.get("file"), cp = (String) req.get("classpath");
43
+ JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
44
+ StandardJavaFileManager fm = jc.getStandardFileManager(null, null, StandardCharsets.UTF_8);
45
+ List<String> opts = new ArrayList<>(List.of("-proc:none", "-Xlint:none", "-sourcepath", root));
46
+ if (cp != null && !cp.isEmpty()) { opts.add("-cp"); opts.add(cp); }
47
+ List<String> errs = new ArrayList<>();
48
+ JavacTask task = (JavacTask) jc.getTask(new StringWriter(), fm, d -> { if (d.getKind() == Diagnostic.Kind.ERROR) errs.add(d.getMessage(null)); }, opts, null, fm.getJavaFileObjects(file));
49
+ Iterable<? extends CompilationUnitTree> cus = task.parse();
50
+ task.analyze();
51
+ trees = Trees.instance(task); els = task.getElements(); types = task.getTypes(); sp = trees.getSourcePositions();
52
+ CompilationUnitTree cu = cus.iterator().next();
53
+ Map<String, Object> out = m("lang", "java", "file", new File(file).getName(), "path", new File(file).getAbsolutePath(), "module", pkg(cu), "root", new File(root).getAbsolutePath());
54
+ List<Object> entries = new ArrayList<>();
55
+ List<?> names = (List<?>) req.get("names");
56
+ // (no names: every class of the file, the executor taking the one whose public methods write its state)
57
+ if (names.isEmpty()) { List<Object> all = new ArrayList<>(); for (TypeElement t : classesOf(cu)) all.add(t.getQualifiedName().toString()); names = all; }
58
+ for (Object n : names) {
59
+ TypeElement te = find(cu, (String) n);
60
+ if (te == null) { entries.add(m("k", "missing", "name", n)); continue; }
61
+ jvm.put("ctorArity", req.get("ctor"));
62
+ entries.add(m("k", "class", "rec", entry(te)));
63
+ }
64
+ out.put("entries", entries); out.put("recs", recs); out.put("funcs", funcs);
65
+ jvm.put("rewrites", rewrites);
66
+ if (!errs.isEmpty()) jvm.put("javac", errs.subList(0, Math.min(5, errs.size())));
67
+ out.put("jvm", jvm);
68
+ return out;
69
+ }
70
+ static String pkg(CompilationUnitTree cu) { return cu.getPackageName() == null ? "" : cu.getPackageName().toString(); }
71
+ List<TypeElement> classesOf(CompilationUnitTree cu) {
72
+ List<TypeElement> all = new ArrayList<>();
73
+ new TreePathScanner<Void, Void>() { @Override public Void visitClass(ClassTree c, Void v) { Element e = trees.getElement(getCurrentPath()); if (e instanceof TypeElement t && t.getKind() == ElementKind.CLASS && (t.getNestingKind() == NestingKind.TOP_LEVEL || t.getModifiers().contains(Modifier.STATIC))) all.add(t); return super.visitClass(c, v); } }.scan(cu, null);
74
+ return all;
75
+ }
76
+ TypeElement find(CompilationUnitTree cu, String name) {
77
+ List<TypeElement> all = classesOf(cu);
78
+ for (TypeElement t : all) { String q = t.getQualifiedName().toString(); if (q.equals(name) || q.endsWith("." + name) || t.getSimpleName().contentEquals(name)) return t; }
79
+ return null;
80
+ }
81
+
82
+ // --- positions and text --------------------------------------------------------------------------------------------
83
+ CompilationUnitTree cuOf(TreePath p) { return p.getCompilationUnit(); }
84
+ String where(TreePath path, Tree t) {
85
+ CompilationUnitTree cu = path.getCompilationUnit();
86
+ long s = sp.getStartPosition(cu, t);
87
+ if (s < 0) return new File(cu.getSourceFile().getName()).getName() + ":0:0";
88
+ return new File(cu.getSourceFile().getName()).getName() + ":" + cu.getLineMap().getLineNumber(s) + ":" + cu.getLineMap().getColumnNumber(s);
89
+ }
90
+ String text(TreePath path, Tree t) {
91
+ try {
92
+ CompilationUnitTree cu = path.getCompilationUnit();
93
+ String src = cu.getSourceFile().getCharContent(true).toString();
94
+ long s = sp.getStartPosition(cu, t), e = sp.getEndPosition(cu, t);
95
+ if (s < 0 || e < s) return t.toString();
96
+ String x = src.substring((int) s, (int) e).replaceAll("\\s+", " ");
97
+ return x.length() <= 60 ? x : x.substring(0, 57) + "...";
98
+ } catch (IOException ex) { return t.toString(); }
99
+ }
100
+ List<Object> span(TreePath path, Tree t) { CompilationUnitTree cu = path.getCompilationUnit(); return List.of(sp.getStartPosition(cu, t), sp.getEndPosition(cu, t)); }
101
+ String tag(TreePath path, Tree t) {
102
+ CompilationUnitTree cu = path.getCompilationUnit();
103
+ TreeMap<Integer, String> tg = tagsOf.computeIfAbsent(cu, c -> { try { return tags(c.getSourceFile().getCharContent(true).toString()); } catch (IOException e) { return new TreeMap<>(); } });
104
+ long s = sp.getStartPosition(cu, t), e = sp.getEndPosition(cu, t);
105
+ if (s < 0) return null;
106
+ int l0 = (int) cu.getLineMap().getLineNumber(s), l1 = (int) cu.getLineMap().getLineNumber(Math.max(s, Math.min(e, s + 1)));
107
+ var hit = tg.subMap(l0, true, Math.max(l0, l1), true);
108
+ return hit.isEmpty() ? null : String.join("; ", hit.values());
109
+ }
110
+
111
+ // --- types ---------------------------------------------------------------------------------------------------------
112
+ JT jt(TypeMirror tm) {
113
+ if (tm == null) return null;
114
+ switch (tm.getKind()) {
115
+ case INT: case LONG: case SHORT: case BYTE: case CHAR: case BOOLEAN: case FLOAT: case DOUBLE: case VOID: return new JT(tm.getKind().name().toLowerCase());
116
+ case DECLARED: {
117
+ DeclaredType d = (DeclaredType) tm;
118
+ List<JT> as = new ArrayList<>();
119
+ for (TypeMirror a : d.getTypeArguments()) { JT x = jt(a); as.add(x == null ? new JT("java.lang.Object") : x); }
120
+ return new JT(((TypeElement) d.asElement()).getQualifiedName().toString(), as, false);
121
+ }
122
+ case WILDCARD: { TypeMirror b = ((WildcardType) tm).getExtendsBound(); return b == null ? new JT("java.lang.Object") : jt(b); }
123
+ case TYPEVAR: return new JT("typevar:" + tm);
124
+ case ARRAY: return new JT("array:" + tm);
125
+ case NULL: return new JT("null");
126
+ default: return null;
127
+ }
128
+ }
129
+ JT ty(TreePath pp, Tree t) { try { return jt(trees.getTypeMirror(new TreePath(pp, t))); } catch (RuntimeException e) { return null; } }
130
+ String erased(TypeMirror tm) {
131
+ TypeMirror e = types.erasure(tm);
132
+ if (e.getKind() == TypeKind.DECLARED) return els.getBinaryName((TypeElement) ((DeclaredType) e).asElement()).toString();
133
+ return e.toString();
134
+ }
135
+ @Override public List<String> enumValues(String fq) {
136
+ TypeElement te = els.getTypeElement(fq);
137
+ if (te == null || te.getKind() != ElementKind.ENUM) return null;
138
+ List<String> out = new ArrayList<>();
139
+ for (Element e : te.getEnclosedElements()) if (e.getKind() == ElementKind.ENUM_CONSTANT) out.add(e.getSimpleName().toString());
140
+ return out;
141
+ }
142
+ // A class of the code's own sources read as a record (a value): a Java record, or a class whose fields its one
143
+ // constructor sets from its arguments (Lombok's @Value, @Data and plain beans too).
144
+ @Override public String rec(String fq) {
145
+ TypeElement te = els.getTypeElement(fq);
146
+ if (te == null || trees.getPath(te) == null || te.getKind() == ElementKind.ENUM || te.getKind() == ElementKind.INTERFACE) return null;
147
+ String name = els.getBinaryName(te).toString();
148
+ if (recs.containsKey(name) || reading.contains(name)) return name;
149
+ return valueRec(te);
150
+ }
151
+ // Another module's class or an interface (the code's own sources' too): a record of other code, its methods' declared
152
+ // results its `rets` (an answer's type), an interface a protocol.
153
+ boolean noOther = false;
154
+ @Override public String other(String fq) {
155
+ if (noOther) return null;
156
+ TypeElement te = els.getTypeElement(fq);
157
+ if (te == null || te.getKind() == ElementKind.ENUM || te.getKind() == ElementKind.ANNOTATION_TYPE) return null;
158
+ if (te.getKind() != ElementKind.INTERFACE && trees.getPath(te) != null) return null;
159
+ String name = els.getBinaryName(te).toString();
160
+ if (recs.containsKey(name)) return name;
161
+ Map<String, Object> methods = new LinkedHashMap<>(), rets = new LinkedHashMap<>();
162
+ Map<String, Integer> seen = new HashMap<>();
163
+ noOther = true;
164
+ try {
165
+ for (Element e : els.getAllMembers(te)) {
166
+ if (e.getKind() != ElementKind.METHOD || e.getModifiers().contains(Modifier.STATIC) || ((TypeElement) e.getEnclosingElement()).getQualifiedName().contentEquals("java.lang.Object")) continue;
167
+ String n = e.getSimpleName().toString();
168
+ if (seen.merge(n, 1, Integer::sum) > 1) { rets.remove(n); continue; }
169
+ methods.put(n, null);
170
+ rets.put(n, stype(jt(((ExecutableElement) e).getReturnType()), this));
171
+ }
172
+ } finally { noOther = false; }
173
+ recs.put(name, m("name", name, "short", te.getSimpleName().toString(), "fields", List.of(), "methods", methods, "kinds", te.getKind() == ElementKind.INTERFACE ? List.of("protocol") : List.of(), "own", false,
174
+ "module", els.getPackageOf(te).getQualifiedName().toString(), "p", "?", "rets", rets));
175
+ return name;
176
+ }
177
+ Map<String, Object> st(TypeMirror tm) { JT t = jt(tm); return stype(t, this); }
178
+ boolean iface(TypeMirror tm) { return tm.getKind() == TypeKind.DECLARED && ((DeclaredType) tm).asElement().getKind() == ElementKind.INTERFACE; }
179
+ List<Object> annos(TreePath path, List<? extends AnnotationTree> as) {
180
+ List<Object> out = new ArrayList<>();
181
+ for (AnnotationTree a : as) {
182
+ TypeMirror t = trees.getTypeMirror(new TreePath(path, a.getAnnotationType()));
183
+ String fq = t != null && t.getKind() == TypeKind.DECLARED ? ((TypeElement) ((DeclaredType) t).asElement()).getQualifiedName().toString() : a.getAnnotationType().toString();
184
+ out.add(anno(fq.substring(fq.lastIndexOf('.') + 1), fq, a.toString()));
185
+ }
186
+ return out;
187
+ }
188
+ static boolean injected(List<? extends AnnotationTree> as) { for (AnnotationTree a : as) { String n = a.getAnnotationType().toString(); if (INJECT.contains(n.substring(n.lastIndexOf('.') + 1))) return true; } return false; }
189
+ static boolean has(List<Object> annos, String name) { for (Object a : annos) if (name.equals(((Map<?, ?>) a).get("name"))) return true; return false; }
190
+
191
+ // --- the classes ---------------------------------------------------------------------------------------------------
192
+ // The class read (its supertypes of the code's own sources merged in): its fields, its constructor as __init__, its
193
+ // methods; what the harness is told (its binary name, each method's JVM name and parameter types).
194
+ List<TypeElement> chain(TypeElement te) {
195
+ List<TypeElement> out = new ArrayList<>();
196
+ for (TypeElement t = te; t != null && trees.getPath(t) != null; ) {
197
+ out.add(t);
198
+ TypeMirror sup = t.getSuperclass();
199
+ t = sup.getKind() == TypeKind.DECLARED ? (TypeElement) ((DeclaredType) sup).asElement() : null;
200
+ }
201
+ return out;
202
+ }
203
+ String entry(TypeElement te) {
204
+ String name = els.getBinaryName(te).toString();
205
+ reading.add(name);
206
+ self = te;
207
+ TreePath cpath = trees.getPath(te);
208
+ ClassTree ct = (ClassTree) cpath.getLeaf();
209
+ List<String> kinds = new ArrayList<>();
210
+ if (!te.getTypeParameters().isEmpty()) kinds.add("generic:" + te.getTypeParameters());
211
+ if (te.getNestingKind() == NestingKind.MEMBER && !te.getModifiers().contains(Modifier.STATIC) && te.getKind() == ElementKind.CLASS) return refusedRec(te, name, "an inner class (it holds its outer object; the subset reads a top-level or static nested class)");
212
+ if (te.getModifiers().contains(Modifier.ABSTRACT)) kinds.add("abstract");
213
+ List<TypeElement> ch = chain(te);
214
+ Map<String, Object> methods = new LinkedHashMap<>(), sigs = new LinkedHashMap<>();
215
+ List<Object> fields = new ArrayList<>(), jfields = new ArrayList<>();
216
+ // fields, from the root class down
217
+ for (int i = ch.size() - 1; i >= 0; i--) {
218
+ TypeElement c = ch.get(i);
219
+ TreePath cp = trees.getPath(c);
220
+ for (Element e : c.getEnclosedElements()) {
221
+ if (e.getKind() != ElementKind.FIELD || e.getModifiers().contains(Modifier.STATIC)) continue;
222
+ VariableTree vt = (VariableTree) trees.getTree(e);
223
+ TreePath vp = trees.getPath(e);
224
+ JT t = jt(e.asType());
225
+ if (t != null && nullable(c, (VariableElement) e, vt)) t = t.nullable(true);
226
+ boolean inj = vt != null && injected(vt.getModifiers().getAnnotations());
227
+ fields.add(m("name", e.getSimpleName().toString(), "t", inj && t != null ? stype(t.nullable(false), this) : stype(t, this), "inject", inj ? true : null));
228
+ jfields.add(m("name", e.getSimpleName().toString(), "jt", String.valueOf(t), "iface", iface(e.asType()) ? true : null, "annos", vp == null ? null : annos(vp, vt.getModifiers().getAnnotations()), "tag", vp == null ? null : tag(vp, vt)));
229
+ }
230
+ }
231
+ // methods: each class's own, the subclass's overriding (a private or overloaded one keyed apart)
232
+ Set<String> seen = new HashSet<>();
233
+ for (TypeElement c : ch) {
234
+ for (Element e : c.getEnclosedElements()) {
235
+ if (e.getKind() != ElementKind.METHOD || e.getModifiers().contains(Modifier.ABSTRACT)) continue;
236
+ ExecutableElement me = (ExecutableElement) e;
237
+ String key = key(me);
238
+ if (!seen.add(key)) continue;
239
+ String id = fid(me);
240
+ methods.put(key, id);
241
+ sigs.put(key, sig(me));
242
+ funcs.put(id, func(me));
243
+ }
244
+ }
245
+ // the constructor: the one there is, or the one of the arity asked for
246
+ List<ExecutableElement> ctors = new ArrayList<>();
247
+ for (Element e : te.getEnclosedElements()) if (e.getKind() == ElementKind.CONSTRUCTOR) ctors.add((ExecutableElement) e);
248
+ Object want = jvm.get("ctorArity");
249
+ List<ExecutableElement> pick = ctors.stream().filter(c -> want == null || c.getParameters().size() == ((Number) want).intValue()).toList();
250
+ Map<String, Object> jctor = m();
251
+ if (pick.size() != 1) {
252
+ methods.put("__init__", name + "#<init>");
253
+ funcs.put(name + "#<init>", stub(te, cpath, "<init>", pick.isEmpty() ? "no constructor of the arity asked for (ctor)" : "a class with " + pick.size() + " constructors (name one by its arity: ctor)"));
254
+ } else {
255
+ ExecutableElement c = pick.get(0);
256
+ methods.put("__init__", name + "#<init>");
257
+ funcs.put(name + "#<init>", ctor(te, c, cpath));
258
+ for (ExecutableElement o : ctors) if (o != c) { methods.put("__init__/" + o.getParameters().size(), fid(o)); funcs.put(fid(o), ctor(te, o, cpath)); }
259
+ jctor = m("params", c.getParameters().stream().map(v -> erased(v.asType())).toList(), "names", c.getParameters().stream().map(v -> v.getSimpleName().toString()).toList(),
260
+ "jts", c.getParameters().stream().map(v -> String.valueOf(jt(v.asType()))).toList(), "ifaces", c.getParameters().stream().map(v -> iface(v.asType())).toList(),
261
+ "annos", trees.getPath(c) == null ? List.of() : annos(trees.getPath(c), ((MethodTree) trees.getTree(c)).getModifiers().getAnnotations()),
262
+ "paramAnnos", trees.getPath(c) == null ? List.of() : ((MethodTree) trees.getTree(c)).getParameters().stream().map(v -> annos(trees.getPath(c), v.getModifiers().getAnnotations())).toList());
263
+ }
264
+ recs.put(name, m("name", name, "short", te.getSimpleName().toString(), "fields", fields, "methods", methods, "kinds", kinds, "own", true, "module", pkg(cpath.getCompilationUnit()), "p", where(cpath, ct),
265
+ "jvm", m("fields", jfields, "annos", annos(cpath, ct.getModifiers().getAnnotations()), "ctor", jctor, "cls", name, "sigs", sigs)));
266
+ jvm.put("cls", name);
267
+ jvm.put("ctor", jctor.get("params"));
268
+ jvm.put("methods", sigs);
269
+ reading.remove(name);
270
+ return name;
271
+ }
272
+ String refusedRec(TypeElement te, String name, String why) {
273
+ TreePath cp = trees.getPath(te);
274
+ funcs.put(name + "#<init>", stub(te, cp, "<init>", why));
275
+ recs.put(name, m("name", name, "short", te.getSimpleName().toString(), "fields", List.of(), "methods", m("__init__", name + "#<init>"), "kinds", List.of(), "own", true, "module", pkg(cp.getCompilationUnit()), "p", where(cp, cp.getLeaf())));
276
+ return name;
277
+ }
278
+ Map<String, Object> stub(TypeElement te, TreePath cp, String n, String why) {
279
+ String p = where(cp, cp.getLeaf());
280
+ return m("id", els.getBinaryName(te) + "#" + n, "name", n, "cls", els.getBinaryName(te).toString(), "p", p, "span", List.of(p.split(":")[0], 0, 0), "params", List.of(m("name", "self", "t", m("k", "any"), "self", true)), "ret", m("k", "none"), "body", List.of(sno(p, why)), "decorators", List.of());
281
+ }
282
+ // A reference field may be null where the class says so: @Nullable, null assigned to it, or no initializer that
283
+ // the constructors don't all set.
284
+ boolean nullable(TypeElement c, VariableElement f, VariableTree vt) {
285
+ if (f.asType().getKind().isPrimitive()) return false;
286
+ if (vt != null && vt.getModifiers().getAnnotations().stream().anyMatch(a -> a.getAnnotationType().toString().endsWith("Nullable"))) return true;
287
+ JT t = jt(f.asType());
288
+ if (t != null && (t.is("java.util.Optional") || atomic(t) || map(t) || LOCKS.contains(t.n))) return false;
289
+ boolean[] nul = {vt != null && vt.getInitializer() != null && vt.getInitializer().getKind() == Tree.Kind.NULL_LITERAL};
290
+ boolean[] setInCtor = {vt != null && vt.getInitializer() != null};
291
+ TreePath cp = trees.getPath(c);
292
+ new TreePathScanner<Void, Void>() {
293
+ @Override public Void visitAssignment(AssignmentTree a, Void v) {
294
+ Element e = trees.getElement(new TreePath(getCurrentPath(), a.getVariable()));
295
+ if (f.equals(e)) {
296
+ if (a.getExpression().getKind() == Tree.Kind.NULL_LITERAL) nul[0] = true;
297
+ for (TreePath q = getCurrentPath(); q != null; q = q.getParentPath()) if (q.getLeaf() instanceof MethodTree mt && mt.getName().contentEquals("<init>")) setInCtor[0] = true;
298
+ }
299
+ return super.visitAssignment(a, v);
300
+ }
301
+ }.scan(cp, null);
302
+ return nul[0] || !setInCtor[0];
303
+ }
304
+ String key(ExecutableElement me) {
305
+ String n = me.getSimpleName().toString();
306
+ TypeElement owner = (TypeElement) me.getEnclosingElement();
307
+ long same = owner.getEnclosedElements().stream().filter(e -> e.getKind() == ElementKind.METHOD && e.getSimpleName().contentEquals(n)).count();
308
+ String k = same > 1 ? n + "/" + me.getParameters().size() : n;
309
+ boolean hidden = me.getModifiers().contains(Modifier.PRIVATE) || Set.of("equals", "hashCode", "toString").contains(n);
310
+ return hidden ? "_" + k : k;
311
+ }
312
+ String fid(ExecutableElement me) { return els.getBinaryName((TypeElement) me.getEnclosingElement()) + "#" + me.getSimpleName() + "(" + String.join(",", me.getParameters().stream().map(v -> erased(v.asType())).toList()) + ")"; }
313
+ Map<String, Object> sig(ExecutableElement me) { return m("name", me.getSimpleName().toString(), "params", me.getParameters().stream().map(v -> erased(v.asType())).toList(), "static", me.getModifiers().contains(Modifier.STATIC) ? true : null, "decl", els.getBinaryName((TypeElement) me.getEnclosingElement()).toString()); }
314
+ // A value record: its fields (a record's components, or the class's fields), no constructor of its own (the executor
315
+ // makes it from its fields in order), its getters read as the fields.
316
+ String valueRec(TypeElement te) {
317
+ String name = els.getBinaryName(te).toString();
318
+ reading.add(name);
319
+ List<Object> fields = new ArrayList<>();
320
+ Map<String, Object> methods = new LinkedHashMap<>();
321
+ List<String> fnames = new ArrayList<>();
322
+ for (Element e : te.getEnclosedElements()) {
323
+ if (e.getKind() != ElementKind.FIELD || e.getModifiers().contains(Modifier.STATIC)) continue;
324
+ fnames.add(e.getSimpleName().toString());
325
+ fields.add(m("name", e.getSimpleName().toString(), "t", st(e.asType())));
326
+ }
327
+ List<ExecutableElement> ctors = new ArrayList<>();
328
+ for (Element e : te.getEnclosedElements()) if (e.getKind() == ElementKind.CONSTRUCTOR) ctors.add((ExecutableElement) e);
329
+ boolean plain = te.getKind() == ElementKind.RECORD || ctors.stream().anyMatch(c -> c.getParameters().size() == fnames.size() && fnames.equals(assignedInOrder(c)));
330
+ TreePath cp = trees.getPath(te);
331
+ recs.put(name, m("name", name, "short", te.getSimpleName().toString(), "fields", fields, "methods", methods, "kinds", plain ? List.of("dataclass") : List.of("value"), "own", true, "module", pkg(cp.getCompilationUnit()), "p", where(cp, cp.getLeaf()), "jvm", m("record", te.getKind() == ElementKind.RECORD ? true : null)));
332
+ reading.remove(name);
333
+ return name;
334
+ }
335
+ // The fields a constructor sets from its arguments, in order (null where it does anything else).
336
+ List<String> assignedInOrder(ExecutableElement c) {
337
+ MethodTree mt = (MethodTree) trees.getTree(c);
338
+ if (mt == null || mt.getBody() == null) return null;
339
+ List<String> out = new ArrayList<>();
340
+ for (StatementTree s : mt.getBody().getStatements()) {
341
+ if (s instanceof ExpressionStatementTree es && es.getExpression() instanceof MethodInvocationTree mi && mi.getMethodSelect().toString().equals("super") && mi.getArguments().isEmpty()) continue;
342
+ if (!(s instanceof ExpressionStatementTree es && es.getExpression() instanceof AssignmentTree a && a.getExpression() instanceof IdentifierTree id)) return null;
343
+ String to = a.getVariable().toString().replace("this.", "");
344
+ if (!to.equals(id.getName().toString()) || out.size() >= c.getParameters().size() || !c.getParameters().get(out.size()).getSimpleName().contentEquals(id.getName())) return null;
345
+ out.add(to);
346
+ }
347
+ return out;
348
+ }
349
+ // The field a getter returns (`return f;` or `return this.f;`), for a value record's calls.
350
+ String getter(ExecutableElement me) {
351
+ TypeElement owner = (TypeElement) me.getEnclosingElement();
352
+ if (owner.getKind() == ElementKind.RECORD && me.getParameters().isEmpty()) for (Element e : owner.getEnclosedElements()) if (e.getKind() == ElementKind.FIELD && e.getSimpleName().contentEquals(me.getSimpleName())) return e.getSimpleName().toString();
353
+ MethodTree mt = (MethodTree) trees.getTree(me);
354
+ if (mt == null || mt.getBody() == null || mt.getBody().getStatements().size() != 1 || !me.getParameters().isEmpty()) {
355
+ // Lombok: a getter generated for a field
356
+ if (owner.getAnnotationMirrors().stream().anyMatch(a -> Set.of("Value", "Data", "Getter").contains(a.getAnnotationType().asElement().getSimpleName().toString()))) {
357
+ String n = me.getSimpleName().toString();
358
+ for (Element e : owner.getEnclosedElements()) if (e.getKind() == ElementKind.FIELD) { String f = e.getSimpleName().toString(); if (n.equals("get" + cap(f)) || n.equals("is" + cap(f))) return f; }
359
+ }
360
+ return null;
361
+ }
362
+ if (mt.getBody().getStatements().get(0) instanceof ReturnTree rt && rt.getExpression() != null) {
363
+ String x = rt.getExpression().toString().replace("this.", "");
364
+ for (Element e : owner.getEnclosedElements()) if (e.getKind() == ElementKind.FIELD && e.getSimpleName().contentEquals(x)) return x;
365
+ }
366
+ return null;
367
+ }
368
+ static String cap(String s) { return s.isEmpty() ? s : Character.toUpperCase(s.charAt(0)) + s.substring(1); }
369
+ boolean own(TypeElement t) { return t != null && (chain(self).contains(t)); }
370
+
371
+ // --- functions -------------------------------------------------------------------------------------------------------
372
+ Map<String, Object> fn(ExecutableElement me, String id, String name, TreePath path, List<Object> body, List<Object> params) {
373
+ CompilationUnitTree cu = path.getCompilationUnit();
374
+ Tree t = path.getLeaf();
375
+ long s = sp.getStartPosition(cu, t), e = sp.getEndPosition(cu, t);
376
+ List<Object> ps = new ArrayList<>();
377
+ if (!me.getModifiers().contains(Modifier.STATIC)) ps.add(m("name", "self", "t", m("k", "any"), "self", true));
378
+ ps.addAll(params);
379
+ return m("id", id, "name", name, "cls", els.getBinaryName((TypeElement) me.getEnclosingElement()).toString(), "p", where(path, t), "span", List.of(new File(cu.getSourceFile().getName()).getName(), cu.getLineMap().getLineNumber(Math.max(0, s)), cu.getLineMap().getLineNumber(Math.max(0, e))),
380
+ "params", ps, "ret", st(me.getReturnType()), "body", body, "decorators", tagDecos(path, ((MethodTree) t).getModifiers().getAnnotations()), "static", me.getModifiers().contains(Modifier.STATIC) ? true : null,
381
+ "generic", me.getTypeParameters().isEmpty() ? null : true, "annos", annos(path, ((MethodTree) t).getModifiers().getAnnotations()), "tag", tag(path, t), "jt", String.valueOf(jt(me.getReturnType())));
382
+ }
383
+ // @GdpSkip, @GdpAnswer("int"), @GdpStrict: the boundary's tags, as the executor reads a decorator.
384
+ List<Object> tagDecos(TreePath path, List<? extends AnnotationTree> as) {
385
+ List<Object> out = new ArrayList<>();
386
+ for (AnnotationTree a : as) { String n = a.getAnnotationType().toString(); n = n.substring(n.lastIndexOf('.') + 1); if (gdpTag(n)) out.add(m("name", n, "text", a.toString().replace("@", ""), "p", where(path, a))); }
387
+ return out;
388
+ }
389
+ List<Object> params(ExecutableElement me, TreePath path) {
390
+ List<Object> out = new ArrayList<>();
391
+ MethodTree mt = (MethodTree) path.getLeaf();
392
+ for (int i = 0; i < me.getParameters().size(); i++) {
393
+ VariableElement v = me.getParameters().get(i);
394
+ boolean inj = injected(mt.getParameters().get(i).getModifiers().getAnnotations()) || (me.getKind() == ElementKind.CONSTRUCTOR && injected(mt.getModifiers().getAnnotations()) && iface(v.asType()));
395
+ out.add(m("name", v.getSimpleName().toString(), "t", pstype(jt(v.asType()), this), "jt", String.valueOf(jt(v.asType())), "iface", iface(v.asType()) ? true : null, "inject", inj ? true : null, "annos", annos(path, mt.getParameters().get(i).getModifiers().getAnnotations())));
396
+ }
397
+ return out;
398
+ }
399
+ Map<String, Object> func(ExecutableElement me) {
400
+ TreePath path = trees.getPath(me);
401
+ MethodTree mt = (MethodTree) path.getLeaf();
402
+ String id = fid(me), p = where(path, mt);
403
+ List<Object> body = new ArrayList<>();
404
+ if (mt.getBody() == null) body.add(sno(p, me.getSimpleName() + ": a method with no body (native)"));
405
+ else body.addAll(block(mt.getBody().getStatements(), new TreePath(path, mt.getBody())));
406
+ if (me.getModifiers().contains(Modifier.SYNCHRONIZED)) body = new ArrayList<>(List.of(with(body, p, "synchronized " + me.getSimpleName())));
407
+ return fn(me, id, me.getSimpleName().toString(), path, body, params(me, path));
408
+ }
409
+ // A constructor: its super(...) first (a superclass of the code's own sources: its constructor inlined), then the
410
+ // fields' defaults and initializers in order (unless it delegates with this(...)), then its body.
411
+ Map<String, Object> ctor(TypeElement te, ExecutableElement c, TreePath cpath) {
412
+ TreePath path = trees.getPath(c);
413
+ MethodTree mt = path == null ? null : (MethodTree) path.getLeaf();
414
+ String p = path == null ? where(cpath, cpath.getLeaf()) : where(path, mt);
415
+ String z = p.split(":")[0] + ":0:0";
416
+ List<Object> body = new ArrayList<>();
417
+ List<? extends StatementTree> ss = mt == null || mt.getBody() == null ? List.of() : mt.getBody().getStatements();
418
+ boolean delegates = false;
419
+ if (!ss.isEmpty() && ss.get(0) instanceof ExpressionStatementTree es && es.getExpression() instanceof MethodInvocationTree mi && (mi.getMethodSelect().toString().equals("super") || mi.getMethodSelect().toString().equals("this"))) {
420
+ TreePath bp = new TreePath(path, mt.getBody());
421
+ TreePath ip = new TreePath(new TreePath(bp, es), mi);
422
+ ExecutableElement callee = (ExecutableElement) trees.getElement(ip);
423
+ List<Object> args = new ArrayList<>();
424
+ for (ExpressionTree a : mi.getArguments()) args.add(ex(a, ip));
425
+ if (mi.getMethodSelect().toString().equals("this")) { delegates = true; body.add(s("expr", p, "x", call(get(self(p), "__init__/" + callee.getParameters().size(), p, "this"), args, p, text(ip, mi)))); }
426
+ else if (callee != null && trees.getPath(callee) != null) {
427
+ String sid = fid(callee);
428
+ if (!funcs.containsKey(sid)) funcs.put(sid, ctor((TypeElement) callee.getEnclosingElement(), callee, trees.getPath(callee.getEnclosingElement())));
429
+ args.add(0, self(p));
430
+ body.add(s("expr", p, "x", call(x("fn", p, "id", sid), args, p, text(ip, mi))));
431
+ } else if (callee != null && !((TypeElement) callee.getEnclosingElement()).getQualifiedName().contentEquals("java.lang.Object")) body.add(sno(p, "super(...): a superclass of other code (its constructor and fields unread)"));
432
+ ss = ss.subList(1, ss.size());
433
+ } else if (te.getSuperclass().getKind() == TypeKind.DECLARED) {
434
+ TypeElement sup = (TypeElement) ((DeclaredType) te.getSuperclass()).asElement();
435
+ if (trees.getPath(sup) != null) {
436
+ ExecutableElement sc = null;
437
+ for (Element e : sup.getEnclosedElements()) if (e.getKind() == ElementKind.CONSTRUCTOR && ((ExecutableElement) e).getParameters().isEmpty()) sc = (ExecutableElement) e;
438
+ if (sc != null) { String sid = fid(sc); if (!funcs.containsKey(sid)) funcs.put(sid, ctor(sup, sc, trees.getPath(sup))); body.add(s("expr", p, "x", call(x("fn", p, "id", sid), List.of(self(p)), p, "super()"))); }
439
+ }
440
+ }
441
+ if (!delegates) {
442
+ ClassTree ct = (ClassTree) cpath.getLeaf();
443
+ for (Tree mem : ct.getMembers()) {
444
+ TreePath mp = new TreePath(cpath, mem);
445
+ if (mem instanceof VariableTree vt) {
446
+ VariableElement f = (VariableElement) trees.getElement(mp);
447
+ if (f == null || f.getModifiers().contains(Modifier.STATIC)) continue;
448
+ // (a field the framework injects: set after the constructor, the store the check gives)
449
+ if (vt.getInitializer() == null && injected(vt.getModifiers().getAnnotations())) continue;
450
+ Map<String, Object> to = get(self(z), vt.getName().toString(), z, "this." + vt.getName());
451
+ JT t = jt(f.asType());
452
+ if (t != null && nullable(te, f, vt)) t = t.nullable(true);
453
+ Map<String, Object> init = vt.getInitializer() == null ? zero(t, z) : at(ex(vt.getInitializer(), mp), ty(mp, vt.getInitializer()), atomic(t) ? held(t) : t);
454
+ body.add(s("set", vt.getInitializer() == null ? z : where(mp, vt), "to", to, "x", init, "t", stype(t, this)));
455
+ } else if (mem instanceof BlockTree bt && !bt.isStatic()) body.addAll(block(bt.getStatements(), mp));
456
+ }
457
+ }
458
+ if (mt != null && mt.getBody() != null) body.addAll(block(ss, new TreePath(path, mt.getBody())));
459
+ List<Object> ps = new ArrayList<>(List.of(m("name", "self", "t", m("k", "any"), "self", true)));
460
+ if (path != null) ps.addAll(params(c, path)); else ps.addAll(c.getParameters().stream().map(v -> (Object) m("name", v.getSimpleName().toString(), "t", st(v.asType()))).toList());
461
+ String id = fid(c);
462
+ return m("id", id, "name", "__init__", "cls", els.getBinaryName(te).toString(), "p", p, "span", List.of(p.split(":")[0], 0, 0), "params", ps, "ret", m("k", "none"), "body", body, "decorators", List.of());
463
+ }
464
+ Map<String, Object> zero(JT t, String p) {
465
+ if (t == null) return x("none", p);
466
+ if (t.nul) return x("none", p);
467
+ String q = prim(t);
468
+ if (q != null) return q.equals("boolean") ? x("bool", p, "v", false) : floating(t) ? x("int", p, "v", "0", "float", true) : lit(0, t, p);
469
+ return x("none", p);
470
+ }
471
+
472
+ // --- statements ----------------------------------------------------------------------------------------------------
473
+ List<Object> block(List<? extends StatementTree> ss, TreePath pp) {
474
+ List<Object> out = new ArrayList<>();
475
+ for (int i = 0; i < ss.size(); i++) {
476
+ StatementTree s = ss.get(i);
477
+ TreePath sp1 = new TreePath(pp, s);
478
+ // lock.lock(); try { ... } finally { lock.unlock(); }: the step atomic
479
+ if (i + 1 < ss.size() && lockCall(s, "lock") != null && ss.get(i + 1) instanceof TryTree tt && tt.getCatches().isEmpty() && tt.getFinallyBlock() != null
480
+ && tt.getFinallyBlock().getStatements().size() == 1 && Objects.equals(lockCall(tt.getFinallyBlock().getStatements().get(0), "unlock"), lockCall(s, "lock"))) {
481
+ TreePath tp = new TreePath(pp, tt);
482
+ out.add(with(block(tt.getBlock().getStatements(), new TreePath(tp, tt.getBlock())), where(sp1, s), text(sp1, s)));
483
+ i++;
484
+ continue;
485
+ }
486
+ out.addAll(stmt(s, sp1));
487
+ }
488
+ return out;
489
+ }
490
+ static String lockCall(StatementTree s, String m) {
491
+ if (s instanceof ExpressionStatementTree es && es.getExpression() instanceof MethodInvocationTree mi && mi.getArguments().isEmpty() && mi.getMethodSelect() instanceof MemberSelectTree ms && ms.getIdentifier().contentEquals(m))
492
+ return ms.getExpression().toString().replace("this.", "");
493
+ return null;
494
+ }
495
+ List<Object> stmt(StatementTree s, TreePath path) {
496
+ String p = where(path, s);
497
+ switch (s.getKind()) {
498
+ case BLOCK: return block(((BlockTree) s).getStatements(), path);
499
+ case EMPTY_STATEMENT: return List.of();
500
+ case VARIABLE: {
501
+ VariableTree v = (VariableTree) s;
502
+ JT t = jt(trees.getElement(path).asType());
503
+ Map<String, Object> init = v.getInitializer() == null ? zero(t, p) : at(ex(v.getInitializer(), path), ty(path, v.getInitializer()), t);
504
+ return List.of(s("set", p, "to", var(v.getName().toString(), p), "x", init, "t", stype(t, this)));
505
+ }
506
+ case EXPRESSION_STATEMENT: return exprStmt(((ExpressionStatementTree) s).getExpression(), new TreePath(path, ((ExpressionStatementTree) s).getExpression()), p);
507
+ case IF: {
508
+ IfTree it = (IfTree) s;
509
+ List<Object> el = it.getElseStatement() == null ? List.of() : stmt(it.getElseStatement(), new TreePath(path, it.getElseStatement()));
510
+ return List.of(s("if", p, "c", ex(it.getCondition(), path), "then", stmt(it.getThenStatement(), new TreePath(path, it.getThenStatement())), "else", el));
511
+ }
512
+ case RETURN: {
513
+ ReturnTree r = (ReturnTree) s;
514
+ if (r.getExpression() == null) return List.of(s("ret", p));
515
+ TreePath mp = path; while (mp != null && !(mp.getLeaf() instanceof MethodTree)) mp = mp.getParentPath();
516
+ JT rt = mp == null ? null : jt(((ExecutableElement) trees.getElement(mp)).getReturnType());
517
+ return List.of(s("ret", p, "x", at(ex(r.getExpression(), path), ty(path, r.getExpression()), rt)));
518
+ }
519
+ case THROW: return List.of(fail(p, text(path, s)));
520
+ case SYNCHRONIZED: { SynchronizedTree st = (SynchronizedTree) s; return List.of(with(block(st.getBlock().getStatements(), new TreePath(path, st.getBlock())), p, "synchronized (" + st.getExpression().toString().replaceAll("^\\(|\\)$", "") + ")")); }
521
+ case SWITCH: { SwitchTree sw = (SwitchTree) s; return sw(sw.getExpression(), sw.getCases(), path, p); }
522
+ case BREAK: return ((BreakTree) s).getLabel() == null ? List.of(s("break", p)) : List.of(sno(p, "a labeled break"));
523
+ case CONTINUE: return List.of(sno(p, "continue (a loop's next pass: the subset reads a compare-and-set loop's first)"));
524
+ case ASSERT: return List.of();
525
+ case WHILE_LOOP: { WhileLoopTree w = (WhileLoopTree) s; return once(w.getCondition(), w.getStatement(), path, p); }
526
+ case DO_WHILE_LOOP: { DoWhileLoopTree w = (DoWhileLoopTree) s; return once(w.getCondition(), w.getStatement(), path, p); }
527
+ case FOR_LOOP: { ForLoopTree f = (ForLoopTree) s; if (f.getCondition() == null && f.getInitializer().isEmpty() && f.getUpdate().isEmpty()) return once(null, f.getStatement(), path, p); return List.of(sno(p, "a loop")); }
528
+ case ENHANCED_FOR_LOOP: return List.of(sno(p, "a loop over a collection"));
529
+ case TRY: return List.of(sno(p, "try (an exception caught, or a finally of other than a lock's unlock: the subset reads an exception only as the step's failure)"));
530
+ case LABELED_STATEMENT: return List.of(sno(p, "a labeled statement"));
531
+ case YIELD: return List.of(sno(p, "yield (a switch expression's block)"));
532
+ default: return List.of(sno(p, s.getKind().toString().toLowerCase().replace('_', ' ') + " (outside the subset)"));
533
+ }
534
+ }
535
+ // while (true) / for (;;) / do ... while (true): a compare-and-set retry loop, read as its first pass (the CAS succeeds
536
+ // the first time when calls don't interleave); a pass that would go around again is refused where it is reached.
537
+ List<Object> once(ExpressionTree cond, StatementTree body, TreePath path, String p) {
538
+ ExpressionTree c = cond; while (c instanceof ParenthesizedTree pt) c = pt.getExpression();
539
+ if (c != null && !(c instanceof LiteralTree lt && Boolean.TRUE.equals(lt.getValue()))) return List.of(sno(p, "a loop"));
540
+ List<Object> b = new ArrayList<>(stmt(body, new TreePath(path, body)));
541
+ b.add(sno(p, "the loop goes around again (the subset reads a retry loop's first pass: a compare-and-set that succeeds when calls don't interleave)"));
542
+ return List.of(breakable(b, p));
543
+ }
544
+ // A switch: a chain of ifs on ==, each case's arm its statements and those it falls through into, inside a block a
545
+ // break leaves.
546
+ List<Object> sw(ExpressionTree sel, List<? extends CaseTree> cases, TreePath path, String p) {
547
+ List<Object> out = new ArrayList<>();
548
+ String tv = "$sw" + (tmp++);
549
+ out.add(s("set", p, "to", var(tv, p), "x", ex(sel, path)));
550
+ JT st = ty(path, sel);
551
+ List<List<Object>> bodies = new ArrayList<>();
552
+ List<Boolean> ends = new ArrayList<>();
553
+ for (CaseTree c : cases) {
554
+ TreePath cp = new TreePath(path, c);
555
+ List<Object> b = new ArrayList<>();
556
+ if (c.getCaseKind() == CaseTree.CaseKind.RULE) {
557
+ Tree body = c.getBody();
558
+ if (body instanceof StatementTree bs) b.addAll(stmt(bs, new TreePath(cp, bs))); else b.add(s("expr", where(cp, body), "x", ex((ExpressionTree) body, cp)));
559
+ ends.add(true);
560
+ } else {
561
+ b.addAll(block(c.getStatements(), cp));
562
+ StatementTree last = c.getStatements().isEmpty() ? null : c.getStatements().get(c.getStatements().size() - 1);
563
+ ends.add(last != null && (last instanceof BreakTree || last instanceof ReturnTree || last instanceof ThrowTree || last instanceof ContinueTree));
564
+ }
565
+ bodies.add(b);
566
+ }
567
+ // each case's arm: its body, and the next ones' while it falls through
568
+ List<Object> chain = new ArrayList<>(), dflt = List.of();
569
+ List<Object[]> arms = new ArrayList<>();
570
+ for (int i = 0; i < cases.size(); i++) {
571
+ List<Object> arm = new ArrayList<>();
572
+ for (int j = i; j < cases.size(); j++) { arm.addAll(bodies.get(j)); if (ends.get(j)) break; }
573
+ CaseTree c = cases.get(i);
574
+ TreePath cp = new TreePath(path, c);
575
+ if (c.getExpressions().isEmpty()) { dflt = arm; continue; }
576
+ List<Object> conds = new ArrayList<>();
577
+ for (ExpressionTree e : c.getExpressions()) conds.add(cmp("==", var(tv, p), label(e, new TreePath(cp, e), st), where(cp, e), text(cp, e)));
578
+ arms.add(new Object[]{conds.size() == 1 ? conds.get(0) : x("or", where(cp, c), "xs", conds), arm, where(cp, c)});
579
+ }
580
+ List<Object> acc = dflt;
581
+ for (int i = arms.size() - 1; i >= 0; i--) { @SuppressWarnings("unchecked") List<Object> a = (List<Object>) arms.get(i)[1]; acc = List.of(s("if", p.split(":")[0] + ":0:0", "c", arms.get(i)[0], "then", a, "else", acc)); }
582
+ chain.addAll(acc);
583
+ out.add(breakable(chain, p));
584
+ return out;
585
+ }
586
+ Map<String, Object> label(ExpressionTree e, TreePath path, JT st) {
587
+ Element el = trees.getElement(path);
588
+ if (el != null && el.getKind() == ElementKind.ENUM_CONSTANT) return str(el.getSimpleName().toString(), where(path, e));
589
+ return at(ex(e, path), ty(path, e), st);
590
+ }
591
+ // An expression used as a statement: an assignment, ++ and --, a call (a map's put, an atomic's set, a check).
592
+ List<Object> exprStmt(ExpressionTree e, TreePath path, String p) {
593
+ switch (e.getKind()) {
594
+ case ASSIGNMENT: {
595
+ AssignmentTree a = (AssignmentTree) e;
596
+ TreePath vp = new TreePath(path, a.getVariable());
597
+ JT t = ty(path, a.getVariable());
598
+ return List.of(s("set", p, "to", place(a.getVariable(), path), "x", at(ex(a.getExpression(), path), ty(path, a.getExpression()), t)));
599
+ }
600
+ case PLUS_ASSIGNMENT: case MINUS_ASSIGNMENT: case MULTIPLY_ASSIGNMENT: case DIVIDE_ASSIGNMENT: case REMAINDER_ASSIGNMENT: {
601
+ CompoundAssignmentTree a = (CompoundAssignmentTree) e;
602
+ JT t = ty(path, a.getVariable()), u = ty(path, a.getExpression());
603
+ String op = switch (e.getKind()) { case PLUS_ASSIGNMENT -> "+"; case MINUS_ASSIGNMENT -> "-"; case MULTIPLY_ASSIGNMENT -> "*"; case DIVIDE_ASSIGNMENT -> "/"; default -> "%"; };
604
+ if (t != null && t.is("java.lang.String")) return List.of(s("set", p, "to", place(a.getVariable(), path), "x", x("bin", p, "op", "+", "x", ex(a.getVariable(), path), "y", ex(a.getExpression(), path), "text", text(path, e))));
605
+ JT w = promote(t, u);
606
+ Map<String, Object> v = arith(op, ex(a.getVariable(), path), t, ex(a.getExpression(), path), u, w, "wrap", p, text(path, e));
607
+ return List.of(s("set", p, "to", place(a.getVariable(), path), "x", narrow(v, w, t, p)));
608
+ }
609
+ case PREFIX_INCREMENT: case POSTFIX_INCREMENT: case PREFIX_DECREMENT: case POSTFIX_DECREMENT: {
610
+ ExpressionTree v = ((UnaryTree) e).getExpression();
611
+ JT t = ty(path, v), w = promote(t, new JT("int"));
612
+ boolean inc = e.getKind() == Tree.Kind.PREFIX_INCREMENT || e.getKind() == Tree.Kind.POSTFIX_INCREMENT;
613
+ return List.of(s("set", p, "to", place(v, path), "x", narrow(arith(inc ? "+" : "-", ex(v, path), t, lit(1, w, p), w, w, "wrap", p, text(path, e)), w, t, p)));
614
+ }
615
+ case METHOD_INVOCATION: {
616
+ Object r = invoke((MethodInvocationTree) e, path, true);
617
+ if (r instanceof Low l && l.ss() != null) return l.ss();
618
+ return List.of(s("expr", p, "x", r instanceof Low l ? l.x() : r));
619
+ }
620
+ default: return List.of(s("expr", p, "x", ex(e, path)));
621
+ }
622
+ }
623
+ // A value computed at a wider type put back at a narrower one (a compound assignment's implicit cast): wrapped.
624
+ Map<String, Object> narrow(Map<String, Object> v, JT from, JT to, String p) {
625
+ if (to == null || from == null || Objects.equals(prim(from), prim(to)) || ity(to) == null) return v;
626
+ return x("conv", p, "x", v, "ity", ity(to), "why", "a conversion");
627
+ }
628
+ Map<String, Object> place(ExpressionTree v, TreePath path) {
629
+ TreePath vp = new TreePath(path, v);
630
+ Element el = trees.getElement(vp);
631
+ String p = where(vp, v);
632
+ if (el != null && el.getKind() == ElementKind.FIELD && !el.getModifiers().contains(Modifier.STATIC)) {
633
+ Map<String, Object> o = v instanceof MemberSelectTree ms ? ex(ms.getExpression(), vp) : self(p);
634
+ return get(o, el.getSimpleName().toString(), p, text(vp, v));
635
+ }
636
+ if (el != null && (el.getKind() == ElementKind.LOCAL_VARIABLE || el.getKind() == ElementKind.PARAMETER)) return var(el.getSimpleName().toString(), p);
637
+ if (v instanceof ArrayAccessTree) return no(p, text(vp, v) + ": an array's item");
638
+ if (el != null && el.getModifiers().contains(Modifier.STATIC)) return no(p, text(vp, v) + ": a static field (shared by every object, outside the object's state)");
639
+ return no(p, text(vp, v) + ": an assignment the subset doesn't read");
640
+ }
641
+
642
+ // --- expressions ---------------------------------------------------------------------------------------------------
643
+ Map<String, Object> ex(ExpressionTree e, TreePath pp) {
644
+ TreePath path = new TreePath(pp, e);
645
+ String p = where(path, e), t = text(path, e);
646
+ JT type = ty(pp, e);
647
+ switch (e.getKind()) {
648
+ case PARENTHESIZED: return ex(((ParenthesizedTree) e).getExpression(), path);
649
+ case INT_LITERAL: case LONG_LITERAL: return lit(((Number) ((LiteralTree) e).getValue()).longValue(), type, p);
650
+ case CHAR_LITERAL: return lit((Character) ((LiteralTree) e).getValue(), new JT("char"), p);
651
+ case BOOLEAN_LITERAL: return x("bool", p, "v", ((LiteralTree) e).getValue());
652
+ case STRING_LITERAL: return str((String) ((LiteralTree) e).getValue(), p);
653
+ case NULL_LITERAL: return x("none", p);
654
+ case FLOAT_LITERAL: case DOUBLE_LITERAL: {
655
+ double d = ((Number) ((LiteralTree) e).getValue()).doubleValue();
656
+ return d == Math.floor(d) && Math.abs(d) < 9.007199254740992E15 ? x("int", p, "v", Long.toString((long) d), "float", true) : no(p, t + ": a float that isn't whole (a binary fraction)");
657
+ }
658
+ case IDENTIFIER: case MEMBER_SELECT: return name(e, path, p, t, type);
659
+ case METHOD_INVOCATION: { Object r = invoke((MethodInvocationTree) e, pp, false); return r instanceof Low l ? (l.x() != null ? l.x() : no(p, t + ": a call used as a value")) : (Map<String, Object>) r; }
660
+ case NEW_CLASS: return make((NewClassTree) e, path, p, t, type);
661
+ case CONDITIONAL_EXPRESSION: { ConditionalExpressionTree c = (ConditionalExpressionTree) e; return x("ite", p, "c", ex(c.getCondition(), path), "a", at(ex(c.getTrueExpression(), path), ty(path, c.getTrueExpression()), type), "b", at(ex(c.getFalseExpression(), path), ty(path, c.getFalseExpression()), type)); }
662
+ case LOGICAL_COMPLEMENT: return not(ex(((UnaryTree) e).getExpression(), path), p);
663
+ case UNARY_MINUS: { ExpressionTree v = ((UnaryTree) e).getExpression(); if (floating(type)) return x("neg", p, "x", ex(v, path)); return x("unop", p, "op", "-", "x", at(ex(v, path), ty(path, v), type), "text", t); }
664
+ case UNARY_PLUS: return ex(((UnaryTree) e).getExpression(), path);
665
+ case TYPE_CAST: {
666
+ TypeCastTree c = (TypeCastTree) e;
667
+ JT from = ty(path, c.getExpression());
668
+ Map<String, Object> v = ex(c.getExpression(), path);
669
+ if (ity(type) == null || from == null) return v;
670
+ // (a float's whole value into an integer: Java's saturates at the type's range)
671
+ if (floating(from)) return x("bin", p, "op", "+", "x", x("as", p, "x", v, "ity", ity(type)), "y", lit(0, type, p), "ovf", "sat", "text", t);
672
+ int fb = (int) ity(from).get("bits"), tb = (int) ity(type).get("bits");
673
+ return tb >= fb && !"char".equals(prim(type)) ? x("as", p, "x", v, "ity", ity(type)) : x("conv", p, "x", v, "ity", ity(type), "why", t);
674
+ }
675
+ case SWITCH_EXPRESSION: return no(p, t + ": a switch expression (the subset reads switch statements)");
676
+ case LAMBDA_EXPRESSION: case MEMBER_REFERENCE: return no(p, t + ": a lambda (a closure)");
677
+ case INSTANCE_OF: return no(p, t + ": instanceof");
678
+ case ASSIGNMENT: case PLUS_ASSIGNMENT: case MINUS_ASSIGNMENT: case PREFIX_INCREMENT: case POSTFIX_INCREMENT: case PREFIX_DECREMENT: case POSTFIX_DECREMENT: return no(p, t + ": an assignment inside an expression");
679
+ case ARRAY_ACCESS: case NEW_ARRAY: return no(p, t + ": an array (outside the subset)");
680
+ default: break;
681
+ }
682
+ if (e instanceof BinaryTree b) return binary(b, path, p, t, type);
683
+ return no(p, t + ": " + e.getKind().toString().toLowerCase().replace('_', ' ') + " (outside the subset)");
684
+ }
685
+ Map<String, Object> binary(BinaryTree b, TreePath path, String p, String t, JT type) {
686
+ JT ta = ty(path, b.getLeftOperand()), tb = ty(path, b.getRightOperand());
687
+ Map<String, Object> l = ex(b.getLeftOperand(), path), r = ex(b.getRightOperand(), path);
688
+ switch (b.getKind()) {
689
+ case CONDITIONAL_AND: return x("and", p, "xs", List.of(l, r));
690
+ case CONDITIONAL_OR: return x("or", p, "xs", List.of(l, r));
691
+ case AND: case OR: if ("boolean".equals(prim(type))) return x(b.getKind() == Tree.Kind.AND ? "and" : "or", p, "xs", List.of(l, r)); return no(p, t + ": a bit operation (outside the subset)");
692
+ case XOR: if ("boolean".equals(prim(type))) return cmp("!=", l, r, p, t); return no(p, t + ": a bit operation (outside the subset)");
693
+ case EQUAL_TO: case NOT_EQUAL_TO: {
694
+ boolean eq = b.getKind() == Tree.Kind.EQUAL_TO;
695
+ if (b.getRightOperand().getKind() == Tree.Kind.NULL_LITERAL) return cmp(eq ? "is" : "is not", l, r, p, t);
696
+ if (b.getLeftOperand().getKind() == Tree.Kind.NULL_LITERAL) return cmp(eq ? "is" : "is not", r, l, p, t);
697
+ if (num(ta) && num(tb)) { JT w = promote(ta, tb); l = at(l, ta, w); r = at(r, tb, w); }
698
+ return cmp(eq ? "==" : "!=", l, r, p, t);
699
+ }
700
+ case LESS_THAN: case LESS_THAN_EQUAL: case GREATER_THAN: case GREATER_THAN_EQUAL: {
701
+ String op = switch (b.getKind()) { case LESS_THAN -> "<"; case LESS_THAN_EQUAL -> "<="; case GREATER_THAN -> ">"; default -> ">="; };
702
+ return cmp(op, l, r, p, t);
703
+ }
704
+ case PLUS: case MINUS: case MULTIPLY: case DIVIDE: case REMAINDER: {
705
+ if (type != null && type.is("java.lang.String")) return x("bin", p, "op", "+", "x", l, "y", r, "text", t);
706
+ String op = switch (b.getKind()) { case PLUS -> "+"; case MINUS -> "-"; case MULTIPLY -> "*"; case DIVIDE -> "/"; default -> "%"; };
707
+ if (floating(type) && (op.equals("/") || op.equals("%"))) return no(p, t + ": a float division (the subset reads whole numbers)");
708
+ return arith(op, l, ta, r, tb, type, "wrap", p, t);
709
+ }
710
+ case LEFT_SHIFT: case RIGHT_SHIFT: return x("binop", p, "op", b.getKind() == Tree.Kind.LEFT_SHIFT ? "<<" : ">>", "x", at(l, ta, type), "y", r, "text", t);
711
+ default: return no(p, t + ": a bit operation (outside the subset)");
712
+ }
713
+ }
714
+ // A name: a local, a field of this object or another, a constant (folded), an enum's constant (a choice's literal).
715
+ Map<String, Object> name(ExpressionTree e, TreePath path, String p, String t, JT type) {
716
+ if (e instanceof IdentifierTree id && (id.getName().contentEquals("this") || id.getName().contentEquals("super"))) return self(p);
717
+ Element el = trees.getElement(path);
718
+ if (el == null) return no(p, t + ": a name javac couldn't resolve (its class not on the classpath?)");
719
+ switch (el.getKind()) {
720
+ case LOCAL_VARIABLE: case PARAMETER: case RESOURCE_VARIABLE: case BINDING_VARIABLE: case EXCEPTION_PARAMETER: return var(el.getSimpleName().toString(), p);
721
+ case ENUM_CONSTANT: return str(el.getSimpleName().toString(), p);
722
+ case FIELD: {
723
+ VariableElement v = (VariableElement) el;
724
+ Object k = v.getConstantValue();
725
+ if (k instanceof Number n && !(k instanceof Double || k instanceof Float)) return lit(n.longValue(), jt(v.asType()), p);
726
+ if (k instanceof Boolean bo) return x("bool", p, "v", bo);
727
+ if (k instanceof String s) return str(s, p);
728
+ if (k instanceof Character c) return lit(c, new JT("char"), p);
729
+ if (v.getModifiers().contains(Modifier.STATIC)) {
730
+ String q = ((TypeElement) v.getEnclosingElement()).getQualifiedName() + "." + v.getSimpleName();
731
+ return x("opaque", p, "why", t + ": a static field (shared by every object, outside the object's state)", "q", q);
732
+ }
733
+ if (e instanceof MemberSelectTree ms) {
734
+ if (ms.getExpression() instanceof IdentifierTree id && id.getName().contentEquals("this")) return get(self(p), v.getSimpleName().toString(), p, t);
735
+ return get(ex(ms.getExpression(), path), v.getSimpleName().toString(), p, t);
736
+ }
737
+ return get(self(p), v.getSimpleName().toString(), p, t);
738
+ }
739
+ default:
740
+ if (e instanceof IdentifierTree id && id.getName().contentEquals("this")) return self(p);
741
+ if (e instanceof MemberSelectTree ms && ms.getIdentifier().contentEquals("length")) return no(p, t + ": an array's length");
742
+ return no(p, t + ": " + el.getKind().toString().toLowerCase() + " (outside the subset)");
743
+ }
744
+ }
745
+ // `new`: a record of the code's own (made from its fields), an atomic (its value), a map (empty), a lock or a
746
+ // monitor (Object), an exception (only thrown); anything else is other code's object.
747
+ Map<String, Object> make(NewClassTree n, TreePath path, String p, String t, JT type) {
748
+ if (n.getClassBody() != null) return no(p, t + ": an anonymous class");
749
+ List<Map<String, Object>> args = new ArrayList<>();
750
+ ExecutableElement c = (ExecutableElement) trees.getElement(path);
751
+ for (int i = 0; i < n.getArguments().size(); i++) {
752
+ ExpressionTree a = n.getArguments().get(i);
753
+ JT pt = c != null && i < c.getParameters().size() ? jt(c.getParameters().get(i).asType()) : null;
754
+ args.add(at(ex(a, path), ty(path, a), pt));
755
+ }
756
+ if (type == null) return no(p, t + ": a class javac couldn't resolve");
757
+ if (atomic(type)) return args.isEmpty() ? zero(held(type), p) : at(args.get(0), ty(path, n.getArguments().get(0)), held(type));
758
+ if (map(type)) return args.isEmpty() || (n.getArguments().size() == 1 && num(ty(path, n.getArguments().get(0)))) ? x("dict", p, "keys", List.of(), "vals", List.of(), "text", t) : no(p, t + ": a map made from another");
759
+ if (LOCKS.contains(type.n) || type.is("java.lang.Object")) return lock(p, t);
760
+ String r = rec(type.n);
761
+ if (r != null) return call(x("cls", p, "rec", r), args, p, t);
762
+ return x("opaque", p, "why", t + ": an object of other code made", "jt", type.toString());
763
+ }
764
+ // A call: the class's own method (inlined), the library's (lowered), or other code's (`ext`: answered or skipped by
765
+ // the caller, else refused). The site's span and type are kept for the check (an answered call's stub) and for the
766
+ // boundary's inference (the callee's declared type, whether its owner is an interface).
767
+ Object invoke(MethodInvocationTree mi, TreePath pp, boolean stmt) {
768
+ TreePath path = new TreePath(pp, mi);
769
+ String p = where(path, mi), t = text(path, mi);
770
+ Element el = trees.getElement(path);
771
+ if (!(el instanceof ExecutableElement me)) return no(p, t + ": a call javac couldn't resolve (its class not on the classpath?)");
772
+ TypeElement owner = (TypeElement) me.getEnclosingElement();
773
+ ExpressionTree sel = mi.getMethodSelect();
774
+ Map<String, Object> recv = null;
775
+ JT recvT = null;
776
+ boolean isStatic = me.getModifiers().contains(Modifier.STATIC), sup = false;
777
+ if (sel instanceof MemberSelectTree ms && !isStatic) {
778
+ ExpressionTree r = ms.getExpression();
779
+ if (r instanceof IdentifierTree id && id.getName().contentEquals("super")) { sup = true; recv = self(p); }
780
+ else { recv = ex(r, path); recvT = ty(path, r); }
781
+ } else if (!isStatic) recv = self(p);
782
+ List<Map<String, Object>> args = new ArrayList<>();
783
+ List<JT> argT = new ArrayList<>();
784
+ boolean pure = true;
785
+ for (int i = 0; i < mi.getArguments().size(); i++) {
786
+ ExpressionTree a = mi.getArguments().get(i);
787
+ JT pt = i < me.getParameters().size() && !me.isVarArgs() ? jt(me.getParameters().get(i).asType()) : null;
788
+ JT at0 = ty(path, a);
789
+ args.add(pt != null && num(pt) ? at(ex(a, path), at0, pt) : ex(a, path));
790
+ argT.add(pt != null && num(pt) ? pt : at0);
791
+ pure &= pure(a);
792
+ }
793
+ JT out = ty(pp, mi);
794
+ String oq = owner.getQualifiedName().toString(), n = me.getSimpleName().toString();
795
+ if (own(owner) || (recvT != null && rec(recvT.n) != null && trees.getPath(owner) != null)) {
796
+ if (isStatic) { String id = fid(me); if (!funcs.containsKey(id)) funcs.put(id, func(me)); return call(x("fn", p, "id", id), args, p, t); }
797
+ if (!own(owner)) { String f = getter(me); if (f != null) return get(recv, f, p, t); return no(p, t + ": a method of a value record (the subset reads its getters)"); }
798
+ if (sup) { String id = fid(me); if (!funcs.containsKey(id)) funcs.put(id, func(me)); return call(x("fn", p, "id", id), prepend(recv, args), p, t); }
799
+ return call(get(recv, key(me), p, t), args, p, t);
800
+ }
801
+ Low l = lib(new Call(oq, n, recv, recvT == null ? jt(owner.asType()) : recvT, args, argT, out, p, t, stmt, pure && (recv == null || pure(sel))));
802
+ if (l != null) {
803
+ if (l.x() != null && "clock".equals(l.x().get("e"))) rewrites.add(m("span", span(path, mi), "to", "now"));
804
+ return l;
805
+ }
806
+ String callee = sel.toString().replace("this.", "");
807
+ // (a method of an object of other code the class holds or is given: called on it, so an injected dependency is
808
+ // read as one; a static method of other code: `ext`, its declared result the answer's type)
809
+ Map<String, Object> f = recv != null && recvT != null && other(recvT.n) != null ? get(recv, n, p, callee) : x("ext", p, "q", oq + "." + n, "text", callee, "patch", m("mod", oq, "path", List.of(n)), "ret", stype(out, this));
810
+ return m("e", "call", "p", p, "text", t, "f", f, "args", argsRead(args), "kw", List.of(),
811
+ "jt", String.valueOf(out), "ity", ity(out), "decl", oq, "iface", owner.getKind() == ElementKind.INTERFACE ? true : null, "span", span(path, mi), "tag", tag(path, mi));
812
+ }
813
+ static List<Object> prepend(Object a, List<Map<String, Object>> xs) { List<Object> out = new ArrayList<>(); out.add(a); out.addAll(xs); return out; }
814
+ static List<Map<String, Object>> argsRead(List<Map<String, Object>> args) { return args; }
815
+ boolean pure(Tree t) {
816
+ boolean[] ok = {true};
817
+ new TreeScanner<Void, Void>() {
818
+ @Override public Void visitMethodInvocation(MethodInvocationTree n, Void v) { ok[0] = false; return null; }
819
+ @Override public Void visitNewClass(NewClassTree n, Void v) { ok[0] = false; return null; }
820
+ @Override public Void visitAssignment(AssignmentTree n, Void v) { ok[0] = false; return null; }
821
+ @Override public Void visitUnary(UnaryTree n, Void v) { if (n.getKind().toString().contains("CREMENT")) ok[0] = false; return super.visitUnary(n, v); }
822
+ }.scan(t, null);
823
+ return ok[0];
824
+ }
825
+ }