gdp-wired 0.45.0 → 0.47.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 (126) hide show
  1. package/README.md +61 -8
  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 +423 -31
  7. package/dist/core/calendar.d.ts +29 -0
  8. package/dist/core/calendar.js +82 -0
  9. package/dist/core/cli.d.ts +4 -0
  10. package/dist/core/cli.js +206 -40
  11. package/dist/core/compose.js +3 -1
  12. package/dist/core/counts.d.ts +4 -1
  13. package/dist/core/counts.js +314 -85
  14. package/dist/core/cycles.js +8 -1
  15. package/dist/core/cyclic.d.ts +1 -0
  16. package/dist/core/cyclic.js +13 -7
  17. package/dist/core/data-synth.d.ts +3 -0
  18. package/dist/core/data-synth.js +252 -0
  19. package/dist/core/data.d.ts +2 -1
  20. package/dist/core/data.js +223 -24
  21. package/dist/core/discover.js +3 -1
  22. package/dist/core/draft.d.ts +19 -0
  23. package/dist/core/draft.js +53 -0
  24. package/dist/core/dsl.d.ts +37 -3
  25. package/dist/core/dsl.js +167 -26
  26. package/dist/core/effect-schema.d.ts +90 -0
  27. package/dist/core/effect-schema.js +500 -0
  28. package/dist/core/effect.d.ts +4 -11
  29. package/dist/core/effect.js +3 -79
  30. package/dist/core/exists.d.ts +1 -0
  31. package/dist/core/exists.js +191 -16
  32. package/dist/core/extract-c.d.ts +2 -0
  33. package/dist/core/extract-c.js +169 -22
  34. package/dist/core/extract-check.d.ts +1 -0
  35. package/dist/core/extract-check.js +97 -6
  36. package/dist/core/extract-go-check.d.ts +1 -1
  37. package/dist/core/extract-go-check.js +26 -5
  38. package/dist/core/extract-go.d.ts +8 -0
  39. package/dist/core/extract-go.js +67 -6
  40. package/dist/core/extract-ir.d.ts +1 -0
  41. package/dist/core/extract-ir.js +15 -0
  42. package/dist/core/extract-jvm.d.ts +1 -1
  43. package/dist/core/extract-jvm.js +2 -0
  44. package/dist/core/extract-orm.d.ts +12 -0
  45. package/dist/core/extract-orm.js +244 -0
  46. package/dist/core/extract-print.js +20 -1
  47. package/dist/core/extract-py.d.ts +1 -0
  48. package/dist/core/extract-py.js +1 -1
  49. package/dist/core/extract-read.d.ts +26 -1
  50. package/dist/core/extract-read.js +14 -7
  51. package/dist/core/extract-rs.js +63 -15
  52. package/dist/core/extract-shapes.d.ts +1 -0
  53. package/dist/core/extract-shapes.js +84 -0
  54. package/dist/core/extract-sol.d.ts +10 -1
  55. package/dist/core/extract-sol.js +70 -22
  56. package/dist/core/extract-standalone.d.ts +3 -0
  57. package/dist/core/extract-standalone.js +221 -0
  58. package/dist/core/extract-step.d.ts +151 -1
  59. package/dist/core/extract-step.js +1232 -60
  60. package/dist/core/extract-swift.js +6 -2
  61. package/dist/core/extract.d.ts +9 -0
  62. package/dist/core/extract.js +77 -7
  63. package/dist/core/fiber-run.d.ts +5 -0
  64. package/dist/core/fiber-run.js +18 -0
  65. package/dist/core/infer.d.ts +4 -1
  66. package/dist/core/infer.js +918 -217
  67. package/dist/core/jvm/JavaReader.java +23 -6
  68. package/dist/core/jvm/Jvm.java +3 -0
  69. package/dist/core/jvm/KtReader.java +6 -5
  70. package/dist/core/laws.d.ts +10 -3
  71. package/dist/core/laws.js +226 -23
  72. package/dist/core/machine.d.ts +15 -1
  73. package/dist/core/machine.js +187 -15
  74. package/dist/core/nonterm.js +14 -1
  75. package/dist/core/orm/harness.js +61 -0
  76. package/dist/core/orm-fixtures/schema.prisma +5 -0
  77. package/dist/core/py/harness.py +183 -10
  78. package/dist/core/py/reader.py +234 -40
  79. package/dist/core/reader-fixtures/README.md +28 -0
  80. package/dist/core/reader-fixtures/c-693042.cpp +8 -0
  81. package/dist/core/reader-fixtures/go-685506.go +14 -0
  82. package/dist/core/reader-fixtures/jvm-724362.kt +8 -0
  83. package/dist/core/reader-fixtures/jvm-737430.kt +7 -0
  84. package/dist/core/reader-fixtures/jvm-765282.kt +3 -0
  85. package/dist/core/reader-fixtures/swift-735726.swift +15 -0
  86. package/dist/core/reader-fixtures/swift-735990.swift +15 -0
  87. package/dist/core/reader-fixtures/swift-739158.swift +4 -0
  88. package/dist/core/reader-fixtures/swift-744834.swift +15 -0
  89. package/dist/core/reader-fixtures/swift-746946.swift +31 -0
  90. package/dist/core/reader-fixtures/typescript-673062.ts.txt +2 -0
  91. package/dist/core/relation.d.ts +1 -1
  92. package/dist/core/relation.js +29 -2
  93. package/dist/core/relational.js +4 -2
  94. package/dist/core/rs/Cargo.toml +1 -1
  95. package/dist/core/rs/src/main.rs +466 -11
  96. package/dist/core/sample-cache.d.ts +8 -0
  97. package/dist/core/sample-cache.js +46 -0
  98. package/dist/core/security.d.ts +38 -0
  99. package/dist/core/security.js +88 -0
  100. package/dist/core/sol/harness.py +57 -4
  101. package/dist/core/sol-concrete.d.ts +23 -0
  102. package/dist/core/sol-concrete.js +195 -0
  103. package/dist/core/solver.js +3 -1
  104. package/dist/core/swift/Sources/gdp-swiftreader/main.swift +50 -7
  105. package/dist/core/system.js +1 -1
  106. package/dist/core/transfer.js +22 -9
  107. package/dist/core/translate.js +39 -10
  108. package/dist/core/watch.js +50 -5
  109. package/dist/interchange/format.js +11 -1
  110. package/dist/kernel/cdcl.d.ts +5 -0
  111. package/dist/kernel/cdcl.js +56 -9
  112. package/dist/kernel/epr.js +108 -26
  113. package/dist/kernel/kernel.d.ts +29 -1
  114. package/dist/kernel/kernel.js +325 -62
  115. package/dist/kernel/model-sequence.d.ts +3 -0
  116. package/dist/kernel/model-sequence.js +34 -0
  117. package/dist/kernel/prove.d.ts +10 -3
  118. package/dist/kernel/prove.js +332 -71
  119. package/dist/kernel/reader.d.ts +3 -0
  120. package/dist/kernel/reader.js +101 -14
  121. package/dist/kernel/share.d.ts +1 -0
  122. package/dist/kernel/share.js +27 -0
  123. package/dist/lean-kernel/emit.js +30 -37
  124. package/dist/lean-kernel/lean-terms.js +5 -0
  125. package/dist/lean-kernel/library.js +10 -10
  126. package/package.json +6 -1
