gdp-wired 0.44.0 → 0.46.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 (133) hide show
  1. package/README.md +58 -7
  2. package/dist/core/bitsets.d.ts +2 -0
  3. package/dist/core/bitsets.js +23 -0
  4. package/dist/core/bmc.js +6 -2
  5. package/dist/core/c/reader.d.ts +9 -1
  6. package/dist/core/c/reader.js +445 -38
  7. package/dist/core/calendar.d.ts +29 -0
  8. package/dist/core/calendar.js +82 -0
  9. package/dist/core/check.js +3 -2
  10. package/dist/core/cli.d.ts +4 -0
  11. package/dist/core/cli.js +335 -39
  12. package/dist/core/compose.js +3 -1
  13. package/dist/core/counts.d.ts +5 -2
  14. package/dist/core/counts.js +335 -88
  15. package/dist/core/cycles.js +8 -1
  16. package/dist/core/cyclic.d.ts +1 -0
  17. package/dist/core/cyclic.js +13 -7
  18. package/dist/core/data-synth.d.ts +3 -0
  19. package/dist/core/data-synth.js +252 -0
  20. package/dist/core/data.d.ts +8 -2
  21. package/dist/core/data.js +1113 -172
  22. package/dist/core/discover.js +3 -1
  23. package/dist/core/draft.d.ts +19 -0
  24. package/dist/core/draft.js +53 -0
  25. package/dist/core/dsl.d.ts +39 -3
  26. package/dist/core/dsl.js +250 -31
  27. package/dist/core/effect-prims.js +2 -2
  28. package/dist/core/effect.d.ts +1 -4
  29. package/dist/core/effect.js +1 -15
  30. package/dist/core/ex/reader.exs +17 -1
  31. package/dist/core/exists.d.ts +16 -1
  32. package/dist/core/exists.js +447 -50
  33. package/dist/core/extract-c.d.ts +2 -0
  34. package/dist/core/extract-c.js +185 -31
  35. package/dist/core/extract-check.d.ts +7 -0
  36. package/dist/core/extract-check.js +115 -3
  37. package/dist/core/extract-ex.js +3 -3
  38. package/dist/core/extract-go-check.d.ts +1 -1
  39. package/dist/core/extract-go-check.js +21 -13
  40. package/dist/core/extract-go.d.ts +1 -0
  41. package/dist/core/extract-go.js +58 -9
  42. package/dist/core/extract-ir.d.ts +1 -0
  43. package/dist/core/extract-ir.js +15 -0
  44. package/dist/core/extract-jvm.d.ts +1 -1
  45. package/dist/core/extract-jvm.js +65 -14
  46. package/dist/core/extract-orm.d.ts +12 -0
  47. package/dist/core/extract-orm.js +244 -0
  48. package/dist/core/extract-print.js +23 -1
  49. package/dist/core/extract-py.d.ts +1 -0
  50. package/dist/core/extract-py.js +4 -4
  51. package/dist/core/extract-rb.js +3 -3
  52. package/dist/core/extract-read.d.ts +25 -0
  53. package/dist/core/extract-read.js +60 -5
  54. package/dist/core/extract-rs.js +22 -20
  55. package/dist/core/extract-shapes.js +22 -0
  56. package/dist/core/extract-sol.d.ts +10 -1
  57. package/dist/core/extract-sol.js +89 -30
  58. package/dist/core/extract-step.d.ts +201 -4
  59. package/dist/core/extract-step.js +1514 -111
  60. package/dist/core/extract-swift.js +24 -13
  61. package/dist/core/extract.d.ts +9 -0
  62. package/dist/core/extract.js +88 -7
  63. package/dist/core/fiber-run.d.ts +5 -0
  64. package/dist/core/fiber-run.js +18 -0
  65. package/dist/core/fresh.d.ts +2 -2
  66. package/dist/core/fresh.js +7 -3
  67. package/dist/core/go/reader.go +7 -1
  68. package/dist/core/infer.d.ts +4 -1
  69. package/dist/core/infer.js +1020 -246
  70. package/dist/core/jvm/JavaReader.java +33 -8
  71. package/dist/core/jvm/Jvm.java +20 -1
  72. package/dist/core/jvm/KtReader.java +59 -6
  73. package/dist/core/laws.d.ts +10 -3
  74. package/dist/core/laws.js +193 -14
  75. package/dist/core/machine.d.ts +16 -3
  76. package/dist/core/machine.js +212 -28
  77. package/dist/core/nonterm.js +14 -1
  78. package/dist/core/orm/harness.js +61 -0
  79. package/dist/core/orm-fixtures/schema.prisma +5 -0
  80. package/dist/core/py/harness.py +260 -21
  81. package/dist/core/py/reader.py +278 -39
  82. package/dist/core/rb/reader.rb +52 -5
  83. package/dist/core/reader-fixtures/README.md +28 -0
  84. package/dist/core/reader-fixtures/c-693042.cpp +8 -0
  85. package/dist/core/reader-fixtures/go-685506.go +14 -0
  86. package/dist/core/reader-fixtures/jvm-724362.kt +8 -0
  87. package/dist/core/reader-fixtures/jvm-737430.kt +7 -0
  88. package/dist/core/reader-fixtures/jvm-765282.kt +3 -0
  89. package/dist/core/reader-fixtures/swift-735726.swift +15 -0
  90. package/dist/core/reader-fixtures/swift-735990.swift +15 -0
  91. package/dist/core/reader-fixtures/swift-739158.swift +4 -0
  92. package/dist/core/reader-fixtures/swift-744834.swift +15 -0
  93. package/dist/core/reader-fixtures/swift-746946.swift +31 -0
  94. package/dist/core/reader-fixtures/typescript-673062.ts.txt +2 -0
  95. package/dist/core/relation.d.ts +1 -1
  96. package/dist/core/relation.js +29 -2
  97. package/dist/core/relational.js +4 -2
  98. package/dist/core/rs/src/main.rs +18 -2
  99. package/dist/core/sample-cache.d.ts +8 -0
  100. package/dist/core/sample-cache.js +46 -0
  101. package/dist/core/security.d.ts +38 -0
  102. package/dist/core/security.js +88 -0
  103. package/dist/core/sol/harness.py +63 -7
  104. package/dist/core/sol-concrete.d.ts +23 -0
  105. package/dist/core/sol-concrete.js +195 -0
  106. package/dist/core/solver.js +8 -5
  107. package/dist/core/swift/Sources/gdp-swiftreader/main.swift +50 -7
  108. package/dist/core/system.d.ts +62 -1
  109. package/dist/core/system.js +263 -4
  110. package/dist/core/transfer.js +39 -9
  111. package/dist/core/translate.js +39 -10
  112. package/dist/core/watch.js +51 -6
  113. package/dist/interchange/check.js +10 -10
  114. package/dist/interchange/format.d.ts +4 -0
  115. package/dist/interchange/format.js +24 -6
  116. package/dist/kernel/cdcl.d.ts +5 -0
  117. package/dist/kernel/cdcl.js +88 -10
  118. package/dist/kernel/epr.js +141 -29
  119. package/dist/kernel/kernel.d.ts +31 -1
  120. package/dist/kernel/kernel.js +391 -101
  121. package/dist/kernel/model-sequence.d.ts +3 -0
  122. package/dist/kernel/model-sequence.js +34 -0
  123. package/dist/kernel/prove.d.ts +30 -1
  124. package/dist/kernel/prove.js +481 -71
  125. package/dist/kernel/reader.d.ts +3 -0
  126. package/dist/kernel/reader.js +101 -14
  127. package/dist/kernel/share.d.ts +1 -0
  128. package/dist/kernel/share.js +27 -0
  129. package/dist/lean-kernel/emit.d.ts +9 -3
  130. package/dist/lean-kernel/emit.js +200 -66
  131. package/dist/lean-kernel/lean-terms.js +5 -0
  132. package/dist/lean-kernel/library.js +10 -10
  133. package/package.json +7 -2
