gdp-wired 0.43.0 → 0.45.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 (79) hide show
  1. package/README.md +8 -3
  2. package/dist/core/c/reader.js +22 -7
  3. package/dist/core/check.js +3 -2
  4. package/dist/core/cli.d.ts +7 -0
  5. package/dist/core/cli.js +184 -12
  6. package/dist/core/counts.d.ts +1 -1
  7. package/dist/core/counts.js +30 -12
  8. package/dist/core/data.d.ts +6 -1
  9. package/dist/core/data.js +894 -152
  10. package/dist/core/dsl.d.ts +2 -0
  11. package/dist/core/dsl.js +88 -10
  12. package/dist/core/effect-prims.d.ts +60 -0
  13. package/dist/core/effect-prims.js +625 -0
  14. package/dist/core/effect.d.ts +17 -1
  15. package/dist/core/effect.js +108 -4
  16. package/dist/core/ex/harness.exs +2 -0
  17. package/dist/core/ex/reader.exs +17 -1
  18. package/dist/core/exists.d.ts +15 -1
  19. package/dist/core/exists.js +263 -41
  20. package/dist/core/extract-c.d.ts +2 -0
  21. package/dist/core/extract-c.js +22 -13
  22. package/dist/core/extract-check.d.ts +7 -0
  23. package/dist/core/extract-check.js +57 -4
  24. package/dist/core/extract-ex.js +5 -5
  25. package/dist/core/extract-go-check.js +22 -17
  26. package/dist/core/extract-go.d.ts +3 -0
  27. package/dist/core/extract-go.js +24 -9
  28. package/dist/core/extract-jvm.js +68 -16
  29. package/dist/core/extract-print.js +3 -0
  30. package/dist/core/extract-py.js +5 -5
  31. package/dist/core/extract-rb.js +5 -5
  32. package/dist/core/extract-read.d.ts +8 -0
  33. package/dist/core/extract-read.js +55 -0
  34. package/dist/core/extract-rs.js +28 -25
  35. package/dist/core/extract-shapes.js +20 -0
  36. package/dist/core/extract-sol.js +23 -12
  37. package/dist/core/extract-step.d.ts +59 -3
  38. package/dist/core/extract-step.js +334 -64
  39. package/dist/core/extract-swift.js +22 -15
  40. package/dist/core/extract.d.ts +1 -0
  41. package/dist/core/extract.js +27 -2
  42. package/dist/core/fresh.d.ts +2 -2
  43. package/dist/core/fresh.js +7 -3
  44. package/dist/core/go/reader.go +7 -1
  45. package/dist/core/infer.js +113 -40
  46. package/dist/core/jvm/Harness.java +8 -1
  47. package/dist/core/jvm/JavaReader.java +10 -2
  48. package/dist/core/jvm/Jvm.java +18 -2
  49. package/dist/core/jvm/KtReader.java +60 -5
  50. package/dist/core/machine.d.ts +2 -0
  51. package/dist/core/machine.js +32 -6
  52. package/dist/core/py/harness.py +128 -24
  53. package/dist/core/py/reader.py +50 -5
  54. package/dist/core/rb/reader.rb +52 -5
  55. package/dist/core/rs/src/main.rs +10 -0
  56. package/dist/core/sol/Replay.sol +52 -0
  57. package/dist/core/sol/harness.py +511 -0
  58. package/dist/core/solver.js +5 -4
  59. package/dist/core/system.d.ts +62 -1
  60. package/dist/core/system.js +274 -6
  61. package/dist/core/transfer.js +17 -0
  62. package/dist/core/watch.js +1 -1
  63. package/dist/interchange/check.d.ts +18 -1
  64. package/dist/interchange/check.js +19 -12
  65. package/dist/interchange/cli.d.ts +2 -0
  66. package/dist/interchange/cli.js +45 -0
  67. package/dist/interchange/format.d.ts +5 -1
  68. package/dist/interchange/format.js +25 -9
  69. package/dist/kernel/cdcl.js +65 -14
  70. package/dist/kernel/epr.js +35 -5
  71. package/dist/kernel/kernel.d.ts +2 -0
  72. package/dist/kernel/kernel.js +67 -40
  73. package/dist/kernel/prove.d.ts +22 -0
  74. package/dist/kernel/prove.js +156 -7
  75. package/dist/kernel/reader.js +3 -2
  76. package/dist/lean-kernel/emit.d.ts +9 -3
  77. package/dist/lean-kernel/emit.js +170 -29
  78. package/dist/lean-kernel/library.js +1 -1
  79. package/package.json +12 -3