@@ -66,7 +66,8 @@ public final class JavaReader implements Jvm.Env {
66
66
  for (Object n : names) {
67
67
  TypeElement te = find(cu, (String) n);
68
68
  if (te == null) { entries.add(m("k", "missing", "name", n)); continue; }
69
- 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);
70
71
  entries.add(m("k", "class", "rec", entry(te)));
71
72
  }
72
73
  out.put("entries", entries); out.put("recs", recs); out.put("funcs", funcs);
@@ -254,7 +255,8 @@ public final class JavaReader implements Jvm.Env {
254
255
  List<ExecutableElement> ctors = new ArrayList<>();
255
256
  for (Element e : te.getEnclosedElements()) if (e.getKind() == ElementKind.CONSTRUCTOR) ctors.add((ExecutableElement) e);
256
257
  Object want = jvm.get("ctorArity");
257
- 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();
258
260
  Map<String, Object> jctor = m();
259
261
  if (pick.size() != 1) {
260
262
  methods.put("__init__", name + "#<init>");
@@ -263,13 +265,15 @@ public final class JavaReader implements Jvm.Env {
263
265
  ExecutableElement c = pick.get(0);
264
266
  methods.put("__init__", name + "#<init>");
265
267
  funcs.put(name + "#<init>", ctor(te, c, cpath));
266
- 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)); }
267
270
  jctor = m("params", c.getParameters().stream().map(v -> erased(v.asType())).toList(), "names", c.getParameters().stream().map(v -> v.getSimpleName().toString()).toList(),
268
271
  "jts", c.getParameters().stream().map(v -> String.valueOf(jt(v.asType()))).toList(), "ifaces", c.getParameters().stream().map(v -> iface(v.asType())).toList(),
269
272
  "annos", trees.getPath(c) == null ? List.of() : annos(trees.getPath(c), ((MethodTree) trees.getTree(c)).getModifiers().getAnnotations()),
270
273
  "paramAnnos", trees.getPath(c) == null ? List.of() : ((MethodTree) trees.getTree(c)).getParameters().stream().map(v -> annos(trees.getPath(c), v.getModifiers().getAnnotations())).toList());
271
274
  }
272
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,
273
277
  "jvm", m("fields", jfields, "annos", annos(cpath, ct.getModifiers().getAnnotations()), "ctor", jctor, "cls", name, "sigs", sigs)));
274
278
  jvm.put("cls", name);
275
279
  jvm.put("ctor", jctor.get("params"));
@@ -277,6 +281,9 @@ public final class JavaReader implements Jvm.Env {
277
281
  reading.remove(name);
278
282
  return name;
279
283
  }
284
+ String ctorSignature(ExecutableElement c) {
285
+ return "(" + String.join(",", c.getParameters().stream().map(v -> erased(v.asType())).toList()) + ")";
286
+ }
280
287
  String refusedRec(TypeElement te, String name, String why) {
281
288
  TreePath cp = trees.getPath(te);
282
289
  funcs.put(name + "#<init>", stub(te, cp, "<init>", why));
@@ -430,7 +437,7 @@ public final class JavaReader implements Jvm.Env {
430
437
  ExecutableElement callee = (ExecutableElement) trees.getElement(ip);
431
438
  List<Object> args = new ArrayList<>();
432
439
  for (ExpressionTree a : mi.getArguments()) args.add(ex(a, ip));
433
- 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)))); }
434
441
  else if (callee != null && trees.getPath(callee) != null) {
435
442
  String sid = fid(callee);
436
443
  if (!funcs.containsKey(sid)) funcs.put(sid, ctor((TypeElement) callee.getEnclosingElement(), callee, trees.getPath(callee.getEnclosingElement())));
@@ -674,7 +681,11 @@ public final class JavaReader implements Jvm.Env {
674
681
  TypeCastTree c = (TypeCastTree) e;
675
682
  JT from = ty(path, c.getExpression());
676
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);
677
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);
678
689
  // (a float's whole value into an integer: Java's saturates at the type's range)
679
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);
680
691
  int fb = (int) ity(from).get("bits"), tb = (int) ity(type).get("bits");
@@ -712,7 +723,10 @@ public final class JavaReader implements Jvm.Env {
712
723
  case PLUS: case MINUS: case MULTIPLY: case DIVIDE: case REMAINDER: {
713
724
  if (type != null && type.is("java.lang.String")) return x("bin", p, "op", "+", "x", l, "y", r, "text", t);
714
725
  String op = switch (b.getKind()) { case PLUS -> "+"; case MINUS -> "-"; case MULTIPLY -> "*"; case DIVIDE -> "/"; default -> "%"; };
715
- 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)");
716
730
  return arith(op, l, ta, r, tb, type, "wrap", p, t);
717
731
  }
718
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);
@@ -794,7 +808,10 @@ public final class JavaReader implements Jvm.Env {
794
808
  ExpressionTree a = mi.getArguments().get(i);
795
809
  JT pt = i < me.getParameters().size() && !me.isVarArgs() ? jt(me.getParameters().get(i).asType()) : null;
796
810
  JT at0 = ty(path, a);
797
- 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);
798
815
  argT.add(pt != null && num(pt) ? pt : at0);
799
816
  pure &= pure(a);