@@ -35,8 +35,16 @@ public final class JavaReader implements Jvm.Env {
35
35
  public static void main(String[] argv) throws Exception {
36
36
  Map<?, ?> req = (Map<?, ?>) parse(argv[0]);
37
37
  JavaReader r = new JavaReader();
38
- System.out.println(json(r.read(req)));
38
+ String out = null;
39
+ try { out = json(r.read(req)); } catch (RuntimeException | Error e) {
40
+ if (Jvm.overflowed(e)) Jvm.refuse("the source nests too deeply to read");
41
+ // (javac's error recovery leaves trees the walk can't read: the errors it reported are the reason)
42
+ if (r.errs.isEmpty()) Jvm.failed("Java", e);
43
+ Jvm.refuse("the source doesn't compile: " + String.join(" | ", r.errs.subList(0, Math.min(3, r.errs.size()))));
44
+ }
45
+ System.out.println(out);
39
46
  }
47
+ final List<String> errs = new ArrayList<>();
40
48
 
41
49
  Map<String, Object> read(Map<?, ?> req) throws IOException {
42
50
  String root = (String) req.get("root"), file = (String) req.get("file"), cp = (String) req.get("classpath");
@@ -44,9 +52,9 @@ public final class JavaReader implements Jvm.Env {
44
52
  StandardJavaFileManager fm = jc.getStandardFileManager(null, null, StandardCharsets.UTF_8);
45
53
  List<String> opts = new ArrayList<>(List.of("-proc:none", "-Xlint:none", "-sourcepath", root));
46
54
  if (cp != null && !cp.isEmpty()) { opts.add("-cp"); opts.add(cp); }
47
- List<String> errs = new ArrayList<>();
48
55
  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
56
  Iterable<? extends CompilationUnitTree> cus = task.parse();
57
+ if (!errs.isEmpty()) Jvm.refuse("the source doesn't parse: " + String.join(" | ", errs.subList(0, Math.min(3, errs.size()))));
50
58
  task.analyze();
51
59
  trees = Trees.instance(task); els = task.getElements(); types = task.getTypes(); sp = trees.getSourcePositions();
52
60
  CompilationUnitTree cu = cus.iterator().next();
@@ -58,7 +66,8 @@ public final class JavaReader implements Jvm.Env {
58
66
  for (Object n : names) {
59
67
  TypeElement te = find(cu, (String) n);
60
68
  if (te == null) { entries.add(m("k", "missing", "name", n)); continue; }
61
- jvm.put("ctorArity", req.get("ctor"));
69
+ jvm.put("ctorArity", req.get("ctor") instanceof Number ? req.get("ctor") : null);
70
+ jvm.put("ctorSignature", req.get("ctor") instanceof String ? req.get("ctor") : null);
62
71
  entries.add(m("k", "class", "rec", entry(te)));
63
72
  }
64
73
  out.put("entries", entries); out.put("recs", recs); out.put("funcs", funcs);
@@ -246,7 +255,8 @@ public final class JavaReader implements Jvm.Env {
246
255
  List<ExecutableElement> ctors = new ArrayList<>();
247
256
  for (Element e : te.getEnclosedElements()) if (e.getKind() == ElementKind.CONSTRUCTOR) ctors.add((ExecutableElement) e);
248
257
  Object want = jvm.get("ctorArity");
249
- List<ExecutableElement> pick = ctors.stream().filter(c -> want == null || c.getParameters().size() == ((Number) want).intValue()).toList();
258
+ String wantedSignature = (String) jvm.get("ctorSignature");
259
+ List<ExecutableElement> pick = ctors.stream().filter(c -> wantedSignature != null ? ctorSignature(c).equals(wantedSignature.replace(" ", "")) : want == null || c.getParameters().size() == ((Number) want).intValue()).toList();
250
260
  Map<String, Object> jctor = m();
251
261
  if (pick.size() != 1) {
252
262
  methods.put("__init__", name + "#<init>");
@@ -255,13 +265,15 @@ public final class JavaReader implements Jvm.Env {
255
265
  ExecutableElement c = pick.get(0);
256
266
  methods.put("__init__", name + "#<init>");
257
267
  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)); }
268
+ methods.put("__init__/" + fid(c), name + "#<init>");
269
+ for (ExecutableElement o : ctors) if (o != c) { methods.put("__init__/" + fid(o), fid(o)); funcs.put(fid(o), ctor(te, o, cpath)); }
259
270
  jctor = m("params", c.getParameters().stream().map(v -> erased(v.asType())).toList(), "names", c.getParameters().stream().map(v -> v.getSimpleName().toString()).toList(),
260
271
  "jts", c.getParameters().stream().map(v -> String.valueOf(jt(v.asType()))).toList(), "ifaces", c.getParameters().stream().map(v -> iface(v.asType())).toList(),
261
272
  "annos", trees.getPath(c) == null ? List.of() : annos(trees.getPath(c), ((MethodTree) trees.getTree(c)).getModifiers().getAnnotations()),
262
273
  "paramAnnos", trees.getPath(c) == null ? List.of() : ((MethodTree) trees.getTree(c)).getParameters().stream().map(v -> annos(trees.getPath(c), v.getModifiers().getAnnotations())).toList());
263
274
  }
264
275
  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),
276
+ "initializers", want == null && wantedSignature == null && pick.size() > 1 ? ctors.stream().map(this::ctorSignature).toList() : null,
265
277
  "jvm", m("fields", jfields, "annos", annos(cpath, ct.getModifiers().getAnnotations()), "ctor", jctor, "cls", name, "sigs", sigs)));