@@ -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,12 +120,12 @@ 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); }
113
127
  static boolean map(JT t) { return t != null && MAPS.contains(t.n); }
114
- static boolean atomic(JT t) { return t != null && t.n.startsWith("java.util.concurrent.atomic.Atomic") || t.n.startsWith("kotlinx.atomicfu.Atomic"); }
128
+ static boolean atomic(JT t) { return t != null && (t.n.startsWith("java.util.concurrent.atomic.Atomic") || t.n.startsWith("kotlinx.atomicfu.Atomic")); }
115
129
  // The type an atomic holds.
116
130
  static JT held(JT t) {
117
131
  return switch (t.simple()) { case "AtomicInteger", "AtomicInt" -> new JT("int"); case "AtomicLong" -> new JT("long"); case "AtomicBoolean" -> new JT("boolean"); default -> t.arg(0); };
@@ -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; }
@@ -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
+ // (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)
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)");
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);
@@ -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) {
@@ -389,6 +403,36 @@ public final class KtReader implements Jvm.Env {
389
403
  }
390
404
  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
405
  }
406
+ // What a data class's copy runs that the subset doesn't read as an update with its init blocks after: a property
407
+ // its body computes from the constructor's parameters (computed again), an init block that sets one, an init block of
408
+ // another class than the one read.
409
+ String copyRuns(KtClassOrObject k) {
410
+ if (!(k instanceof KtClass kc)) return null;
411
+ Set<String> ps = new HashSet<>();
412
+ for (KtParameter pa : kc.getPrimaryConstructorParameters()) ps.add(pa.getName());
413
+ for (KtDeclaration d : body(k)) {
414
+ 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())))
415
+ return "a copy of a data class whose property " + pr.getName() + " is computed from its constructor (copy computes it again)";
416
+ if (d instanceof KtAnonymousInitializer ai) {
417
+ if (k != self) return "a copy of another data class with an init block (copy runs it again)";
418
+ if (com.intellij.psi.util.PsiTreeUtil.findChildrenOfType(ai, KtBinaryExpression.class).stream().anyMatch(b -> KtTokens.ALL_ASSIGNMENTS.contains(b.getOperationToken())))
419
+ return "a copy of a data class whose init block sets a property (copy runs it again)";
420
+ }
421
+ }
422
+ return null;
423
+ }
424
+ // The init blocks run on a copy (self): the copy returned.
425
+ String copyCheck(KtClassOrObject k) {
426
+ String id = binOf(k) + "#<copy>";
427
+ if (!funcs.containsKey(id)) {
428
+ Ctx cx = new Ctx(new ArrayList<>(), new HashMap<>(), 0, false);
429
+ List<Object> b = new ArrayList<>();
430
+ for (KtDeclaration d : body(k)) if (d instanceof KtAnonymousInitializer ai && ai.getBody() instanceof KtBlockExpression bl) b.addAll(block(bl.getStatements(), cx, null));
431
+ b.add(s("ret", where(k), "x", self(where(k))));
432
+ funcs.put(id, fn(id, "copy", k, List.of(), new JT(binOf(k)), b, null));
433
+ }
434
+ return id;
435
+ }
392
436
  static List<Object> prepend(Object a, List<Object> xs) { List<Object> out = new ArrayList<>(); out.add(a); out.addAll(xs); return out; }
393
437
 
394
438
  // --- statements ------------------------------------------------------------------------------------------------------
@@ -610,11 +654,13 @@ public final class KtReader implements Jvm.Env {
610
654
  if (et == KtNodeTypes.INTEGER_CONSTANT) {
611
655
  boolean lng = s.endsWith("L") || s.endsWith("l");
612
656
  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);
657
+ long v;
658
+ 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); }
659
+ catch (NumberFormatException nfe) { return no1(k, "an integer literal past 64 bits"); }
614
660
  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
661
  return new X(lit(v, ty, p), ty);
616
662
  }
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)"); }
663
+ 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
664
  if (et == KtNodeTypes.CHARACTER_CONSTANT) return no1(e, "a character literal");
619
665
  }