800
817
  }
@@ -227,6 +227,9 @@ public final class Jvm {
227
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;
228
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;
229
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;
230
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;
231
234
  }
232
235
  return null;
@@ -70,11 +70,11 @@ public final class KtReader implements Jvm.Env {
70
70
  Map<String, Object> read(Map<?, ?> req) throws Exception {
71
71
  String path = (String) req.get("file"), root = (String) req.get("root");
72
72
  src = Files.readString(Path.of(path));
73
- // (the PSI recovering from deep unclosed nesting took 23 minutes on one source: past MAX_DEPTH brackets it is refused
74
- // before the parse, as the Rust reader refuses it)
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
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--; }
77
- if (most > 1000) Jvm.refuse(new File(path).getName() + ": the source nests " + most + " brackets deep (past 1000)");
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)");
78
78
  base = new File(path).getName();
79
79
  KtPsiFactory f = factory();
80
80
  file = f.createFile(base, src);
@@ -128,7 +128,7 @@ public final class KtReader implements Jvm.Env {
128
128
 
129
129
  // --- positions ---------------------------------------------------------------------------------------------------------
130
130
  int line(int off) { int i = Arrays.binarySearch(lines, off); return i >= 0 ? i + 1 : -i - 1; }
131
- 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); }
132
132
  String zero() { return base + ":0:0"; }
133
133
  static String text(PsiElement e) { String x = e.getText().replaceAll("\\s+", " "); return x.length() <= 60 ? x : x.substring(0, 57) + "..."; }
134
134
  List<Object> span(PsiElement e) { return List.of(e.getTextRange().getStartOffset(), e.getTextRange().getEndOffset()); }
@@ -313,6 +313,7 @@ public final class KtReader implements Jvm.Env {
313
313
  }
314
314
  static List<KtDeclaration> body(KtClassOrObject k) { return k.getBody() == null ? List.of() : k.getBody().getDeclarations(); }
315
315
  String key(KtClassOrObject k, KtNamedFunction fn) {
316
+ if (fn.getName() == null) Jvm.refuse(where(fn) + ": a function declaration is missing its name");
316
317
  long same = body(k).stream().filter(d -> d instanceof KtNamedFunction f && Objects.equals(f.getName(), fn.getName())).count();
317
318
  String n = same > 1 ? fn.getName() + "/" + fn.getValueParameters().size() : fn.getName();
318
319
  return fn.hasModifier(KtTokens.PRIVATE_KEYWORD) || Set.of("equals", "hashCode", "toString").contains(fn.getName()) ? "_" + n : n;
@@ -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 {};
package/dist/core/laws.js CHANGED
@@ -29,6 +29,8 @@
29
29
  // mode == "closed", outcome == SLOW_ERROR, mode == :closed a choice by its value
30
30
  import { Choice, Int, Str, Term, all, any, forall, no, not, yes } from "./dsl.js";
31
31
  import { agreement, isolation, noninterference } from "./relational.js";
32
+ import { CalendarError, businessDays } from "./calendar.js";
33
+ export { businessDays } from "./calendar.js";
32
34
  export class LawError extends Error {
33
35
  }
34
36
  // --- reading the code's text -------------------------------------------------------------------------------------------
@@ -56,7 +58,7 @@ export function lawsIn(text, where = '') {
56
58
  }
57
59
  const WORDS = { '->': '.', '::': '.', and: '&&', or: '||', not: '!', implies: '=>', '∧': '&&', '∨': '||', '¬': '!', '→': '=>', '==>': '=>', '≤': '<=', '≥': '>=', '≠': '!=', '∀': 'forall', AND: '&&', OR: '||', NOT: '!' };
58
60
  function tokens(s) {
59
- const out = [], re = /\s*(f?"(?:[^"\\]|\\.)*"|f?'(?:[^'\\]|\\.)*'|`[^`]*`|\d+(?:\.\d+)?|@?[A-Za-z_][\w?]*|->|::|==>|=>|<=|>=|==|!=|&&|\|\||\/\/|[-+*%/<>()[\],.:!∧∨¬→≤≥≠∀])/y;
61
+ const out = [], re = /\s*(f?"(?:[^"\\]|\\.)*"|f?'(?:[^'\\]|\\.)*'|`[^`]*`|0[xX][0-9a-fA-F]+[uUlL]*|0[bB][01]+[uUlL]*|\d+(?:\.\d+)?[uUlL]*|@?[A-Za-z_][\w?]*|->|::|==>|=>|<=|>=|==|!=|&&|\|\||\/\/|[-+*%/<>()[\],.:!∧∨¬→≤≥≠∀&|])/y;
60
62
  let m, at = 0;