266
278
  jvm.put("cls", name);
267
279
  jvm.put("ctor", jctor.get("params"));
@@ -269,6 +281,9 @@ public final class JavaReader implements Jvm.Env {
269
281
  reading.remove(name);
270
282
  return name;
271
283
  }
284
+ String ctorSignature(ExecutableElement c) {
285
+ return "(" + String.join(",", c.getParameters().stream().map(v -> erased(v.asType())).toList()) + ")";
286
+ }
272
287
  String refusedRec(TypeElement te, String name, String why) {
273
288
  TreePath cp = trees.getPath(te);
274
289
  funcs.put(name + "#<init>", stub(te, cp, "<init>", why));
@@ -422,7 +437,7 @@ public final class JavaReader implements Jvm.Env {
422
437
  ExecutableElement callee = (ExecutableElement) trees.getElement(ip);
423
438
  List<Object> args = new ArrayList<>();
424
439
  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)))); }
440
+ if (mi.getMethodSelect().toString().equals("this")) { delegates = true; body.add(s("expr", p, "x", call(get(self(p), "__init__/" + fid(callee), p, "this"), args, p, text(ip, mi)))); }
426
441
  else if (callee != null && trees.getPath(callee) != null) {
427
442
  String sid = fid(callee);
428
443
  if (!funcs.containsKey(sid)) funcs.put(sid, ctor((TypeElement) callee.getEnclosingElement(), callee, trees.getPath(callee.getEnclosingElement())));
@@ -666,7 +681,11 @@ public final class JavaReader implements Jvm.Env {
666
681
  TypeCastTree c = (TypeCastTree) e;
667
682
  JT from = ty(path, c.getExpression());
668
683
  Map<String, Object> v = ex(c.getExpression(), path);
684
+ // (an integer into a float: exact below 2^24, an edge past it; into a double, below the rule's own 2^53)
685
+ if ("float".equals(prim(type)) && from != null && integral(from)) return x("fbits", p, "x", v, "bits", 24, "text", t);
669
686
  if (ity(type) == null || from == null) return v;
687
+ // (a float division into an integer: truncated toward zero, a whole number within the type's range)
688
+ if (floating(from) && "bin".equals(v.get("e")) && Boolean.TRUE.equals(v.get("fdiv"))) v = x("rnd", p, "mode", "trunc", "x", v, "text", t);
670
689
  // (a float's whole value into an integer: Java's saturates at the type's range)
671
690
  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
691
  int fb = (int) ity(from).get("bits"), tb = (int) ity(type).get("bits");
@@ -704,7 +723,10 @@ public final class JavaReader implements Jvm.Env {
704
723
  case PLUS: case MINUS: case MULTIPLY: case DIVIDE: case REMAINDER: {
705
724
  if (type != null && type.is("java.lang.String")) return x("bin", p, "op", "+", "x", l, "y", r, "text", t);
706
725
  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)");
726
+ // (a float division: a true division, kept only where a rounding to a whole number reads it (Math.round, floor,
727
+ // ceil, rint, a cast); its precision, a double's 53 bits or a float's 24, bounds where that is exact)
728
+ if (floating(type) && op.equals("/")) return x("bin", p, "op", "/", "x", l, "y", r, "text", t, "fdiv", true, "prec", "float".equals(prim(type)) || "float".equals(prim(ta)) || "float".equals(prim(tb)) ? 24 : 53);
729
+ if (floating(type) && op.equals("%")) return no(p, t + ": a float remainder (the subset reads whole numbers)");
708
730
  return arith(op, l, ta, r, tb, type, "wrap", p, t);
709
731
  }
710
732
  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);
@@ -786,7 +808,10 @@ public final class JavaReader implements Jvm.Env {
786
808
  ExpressionTree a = mi.getArguments().get(i);
787
809
  JT pt = i < me.getParameters().size() && !me.isVarArgs() ? jt(me.getParameters().get(i).asType()) : null;
788
810
  JT at0 = ty(path, a);
789
- args.add(pt != null && num(pt) ? at(ex(a, path), at0, pt) : ex(a, path));
811
+ // (an integer passed as a float: exact below 2^24, an edge past it)
812
+ Map<String, Object> av = pt != null && num(pt) ? at(ex(a, path), at0, pt) : ex(a, path);
813
+ if (pt != null && "float".equals(prim(pt)) && at0 != null && integral(at0)) av = x("fbits", where(new TreePath(path, a), a), "x", av, "bits", 24, "text", text(new TreePath(path, a), a));
814
+ args.add(av);
790
815
  argT.add(pt != null && num(pt) ? pt : at0);
791
816
  pure &= pure(a);
792
817
  }
@@ -48,6 +48,20 @@ public final class Jvm {
48
48
  return n.contains(".") || n.contains("e") || n.contains("E") ? (Object) Double.parseDouble(n) : (Object) Long.parseLong(n);
49
49
  }
50
50
  static String json(Object o) { StringBuilder b = new StringBuilder(); json(o, b); return b.toString(); }
51
+ // A source a reader can't read, said so on stderr (core/extract-read.ts's statedRefusal): a syntax error, or nesting
52
+ // past the reader's stack (javac's parser and the walk recurse on each level), found anywhere in a throw's causes.
53
+ static void refuse(String why) { System.err.println("gdp: refused: " + why.replace('\n', ' ')); System.exit(3); }
54
+ // A reader's own failure on a source it parsed (javac's internal assertions on a tree it recovered, a type the walk
55
+ // couldn't resolve): refused, the reason naming the failure and where, so it is never read as a missing tool.
56
+ static void failed(String lang, Throwable e) {
57
+ Throwable r = e; while (r.getCause() != null) r = r.getCause();
58
+ StackTraceElement at = r.getStackTrace().length > 0 ? r.getStackTrace()[0] : null;
59
+ // (the compiler's own failure, javac's or Kotlin's, on what it recovered from the source: the source is past it)
60
+ if (at != null && (at.getClassName().startsWith("com.sun.tools.javac") || at.getClassName().startsWith("org.jetbrains.kotlin") || at.getClassName().startsWith("com.intellij")))
61
+ refuse("the " + lang + " compiler failed on this source (" + r.getClass().getSimpleName() + ")");
62
+ refuse("the " + lang + " reader failed on this source (" + r.getClass().getSimpleName() + (at != null ? " at " + at.getClassName() + "." + at.getMethodName() + ":" + at.getLineNumber() : "") + ")");
63
+ }
64
+ static boolean overflowed(Throwable t) { for (; t != null; t = t.getCause()) if (t instanceof StackOverflowError) return true; return false; }
51
65
  static void json(Object o, StringBuilder b) {
52
66
  if (o == null) b.append("null");
53
67
  else if (o instanceof String s) {
@@ -106,7 +120,7 @@ public final class Jvm {
106
120
  static final Set<String> LOCKS = Set.of("java.util.concurrent.locks.ReentrantLock", "java.util.concurrent.locks.Lock", "java.util.concurrent.locks.ReentrantReadWriteLock", "java.util.concurrent.locks.ReadWriteLock", "java.util.concurrent.locks.StampedLock", "kotlinx.coroutines.sync.Mutex");
107
121
  static final List<String> UNITS = List.of("NANOSECONDS", "MICROSECONDS", "MILLISECONDS", "SECONDS", "MINUTES", "HOURS", "DAYS");
108
122
  static final long[] NANOS = {1L, 1_000L, 1_000_000L, 1_000_000_000L, 60_000_000_000L, 3_600_000_000_000L, 86_400_000_000_000L};
109
- static String prim(JT t) { return PRIM.contains(t.n) ? t.n : BOX.get(t.n); }
123
+ static String prim(JT t) { return t == null ? null : PRIM.contains(t.n) ? t.n : BOX.get(t.n); } // (null: a type the reader could not resolve)
110
124
  static boolean num(JT t) { String q = prim(t); return q != null && !q.equals("boolean") && !q.equals("void"); }
111
125
  static boolean integral(JT t) { String q = prim(t); return q != null && Set.of("int", "long", "short", "byte", "char").contains(q); }
112
126
  static boolean floating(JT t) { String q = prim(t); return "float".equals(q) || "double".equals(q); }
@@ -186,6 +200,8 @@ public final class Jvm {
186
200
 
187
201
  // An operand at a type (Java's binary promotion made explicit: the executor computes at its operands' type).
188
202
  static Map<String, Object> at(Map<String, Object> v, JT from, JT to) {
203
+ // (a boxed value unboxed: null is a NullPointerException)
204
+ if (from != null && to != null && BOX.containsKey(from.n) && PRIM.contains(to.n) && !to.n.equals("void")) v = x("expect", (String) v.get("p"), "x", v, "text", String.valueOf(v.getOrDefault("text", from.n)), "npe", true);
189
205
  Map<String, Object> it = ity(to);
190
206
  if (it == null || (from != null && Objects.equals(prim(from), prim(to)))) return v;
191
207
  if ("int".equals(v.get("e"))) { Map<String, Object> c = new LinkedHashMap<>(v); c.put("ity", it); return c; }
@@ -211,6 +227,9 @@ public final class Jvm {
211
227
  case "negateExact": if (na == 1) return ex(arith("-", lit(0, c.out, p), c.out, a.get(0), a0, c.out, "trap", p, t)); break;
212
228
  case "toIntExact": if (na == 1) return ex(arith("+", x("as", p, "x", a.get(0), "ity", ity(new JT("int"))), c.out, lit(0, c.out, p), c.out, c.out, "trap", p, t)); break;
213
229
  case "floorDiv", "floorMod": if (na == 2) return ex(x("as", p, "x", x("bin", p, "op", n.equals("floorDiv") ? "//" : "%", "x", a.get(0), "y", a.get(1), "text", t), "ity", ity(c.out))); break;
230
+ // (a float division rounded to a whole number: round ties up, rint ties to the even one, floor, ceil)
231
+ // (of an integer, javac's round(float), the argument converted to a float first: the reader's fbits, an edge)
232
+ case "round", "rint", "floor", "ceil": if (na == 1) return ex(x("rnd", p, "mode", switch (n) { case "round" -> o.equals("kotlin.math.MathKt") ? "even" : "up"; case "rint" -> "even"; default -> n; }, "x", a.get(0), "text", t)); break;
214
233
  case "clamp": if (na == 3) return ex(x("minmax", p, "op", "max", "xs", List.of(at(a.get(1), c.argT.get(1), c.out), x("minmax", p, "op", "min", "xs", List.of(at(a.get(0), a0, c.out), at(a.get(2), c.argT.get(2), c.out)), "ity", ity(c.out))), "ity", ity(c.out), "text", t)); break;
215
234
  }
216
235
  return null;
@@ -51,7 +51,9 @@ public final class KtReader implements Jvm.Env {
51
51
  public static void main(String[] argv) throws Exception {
52
52
  Map<?, ?> req = (Map<?, ?>) parse(argv[0]);
53
53
  Jvm.kotlin = true;
54
- System.out.println(json(new KtReader().read(req)));
54
+ String out = null;
55
+ try { out = json(new KtReader().read(req)); } catch (RuntimeException | Error e) { if (!Jvm.overflowed(e)) Jvm.failed("Kotlin", e); Jvm.refuse("the source nests too deeply to read"); }
56
+ System.out.println(out);
55
57
  }
56
58
  static KtPsiFactory factory() throws Exception {
57
59
  CompilerConfiguration cfg = new CompilerConfiguration();
@@ -68,9 +70,21 @@ public final class KtReader implements Jvm.Env {
68
70
  Map<String, Object> read(Map<?, ?> req) throws Exception {
69
71
  String path = (String) req.get("file"), root = (String) req.get("root");
70
72
  src = Files.readString(Path.of(path));
73
+ // A linear, conservative text limit before PSI error recovery (which can be exponential
74
+ // on unclosed delimiters). Includes strings/comments; this is a resource refusal, not a syntax claim.
75
+ int depth = 0, most = 0;
76
+ for (int i = 0; i < src.length(); i++) { char c = src.charAt(i); if (c == '(' || c == '[' || c == '{') most = Math.max(most, ++depth); else if (c == ')' || c == ']' || c == '}') depth = Math.max(0, depth - 1); }
77
+ if (most > 32) Jvm.refuse(new File(path).getName() + ": the source nests " + most + " delimiter characters deep (reader limit 32, including strings and comments)");
71
78
  base = new File(path).getName();
72
79
  KtPsiFactory f = factory();
73
80
  file = f.createFile(base, src);
81
+ // (the PSI recovers from a syntax error and leaves an error element where it was: what the walk past it reads is
82
+ // not the code the compiler would refuse, so the source is refused there)
83
+ com.intellij.psi.PsiErrorElement bad = com.intellij.psi.util.PsiTreeUtil.findChildOfType(file, com.intellij.psi.PsiErrorElement.class);
84
+ if (bad != null) {
85
+ int at = bad.getTextRange().getStartOffset(), line = 1 + (int) src.substring(0, Math.min(at, src.length())).chars().filter(c -> c == '\n').count();
86
+ Jvm.refuse("the source doesn't parse: line " + line + ": " + bad.getErrorDescription());
87
+ }
74
88
  pkg = file.getPackageFqName().asString();
75
89
  List<Integer> ls = new ArrayList<>(List.of(0));
76
90
  for (int i = 0; i < src.length(); i++) if (src.charAt(i) == '\n') ls.add(i + 1);
@@ -114,7 +128,7 @@ public final class KtReader implements Jvm.Env {
114
128
 
115
129
  // --- positions ---------------------------------------------------------------------------------------------------------
116
130
  int line(int off) { int i = Arrays.binarySearch(lines, off); return i >= 0 ? i + 1 : -i - 1; }
117
- String where(PsiElement e) { int o = e.getTextRange().getStartOffset(), l = line(o); return base + ":" + l + ":" + (o - lines[l - 1] + 1); }
131
+ String where(PsiElement e) { if (e == null) Jvm.refuse(base + ": incomplete syntax: a required expression is missing"); int o = e.getTextRange().getStartOffset(), l = line(o); return base + ":" + l + ":" + (o - lines[l - 1] + 1); }
118
132
  String zero() { return base + ":0:0"; }
119
133
  static String text(PsiElement e) { String x = e.getText().replaceAll("\\s+", " "); return x.length() <= 60 ? x : x.substring(0, 57) + "..."; }
120
134
  List<Object> span(PsiElement e) { return List.of(e.getTextRange().getStartOffset(), e.getTextRange().getEndOffset()); }
@@ -158,7 +172,7 @@ public final class KtReader implements Jvm.Env {
158
172
  }
159
173
  return null;
160
174
  }
161
- static JT boxed(JT t) { String b = UNBOX.get(t.n); return b == null ? t : new JT(b, t.a, t.nul); }
175
+ static JT boxed(JT t) { if (t == null) return null; String b = UNBOX.get(t.n); return b == null ? t : new JT(b, t.a, t.nul); }
162
176
  // A JVM parameter's erased type, as the harness looks the method up.
163
177
  static String erased(JT t) { if (t == null) return "java.lang.Object"; if (t.nul) return UNBOX.getOrDefault(t.n, t.n); return t.n.equals("void") ? "java.lang.Object" : t.n; }
164
178
  @Override public List<String> enumValues(String fq) {
@@ -299,6 +313,7 @@ public final class KtReader implements Jvm.Env {
299
313
  }
300
314
  static List<KtDeclaration> body(KtClassOrObject k) { return k.getBody() == null ? List.of() : k.getBody().getDeclarations(); }
301
315
  String key(KtClassOrObject k, KtNamedFunction fn) {
316
+ if (fn.getName() == null) Jvm.refuse(where(fn) + ": a function declaration is missing its name");
302
317
  long same = body(k).stream().filter(d -> d instanceof KtNamedFunction f && Objects.equals(f.getName(), fn.getName())).count();
303
318
  String n = same > 1 ? fn.getName() + "/" + fn.getValueParameters().size() : fn.getName();
304
319
  return fn.hasModifier(KtTokens.PRIVATE_KEYWORD) || Set.of("equals", "hashCode", "toString").contains(fn.getName()) ? "_" + n : n;
@@ -389,6 +404,36 @@ public final class KtReader implements Jvm.Env {
389
404
  }
390
405
  return m("id", binOf(c) + "#<init>", "name", "__init__", "cls", selfName, "p", p, "span", List.of(base, 0, 0), "params", prepend(m("name", "self", "t", m("k", "any"), "self", true), params), "ret", m("k", "none"), "body", body, "decorators", List.of());
391
406
  }
407
+ // What a data class's copy runs that the subset doesn't read as an update with its init blocks after: a property
408
+ // its body computes from the constructor's parameters (computed again), an init block that sets one, an init block of
409
+ // another class than the one read.
410
+ String copyRuns(KtClassOrObject k) {
411
+ if (!(k instanceof KtClass kc)) return null;
412
+ Set<String> ps = new HashSet<>();
413
+ for (KtParameter pa : kc.getPrimaryConstructorParameters()) ps.add(pa.getName());
414
+ for (KtDeclaration d : body(k)) {
415
+ if (d instanceof KtProperty pr && !computed(pr) && pr.getInitializer() != null && com.intellij.psi.util.PsiTreeUtil.findChildrenOfType(pr.getInitializer(), KtNameReferenceExpression.class).stream().anyMatch(r -> ps.contains(r.getReferencedName())))
416
+ return "a copy of a data class whose property " + pr.getName() + " is computed from its constructor (copy computes it again)";
417
+ if (d instanceof KtAnonymousInitializer ai) {
418
+ if (k != self) return "a copy of another data class with an init block (copy runs it again)";
419
+ if (com.intellij.psi.util.PsiTreeUtil.findChildrenOfType(ai, KtBinaryExpression.class).stream().anyMatch(b -> KtTokens.ALL_ASSIGNMENTS.contains(b.getOperationToken())))
420
+ return "a copy of a data class whose init block sets a property (copy runs it again)";
421
+ }
422
+ }
423
+ return null;
424
+ }
425
+ // The init blocks run on a copy (self): the copy returned.
426
+ String copyCheck(KtClassOrObject k) {
427
+ String id = binOf(k) + "#<copy>";
428
+ if (!funcs.containsKey(id)) {
429
+ Ctx cx = new Ctx(new ArrayList<>(), new HashMap<>(), 0, false);
430
+ List<Object> b = new ArrayList<>();
431
+ for (KtDeclaration d : body(k)) if (d instanceof KtAnonymousInitializer ai && ai.getBody() instanceof KtBlockExpression bl) b.addAll(block(bl.getStatements(), cx, null));
432
+ b.add(s("ret", where(k), "x", self(where(k))));
433
+ funcs.put(id, fn(id, "copy", k, List.of(), new JT(binOf(k)), b, null));
434
+ }
435
+ return id;
436
+ }
392
437
  static List<Object> prepend(Object a, List<Object> xs) { List<Object> out = new ArrayList<>(); out.add(a); out.addAll(xs); return out; }
393
438
 
394
439
  // --- statements ------------------------------------------------------------------------------------------------------
@@ -610,11 +655,13 @@ public final class KtReader implements Jvm.Env {
610
655
  if (et == KtNodeTypes.INTEGER_CONSTANT) {
611
656
  boolean lng = s.endsWith("L") || s.endsWith("l");
612
657
  String d = s.replaceAll("[lLuU]+$", "");
613
- long v = d.startsWith("0x") || d.startsWith("0X") ? Long.parseLong(d.substring(2), 16) : d.startsWith("0b") || d.startsWith("0B") ? Long.parseLong(d.substring(2), 2) : Long.parseLong(d);
658
+ long v;
659
+ try { v = d.startsWith("0x") || d.startsWith("0X") ? Long.parseLong(d.substring(2), 16) : d.startsWith("0b") || d.startsWith("0B") ? Long.parseLong(d.substring(2), 2) : Long.parseLong(d); }
660
+ catch (NumberFormatException nfe) { return no1(k, "an integer literal past 64 bits"); }
614
661
  JT ty = lng || v > Integer.MAX_VALUE || v < Integer.MIN_VALUE ? new JT("long") : want != null && integral(want) ? new JT(prim(want)) : new JT("int");
615
662
  return new X(lit(v, ty, p), ty);
616
663
  }
617
- if (et == KtNodeTypes.FLOAT_CONSTANT) { double d = Double.parseDouble(s.replaceAll("[fF]$", "")); return d == Math.floor(d) && Math.abs(d) < 9.007199254740992E15 ? new X(x("int", p, "v", Long.toString((long) d), "float", true), new JT(s.endsWith("f") || s.endsWith("F") ? "float" : "double")) : no1(e, "a float that isn't whole (a binary fraction)"); }
664
+ if (et == KtNodeTypes.FLOAT_CONSTANT) { double d; try { d = Double.parseDouble(s.replaceAll("[fF]$", "")); } catch (NumberFormatException nfe) { return no1(k, "a float literal that isn't a number"); } return d == Math.floor(d) && Math.abs(d) < 9.007199254740992E15 ? new X(x("int", p, "v", Long.toString((long) d), "float", true), new JT(s.endsWith("f") || s.endsWith("F") ? "float" : "double")) : no1(e, "a float that isn't whole (a binary fraction)"); }
618
665
  if (et == KtNodeTypes.CHARACTER_CONSTANT) return no1(e, "a character literal");
619
666
  }
620
667
  if (e instanceof KtStringTemplateExpression st) {
@@ -890,7 +937,13 @@ public final class KtReader implements Jvm.Env {
890
937
  if (!args.isEmpty()) return no1(ce, "copy given arguments by position");
891
938
  List<Object> fs = new ArrayList<>();
892
939
  for (Object k0 : kw) fs.add(k0);
893
- return new X(x("upd", p, "x", recv == null ? self(p) : recv.ir(), "fields", fs, "text", t), recv == null ? new JT(selfName) : recv.t());
940
+ Map<String, Object> u = x("upd", p, "x", recv == null ? self(p) : recv.ir(), "fields", fs, "text", t);
941
+ // (copy makes the object anew by its primary constructor: its init blocks run again, on the copy's fields)
942
+ KtClassOrObject of = recv == null ? self : classes.get(recv.t().n);
943
+ String why = copyRuns(of);
944
+ if (why != null) return no1(ce, why);
945
+ if (of != null && body(of).stream().anyMatch(d -> d instanceof KtAnonymousInitializer)) u = m("e", "call", "p", p, "text", t, "f", x("fn", p, "id", copyCheck(of)), "args", List.of(u), "kw", List.of());
946
+ return new X(u, recv == null ? new JT(selfName) : recv.t());
894
947
  }
895
948
  // a constructor: a class of the code's own (made from its fields), an atomic, a map, a lock
896
949
  String ctorOf = recv == null && Character.isUpperCase(n.charAt(0)) ? resolve(n) : null;
@@ -1,5 +1,7 @@
1
1
  import type { Extraction, Name } from './extract.js';
2
2
  import { type TwoRunLaw } from './relational.js';
3
+ import { type Calendar } from './calendar.js';
4
+ export { businessDays, type Calendar } from './calendar.js';
3
5
  export type LawText = {
4
6
  name: string;
5
7
  expr: string;
@@ -65,13 +67,19 @@ type X = {
65
67
  k: 'dur';
66
68
  v: number;
67
69
  text: string;
70
+ } | {
71
+ k: 'bdur';
72
+ v: number;
73
+ text: string;
68
74
  };
69
75
  export declare function duration(text: string, clock?: 's' | 'ms'): number;
70
76
  export declare function parse(s: string): X;
71
77
  export declare function namesWithClock(x: Extraction): Name[];
72
- export declare function buildLaw(x: Extraction, l: LawText, opts?: {
78
+ export type LawOpts = {
73
79
  clock?: number;
74
- }): Built;
80
+ calendar?: Calendar;
81
+ };
82
+ export declare function buildLaw(x: Extraction, l: LawText, opts?: LawOpts): Built;
75
83
  export type Cite = {
76
84
  law: string;
77
85
  text: string;
@@ -84,4 +92,3 @@ export declare const isLeadsTo: (expr: string) => boolean;
84
92
  export declare function buildLeadsTo(x: Extraction, l: LawText, opts?: {
85
93
  clock?: number;
86
94
  }): unknown;
87
- export {};