620
666
  if (e instanceof KtStringTemplateExpression st) {
@@ -863,6 +909,9 @@ public final class KtReader implements Jvm.Env {
863
909
  X body = inline(lam, null, recv, c, stmt && n.equals("let"), p);
864
910
  return n.equals("also") ? recv : body;
865
911
  }
912
+ // (any other call given a lambda: other code runs it, any number of times; repeat(n) { } a loop. require's and
913
+ // check's lambda is their failure's message, read as they are)
914
+ if (lam != null && !(recv == null && Set.of("require", "check", "requireNotNull", "checkNotNull").contains(n))) return no1(ce, recv == null && n.equals("repeat") ? "a loop (repeat)" : "a lambda given to " + n + " (a closure other code runs)");
866
915
  List<Map<String, Object>> args = new ArrayList<>();
867
916
  List<JT> argT = new ArrayList<>();
868
917
  List<Object> kw = new ArrayList<>();
@@ -887,7 +936,13 @@ public final class KtReader implements Jvm.Env {
887
936
  if (!args.isEmpty()) return no1(ce, "copy given arguments by position");
888
937
  List<Object> fs = new ArrayList<>();
889
938
  for (Object k0 : kw) fs.add(k0);
890
- return new X(x("upd", p, "x", recv == null ? self(p) : recv.ir(), "fields", fs, "text", t), recv == null ? new JT(selfName) : recv.t());
939
+ Map<String, Object> u = x("upd", p, "x", recv == null ? self(p) : recv.ir(), "fields", fs, "text", t);
940
+ // (copy makes the object anew by its primary constructor: its init blocks run again, on the copy's fields)
941
+ KtClassOrObject of = recv == null ? self : classes.get(recv.t().n);
942
+ String why = copyRuns(of);
943
+ if (why != null) return no1(ce, why);
944
+ 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());
945
+ return new X(u, recv == null ? new JT(selfName) : recv.t());
891
946
  }
892
947
  // a constructor: a class of the code's own (made from its fields), an atomic, a map, a lock
893
948
  String ctorOf = recv == null && Character.isUpperCase(n.charAt(0)) ? resolve(n) : null;
@@ -1,4 +1,5 @@
1
1
  import { type Constraint, type Verdict } from './solver.js';
2
+ export declare const lcg: (x: number) => number;
2
3
  export type Rand = (k: number) => number;
3
4
  export declare const seeded: (seed: number) => Rand;
4
5
  export declare const walk: (t: unknown, f: (o: Record<string, unknown>) => void) => void;
@@ -249,6 +250,7 @@ export type Compiled = {
249
250
  };
250
251
  };
251
252
  export declare const loadJs: (m: Machine) => Compiled;