61
63
  while ((m = re.exec(s))) {
62
64
  out.push(WORDS[m[1]] ?? m[1]);
@@ -67,15 +69,16 @@ function tokens(s) {
67
69
  return out;
68
70
  }
69
71
  // Durations, as many seconds: linear over the clock (a day is 86,400 s: the request's time counts seconds, with no
70
- // time zone, leap second or daylight saving). A month, a year, a business day or the end of a day isn't a fixed number
71
- // of seconds, so a law reading one is refused: state it in days.
72
+ // time zone, leap second or daylight saving). A month, a year or the end of a day isn't a fixed number of seconds, so a
73
+ // law reading one is refused: state it in days. Business days are counted over a calendar (core/calendar.ts): only as
74
+ // elapsed between two times, `now - received <= 10 business days`.
72
75
  const SECONDS = { ms: 0.001, millisecond: 0.001, milliseconds: 0.001, second: 1, seconds: 1, sec: 1, secs: 1, minute: 60, minutes: 60, min: 60, mins: 60,
73
76
  hour: 3600, hours: 3600, day: 86_400, days: 86_400, week: 604_800, weeks: 604_800 };
74
77
  const NOT_LINEAR = /^(months?|years?|quarters?|business|working|weekdays?|fortnights?)$/i;
75
78
  function seconds(unit) {
76
79
  const u = unit.toLowerCase();
77
80
  if (NOT_LINEAR.test(u))
78
- throw new LawError(`${unit}: not a fixed number of seconds (a month or a year has several lengths, a business day depends on the calendar): state it in days, hours or seconds`);
81
+ throw new LawError(`${unit}: not a fixed number of seconds (a month or a year has several lengths, a business day depends on the calendar): state it in days, hours or seconds, or count business days over a calendar (businessDays; in a law, now - t <= 10 business days)`);
79
82
  return SECONDS[u];
80
83
  }
81
84
  // A duration in the clock's units ('s': time.time(), 'ms': Date.now()): duration('30 days') is 2,592,000.
@@ -116,7 +119,7 @@ export function parse(s) {
116
119
  const or = left(['||'], () => and()), and = left(['&&'], () => neg());
117
120
  const neg = () => (peek() === '!' ? (eat(), { k: 'un', op: 'not', x: neg() }) : cmp());
118
121
  const cmp = () => {
119
- const a = sum(), op = peek();
122
+ const a = bor(), op = peek();
120
123
  if (op === 'is') {
121
124
  eat();
122
125
  const n = peek() === '!' ? (eat(), true) : false;
@@ -130,10 +133,12 @@ export function parse(s) {
130
133
  }
131
134
  if (op && ['<', '<=', '>', '>=', '==', '!=', 'in'].includes(op)) {
132
135
  eat();
133
- return { k: 'bin', op, a, b: sum() };
136
+ return { k: 'bin', op, a, b: bor() };
134
137
  }
135
138
  return a;
136
139
  };
140
+ // (x & K and x | K, a flag tested or set by a constant: below the comparisons, as Python's, so flags & K != 0 is (flags & K) != 0)
141
+ const bor = left(['|'], () => band()), band = left(['&'], () => sum());
137
142
  const sum = left(['+', '-'], () => prod()), prod = left(['*', '//', '/', '%'], () => unary());
138
143
  const unary = () => (peek() === '-' ? (eat(), { k: 'un', op: '-', x: unary() }) : atom());
139
144
  const atom = () => {
@@ -150,13 +155,19 @@ export function parse(s) {
150
155
  throw new LawError(`${x}: a number that isn't whole`);
151
156
  // (a duration: 30 days, 15 minutes, in seconds until the clock's unit is known)
152
157
  const u = peek()?.toLowerCase(), calendar = u === 'calendar' && /^days?$/i.test(t[i + 1] ?? '');
158
+ if ((u === 'business' || u === 'working') && /^days?$/i.test(t[i + 1] ?? '')) {
159
+ eat();
160
+ eat();
161
+ return { k: 'bdur', v: Number(x), text: `${x} ${u} days` };
162
+ }
153
163
  if (u && (calendar || Object.hasOwn(SECONDS, u) || NOT_LINEAR.test(u))) {
154
164
  eat();
155
165
  if (calendar)
156
166
  eat();
157
167
  return { k: 'dur', v: Number(x) * seconds(calendar ? 'days' : u), text: `${x} ${u}${calendar ? ' days' : ''}` };
158
168
  }
159
- return { k: 'num', v: Number(x) };
169
+ // (C's and the others' hexadecimal and binary literals, an unsigned or long suffix)
170
+ return { k: 'num', v: Number(x.replace(/[uUlL]+$/, '')) };
160
171
  }
161
172
  if (/^f?["'`]/.test(x))
162
173
  return str(x);
@@ -241,7 +252,18 @@ export function namesWithClock(x) {
241
252
  const ns = x.names ?? [], ins = x.rule?.parts?.inputs.map(([n]) => n) ?? [];
242
253
  return ns.some(n => n.role === 'clock') || !ins.includes('now') || ns.some(n => n.code === 'now') ? ns : [...ns, { code: 'now', rule: 'now', role: 'clock' }];
243
254
  }
255
+ const calendarOf = (opts) => {
256
+ if (!opts.calendar)
257
+ return undefined;
258
+ try {
259
+ return businessDays(opts.calendar, opts.clock === 1000 ? 'ms' : 's');
260
+ }
261
+ catch (e) {
262
+ throw e instanceof CalendarError ? new LawError(`the calendar: ${e.message}`) : e;
263
+ }
264
+ };
244
265
  export function buildLaw(x, l, opts = {}) {
266
+ const strictOptional = x.model?.standalone === true;
245
267
  const names = namesWithClock(x), r = x.rule;
246
268
  if (!r)
247
269
  throw new LawError('the extraction has no rule');
@@ -249,7 +271,8 @@ export function buildLaw(x, l, opts = {}) {
249
271
  throw new LawError(`${l.name}: a law is stated as <name>: <expr>`);
250
272
  const e = parse(l.expr);
251
273
  // A first reading finds what the law reads: a request, a result, the failure or the state before make it a step law.
252
- const probe = { consts: x.consts, b: {}, a: {}, step: true, method: l.method, keys: new Map(), roles: new Set(), methods: new Set(), clock: opts.clock };
274
+ const cal = opts.clock === undefined ? undefined : calendarOf(opts);
275
+ const probe = { strictOptional, consts: x.consts, b: {}, a: {}, step: true, method: l.method, keys: new Map(), roles: new Set(), methods: new Set(), clock: opts.clock, cal };
253
276
  read(e, probe, names, true);
254
277
  // (a law on a method, the line above it, is a law of its step: the state after it, old(x) before)
255
278
  const step = !!l.method || ['input', 'answer', 'result', 'failed', 'clock', 'method', 'old'].some(k => probe.roles.has(k));
@@ -257,12 +280,48 @@ export function buildLaw(x, l, opts = {}) {
257
280
  if (probe.methods.size > 1)
258
281
  throw new LawError(`it reads the arguments of ${[...probe.methods].join(' and ')}: a law of one step is about one method`);
259
282
  const gate = step && method && names.some(n => n.role === 'method') ? method : undefined;
260
- const body = (b, a) => read(e, { consts: x.consts, b, a, step, method, keys: new Map(), roles: new Set(), methods: new Set(), clock: opts.clock }, names, false);
283
+ const body0 = (b, a, pins, bits) => read(e, { strictOptional, consts: x.consts, b, a, step, method, keys: new Map(), roles: new Set(), methods: new Set(), clock: opts.clock, cal, pins, ...(bits ? { bits } : {}) }, names, false);
284
+ // (a step law's bit tests: read once to count the keys they take, then at every value of them, the facts implying it)
285
+ const bitBody = (b, a) => {
286
+ const count = { ks: [], used: 0, hyps: [] };
287
+ const plain = body0(b, a, undefined, count);
288
+ if (!count.used)
289
+ return plain;
290
+ if (count.used > 6)
291
+ throw new LawError(`its bit tests take ${count.used} keys in a law of one step (at most 6: two runs of bits at a place above bit 0, three at bit 0)`);
292
+ const at = (...ks) => { const bits = { ks, used: 0, hyps: [] }; const out = body0(b, a, undefined, bits); return all(...bits.hyps).implies(out); };
293
+ const n = count.used;
294
+ return n === 1 ? forall(k => at(k)) : n === 2 ? forall((k, j) => at(k, j)) : n === 3 ? forall((k, j, i) => at(k, j, i)) : n === 4 ? forall((k, j, i, h) => at(k, j, i, h)) : n === 5 ? forall((k, j, i, h, g) => at(k, j, i, h, g)) : forall((k, j, i, h, g, f) => at(k, j, i, h, g, f));
295
+ };
296
+ // (a law of one step reads no function, so business days there pin each time's week to a key, ∀w. guard → law)
297
+ const body = (b, a) => (step && probe.roles.has('bdays') ? pinned(b, a, (bb, aa, p) => body0(bb, aa, p)) : bitBody(b, a));
261
298
  if (!step)
262
- return { kind: 'law', law: r.law(l.name, (env) => (x.quiet ? env[x.quiet].eq(0).implies(body(env, env)) : body(env, env))) };
299
+ return { kind: 'law', law: r.law(l.name, (env) => (x.quiet ? env[x.quiet].eq(0).implies(body0(env, env)) : body0(env, env))) };
263
300
  const mname = names.find(n => n.role === 'method')?.rule;
264
301
  return { kind: 'step', ...(gate ? { method: gate } : {}), law: r.stepLaw(l.name, (b, a) => body(b, a), gate ? (b) => b[mname].is(gate) : undefined) };
265
302
  }
303
+ // A law of one step over business days: read once to find its times, then held at every week of each (a key, two for
304
+ // a time that may be below 0), under the guards that only each time's own week meets.
305
+ function pinned(b, a, f) {
306
+ const pins = { times: [] };
307
+ f(b, a, pins);
308
+ const n = pins.times.reduce((k, t) => k + (t.nat ? 1 : 2), 0);
309
+ if (n > 6)
310
+ throw new LawError('business days at more than 6 weeks at once (a time that may be below 0 takes two)');
311
+ const g = (ks) => {
312
+ const at = new Map(), guards = [];
313
+ let i = 0;
314
+ for (const t of pins.times)
315
+ at.set(t.id, t.nat ? Int.of(ks[i++]) : new Int(ks[i++], ks[i++]));
316
+ const out = f(b, a, { times: pins.times, at, guards });
317
+ if ('forall' in out)
318
+ throw new LawError('business days in a law over every key: not yet (state it at one key)');
319
+ return all(...guards).implies(out);
320
+ };
321
+ const fs = [(k) => g([k]), (k, j) => g([k, j]), (k, j, h) => g([k, j, h]), (k, j, h, m) => g([k, j, h, m]),
322
+ (k, j, h, m, o) => g([k, j, h, m, o]), (k, j, h, m, o, p) => g([k, j, h, m, o, p])];
323
+ return n ? forall(fs[n - 1]) : f(b, a, undefined);
324
+ }
266
325
  // The expression read: its value (`dry`: only which names it reads, nothing built).
267
326
  function read(e, c, names, dry) {
268
327
  if (e.k === 'forall') {
@@ -285,7 +344,7 @@ function read(e, c, names, dry) {
285
344
  if (dry) {
286
345
  for (const f of chain)
287
346
  c.keys.set(f.v, new Term({ op: 'const', value: 0 }));
288
- return cond(val(body, c, names, true));
347
+ return cond(val(body, c, names, true), c.strictOptional);
289
348
  }
290
349
  const at = (ks) => {
291
350
  const held = overs.map((o, i) => {
@@ -295,17 +354,17 @@ function read(e, c, names, dry) {
295
354
  c.items.set(chain[i].v, { map: m.at(ks[i]), fields: o.over.n.map.fields });
296
355
  return m.at(ks[i]).has;
297
356
  });
298
- return all(...held).implies(cond(val(body, c, names, false)));
357
+ return all(...held).implies(cond(val(body, c, names, false), c.strictOptional));
299
358
  };
300
359
  return chain.length === 1 ? forall(k => at([k])) : chain.length === 2 ? forall((k, j) => at([k, j])) : forall((k, j, i) => at([k, j, i]));
301
360
  }
302
- return cond(val(e, c, names, dry));
361
+ return cond(val(e, c, names, dry), c.strictOptional);
303
362
  }
304
- const cond = (v) => {
363
+ const cond = (v, strictOptional = false) => {
305
364
  if (v.t === 'cond')
306
365
  return v.v;
307
366
  if (v.t === 'opt' && v.v?.t === 'cond')
308
- return v.v.v;
367
+ return strictOptional ? all(not(v.none), v.v.v) : v.v.v;
309
368
  throw new LawError(`a ${v.t === 'num' ? 'number' : v.t} where a condition is read`);
310
369
  };
311
370
  const num = (v) => {
@@ -326,6 +385,7 @@ function val(e, c, names, dry) {
326
385
  const go = (x) => val(x, c, names, dry);
327
386
  switch (e.k) {
328
387
  case 'num': return { t: 'num', v: Int.of(e.v) };
388
+ case 'bdur': throw new LawError(`${e.text}: business days are elapsed between two times, compared: now - received <= ${e.v} business days`);
329
389
  case 'dur':
330
390
  if (c.clock === undefined)
331
391
  throw new LawError(`${e.text}: the clock's unit isn't known here (clock = "s" or "ms" in gdp.toml)`);
@@ -373,6 +433,8 @@ function val(e, c, names, dry) {
373
433
  }
374
434
  }
375
435
  const xs = e.xs.map(go);
436
+ if (c.strictOptional && xs.some(v => v.t === 'opt'))
437
+ throw new LawError('arithmetic on an optional standalone value is not supported');
376
438
  if (dry)
377
439
  return DRY;
378
440
  if (e.f === 'abs')
@@ -381,17 +443,26 @@ function val(e, c, names, dry) {
381
443
  }
382
444
  case 'un': {
383
445
  const v = go(e.x);
446
+ if (c.strictOptional && e.op === '-' && v.t === 'opt')
447
+ throw new LawError('arithmetic on an optional standalone value is not supported');
384
448
  if (dry)
385
449
  return v.t === 'cond' ? v : DRY;
386
- return e.op === '-' ? { t: 'num', v: num(v).negate() } : { t: 'cond', v: not(cond(v)) };
450
+ return e.op === '-' ? { t: 'num', v: num(v).negate() } : { t: 'cond', v: not(cond(v, c.strictOptional)) };
387
451
  }
388
452
  case 'bin': {
389
453
  // (a comparison with x // k on one side, k a positive constant: the same comparison without the division, exact
390
454
  // over the integers (a <= x // k is k·a <= x; a < x // k is k·(a + 1) <= x), so it needs no function, which a law
391
455
  // of one step can't read)
392
456
  const flip = { '<': '>', '<=': '>=', '>': '<', '>=': '<=', '==': '==', '!=': '!=' };
457
+ if (flip[e.op] && (e.a.k === 'bdur' || e.b.k === 'bdur'))
458
+ return { t: 'cond', v: businessCompare(e, flip, c, go, dry) };
393
459
  const divk = (x) => (x.k === 'bin' && x.op === '//' && (constOf(x.b) ?? 0) >= 1 ? x : undefined);
394
460
  if (flip[e.op] && (divk(e.b) || divk(e.a))) {
461
+ // Inspect the original numerator before rewriting division into comparisons.
462
+ if (c.strictOptional)
463
+ for (const d of [divk(e.a), divk(e.b)])
464
+ if (d && go(d.a).t === 'opt')
465
+ throw new LawError('arithmetic on an optional standalone value is not supported');
395
466
  const [op, lhs, d] = divk(e.b) ? [e.op, e.a, divk(e.b)] : [flip[e.op], e.b, divk(e.a)];
396
467
  const k = constOf(d.b), ka = { k: 'bin', op: '*', a: { k: 'num', v: k }, b: lhs }, ka1 = { k: 'bin', op: '*', a: { k: 'num', v: k }, b: { k: 'bin', op: '+', a: lhs, b: { k: 'num', v: 1 } } };
397
468
  const le = (a, b) => ({ k: 'bin', op: '<=', a, b }), lt = (a, b) => ({ k: 'bin', op: '<', a, b });
@@ -420,9 +491,55 @@ function val(e, c, names, dry) {
420
491
  if (a.t === 'lit' && a.err && b.t === 'lit' && b.err)
421
492
  throw a.err;
422
493
  if (['&&', '||', '=>'].includes(e.op))
423
- return dry ? { t: 'cond', v: yes } : { t: 'cond', v: e.op === '&&' ? all(cond(a), cond(b)) : e.op === '||' ? any(cond(a), cond(b)) : cond(a).implies(cond(b)) };
494
+ return dry ? { t: 'cond', v: yes } : { t: 'cond', v: e.op === '&&' ? all(cond(a, c.strictOptional), cond(b, c.strictOptional)) : e.op === '||' ? any(cond(a, c.strictOptional), cond(b, c.strictOptional)) : cond(a, c.strictOptional).implies(cond(b, c.strictOptional)) };
495
+ if (c.strictOptional && ['+', '-', '*', '//', '/', '%', '&', '|'].includes(e.op) && [a, b].some(v => v.t === 'opt'))
496
+ throw new LawError('arithmetic on an optional standalone value is not supported');
424
497
  if (dry)
425
- return ['+', '-', '*', '//', '/', '%'].includes(e.op) ? DRY : { t: 'cond', v: yes };
498
+ return ['+', '-', '*', '//', '/', '%', '&', '|'].includes(e.op) ? DRY : { t: 'cond', v: yes };
499
+ // x & K and x | K with K a constant (a literal or a constant of the code): K's runs of ones, ((x div 2^lo) mod 2^n)·2^lo
500
+ // each, as the extractor reads the code's (core/extract-step.ts's bitop); x | K is x + K − (x & K).
501
+ if (e.op === '&' || e.op === '|') {
502
+ const kOf = (v) => { if (v.t !== 'num')
503
+ return undefined; const p = v.v.pos.e, n = v.v.neg.e; return p.op === 'const' && n.op === 'const' ? p.value - n.value : undefined; };
504
+ const [xv, k] = kOf(b) !== undefined ? [a, kOf(b)] : kOf(a) !== undefined ? [b, kOf(a)] : [a, undefined];
505
+ if (k === undefined)
506
+ throw new LawError(`${e.op} with a constant only (a bit operation of two values is outside linear arithmetic)`);
507
+ const x = num(xv), andK = (kk) => {
508
+ if (kk < 0)
509
+ return x.minus(andK(-kk - 1));
510
+ let out = Int.of(0), lo = 0;
511
+ for (let r = kk; r > 0;) {
512
+ if (r % 2 === 0) {
513
+ r /= 2;
514
+ lo++;
515
+ continue;
516
+ }
517
+ let n = 0;
518
+ while (r % 2 === 1) {
519
+ r = (r - 1) / 2;
520
+ n++;
521
+ }
522
+ out = out.plus(Int.of(run(lo, n)).times(2 ** lo));
523
+ lo += n;
524
+ }
525
+ return out;
526
+ };
527
+ // ((x div 2^lo) mod 2^n): an invariant's by the rule's functions; a step law's (which reads none) by keys q, m,
528
+ // s at every value of which x ≡ q·2^(lo+n) + m·2^lo + s (mod 2^(lo+n), x's natural form pos + neg·(2^(lo+n) − 1)),
529
+ // m < 2^n, s < 2^lo: m is the run
530
+ function run(lo, n) {
531
+ if (!c.bits)
532
+ return x.divBy(2 ** lo).modBy(2 ** n);
533
+ const take = () => c.bits.ks[c.bits.used++] ?? new Term({ op: 'const', value: 0 });
534
+ const q = take(), m = take(), s0 = lo ? take() : undefined, nat = x.pos.plus(x.neg.times(2 ** (lo + n) - 1));
535
+ let parts = q.times(2 ** (lo + n)).plus(m.times(2 ** lo));
536
+ if (s0)
537
+ parts = parts.plus(s0);
538
+ c.bits.hyps.push(nat.eq(parts), m.lt(2 ** n), ...(s0 ? [s0.lt(2 ** lo)] : []));
539
+ return m;
540
+ }
541
+ return { t: 'num', v: e.op === '&' ? andK(k) : x.plus(k).minus(andK(k)) };
542
+ }
426
543
  if (e.op === '+' || e.op === '-')
427
544
  return { t: 'num', v: e.op === '+' ? num(a).plus(num(b)) : num(a).minus(num(b)) };
428
545
  if (e.op === '*') {
@@ -437,23 +554,67 @@ function val(e, c, names, dry) {
437
554
  throw new LawError(`${e.op} by a positive constant only`);
438
555
  return e.op === '%' ? { t: 'num', v: Int.of(num(a).modBy(k)) } : { t: 'num', v: num(a).divBy(k) };
439
556
  }
440
- return { t: 'cond', v: compare(e.op, a, b, e) };
557
+ return { t: 'cond', v: compare(e.op, a, b, e, c.strictOptional) };
441
558
  }
442
559
  case 'path': return path(e, c, names, dry);
443
560
  case 'forall': return fail('forall ... in ...: at the top of the law only');
444
561
  }
445
562
  return fail('an expression of no kind');
446
563
  }
564
+ // `later - earlier ⋈ N business days`: the business days from earlier's day to later's (core/calendar.ts) ⋈ N. In a law
565
+ // of one step each time's week is a key (pinned, its guard collected); elsewhere it is divided out.
566
+ function businessCompare(e, flip, c, go, dry) {
567
+ const [op, diff, n] = e.b.k === 'bdur' ? [e.op, e.a, e.b] : [flip[e.op], e.b, e.a];
568
+ if (diff.k !== 'bin' || diff.op !== '-')
569
+ throw new LawError(`${n.text}: compared with the time elapsed between two times, later - earlier (now - received <= ${n.v} business days)`);
570
+ if (c.clock === undefined)
571
+ throw new LawError(`${n.text}: the clock's unit isn't known here (clock = "s" or "ms" in gdp.toml)`);
572
+ if (!c.cal)
573
+ throw new LawError(`${n.text}: business days need a calendar ([calendar] in gdp.toml: weekend = ["sat", "sun"], holidays = ["2026-12-25", ...], utc_offset = "-05:00")`);
574
+ c.roles.add('bdays');
575
+ const later = go(diff.a), earlier = go(diff.b);
576
+ if (dry)
577
+ return yes;
578
+ const cal = c.cal, at = (x, v) => {
579
+ const t = num(v), p = c.pins;
580
+ if (!p || !c.step)
581
+ return t;
582
+ // (one key per time as it is read: the same text, in the state before or after the step)
583
+ const id = `${JSON.stringify(x)}${c.a === c.b ? '@before' : ''}`;
584
+ if (!p.at) {
585
+ if (!p.times.some(q => q.id === id))
586
+ p.times.push({ id, nat: t.neg.e.op === 'const' && t.neg.e.value === 0 });
587
+ return t;
588
+ }
589
+ const pin = cal.pin(t, p.at.get(id));
590
+ p.guards.push(pin.guard);
591
+ return pin.at;
592
+ };
593
+ const d = cal.between(at(diff.b, earlier), at(diff.a, later));
594
+ return op === '<' ? d.lt(n.v) : op === '<=' ? d.atMost(n.v) : op === '>' ? d.gt(n.v) : op === '>=' ? d.atLeast(n.v) : op === '==' ? d.eq(n.v) : d.ne(n.v);
595
+ }
447
596
  // (a path's last name: a choice's value written as one, Outcome.SLOW_ERROR)
448
597
  const lastName = (x) => (x.segs.length ? x.segs.at(-1).f : x.head);
449
598
  const constOf = (x) => (x.k === 'num' ? x.v : x.k === 'un' && x.op === '-' && x.x.k === 'num' ? -x.x.v : undefined);
450
- function compare(op, a, b, e) {
599
+ function compare(op, a, b, e, strictOptional = false) {
451
600
  if (b.t === 'null' || a.t === 'null') {
452
601
  const o = a.t === 'null' ? b : a, none = o.t === 'opt' ? o.none : o.t === 'cell' ? not(o.rec.has) : undefined;
453
602
  if (!none)
454
603
  throw new LawError(`${show(a.t === 'null' ? e.b : e.a)} is never None here (the rule holds no None for it)`);
455
604
  return op === '==' ? none : op === '!=' ? not(none) : fail(`${op} with None`);
456
605
  }
606
+ // A standalone optional value is absent regardless of its hidden scalar payload.
607
+ // Keep the established law language of other frontends unchanged.
608
+ if (strictOptional && (a.t === 'opt' || b.t === 'opt')) {
609
+ const av = a.t === 'opt' ? a.v : a, bv = b.t === 'opt' ? b.v : b;
610
+ const present = all(a.t === 'opt' ? not(a.none) : yes, b.t === 'opt' ? not(b.none) : yes);
611
+ if (op === '==' || op === '!=') {
612
+ const absent = a.t === 'opt' && b.t === 'opt' ? all(a.none, b.none) : no;
613
+ const equal = any(absent, av && bv ? all(present, compare('==', av, bv, e)) : no);
614
+ return op === '==' ? equal : not(equal);
615
+ }
616
+ return av && bv ? all(present, compare(op, av, bv, e)) : no;
617
+ }
457
618
  const un = (v) => (v.t === 'opt' && v.v ? v.v : v);
458
619
  a = un(a);
459
620
  b = un(b);
@@ -471,6 +632,10 @@ function compare(op, a, b, e) {
471
632
  throw new LawError(`${show(ox)} isn't one of ${ch.values.join(', ')}`);
472
633
  return eq(ch.is(lit));
473
634
  }
635
+ // A quantified map key and a string identity use the same id as m[identity].
636
+ // This is equality of keys, not an ordering or coercion between strings and numbers.
637
+ if (a.t === 'key' && b.t === 'str' || a.t === 'str' && b.t === 'key')
638
+ return eq(key(a).eq(key(b)));
474
639
  if (a.t === 'str' || b.t === 'str') {
475
640
  const [s, o] = a.t === 'str' ? [a.v, b] : [b.v, a];
476
641
  return eq(o.t === 'str' ? s.eq(o.v) : o.t === 'lit' ? s.eq(o.v) : fail('a string compared with what isn\'t one'));
@@ -510,10 +675,21 @@ function path(e, c, names, dry) {
510
675
  c.methods.add(n.method);
511
676
  return rest(e.segs, leaf(n, c, dry), c, names, dry, e);
512
677
  }
678
+ // (a call answered per constant arguments, C's: f(em, BUS_OFF) its answer f_x_18, by the code's constants)
679
+ const call0 = e.segs[0];
680
+ if (call0 && 'call' in call0 && call0.args && names.some(x => x.role === 'answer' && x.code.startsWith(`${e.head}_`))) {
681
+ const sig = splitArgs(call0.args).map(a => { const k = /^-?\d+$/.test(a) ? Number(a) : /^[A-Za-z_]\w*$/.test(a) ? c.consts?.[a] : undefined; return typeof k === 'number' ? String(k).replace('-', 'm') : 'x'; }).join('_');
682
+ const per = names.find(x => x.role === 'answer' && x.code === `${e.head}_${sig}`);
683
+ if (!per)
684
+ throw new LawError(`${e.head}(${call0.args}): no answer of the code for these arguments (its answers: ${names.filter(x => x.role === 'answer' && x.code.startsWith(`${e.head}_`)).map(x => x.code).join(', ')})`);
685
+ c.roles.add(per.role);
686
+ return rest(e.segs.slice(1), leaf(per, c, dry), c, names, dry, e);
687
+ }
513
688
  // (self.x, this.x, state.x, @x: the state's x; a bare `state` or `s` is a name of the code's, a field named so)
514
689
  const explicit = (['self', 'this', 'state', 's'].includes(e.head) && e.segs.length > 0) || e.head.startsWith('@');
515
690
  const parts = [e.head.replace(/^@/, ''), ...e.segs.map(s => ('f' in s ? s.f : undefined))];
516
- const heads = explicit && !e.head.startsWith('@') ? [parts.slice(1)] : [parts, ...(parts.length > 1 && parts[1] !== undefined ? [parts.slice(1)] : [])];
691
+ // (s.x and state.x: the state's x, else a state the code names s or state, a C global's field)
692
+ const heads = explicit && !e.head.startsWith('@') ? [parts.slice(1), ...(['s', 'state'].includes(e.head) ? [parts] : [])] : [parts, ...(parts.length > 1 && parts[1] !== undefined ? [parts.slice(1)] : [])];
517
693
  for (const [hi, p] of heads.entries()) {
518
694
  const fields = [];
519
695
  for (const s of p) {
@@ -530,8 +706,16 @@ function path(e, c, names, dry) {
530
706
  if (hit.method)
531
707
  c.methods.add(hit.method);
532
708
  // (an answered call is one value a step, whatever its arguments: written f(...) or f())
533
- if (hit.role === 'answer' && next && 'call' in next && next.args)
709
+ if (hit.role === 'answer' && next && 'call' in next && next.args) {
710
+ // (a call answered per constant arguments, C's: f(em, BUS_OFF) its answer f_x_18, by the code's constants)
711
+ const sig = splitArgs(next.args).map(a => { const k = /^-?\d+$/.test(a) ? Number(a) : /^[A-Za-z_]\w*$/.test(a) ? c.consts?.[a] : undefined; return typeof k === 'number' ? String(k).replace('-', 'm') : 'x'; }).join('_');
712
+ const per = names.find(x => x.role === 'answer' && x.code === `${code}_${sig}`);
713
+ if (per) {
714
+ c.roles.add(per.role);
715
+ return rest(e.segs.slice(skip + n), leaf(per, c, dry), c, names, dry, e);
716
+ }
534
717
  throw new LawError(`${code}(${next.args}): an answered call's value is the request's, one a step: write it ${code}(...)`);
718
+ }
535
719
  const segs = e.segs.slice(skip + n - 1 + (hit.role === 'answer' && next && 'call' in next ? 1 : 0));
536
720
  // (a map read where it is named: old(m) is the map before the step wherever its cells are read, `k in old(m)`)
537
721
  return rest(segs, hit.map ? { t: 'map', n: hit, maps: names.filter(x => x.map && x.code === hit.code), env: c.a } : leaf(hit, c, dry), c, names, dry, e);
@@ -539,7 +723,12 @@ function path(e, c, names, dry) {
539
723
  }
540
724
  }
541
725
  // A method's argument by its method's name (charge.user), where several methods take one of that name.
542
- // A constant of the module bound to a literal, by its name.
726
+ // A constant of the module bound to a literal, by its name (a qualified one, C++'s A::K, by its path).
727
+ const dotted = e.segs.every(g => 'f' in g) ? [e.head, ...e.segs.map(g => g.f)].join('.') : undefined;
728
+ if (dotted && e.segs.length && c.consts?.[dotted] !== undefined) {
729
+ const v = c.consts[dotted];
730
+ return typeof v === 'number' ? { t: 'num', v: Int.of(v) } : typeof v === 'boolean' ? { t: 'cond', v: v ? yes : no } : { t: 'lit', v };
731
+ }
543
732
  const k = c.consts?.[e.head];
544
733
  if (k !== undefined && !e.segs.length)
545
734
  return typeof k === 'number' ? { t: 'num', v: Int.of(k) } : typeof k === 'boolean' ? { t: 'cond', v: k ? yes : no } : { t: 'lit', v: k };
@@ -835,3 +1024,17 @@ function split(s, sep) {
835
1024
  }
836
1025
  return [...out, rest].map(t => t.trim()).filter(Boolean);
837
1026
  }
1027
+ // (a call's arguments as written, split at the commas outside parentheses)
1028
+ function splitArgs(s) { const out = []; let d = 0, cur = ''; for (const ch of s) {
1029
+ if (ch === '(' || ch === '[')
1030
+ d++;
1031
+ else if (ch === ')' || ch === ']')
1032
+ d--;
1033
+ if (ch === ',' && !d) {
1034
+ out.push(cur.trim());
1035
+ cur = '';
1036
+ }
1037
+ else
1038
+ cur += ch;
1039
+ } if (cur.trim())
1040
+ out.push(cur.trim()); return out; }