253
+ export declare function fastStep(m: Machine): ((params: Env, st: State, input: Request) => State) | undefined;
252
254
  export type Obligation = {
253
255
  phase: 'start' | 'step';
254
256
  law: string;
@@ -7,7 +7,12 @@
7
7
  // every other key the step reads).
8
8
  import { boundOf, crossFree, historyMachine, keyTerm, plainKey, scope, sumRuntime } from "../kernel/kernel.js";
9
9
  import { add, env, eq, k, le, lt, nat, scale, show, solve, sub, v } from "./solver.js";
10
- export const seeded = (seed) => { let x = seed; return k => { x = (x * 1103515245 + 12345) % 2 ** 31; return Math.floor(x / 2 ** 31 * k); }; };
10
+ // The one generator of the repo's random draws: x' = (1103515245 x + 12345) mod 2^31, exact (Math.imul). In doubles
11
+ // the product passes 2^53 and rounds, which folds every seed into one of six short cycles (61 to 10,466 steps; 98.8% of
12
+ // seeds into the same one). Its period is 2^31 (core/rand.test.ts). Draws are its high bits (the low ones repeat with a
13
+ // short period). Every search, test, harness and fuzz draws from it.
14
+ export const lcg = (x) => (Math.imul(x, 1103515245) + 12345) & 0x7fffffff;
15
+ export const seeded = (seed) => { let x = seed; return k => { x = lcg(x); return Math.floor(x / 2 ** 31 * k); }; };
11
16
  // Every object in a term, the term first.
12
17
  export const walk = (t, f) => {
13
18
  if (Array.isArray(t)) {
@@ -207,10 +212,12 @@ const exact = (v) => {
207
212
  throw new RangeError('a value passed 2^53 - 1, past which the proofs over the naturals no longer describe the run');
208
213
  return v;
209
214
  };
215
+ // (a value is a number: a name like constructor or toString, read through an object's prototype, is no value of it)
216
+ const num = (x) => (typeof x === 'number' ? x : undefined);
210
217
  export function evalE(e, env, st, m) {
211
218
  switch (e.op) {
212
219
  case 'var': {
213
- const v = env[e.name] ?? st.scalars[e.name];
220
+ const v = num(env[e.name]) ?? num(st.scalars[e.name]);
214
221
  if (v === undefined)
215
222
  throw new Error(`no value for ${e.name}`);
216
223
  return v;
@@ -224,13 +231,13 @@ export function evalE(e, env, st, m) {
224
231
  case 'max': return Math.max(evalE(e.a, env, st, m), evalE(e.b, env, st, m));
225
232
  case 'if': return evalC(e.c, env, st, m) ? evalE(e.then, env, st, m) : evalE(e.else, env, st, m);
226
233
  case 'get': {
227
- const fn = m.fns?.[e.map], args = fn?.call ? pairedArgs(e.key, fn.arity) : undefined;
234
+ const fn = m.fns && Object.hasOwn(m.fns, e.map) ? m.fns[e.map] : undefined, args = fn?.call ? pairedArgs(e.key, fn.arity) : undefined;
228
235
  if (args) {
229
236
  const xs = args.map(a => evalE(a, env, st, m));
230
237
  return naturalIn(callOf(fn)(...xs), `${e.map}(${xs.join(', ')})`);
231
238
  }
232
239
  const key = evalE(e.key, env, st, m);
233
- return fn ? naturalIn(fnOf(fn)(key), `${e.map}(${key})`) : st.maps[e.map].get(key) ?? st.defaults?.[e.map] ?? m.maps[e.map];
240
+ return fn ? naturalIn(fnOf(fn)(key), `${e.map}(${key})`) : st.maps[e.map].get(key) ?? (st.defaults && Object.hasOwn(st.defaults, e.map) ? st.defaults[e.map] : undefined) ?? m.maps[e.map];
234
241
  }
235
242
  }
236
243
  }
@@ -300,7 +307,7 @@ export function compileE(e, m) {
300
307
  switch (e.op) {
301
308
  case 'var': {
302
309
  const name = e.name;
303
- return (env, st) => { const v = env[name] ?? st.scalars[name]; if (v === undefined)
310
+ return (env, st) => { const v = num(env[name]) ?? num(st.scalars[name]); if (v === undefined)
304
311
  throw new Error(`no value for ${name}`); return v; };
305
312
  }
306
313
  case 'const': {
@@ -660,7 +667,7 @@ export function compileJs(m) {
660
667
  case 'max': return `Math.max(${ex(e.a)}, ${ex(e.b)})`;
661
668
  case 'if': return `(${cx(e.c)} ? ${ex(e.then)} : ${ex(e.else)})`;
662
669
  case 'get': {
663
- const fn = m.fns?.[e.map], args = fn?.call ? pairedArgs(e.key, fn.arity) : undefined;
670
+ const fn = m.fns && Object.hasOwn(m.fns, e.map) ? m.fns[e.map] : undefined, args = fn?.call ? pairedArgs(e.key, fn.arity) : undefined;
664
671
  if (args)
665
672
  return `$n(fnc${fns.indexOf(e.map)}(${args.map(ex).join(', ')}), ${id(`${e.map}()`)})`;
666
673
  return fns.includes(e.map) ? `$n(fn${fns.indexOf(e.map)}(${ex(e.key)}), ${id(`${e.map}()`)})` : `(maps[${id(e.map)}].get(${ex(e.key)}) ?? ${carriedMaps.includes(e.map) ? '0' : `dft[${id(e.map)}] ?? ${plain.maps[e.map]}`})`;
@@ -773,6 +780,25 @@ export function compileFunction(params, body) {
773
780
  return new Function(...params, body);
774
781
  }
775
782
  export const loadJs = (m) => compileFunction([], `${compileJs(m).replace(/^export function/gm, 'function')}\nreturn {init, fork, step}`)();
783
+ // The interpreter's step (persistent: a copy of the state each) through loadJs's, several times faster, a request's counts
784
+ // given to it as maps the request carries (carriedView's, each cell its sum when read); none with a history, or where the
785
+ // generator refuses the machine.
786
+ export function fastStep(m) {
787
+ const cs = Object.keys(m.counts ?? {});
788
+ let js;
789
+ try {
790
+ if (m.history)
791
+ return undefined;
792
+ js = loadJs({ ...m, counts: undefined, inputMaps: [...m.inputMaps ?? [], ...cs] });
793
+ }
794
+ catch {
795
+ return undefined;
796
+ }
797
+ return (params, st, input) => {
798
+ const view = cs.length ? carriedView(m, st, input, undefined, params).maps : {};
799
+ return js.step(params, js.fork(st), cs.length ? { ...input, ...Object.fromEntries(cs.map(c => [c, view[c]])) } : input);
800
+ };
801
+ }
776
802
  const cross = (as, f) => as.flatMap(a => f(a.value).map(b => ({ path: [...a.path, ...b.path], value: b.value })));
777
803
  // Every way a key can differ from each of some focus keys.
778
804
  const apartFrom = (key, keys) => keys.reduce((acc, f) => acc.flatMap(p => [[...p, ...lt(key, f)], [...p, ...lt(f, key)]]), [[]]);
@@ -4,11 +4,12 @@
4
4
  # one that keeps what is set, the clock read as the request's time. Line events count the branch arms reached.
5
5
  #
6
6
  # python3 core/py/harness.py <in-fifo> <out-fifo>
7
- import asyncio, dataclasses, datetime, importlib, inspect, json, os, sys, types
7
+ import asyncio, builtins, dataclasses, datetime, importlib, inspect, json, os, sys, types
8
8
  import time as time_module
9
9
 
10
10
  NOW = [0]
11
11
  CUR = {}
12
+ EFF = {}
12
13
  HIT = set()
13
14
  S = {}
14
15
 
@@ -38,6 +39,13 @@ def resolve(q):
38
39
  mod, _, name = q.rpartition('.')
39
40
  return getattr(importlib.import_module(mod), name)
40
41
 
42
+ class Inert:
43
+ """An attribute of a store the rule leaves out (a registry the constructor adds to): its calls do nothing."""
44
+ def __getattr__(self, name):
45
+ if name.startswith('__'): raise AttributeError(name)
46
+ return Inert()
47
+ def __call__(self, *a, **k): return None
48
+
41
49
  class FakeStore:
42
50
  """A store as the caller stated it: get, set and delete over a dict that keeps what is set (no expiry)."""
43
51
  def __init__(self, decl, name=None):
@@ -45,9 +53,17 @@ class FakeStore:
45
53
  for path, v in (decl.get('attrs') or {}).items():
46
54
  o, parts = self, path.split('.')
47
55
  for p in parts[:-1]:
48
- if not hasattr(o, p): setattr(o, p, types.SimpleNamespace())
56
+ if p not in vars(o): setattr(o, p, types.SimpleNamespace())
49
57
  o = getattr(o, p)
50
58
  setattr(o, parts[-1], v)
59
+ # (an attribute the rule leaves out, a registry the constructor adds to: inert, its calls doing nothing)
60
+ for i in S.get('inert') or []:
61
+ if i['store'] != name: continue
62
+ o, parts = self, i['path'].split('.')
63
+ for p in parts[:-1]:
64
+ if p not in vars(o): setattr(o, p, types.SimpleNamespace())
65
+ o = getattr(o, p)
66
+ if parts[-1] not in vars(o): setattr(o, parts[-1], Inert())
51
67
  asyncs = decl.get('async') or {}
52
68
  def mk(kind, name):
53
69
  # (the key by position, or as key= or name=, redis-py's; nx and xx as redis-py's: True where it set, else None)
@@ -59,7 +75,16 @@ class FakeStore:
59
75
  self.data[key] = val
60
76
  if k.get('nx') or k.get('xx'): return True
61
77
  def delete(*a, **k): self.data.pop(kk(a, k), None)
62
- f0, key = {'get': get, 'set': set_, 'delete': delete}[kind], f"{self.name}.{name}"
78
+ # (add: set where the key holds nothing, True where it set; incr: by amount, absent as 0, the new number)
79
+ def add(*a, **k):
80
+ key = kk(a, k)
81
+ if key in self.data: return False
82
+ self.data[key] = k.get('value', a[1] if len(a) > 1 else None)
83
+ return True
84
+ def incr(*a, **k):
85
+ key = kk(a, k); self.data[key] = (self.data.get(key) or 0) + k.get('amount', a[1] if len(a) > 1 else 1)
86
+ return self.data[key]
87
+ f0, key = {'get': get, 'set': set_, 'delete': delete, 'add': add, 'incr': incr}[kind], f"{self.name}.{name}"
63
88
  # (where the request says the operation raises, inside a try that catches it)
64
89
  def f(*a, **k):
65
90
  r = (CUR.get(key) or {}).get('raise')
@@ -69,15 +94,29 @@ class FakeStore:
69
94
  async def af(*a, **k): return f(*a, **k)
70
95
  return af
71
96
  return f
72
- for kind, dflt in (('get', ['get', 'async_get_cache', 'get_cache']), ('set', ['set', 'async_set_cache', 'set_cache']), ('delete', ['delete', 'delete_cache', 'async_delete_cache'])):
73
- for m in decl.get(kind) or dflt: setattr(self, m, mk(kind, m))
97
+ own = set()
98
+ for kind, dflt in (('get', ['get', 'async_get_cache', 'get_cache']), ('set', ['set', 'async_set_cache', 'set_cache']), ('delete', ['delete', 'delete_cache', 'async_delete_cache']), ('add', []), ('incr', [])):
99
+ for m in decl.get(kind) or dflt: setattr(self, m, mk(kind, m)); own.add(m)
74
100
  # (a method left out: nothing, as the rule takes it; any other is no method of this store, and fails)
75
101
  for m in decl.get('skip') or []:
76
102
  async def anop(*a, **k): return None
77
103
  setattr(self, m, (lambda *a, **k: anop()) if asyncs.get(m) else (lambda *a, **k: None))
78
- # (an injected dependency's other methods: each answered by the request's input)
104
+ # (an injected dependency's other methods: each answered by the request's input; one left out does nothing, and
105
+ # raises where the request says, as its get, set and delete do)
79
106
  for a in S.get('answers') or []:
80
- if a['patch'].get('store') == name and not a.get('pass'): setattr(self, a['patch']['path'][-1], stub(a['key'], a['async']))
107
+ if a['patch'].get('store') != name: continue
108
+ if not a['patch'].get('path'):
109
+ if os.environ.get('GDP_HARNESS_LOG'):
110
+ with open(os.environ['GDP_HARNESS_LOG'], 'a') as f: f.write(f"a store's answer with no method: {json.dumps(a)[:400]}\n")
111
+ continue
112
+ m = a['patch']['path'][-1]
113
+ if a['patch'].get('store') == name and a.get('effect'):
114
+ def rec(key, is_async):
115
+ def f(*x, **k): EFF[key] = True
116
+ async def af(*x, **k): EFF[key] = True
117
+ return af if is_async else f
118
+ setattr(self, m, rec(a['key'], a['async']))
119
+ elif a['patch'].get('store') == name and not (a.get('pass') and m in own): setattr(self, m, stub(a['key'], a['async'], (lambda *x, **k: None) if a.get('pass') else None))
81
120
 
82
121
  def build(spec, stores):
83
122
  if 'in' in spec:
@@ -169,7 +208,7 @@ def state_of(obj, stores):
169
208
  if f.get('opt'): c[f['name'] + '_has'] = x is not None
170
209
  c[f['name']] = (x if x is not None else (f['vals'][0] if f.get('choice') else 0)) if f.get('choice') else enc_num(0 if x is None else x)
171
210
  cells[h] = c
172
- else: cells[h] = {'value': v if l.get('choice') else enc_num(v)}
211
+ else: cells[h] = {'value': v if l.get('choice') else (v.decode('latin-1') if isinstance(v, (bytes, bytearray)) else v) if l.get('str') else enc_num(int(v) if isinstance(v, bool) else v)}
173
212
  s[l['name']] = cells
174
213
  continue
175
214
  v = walk(obj, l['path'])
@@ -211,7 +250,7 @@ def set_state(obj, stores, state):
211
250
  for h, c in (v or {}).items():
212
251
  at = pre + h + post if '{}' in l['tpl'] else l['tpl']
213
252
  if l.get('json'): st.data[at] = json.dumps({f['name']: (c[f['name']] if f.get('choice') else num_in(c[f['name']], False)) for f in l['json'] if not f.get('out') and (not f.get('opt') or c.get(f['name'] + '_has'))})
214
- else: st.data[at] = c['value'] if l.get('choice') else num_in(c['value'], l.get('float'))
253
+ else: st.data[at] = c['value'] if l.get('choice') or l.get('str') else num_in(c['value'], l.get('float'))
215
254
  continue
216
255
  if k == 'num': put(obj, l['path'], num_in(v, l.get('float')))
217
256
  elif k in ('str', 'choice', 'bool'): put(obj, l['path'], v.encode('latin-1') if k == 'str' and is_bytes(l) and isinstance(v, str) else v)
@@ -260,19 +299,56 @@ class _Now(datetime.datetime):
260
299
  """datetime.datetime with now() the request's time (local, naive, as the code's own now())."""
261
300
  @classmethod
262
301
  def now(cls, tz=None): return datetime.datetime.fromtimestamp(NOW[0], tz)
263
-
264
- def pin_clocks(root):
265
- """The clock the repository's modules read (time.time(), datetime.now()) made the request's time."""
266
- root = os.path.realpath(root)
267
- dtm = types.SimpleNamespace(**{k: getattr(datetime, k) for k in dir(datetime) if not k.startswith('__')})
268
- dtm.datetime = _Now
302
+ # (where it is seen anyway, a type read while the clock is pinned, pydantic's: a datetime)
303
+ @classmethod
304
+ def __get_pydantic_core_schema__(cls, source, handler): return handler(datetime.datetime)
305
+
306
+ # The clock the repository's modules read (time.time(), datetime.now()) made the request's time, only while the code
307
+ # runs (making the object, a call): a module's names are its own again between, so a framework that reads them, an
308
+ # annotation or a route's types, sees the real datetime; a module made while the clock was pinned put back too.
309
+ CLOCKS = {'root': None, 'n': -1, 'pins': [], 'depth': 0}
310
+ def scan_clocks():
311
+ if len(sys.modules) == CLOCKS['n']: return
312
+ CLOCKS['n'] = len(sys.modules)
313
+ dtm = CLOCKS.get('dtm')
314
+ if dtm is None:
315
+ dtm = CLOCKS['dtm'] = types.SimpleNamespace(**{k: getattr(datetime, k) for k in dir(datetime) if not k.startswith('__')})
316
+ dtm.datetime = _Now
317
+ pins = []
269
318
  for m in list(sys.modules.values()):
270
319
  f = getattr(m, '__file__', None)
271
- if not f or not os.path.realpath(f).startswith(root + os.sep): continue
320
+ if not f or not os.path.realpath(f).startswith(CLOCKS['root'] + os.sep): continue
272
321
  for n, v in list(vars(m).items()):
273
- if v is time_module: setattr(m, n, Clock(v))
274
- elif v is datetime: setattr(m, n, dtm)
275
- elif v is datetime.datetime: setattr(m, n, _Now)
322
+ if v is time_module or isinstance(v, Clock): pins.append((m, n, time_module, Clock(time_module)))
323
+ elif v is datetime or v is dtm: pins.append((m, n, datetime, dtm))
324
+ elif v is datetime.datetime or v is _Now: pins.append((m, n, datetime.datetime, _Now))
325
+ CLOCKS['pins'] = pins
326
+
327
+ def put_clocks(fake):
328
+ for m, n, real, f in CLOCKS['pins']: setattr(m, n, f if fake else real)
329
+
330
+ # (an import the code makes while it runs, a module of the repository first loaded then: run with the real clock, so
331
+ # what it copies or builds from the module's names is the real datetime, imports inside it too; the clock pinned
332
+ # again after the outermost, the new modules' names too)
333
+ REAL_IMPORT = builtins.__import__
334
+ def clock_import(*a, **k):
335
+ if CLOCKS['depth'] == 0: put_clocks(False)
336
+ CLOCKS['depth'] += 1
337
+ try: return REAL_IMPORT(*a, **k)
338
+ finally:
339
+ CLOCKS['depth'] -= 1
340
+ if CLOCKS['depth'] == 0: scan_clocks(); put_clocks(True)
341
+
342
+ class pinned:
343
+ def __enter__(self):
344
+ scan_clocks(); put_clocks(True)
345
+ builtins.__import__ = clock_import
346
+ def __exit__(self, *a):
347
+ builtins.__import__ = REAL_IMPORT
348
+ put_clocks(False); scan_clocks(); put_clocks(False)
349
+
350
+ def pin_clocks(root):
351
+ CLOCKS['root'] = os.path.realpath(root)
276
352
 
277
353
  def raises_here(key):
278
354
  """Whether a call left out raises here, as the request says: only at the sites the rule read it may raise (a call of
@@ -328,6 +404,19 @@ def hello(req):
328
404
  S['self_stubs'] = []
329
405
  for a in req['answers']:
330
406
  p = a['patch']
407
+ # (an effect: a call recorded, nothing run, None returned)
408
+ if a.get('effect'):
409
+ def rec(key, is_async):
410
+ def f(*x, **k): EFF[key] = True
411
+ async def af(*x, **k): EFF[key] = True
412
+ return af if is_async else f
413
+ f = rec(a['key'], a['async'])
414
+ if p.get('store'): continue
415
+ if p.get('self'): S['self_stubs'].append((p['self'], {**a, 'effect_fn': f})); continue
416
+ o, name = patch_target(p)
417
+ raw = inspect.getattr_static(o, name, None)
418
+ setattr(o, name, staticmethod(f) if isinstance(raw, staticmethod) else f)
419
+ continue
331
420
  if p.get('store'): continue
332
421
  if p.get('self'): S['self_stubs'].append((p['self'], a))
333
422
  else:
@@ -347,10 +436,16 @@ def make(args):
347
436
  else:
348
437
  kw = fixed_args(args, {})
349
438
  sys.settrace(tracer)
350
- try: obj = run(S['cls'](**kw))
439
+ try:
440
+ with pinned(): obj = run(S['cls'](**kw))
351
441
  finally: sys.settrace(None)
352
- for name, a in S['self_stubs']: obj.__dict__[name] = stub(a['key'], a['async'], getattr(obj, name) if a.get('pass') else None)
442
+ for name, a in S['self_stubs']: obj.__dict__[name] = a['effect_fn'] if a.get('effect_fn') else stub(a['key'], a['async'], getattr(obj, name) if a.get('pass') else None)
353
443
  for name in S.get('inject') or []: setattr(obj, name, build({'store': name}, OBJ_STORES))
444
+ # (fields stated: the object configured so after its constructor, as the claim says)
445
+ for f, v in (S.get('fields') or {}).items(): setattr(obj, f, v)
446
+ # (a module's object stated as a store: the store in its place, this object's while it runs)
447
+ for g in S.get('globals') or []: build({'store': g['name']}, OBJ_STORES)
448
+ set_globals(OBJ_STORES)
354
449
  i = len(OBJS) + 1
355
450
  OBJS[i] = (obj, OBJ_STORES)
356
451
  return i
@@ -358,19 +453,24 @@ def make(args):
358
453
  def run(x):
359
454
  return S['loop'].run_until_complete(x) if inspect.isawaitable(x) else x
360
455
 
456
+ def set_globals(stores):
457
+ for g in S.get('globals') or []: setattr(importlib.import_module(g['mod']), g['name'], stores[g['name']])
458
+
361
459
  def call(req):
362
460
  obj, stores = OBJS[req['id']]
363
461
  global OBJ_STORES
364
462
  OBJ_STORES = stores
463
+ set_globals(stores)
365
464
  NOW[0] = int(req.get('now') or 0)
366
465
  CUR.clear(); CUR.update(req.get('answers') or {})
466
+ EFF.clear()
367
467
  fn = getattr(obj, req['m']) if S['cls'] is not None else getattr(S['mod'], req['m'])
368
468
  kwargs = fixed_args(req['a'], {})
369
469
  before = frames(obj if S['cls'] is not None else None)
370
470
  snap = state_of(obj, stores) if S.get('discard') and S['cls'] is not None else None
371
471
  sys.settrace(tracer)
372
472
  try:
373
- out = run(fn(**kwargs))
473
+ with pinned(): out = run(fn(**kwargs))
374
474
  err = None
375
475
  except Exception as e:
376
476
  out, err = None, f"{type(e).__name__}: {e}"[:300]
@@ -384,7 +484,7 @@ def call(req):
384
484
  after = frames(obj if S['cls'] is not None else None)
385
485
  for k in before:
386
486
  if after.get(k) != before[k]: return {'frame': k}
387
- return {'out': tag(out), **({'err': err} if err is not None else {})}
487
+ return {'out': tag(out), **({'err': err} if err is not None else {}), **({'effects': dict(EFF)} if EFF else {})}
388
488
 
389
489
  def main():
390
490
  fin = open(sys.argv[1], 'r'); fout = open(sys.argv[2], 'w')
@@ -396,7 +496,11 @@ def main():
396
496
  if op == 'hello': res = hello(req)
397
497
  elif op == 'new':
398
498
  try: res = {'id': make(req['a'])}
399
- except Exception as e: res = {'err': f"{type(e).__name__}: {e}"[:300]}
499
+ except Exception as e:
500
+ res = {'err': f"{type(e).__name__}: {e}"[:300]}
501
+ if os.environ.get('GDP_HARNESS_LOG'):
502
+ import traceback
503
+ with open(os.environ['GDP_HARNESS_LOG'], 'a') as f: traceback.print_exc(file=f)
400
504
  elif op == 'at':
401
505
  try:
402
506
  i = make(req['a'])