gdp-wired 0.42.0 → 0.44.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.
- package/README.md +14 -3
- package/dist/core/cli.d.ts +8 -1
- package/dist/core/cli.js +271 -30
- package/dist/core/counts.d.ts +8 -1
- package/dist/core/counts.js +171 -302
- package/dist/core/data.js +2 -2
- package/dist/core/dsl.js +26 -30
- package/dist/core/effect-prims.d.ts +60 -0
- package/dist/core/effect-prims.js +625 -0
- package/dist/core/effect-schedule.d.ts +103 -0
- package/dist/core/effect-schedule.js +817 -0
- package/dist/core/effect.d.ts +36 -1
- package/dist/core/effect.js +656 -29
- package/dist/core/ex/harness.exs +2 -0
- package/dist/core/exists.d.ts +5 -0
- package/dist/core/exists.js +98 -34
- package/dist/core/extract-c.d.ts +2 -0
- package/dist/core/extract-c.js +5 -3
- package/dist/core/extract-check.d.ts +2 -0
- package/dist/core/extract-check.js +45 -4
- package/dist/core/extract-ex.js +2 -2
- package/dist/core/extract-go-check.js +4 -6
- package/dist/core/extract-go.d.ts +3 -0
- package/dist/core/extract-go.js +4 -4
- package/dist/core/extract-jvm.js +6 -3
- package/dist/core/extract-print.js +9 -2
- package/dist/core/extract-py.js +2 -2
- package/dist/core/extract-rb.js +2 -2
- package/dist/core/extract-read.js +2 -1
- package/dist/core/extract-rs.js +12 -7
- package/dist/core/extract-sol.js +4 -4
- package/dist/core/extract-step.d.ts +18 -0
- package/dist/core/extract-step.js +135 -31
- package/dist/core/extract-swift.js +3 -3
- package/dist/core/extract.d.ts +8 -0
- package/dist/core/extract.js +13 -1
- package/dist/core/infer.d.ts +1 -0
- package/dist/core/infer.js +10 -7
- package/dist/core/jvm/Harness.java +8 -1
- package/dist/core/jvm/Jvm.java +1 -1
- package/dist/core/jvm/KtReader.java +3 -0
- package/dist/core/laws.d.ts +4 -0
- package/dist/core/laws.js +176 -9
- package/dist/core/machine.d.ts +3 -0
- package/dist/core/machine.js +17 -3
- package/dist/core/py/harness.py +64 -19
- package/dist/core/py/reader.py +51 -1
- package/dist/core/sol/Replay.sol +52 -0
- package/dist/core/sol/harness.py +508 -0
- package/dist/core/system.d.ts +44 -0
- package/dist/core/system.js +435 -0
- package/dist/interchange/check.d.ts +18 -1
- package/dist/interchange/check.js +9 -2
- package/dist/interchange/cli.d.ts +2 -0
- package/dist/interchange/cli.js +45 -0
- package/dist/interchange/format.d.ts +1 -1
- package/dist/interchange/format.js +15 -7
- package/dist/kernel/cdcl.js +32 -12
- package/dist/kernel/kernel.js +3 -2
- package/dist/kernel/prove.d.ts +1 -0
- package/dist/kernel/prove.js +69 -8
- package/dist/kernel/reader.js +3 -2
- package/dist/lean-kernel/emit.js +3 -3
- package/dist/lean-kernel/lean-terms.d.ts +1 -0
- package/dist/lean-kernel/lean-terms.js +8 -4
- package/package.json +12 -3
package/dist/core/extract.js
CHANGED
|
@@ -369,6 +369,11 @@ const isBool = (x, m) => {
|
|
|
369
369
|
return o.field === 'has' || [...m.maps, ...(m.seqs ?? []), ...(m.folds ?? []).map(d => ({ name: d.run, fields: d.fields }))].some(d => d.name === o.map && d.fields.some(f => f.name === o.field && f.sort.k === 'bool'));
|
|
370
370
|
return false;
|
|
371
371
|
};
|
|
372
|
+
// (a choice by cases, `when(c, 'a', 'b')`: printed where it is read, through its variable, never hoisted as a number)
|
|
373
|
+
const isChoice = (x) => {
|
|
374
|
+
const o = x;
|
|
375
|
+
return o.op === 'lit' || (o.op === 'var' && Array.isArray(o.values)) || (o.op === 'ite' && (isChoice(o.a) || isChoice(o.b)));
|
|
376
|
+
};
|
|
372
377
|
// The env's names: those the terms read, the choices a literal is printed through, and the maps written.
|
|
373
378
|
function withChoices(env, text, P, extra = []) {
|
|
374
379
|
const names = new Set(env.slice(1, -1).split(', ').filter(Boolean));
|
|
@@ -412,7 +417,14 @@ function hoist(m, P, roots) {
|
|
|
412
417
|
const names = new Set([...m.params, ...m.inputs, ...m.state].map(v => v.name).concat(m.maps.map(d => d.name)));
|
|
413
418
|
for (const k of order) {
|
|
414
419
|
const node = hoistNodes.get(k), size = k.length;
|
|
415
|
-
if ((count.get(k) ?? 0) < 2 || size < 60)
|
|
420
|
+
if ((count.get(k) ?? 0) < 2 || size < 60 || isChoice(node))
|
|
421
|
+
continue;
|
|
422
|
+
// (a product of integers kept at 0 or above only by the conditions the path is under: printed where it is read,
|
|
423
|
+
// under them, never hoisted out of them)
|
|
424
|
+
let guarded = false;
|
|
425
|
+
walk(node, o => { if (o.op === 'mul' && !(natOK(o.a, { m, sorts: P.sorts, atoms: [] }) && natOK(o.b, { m, sorts: P.sorts, atoms: [] })))
|
|
426
|
+
guarded = true; });
|
|
427
|
+
if (guarded)
|
|
416
428
|
continue;
|
|
417
429
|
if (!isBool(node, m)) {
|
|
418
430
|
const ctx = { m, sorts: P.sorts, atoms: [] }, free = natOK(node, ctx);
|
package/dist/core/infer.d.ts
CHANGED
package/dist/core/infer.js
CHANGED
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
// rules it out (and the most of those seen) is added; a chosen candidate that nothing supports, or that makes a proof slow, is dropped; the set proven as a whole
|
|
33
33
|
// is the answer, after each chosen candidate the proof doesn't need is taken out again
|
|
34
34
|
import { quietly } from "./cyclic.js";
|
|
35
|
-
import { all, any, atMost, carriedView, compileC, compileE, loadJs, divisorsIn, evalC, evalE, get, interpret, machineTerms, fnValue, modName, n, not, plus, same,
|
|
35
|
+
import { all, any, atMost, carriedView, compileC, compileE, loadJs, divisorsIn, evalC, evalE, get, interpret, machineTerms, fnValue, modName, n, not, plus, same, searchSeeded, times, walk, withArithmetic, x } from "./machine.js";
|
|
36
36
|
import { bool, proveRule, proveSteps, verdictOf } from "./dsl.js";
|
|
37
37
|
import { allowed, keysOf, linKey, watch } from "./watch.js";
|
|
38
38
|
import { clock, counted, fullWork, decideLaw, decideNote, machineKey, memoHits, withStrict, fullRate, grow, keyValue, lawInstances, proveLaw, proveLaws, proveSetFast, proveStepLaws, stepLawInstances, usedHyps, withDeadline, withModels, withTrees, withWall, withWork } from "../kernel/prove.js";
|
|
@@ -161,6 +161,9 @@ function constantsOf(m, laws) {
|
|
|
161
161
|
}
|
|
162
162
|
// A key's linear form over the names `ok` admits, into `out` (`1` the constant); false where it is none.
|
|
163
163
|
const conj = (c) => (c.op === 'and' ? c.xs.flatMap(conj) : [c]);
|
|
164
|
+
// A few values: at most four, none past 8: a mode's, and a view's cell reads each of them as a literal (as it does any
|
|
165
|
+
// three: a program counter's four phases are a mode, and were no literal of a view)
|
|
166
|
+
const few = (vals) => vals.length <= 4 && vals.every(x => x <= 8);
|
|
164
167
|
function pairingOf(m) {
|
|
165
168
|
const inputs = new Set(m.inputs), input = (v) => inputs.has(v);
|
|
166
169
|
let found;
|
|
@@ -695,13 +698,13 @@ function comparisons(m, laws, atoms, coords, more = []) {
|
|
|
695
698
|
return [...found.values()];
|
|
696
699
|
}
|
|
697
700
|
export function inferLaws(target, laws, stepLaws = [], opts = {}) {
|
|
698
|
-
return quietly(() => withDeadline(clock() + (opts.ms ?? 20000), () => inferLawsSearch(target, laws, stepLaws, opts)));
|
|
701
|
+
return quietly(() => withDeadline(clock() + (opts.wall === undefined ? opts.ms ?? 20000 : Math.max(0, opts.wall - performance.now())), () => inferLawsSearch(target, laws, stepLaws, opts)));
|
|
699
702
|
}
|
|
700
703
|
function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
701
704
|
// (GDP_INFER_TRACE=2: each phase's progress too, to stderr)
|
|
702
705
|
if (env.GDP_INFER_TRACE === '2' && !opts.progress)
|
|
703
706
|
opts = { ...opts, progress: (phase, info) => globalThis.process.stderr.write(`[infer ${phase}] ${JSON.stringify(info)}\n`) };
|
|
704
|
-
const t0 = performance.now(), ms = opts.ms ?? 20000, wallUntil = t0 + ms, rule = isRule(target) ? target.withSumsOf(laws, stepLaws) : undefined;
|
|
707
|
+
const t0 = performance.now(), ms = opts.ms ?? 20000, wallUntil = opts.wall ?? t0 + ms, rule = isRule(target) ? target.withSumsOf(laws, stepLaws) : undefined;
|
|
705
708
|
// The clock the budgets read (counted milliseconds since the start, or wall time where `timed`), and the stop.
|
|
706
709
|
const timed = !!opts.timed, w0 = work.n, used = { tries: 0, rows: 0, evals: 0, watched: 0, erows: 0, etries: 0 };
|
|
707
710
|
const now = () => (timed ? performance.now() - t0
|
|
@@ -764,7 +767,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
|
764
767
|
if ((first.proven && first.checked) || first.run)
|
|
765
768
|
return { ...first, found: [], stats: stats(0, 0, 0) };
|
|
766
769
|
// --- runs ------------------------------------------------------------------------------------------------------------
|
|
767
|
-
const run = interpret(m), rand =
|
|
770
|
+
const run = interpret(m), rand = searchSeeded(17), kinds = rule ? rule.kindsOfState() : [];
|
|
768
771
|
const given = rule ? [...rule.kindLaws().filter(k => !laws.some(l => l.name === k.name)), ...laws] : laws;
|
|
769
772
|
const randomParams = (bound, r = rand) => (rule ? rule.randomParams(r, bound) : Object.fromEntries(m.params.map(p => [p, r(bound + 1)])));
|
|
770
773
|
const randomInput = (params, bound, r = rand) => (rule ? rule.randomInput(r, bound, params)
|
|
@@ -957,7 +960,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
|
957
960
|
modes.push({ atom: i, values: [0, 1], bool: true });
|
|
958
961
|
else if (typeof decoded === 'string' && values)
|
|
959
962
|
modes.push({ atom: i, values: values.map((_, j) => j), choice: values });
|
|
960
|
-
else if (!k && seenValues.length && seenValues
|
|
963
|
+
else if (!k && seenValues.length && few(seenValues))
|
|
961
964
|
modes.push({ atom: i, values: seenValues });
|
|
962
965
|
});
|
|
963
966
|
const modeOf = (i) => modes.find(mo => mo.atom === i);
|
|
@@ -3014,7 +3017,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
|
3014
3017
|
for (const i of [...v.atoms.filter(j => !atoms[j].int && !atoms[j].term), ...modes.filter(mo => !atoms[mo.atom].cell && !atoms[mo.atom].param).map(mo => mo.atom)]) {
|
|
3015
3018
|
const vals = [...new Set(R.map(r => r[i]))].sort((a, b) => a - b);
|
|
3016
3019
|
// (a value of a key's sort: 0 alone, an order literal below)
|
|
3017
|
-
for (const value of valued(i) ? vals.filter(q => q === 0) : vals.length <= 3 ? vals : []) {
|
|
3020
|
+
for (const value of valued(i) ? vals.filter(q => q === 0) : vals.length <= 3 || few(vals) ? vals : []) {
|
|
3018
3021
|
const top = value > 0 && value === vals.at(-1);
|
|
3019
3022
|
add(top ? { lin: { coef: [[i, -1]], d: -value } } : { at: { atom: i, value } }, `${i}`, ren => `${term(i, ren)}=${value}`, reads(i), r => (top ? r[i] >= value : r[i] === value));
|
|
3020
3023
|
}
|
|
@@ -3123,7 +3126,7 @@ function inferLawsSearch(target, laws, stepLaws = [], opts = {}) {
|
|
|
3123
3126
|
for (const f of live)
|
|
3124
3127
|
byView.set(f.view, [...(byView.get(f.view) ?? []), f]);
|
|
3125
3128
|
let read = 0, still = 0, lastKill = 0;
|
|
3126
|
-
const r = instance(grow, share,
|
|
3129
|
+
const r = instance(grow, share, searchSeeded(29 + k), most5, q => {
|
|
3127
3130
|
if (read >= most5 || (read >= (k ? 0 : least5) && still >= quiet) || stop())
|
|
3128
3131
|
return false;
|
|
3129
3132
|
states++;
|
|
@@ -46,7 +46,7 @@ public final class Harness {
|
|
|
46
46
|
if (dels.contains(n) && a != null && a.length >= 1) { st.data.remove(String.valueOf(a[0])); return m.getReturnType() == void.class || m.getReturnType().isPrimitive() ? conv(null, m.getReturnType(), null) : null; }
|
|
47
47
|
for (Object a0 : list(S.get("answers"))) {
|
|
48
48
|
Map<?, ?> an = (Map<?, ?>) a0, pt = (Map<?, ?>) an.get("patch");
|
|
49
|
-
if (pt != null && name.equals(pt.get("store")) && n.equals(list(pt.get("path")).get(list(pt.get("path")).size() - 1))) { Object v = CUR.get(an.get("key")); return v == null || ((Map<?, ?>) v).containsKey("none") ? conv(null,
|
|
49
|
+
if (pt != null && name.equals(pt.get("store")) && n.equals(list(pt.get("path")).get(list(pt.get("path")).size() - 1))) { Object v = CUR.get(an.get("key")); Class<?> rc = stated(m.getReturnType(), an.get("sort")); return v == null || ((Map<?, ?>) v).containsKey("none") ? conv(null, rc, m.getGenericReturnType()) : conv(((Map<?, ?>) v).get("in"), rc, m.getGenericReturnType()); }
|
|
50
50
|
}
|
|
51
51
|
// (a method the rule leaves out runs as nothing, as the rule takes it; any other fails: the check reports it)
|
|
52
52
|
if (d == null || !list(d.get("skip")).contains(n)) throw new UnsupportedOperationException(name + "." + n + ": a method of the injected dependency the rule doesn't read");
|
|
@@ -119,6 +119,13 @@ public final class Harness {
|
|
|
119
119
|
}
|
|
120
120
|
|
|
121
121
|
// --- values ---------------------------------------------------------------------------------------------------------
|
|
122
|
+
// The class an answer is given as: the method's declared one, or where that is a type variable's erasure (a generic
|
|
123
|
+
// result, Object), the type the answer is stated in.
|
|
124
|
+
static Class<?> stated(Class<?> c, Object sort) {
|
|
125
|
+
if (c != Object.class || !(sort instanceof String s)) return c;
|
|
126
|
+
return switch (s.replaceAll("\\s*\\|\\s*None$|\\?$", "")) { case "int", "Integer", "Int", "i32" -> Integer.class; case "long", "Long", "i64" -> Long.class; case "short", "Short" -> Short.class; case "byte", "Byte" -> Byte.class;
|
|
127
|
+
case "float", "double", "Double" -> Double.class; case "Float" -> Float.class; case "bool", "boolean", "Boolean" -> Boolean.class; case "str", "String" -> String.class; default -> c; };
|
|
128
|
+
}
|
|
122
129
|
static Object conv(Object v, Class<?> c, Type g) {
|
|
123
130
|
if (c == Optional.class) return v == null ? Optional.empty() : Optional.of(conv(v, g instanceof ParameterizedType pt ? raw(pt.getActualTypeArguments()[0]) : Object.class, null));
|
|
124
131
|
if (v == null) return c.isPrimitive() ? conv(0L, c, null) : null;
|
package/dist/core/jvm/Jvm.java
CHANGED
|
@@ -111,7 +111,7 @@ public final class Jvm {
|
|
|
111
111
|
static boolean integral(JT t) { String q = prim(t); return q != null && Set.of("int", "long", "short", "byte", "char").contains(q); }
|
|
112
112
|
static boolean floating(JT t) { String q = prim(t); return "float".equals(q) || "double".equals(q); }
|
|
113
113
|
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"); }
|
|
114
|
+
static boolean atomic(JT t) { return t != null && (t.n.startsWith("java.util.concurrent.atomic.Atomic") || t.n.startsWith("kotlinx.atomicfu.Atomic")); }
|
|
115
115
|
// The type an atomic holds.
|
|
116
116
|
static JT held(JT t) {
|
|
117
117
|
return switch (t.simple()) { case "AtomicInteger", "AtomicInt" -> new JT("int"); case "AtomicLong" -> new JT("long"); case "AtomicBoolean" -> new JT("boolean"); default -> t.arg(0); };
|
|
@@ -863,6 +863,9 @@ public final class KtReader implements Jvm.Env {
|
|
|
863
863
|
X body = inline(lam, null, recv, c, stmt && n.equals("let"), p);
|
|
864
864
|
return n.equals("also") ? recv : body;
|
|
865
865
|
}
|
|
866
|
+
// (any other call given a lambda: other code runs it, any number of times; repeat(n) { } a loop. require's and
|
|
867
|
+
// check's lambda is their failure's message, read as they are)
|
|
868
|
+
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
869
|
List<Map<String, Object>> args = new ArrayList<>();
|
|
867
870
|
List<JT> argT = new ArrayList<>();
|
|
868
871
|
List<Object> kw = new ArrayList<>();
|
package/dist/core/laws.d.ts
CHANGED
|
@@ -80,4 +80,8 @@ export type Cite = {
|
|
|
80
80
|
export declare function citesIn(text: string, where?: string): Cite[];
|
|
81
81
|
export declare const isTwoRuns: (expr: string) => boolean;
|
|
82
82
|
export declare function buildTwoRuns(x: Extraction, l: LawText, others?: Record<string, Extraction>): TwoRunLaw;
|
|
83
|
+
export declare const isLeadsTo: (expr: string) => boolean;
|
|
84
|
+
export declare function buildLeadsTo(x: Extraction, l: LawText, opts?: {
|
|
85
|
+
clock?: number;
|
|
86
|
+
}): unknown;
|
|
83
87
|
export {};
|
package/dist/core/laws.js
CHANGED
|
@@ -249,7 +249,7 @@ export function buildLaw(x, l, opts = {}) {
|
|
|
249
249
|
throw new LawError(`${l.name}: a law is stated as <name>: <expr>`);
|
|
250
250
|
const e = parse(l.expr);
|
|
251
251
|
// 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 = { b: {}, a: {}, step: true, method: l.method, keys: new Map(), roles: new Set(), methods: new Set(), clock: opts.clock };
|
|
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 };
|
|
253
253
|
read(e, probe, names, true);
|
|
254
254
|
// (a law on a method, the line above it, is a law of its step: the state after it, old(x) before)
|
|
255
255
|
const step = !!l.method || ['input', 'answer', 'result', 'failed', 'clock', 'method', 'old'].some(k => probe.roles.has(k));
|
|
@@ -257,7 +257,7 @@ export function buildLaw(x, l, opts = {}) {
|
|
|
257
257
|
if (probe.methods.size > 1)
|
|
258
258
|
throw new LawError(`it reads the arguments of ${[...probe.methods].join(' and ')}: a law of one step is about one method`);
|
|
259
259
|
const gate = step && method && names.some(n => n.role === 'method') ? method : undefined;
|
|
260
|
-
const body = (b, a) => read(e, { b, a, step, method, keys: new Map(), roles: new Set(), methods: new Set(), clock: opts.clock }, names, false);
|
|
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);
|
|
261
261
|
if (!step)
|
|
262
262
|
return { kind: 'law', law: r.law(l.name, (env) => (x.quiet ? env[x.quiet].eq(0).implies(body(env, env)) : body(env, env))) };
|
|
263
263
|
const mname = names.find(n => n.role === 'method')?.rule;
|
|
@@ -353,8 +353,24 @@ function val(e, c, names, dry) {
|
|
|
353
353
|
throw new LawError(`sum(${m.n.code}): its cells have ${fs.join(', ')} (the sum is of a map of numbers)`);
|
|
354
354
|
if (dry)
|
|
355
355
|
return DRY;
|
|
356
|
-
const map = (c.a[m.n.rule] ?? c.b[m.n.rule]);
|
|
357
|
-
|
|
356
|
+
const map = ((m.env ?? c.a)[m.n.rule] ?? c.b[m.n.rule]);
|
|
357
|
+
try {
|
|
358
|
+
// (a map of integers: the sum of its cells' positive parts less the sum of their negative parts, each a sum of
|
|
359
|
+
// naturals the kernel keeps exact)
|
|
360
|
+
const one = map.at(new Term({ op: 'const', value: 0 }))[fs[0]];
|
|
361
|
+
if (one instanceof Int) {
|
|
362
|
+
// (after the step: the sums over the map before it, as the state after it holds them, primed)
|
|
363
|
+
const after = (m.env ?? c.a) === c.a && c.step && c.a !== c.b, src = (after ? c.b[m.n.rule] : map);
|
|
364
|
+
const sumOf = (part) => { const t = src.sum(cell => cell[fs[0]][part]); return after && t.e.op === 'var' ? new Term({ op: 'var', name: `${t.e.name}'` }) : t; };
|
|
365
|
+
return { t: 'num', v: new Int(sumOf('pos'), sumOf('neg')) };
|
|
366
|
+
}
|
|
367
|
+
return { t: 'num', v: Int.of(map.sum(cell => cell[fs[0]])) };
|
|
368
|
+
}
|
|
369
|
+
catch (x) {
|
|
370
|
+
if (x instanceof TypeError)
|
|
371
|
+
throw new LawError(`sum(${m.n.code}): a sum is of naturals, and ${m.n.code}'s cells are integers (a cell the code may set below 0): state them as naturals (domains, in gdp.toml) where the code never does`);
|
|
372
|
+
throw x;
|
|
373
|
+
}
|
|
358
374
|
}
|
|
359
375
|
const xs = e.xs.map(go);
|
|
360
376
|
if (dry)
|
|
@@ -370,6 +386,20 @@ function val(e, c, names, dry) {
|
|
|
370
386
|
return e.op === '-' ? { t: 'num', v: num(v).negate() } : { t: 'cond', v: not(cond(v)) };
|
|
371
387
|
}
|
|
372
388
|
case 'bin': {
|
|
389
|
+
// (a comparison with x // k on one side, k a positive constant: the same comparison without the division, exact
|
|
390
|
+
// 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
|
+
// of one step can't read)
|
|
392
|
+
const flip = { '<': '>', '<=': '>=', '>': '<', '>=': '<=', '==': '==', '!=': '!=' };
|
|
393
|
+
const divk = (x) => (x.k === 'bin' && x.op === '//' && (constOf(x.b) ?? 0) >= 1 ? x : undefined);
|
|
394
|
+
if (flip[e.op] && (divk(e.b) || divk(e.a))) {
|
|
395
|
+
const [op, lhs, d] = divk(e.b) ? [e.op, e.a, divk(e.b)] : [flip[e.op], e.b, divk(e.a)];
|
|
396
|
+
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
|
+
const le = (a, b) => ({ k: 'bin', op: '<=', a, b }), lt = (a, b) => ({ k: 'bin', op: '<', a, b });
|
|
398
|
+
// a ⋈ ⌊x/k⌋: <= : k·a <= x; < : k·(a+1) <= x; >= : x < k·(a+1); > : x < k·a; == : both; != : not both
|
|
399
|
+
const x = d.a, eq = { k: 'bin', op: '&&', a: le(ka, x), b: lt(x, ka1) };
|
|
400
|
+
const out = op === '<=' ? le(ka, x) : op === '<' ? le(ka1, x) : op === '>=' ? lt(x, ka1) : op === '>' ? lt(x, ka) : op === '==' ? eq : { k: 'un', op: 'not', x: eq };
|
|
401
|
+
return go(out);
|
|
402
|
+
}
|
|
373
403
|
if (e.op === 'in') {
|
|
374
404
|
const m = go(e.b);
|
|
375
405
|
if (m.t !== 'map')
|
|
@@ -455,7 +485,7 @@ const show = (x) => (x.k === 'path' ? [x.head, ...x.segs.map(s => ('f' in s ? `.
|
|
|
455
485
|
// A map's key as the rule holds it: a string's id, a natural.
|
|
456
486
|
const key = (k) => (k.t === 'opt' && k.v ? key(k.v) : k.t === 'key' ? k.v : k.t === 'str' ? k.v.id : k.t === 'lit' ? fail('a literal key (the rule keys a map by the request\'s values)') : (() => { const n = num(k); return n.neg.e.op === 'const' && n.neg.e.value === 0 ? n.pos : n.clamped; })());
|
|
457
487
|
function cellOf(m, k, c) {
|
|
458
|
-
const map = (c.a[m.n.rule] ?? c.b[m.n.rule]);
|
|
488
|
+
const map = ((m.env ?? c.a)[m.n.rule] ?? c.b[m.n.rule]);
|
|
459
489
|
return { rec: map.at(k), fields: m.n.map.fields };
|
|
460
490
|
}
|
|
461
491
|
// A path: the longest prefix of it the code names (in the law's method first: its arguments shadow the fields, as in the
|
|
@@ -469,7 +499,9 @@ function path(e, c, names, dry) {
|
|
|
469
499
|
return dry ? DRY : rest(e.segs, { t: 'cell', rec: item.map, fields: item.fields }, c, names, dry, e);
|
|
470
500
|
if (c.keys.has(e.head) && dry)
|
|
471
501
|
return DRY;
|
|
472
|
-
|
|
502
|
+
// (result and failed are the step's, unless the code has a name of its own so: a field named failed, read bare, is
|
|
503
|
+
// that field, as self.failed always is)
|
|
504
|
+
if ((e.head === 'result' || e.head === 'failed') && !names.some(n => n.code === e.head && n.role !== 'failed' && n.role !== 'result')) {
|
|
473
505
|
const n = e.head === 'failed' ? names.find(x => x.role === 'failed') : results(names, c);
|
|
474
506
|
if (!n)
|
|
475
507
|
throw new LawError(e.head === 'failed' ? 'the rule keeps no failure (with failures: \'kept\' it does: `failures = "kept"` in gdp.toml or --failures kept)' : 'the method returns nothing the rule keeps');
|
|
@@ -478,7 +510,8 @@ function path(e, c, names, dry) {
|
|
|
478
510
|
c.methods.add(n.method);
|
|
479
511
|
return rest(e.segs, leaf(n, c, dry), c, names, dry, e);
|
|
480
512
|
}
|
|
481
|
-
|
|
513
|
+
// (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
|
+
const explicit = (['self', 'this', 'state', 's'].includes(e.head) && e.segs.length > 0) || e.head.startsWith('@');
|
|
482
515
|
const parts = [e.head.replace(/^@/, ''), ...e.segs.map(s => ('f' in s ? s.f : undefined))];
|
|
483
516
|
const heads = explicit && !e.head.startsWith('@') ? [parts.slice(1)] : [parts, ...(parts.length > 1 && parts[1] !== undefined ? [parts.slice(1)] : [])];
|
|
484
517
|
for (const [hi, p] of heads.entries()) {
|
|
@@ -500,11 +533,16 @@ function path(e, c, names, dry) {
|
|
|
500
533
|
if (hit.role === 'answer' && next && 'call' in next && next.args)
|
|
501
534
|
throw new LawError(`${code}(${next.args}): an answered call's value is the request's, one a step: write it ${code}(...)`);
|
|
502
535
|
const segs = e.segs.slice(skip + n - 1 + (hit.role === 'answer' && next && 'call' in next ? 1 : 0));
|
|
503
|
-
|
|
536
|
+
// (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
|
+
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);
|
|
504
538
|
}
|
|
505
539
|
}
|
|
506
540
|
}
|
|
507
541
|
// 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.
|
|
543
|
+
const k = c.consts?.[e.head];
|
|
544
|
+
if (k !== undefined && !e.segs.length)
|
|
545
|
+
return typeof k === 'number' ? { t: 'num', v: Int.of(k) } : typeof k === 'boolean' ? { t: 'cond', v: k ? yes : no } : { t: 'lit', v: k };
|
|
508
546
|
const m = names.find(n => n.role === 'input' && n.method === e.head && e.segs[0] && 'f' in e.segs[0] && n.code === e.segs[0].f);
|
|
509
547
|
if (m) {
|
|
510
548
|
c.roles.add('input');
|
|
@@ -524,6 +562,10 @@ function find(code, names, c, stateOnly, called) {
|
|
|
524
562
|
const here = inputs.filter(n => n.method === c.method);
|
|
525
563
|
if (here.length)
|
|
526
564
|
return here[0];
|
|
565
|
+
// (a field of that name: the field, never another method's argument)
|
|
566
|
+
const field = names.find(n => n.role === 'state' && at(n));
|
|
567
|
+
if (field)
|
|
568
|
+
return field;
|
|
527
569
|
if (new Set(inputs.map(n => n.method)).size === 1)
|
|
528
570
|
return inputs[0];
|
|
529
571
|
throw new LawError(`${code} is an argument of ${inputs.map(n => n.method).join(', ')}: write the law on the method it is about (the line above it), or as <method>.${code}`);
|
|
@@ -610,7 +652,7 @@ function storeKey(m, k, c, names, dry) {
|
|
|
610
652
|
const hit = m.maps.find(x => x.map.tpl === tpl) ?? (holes.length === 1 && tpl === '{}' && m.maps.length === 1 ? m.maps[0] : undefined);
|
|
611
653
|
if (!hit || holes.length !== 1)
|
|
612
654
|
throw new LawError(`${m.n.code}[${tpl}]: its keys are ${m.maps.map(x => JSON.stringify(x.map.tpl.replace('{}', '<key>'))).join(', ')}`);
|
|
613
|
-
return [{ t: 'map', n: hit, maps: [hit] }, val(holes[0], c, names, dry)];
|
|
655
|
+
return [{ t: 'map', n: hit, maps: [hit], ...(m.env ? { env: m.env } : {}) }, val(holes[0], c, names, dry)];
|
|
614
656
|
}
|
|
615
657
|
const CITE = /(?:#|\/\/|--|%|\/\*|^\s*\*)\s*gdp:\s*cite\s+([^:]+?)\s*:\s*(.+?)\s*(?:\*\/)?\s*$/;
|
|
616
658
|
export function citesIn(text, where = '') {
|
|
@@ -668,3 +710,128 @@ export function buildTwoRuns(x, l, others = {}) {
|
|
|
668
710
|
}
|
|
669
711
|
throw new LawError('not a law about two runs');
|
|
670
712
|
}
|
|
713
|
+
// --- liveness: "whenever <from>, later <to>" ---------------------------------------------------------------------------
|
|
714
|
+
// `<from> leads to <to> by <rank>[, <rank>...] via <helpful>[; <helpful>...] [strongly]`, each helpful request
|
|
715
|
+
// `[<cond> ->] <method>(<arg> = <value>, ...)`: in every run that takes each helpful request (where its condition holds)
|
|
716
|
+
// infinitely often, a state where `from` holds is followed by one where `to` does (core/dsl.ts's leadsTo, proven by
|
|
717
|
+
// proveLeadsTo: no step raises the rank (in order) while `from` holds and `to` doesn't, except into `to`, and each helpful
|
|
718
|
+
// request lowers it or reaches `to`). `strongly`: strong fairness (a request taken wherever, infinitely often, it is
|
|
719
|
+
// allowed). The conditions and the rank read the state and the params; a helpful request's values are literals (true,
|
|
720
|
+
// false, a number, one of a choice's values) or terms of the state.
|
|
721
|
+
const LEADS = /^(.*?)\s+leads\s+to\s+(.*?)(?:\s+by\s+(.*?))?\s+via\s+(.*?)(\s+strongly)?\s*$/s;
|
|
722
|
+
export const isLeadsTo = (expr) => LEADS.test(expr.trim());
|
|
723
|
+
export function buildLeadsTo(x, l, opts = {}) {
|
|
724
|
+
const m = LEADS.exec(l.expr.trim());
|
|
725
|
+
if (!m)
|
|
726
|
+
throw new LawError(`${l.name}: <from> leads to <to> [by <rank>] via <method>(<arg> = <value>, ...)`);
|
|
727
|
+
const names = namesWithClock(x), r = x.rule;
|
|
728
|
+
const model = x.model;
|
|
729
|
+
const sorts = x.sorts;
|
|
730
|
+
const ctxOf = (env) => ({ consts: x.consts, b: env, a: env, step: false, keys: new Map(), roles: new Set(), methods: new Set(), clock: opts.clock });
|
|
731
|
+
const stateOnly = (text, what) => {
|
|
732
|
+
const e = parse(text), probe = ctxOf({});
|
|
733
|
+
if (e.k === 'forall')
|
|
734
|
+
read(e, probe, names, true);
|
|
735
|
+
else
|
|
736
|
+
val(e, probe, names, true); // (what it reads: a bare yes/no field reads as one)
|
|
737
|
+
if ([...probe.roles].some(k => ['input', 'answer', 'result', 'failed', 'old', 'method'].includes(k)))
|
|
738
|
+
throw new LawError(`${what} reads the request or the step: it reads the state and the params`);
|
|
739
|
+
return e;
|
|
740
|
+
};
|
|
741
|
+
const from = stateOnly(m[1], 'its from'), to = stateOnly(m[2], 'its to');
|
|
742
|
+
const ranks = (m[3] ? split(m[3], ',') : []).map(t => { const e = parse(t); val(e, ctxOf({}), names, true); return e; });
|
|
743
|
+
const mname = names.find(n => n.role === 'method')?.rule;
|
|
744
|
+
const helpful = split(m[4], ';').map(h => {
|
|
745
|
+
const arrow = topIndex(h, '->');
|
|
746
|
+
const when = arrow >= 0 ? stateOnly(h.slice(0, arrow), 'a helpful request\'s condition') : undefined;
|
|
747
|
+
const call = /^\s*(\w+)\s*\((.*)\)\s*$/s.exec(arrow >= 0 ? h.slice(arrow + 2) : h);
|
|
748
|
+
if (!call)
|
|
749
|
+
throw new LawError(`a helpful request is <method>(<arg> = <value>, ...): ${h.trim()}`);
|
|
750
|
+
const method = call[1], args = call[2].trim() ? split(call[2], ',').map(a => { const eq = a.indexOf('='); if (eq < 0)
|
|
751
|
+
throw new LawError(`${method}(${a.trim()}): <arg> = <value>`); return [a.slice(0, eq).trim(), a.slice(eq + 1).trim()]; }) : [];
|
|
752
|
+
const ins = names.filter(n => n.role === 'input' && (n.method === method || !n.method));
|
|
753
|
+
if (mname && !names.some(n => n.method === method)) {
|
|
754
|
+
const ev = model?.inputs.find(v => v.name === mname);
|
|
755
|
+
if (!ev?.sort.values?.includes(method))
|
|
756
|
+
throw new LawError(`no method ${method} (its methods: ${ev?.sort.values?.join(', ') ?? 'none'})`);
|
|
757
|
+
}
|
|
758
|
+
const vals = args.map(([a, v]) => {
|
|
759
|
+
const n = ins.find(y => y.code === a) ?? (() => { throw new LawError(`${method}(${a}): no such argument (its arguments: ${ins.filter(y => y.method === method).map(y => y.code).join(', ')})`); })();
|
|
760
|
+
if (!n.rule)
|
|
761
|
+
throw new LawError(`${method}(${a}): an argument the rule doesn't keep`);
|
|
762
|
+
return [n.rule, v, model?.inputs.find(y => y.name === n.rule)?.sort, sorts?.get(n.rule)];
|
|
763
|
+
});
|
|
764
|
+
return { when, method, vals };
|
|
765
|
+
});
|
|
766
|
+
const strongly = !!m[5];
|
|
767
|
+
const term = (e, env) => { const v = val(e, ctxOf(env), names, false); const n = num(v); return n.clamped; };
|
|
768
|
+
const request = (h) => (env) => {
|
|
769
|
+
const out = {};
|
|
770
|
+
if (mname) {
|
|
771
|
+
const ev = model.inputs.find(v => v.name === mname);
|
|
772
|
+
out[mname] = ev.sort.values.indexOf(h.method);
|
|
773
|
+
}
|
|
774
|
+
for (const [rule, text, sort, dom] of h.vals) {
|
|
775
|
+
const lit = text.replace(/^["']|["']$/g, '');
|
|
776
|
+
if (sort?.k === 'bool') {
|
|
777
|
+
if (!['true', 'false', 'True', 'False'].includes(text))
|
|
778
|
+
throw new LawError(`${h.method}: ${rule} is a yes/no: true or false`);
|
|
779
|
+
out[rule] = /^t/i.test(text) ? 1 : 0;
|
|
780
|
+
}
|
|
781
|
+
else if (sort?.k === 'choice') {
|
|
782
|
+
const i = sort.values.indexOf(lit);
|
|
783
|
+
if (i < 0)
|
|
784
|
+
throw new LawError(`${text} isn't one of ${sort.values.join(', ')}`);
|
|
785
|
+
out[rule] = i;
|
|
786
|
+
}
|
|
787
|
+
else if (sort?.k === 'num' && dom !== 'int')
|
|
788
|
+
out[rule] = /^\d+$/.test(text) ? Number(text) : term(parse(text), env);
|
|
789
|
+
// (an integer: its two parts, the natural above 0 and the one below)
|
|
790
|
+
else if (sort?.k === 'num') {
|
|
791
|
+
const n = num(val(parse(text), ctxOf(env), names, false));
|
|
792
|
+
out[rule] = n.pos;
|
|
793
|
+
out[`${rule}$neg`] = n.neg;
|
|
794
|
+
}
|
|
795
|
+
else
|
|
796
|
+
throw new LawError(`${h.method}: ${rule}, a ${sort?.k ?? 'value'}, isn't given in a helpful request (numbers, yes/no and choices are)`);
|
|
797
|
+
}
|
|
798
|
+
return out;
|
|
799
|
+
};
|
|
800
|
+
return r.leadsTo(l.name, {
|
|
801
|
+
from: (env) => read(from, ctxOf(env), names, false),
|
|
802
|
+
to: (env) => read(to, ctxOf(env), names, false),
|
|
803
|
+
...(ranks.length ? { rank: (env) => ranks.map(e => term(e, env)) } : {}),
|
|
804
|
+
helpful: helpful.map(h => ({ ...(h.when ? { when: (env) => read(h.when, ctxOf(env), names, false) } : {}), request: request(h) })),
|
|
805
|
+
...(strongly ? { fairness: 'strong' } : {}),
|
|
806
|
+
});
|
|
807
|
+
}
|
|
808
|
+
// (the index of `tok` outside parentheses and quotes, or -1; a text split there)
|
|
809
|
+
function topIndex(s, tok) {
|
|
810
|
+
let depth = 0, q = '';
|
|
811
|
+
for (let i = 0; i < s.length; i++) {
|
|
812
|
+
const ch = s[i];
|
|
813
|
+
if (q) {
|
|
814
|
+
if (ch === q)
|
|
815
|
+
q = '';
|
|
816
|
+
continue;
|
|
817
|
+
}
|
|
818
|
+
if (ch === '"' || ch === "'")
|
|
819
|
+
q = ch;
|
|
820
|
+
else if (ch === '(' || ch === '[')
|
|
821
|
+
depth++;
|
|
822
|
+
else if (ch === ')' || ch === ']')
|
|
823
|
+
depth--;
|
|
824
|
+
else if (depth === 0 && s.startsWith(tok, i))
|
|
825
|
+
return i;
|
|
826
|
+
}
|
|
827
|
+
return -1;
|
|
828
|
+
}
|
|
829
|
+
function split(s, sep) {
|
|
830
|
+
const out = [];
|
|
831
|
+
let rest = s;
|
|
832
|
+
for (let i = topIndex(rest, sep); i >= 0; i = topIndex(rest, sep)) {
|
|
833
|
+
out.push(rest.slice(0, i));
|
|
834
|
+
rest = rest.slice(i + sep.length);
|
|
835
|
+
}
|
|
836
|
+
return [...out, rest].map(t => t.trim()).filter(Boolean);
|
|
837
|
+
}
|
package/dist/core/machine.d.ts
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
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;
|
|
5
|
+
export declare const lcgFloat: (x: number) => number;
|
|
6
|
+
export declare const searchSeeded: (seed: number) => Rand;
|
|
4
7
|
export declare const walk: (t: unknown, f: (o: Record<string, unknown>) => void) => void;
|
|
5
8
|
export declare const walkOnce: (t: unknown, f: (o: object) => void) => void;
|
|
6
9
|
export type E = {
|
package/dist/core/machine.js
CHANGED
|
@@ -7,7 +7,21 @@
|
|
|
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
|
-
|
|
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 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); }; };
|
|
16
|
+
// The searches still on the float form's stream (one 10,466-step cycle whatever the seed): infer.ts's runs and
|
|
17
|
+
// candidates, data.ts's rng, and the CHC and ITS runners' own runs (which feed infer). Under exact draws their results
|
|
18
|
+
// hinge on the draw: over 20 seed shifts, the system test's lease 1, the infer test's in-flight bound 15, the CHC task
|
|
19
|
+
// s_split_22 2, frontier2's break_safe 18, and bstInsert 9 (data.ts: which 240 random models its search compares terms
|
|
20
|
+
// in decides it, 0 of 8 shifts with the models fixed, the same 01001101 with only the models shifted). The rest of the
|
|
21
|
+
// searches (dsl's walks, nonterm, effect's runs, discover, live, cycles, fresh, xstate, the extractors' checks) draw
|
|
22
|
+
// from `seeded`. One moves to `seeded` once its result no longer turns on the draw.
|
|
23
|
+
export const lcgFloat = (x) => (x * 1103515245 + 12345) % 2 ** 31;
|
|
24
|
+
export const searchSeeded = (seed) => { let x = seed; return k => { x = lcgFloat(x); return Math.floor(x / 2 ** 31 * k); }; };
|
|
11
25
|
// Every object in a term, the term first.
|
|
12
26
|
export const walk = (t, f) => {
|
|
13
27
|
if (Array.isArray(t)) {
|
|
@@ -672,8 +686,8 @@ export function compileJs(m) {
|
|
|
672
686
|
case '<': return `(${ex(c.a)} < ${ex(c.b)})`;
|
|
673
687
|
case '<=': return `(${ex(c.a)} <= ${ex(c.b)})`;
|
|
674
688
|
case '=': return `(${ex(c.a)} === ${ex(c.b)})`;
|
|
675
|
-
case 'and': return `(${c.xs.map(cx).join(' && ')})
|
|
676
|
-
case 'or': return `(${c.xs.map(cx).join(' || ')})
|
|
689
|
+
case 'and': return c.xs.length ? `(${c.xs.map(cx).join(' && ')})` : 'true';
|
|
690
|
+
case 'or': return c.xs.length ? `(${c.xs.map(cx).join(' || ')})` : 'false';
|
|
677
691
|
case 'not': return `(!${cx(c.x)})`;
|
|
678
692
|
case 'flag': return `flag${flags.indexOf(c.name)}`;
|
|
679
693
|
case 'all': {
|
package/dist/core/py/harness.py
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
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]
|
|
@@ -82,6 +82,7 @@ class FakeStore:
|
|
|
82
82
|
def build(spec, stores):
|
|
83
83
|
if 'in' in spec:
|
|
84
84
|
v = spec['in']
|
|
85
|
+
if spec.get('bytes') and isinstance(v, str): return v.encode('latin-1')
|
|
85
86
|
return float(v) if spec.get('float') and isinstance(v, int) and not isinstance(v, bool) else v
|
|
86
87
|
if spec.get('none'): return None
|
|
87
88
|
if spec.get('inert'): return {} if spec.get('dict') else Inert()
|
|
@@ -174,13 +175,14 @@ def state_of(obj, stores):
|
|
|
174
175
|
v = walk(obj, l['path'])
|
|
175
176
|
if k == 'none': s[l['name']] = v is None
|
|
176
177
|
elif k == 'num': s[l['name']] = '0' if v is None else enc_num(v)
|
|
177
|
-
elif k in ('str', 'choice'): s[l['name']] = '' if v is None else v
|
|
178
|
+
elif k in ('str', 'choice'): s[l['name']] = '' if v is None else v.decode('latin-1') if isinstance(v, (bytes, bytearray)) else v
|
|
178
179
|
elif k == 'bool': s[l['name']] = False if v is None else v
|
|
179
180
|
elif k == 'map':
|
|
180
181
|
cells = {}
|
|
181
182
|
# (a list: its items by their places, 0 first)
|
|
182
|
-
for key, x in (enumerate(v or []) if l.get('ordered') else (v or {}).items()):
|
|
183
|
-
if l.get('
|
|
183
|
+
for key, x in (enumerate(v or []) if l.get('ordered') else ((k, None) for k in v or ()) if l.get('set') else (v or {}).items()):
|
|
184
|
+
if l.get('set'): cells[str(key)] = {}
|
|
185
|
+
elif l.get('fields'): cells[str(key)] = {f['name']: (lambda y: y if f.get('choice') else enc_num(y))(x[f['name']] if isinstance(x, dict) else getattr(x, f['name'])) for f in l['fields']}
|
|
184
186
|
else: cells[str(key)] = {'value': enc_num(x)}
|
|
185
187
|
s[l['name']] = cells
|
|
186
188
|
# A store's key no template names: the code keeps state the rule has no place for.
|
|
@@ -190,6 +192,10 @@ def state_of(obj, stores):
|
|
|
190
192
|
if not any(tpl_match(t, key) is not None for t in tpls): raise ValueError(f"the store {name} holds {key!r}, a key no template of the rule names")
|
|
191
193
|
return s
|
|
192
194
|
|
|
195
|
+
def is_bytes(l):
|
|
196
|
+
t = l.get('t') or {}
|
|
197
|
+
return bool((t.get('of') if t.get('k') == 'opt' else t).get('bytes'))
|
|
198
|
+
|
|
193
199
|
def num_in(x, flt):
|
|
194
200
|
return float(int(x)) if flt else int(x)
|
|
195
201
|
|
|
@@ -208,15 +214,16 @@ def set_state(obj, stores, state):
|
|
|
208
214
|
else: st.data[at] = c['value'] if l.get('choice') else num_in(c['value'], l.get('float'))
|
|
209
215
|
continue
|
|
210
216
|
if k == 'num': put(obj, l['path'], num_in(v, l.get('float')))
|
|
211
|
-
elif k in ('str', 'choice', 'bool'): put(obj, l['path'], v)
|
|
217
|
+
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)
|
|
212
218
|
elif k == 'map':
|
|
213
219
|
d = {}
|
|
214
220
|
for key, c in (v or {}).items():
|
|
215
221
|
kk = int(key) if l.get('key') == 'num' else key
|
|
216
|
-
if l.get('
|
|
222
|
+
if l.get('set'): d[kk] = True
|
|
223
|
+
elif l.get('fields'):
|
|
217
224
|
d[kk] = make_rec(resolve(l['cls']), {f['name']: (num_in(c[f['name']], f.get('float')) if isinstance(c[f['name']], str) and not f.get('choice') else c[f['name']]) for f in l['fields']})
|
|
218
225
|
else: d[kk] = num_in(c['value'], l.get('float')) if isinstance(c['value'], str) else c['value']
|
|
219
|
-
put(obj, l['path'], [d[kk] for kk in sorted(d)] if l.get('ordered') else d)
|
|
226
|
+
put(obj, l['path'], [d[kk] for kk in sorted(d)] if l.get('ordered') else set(d) if l.get('set') else d)
|
|
220
227
|
for l in S['leaves']:
|
|
221
228
|
if l['kind'] == 'none' and state.get(l['name']) is True: put(obj, l['path'], None)
|
|
222
229
|
|
|
@@ -253,19 +260,56 @@ class _Now(datetime.datetime):
|
|
|
253
260
|
"""datetime.datetime with now() the request's time (local, naive, as the code's own now())."""
|
|
254
261
|
@classmethod
|
|
255
262
|
def now(cls, tz=None): return datetime.datetime.fromtimestamp(NOW[0], tz)
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
263
|
+
# (where it is seen anyway, a type read while the clock is pinned, pydantic's: a datetime)
|
|
264
|
+
@classmethod
|
|
265
|
+
def __get_pydantic_core_schema__(cls, source, handler): return handler(datetime.datetime)
|
|
266
|
+
|
|
267
|
+
# The clock the repository's modules read (time.time(), datetime.now()) made the request's time, only while the code
|
|
268
|
+
# runs (making the object, a call): a module's names are its own again between, so a framework that reads them, an
|
|
269
|
+
# annotation or a route's types, sees the real datetime; a module made while the clock was pinned put back too.
|
|
270
|
+
CLOCKS = {'root': None, 'n': -1, 'pins': [], 'depth': 0}
|
|
271
|
+
def scan_clocks():
|
|
272
|
+
if len(sys.modules) == CLOCKS['n']: return
|
|
273
|
+
CLOCKS['n'] = len(sys.modules)
|
|
274
|
+
dtm = CLOCKS.get('dtm')
|
|
275
|
+
if dtm is None:
|
|
276
|
+
dtm = CLOCKS['dtm'] = types.SimpleNamespace(**{k: getattr(datetime, k) for k in dir(datetime) if not k.startswith('__')})
|
|
277
|
+
dtm.datetime = _Now
|
|
278
|
+
pins = []
|
|
262
279
|
for m in list(sys.modules.values()):
|
|
263
280
|
f = getattr(m, '__file__', None)
|
|
264
|
-
if not f or not os.path.realpath(f).startswith(root + os.sep): continue
|
|
281
|
+
if not f or not os.path.realpath(f).startswith(CLOCKS['root'] + os.sep): continue
|
|
265
282
|
for n, v in list(vars(m).items()):
|
|
266
|
-
if v is time_module:
|
|
267
|
-
elif v is datetime:
|
|
268
|
-
elif v is datetime.datetime:
|
|
283
|
+
if v is time_module or isinstance(v, Clock): pins.append((m, n, time_module, Clock(time_module)))
|
|
284
|
+
elif v is datetime or v is dtm: pins.append((m, n, datetime, dtm))
|
|
285
|
+
elif v is datetime.datetime or v is _Now: pins.append((m, n, datetime.datetime, _Now))
|
|
286
|
+
CLOCKS['pins'] = pins
|
|
287
|
+
|
|
288
|
+
def put_clocks(fake):
|
|
289
|
+
for m, n, real, f in CLOCKS['pins']: setattr(m, n, f if fake else real)
|
|
290
|
+
|
|
291
|
+
# (an import the code makes while it runs, a module of the repository first loaded then: run with the real clock, so
|
|
292
|
+
# what it copies or builds from the module's names is the real datetime, imports inside it too; the clock pinned
|
|
293
|
+
# again after the outermost, the new modules' names too)
|
|
294
|
+
REAL_IMPORT = builtins.__import__
|
|
295
|
+
def clock_import(*a, **k):
|
|
296
|
+
if CLOCKS['depth'] == 0: put_clocks(False)
|
|
297
|
+
CLOCKS['depth'] += 1
|
|
298
|
+
try: return REAL_IMPORT(*a, **k)
|
|
299
|
+
finally:
|
|
300
|
+
CLOCKS['depth'] -= 1
|
|
301
|
+
if CLOCKS['depth'] == 0: scan_clocks(); put_clocks(True)
|
|
302
|
+
|
|
303
|
+
class pinned:
|
|
304
|
+
def __enter__(self):
|
|
305
|
+
scan_clocks(); put_clocks(True)
|
|
306
|
+
builtins.__import__ = clock_import
|
|
307
|
+
def __exit__(self, *a):
|
|
308
|
+
builtins.__import__ = REAL_IMPORT
|
|
309
|
+
put_clocks(False); scan_clocks(); put_clocks(False)
|
|
310
|
+
|
|
311
|
+
def pin_clocks(root):
|
|
312
|
+
CLOCKS['root'] = os.path.realpath(root)
|
|
269
313
|
|
|
270
314
|
def raises_here(key):
|
|
271
315
|
"""Whether a call left out raises here, as the request says: only at the sites the rule read it may raise (a call of
|
|
@@ -340,7 +384,8 @@ def make(args):
|
|
|
340
384
|
else:
|
|
341
385
|
kw = fixed_args(args, {})
|
|
342
386
|
sys.settrace(tracer)
|
|
343
|
-
try:
|
|
387
|
+
try:
|
|
388
|
+
with pinned(): obj = run(S['cls'](**kw))
|
|
344
389
|
finally: sys.settrace(None)
|
|
345
390
|
for name, a in S['self_stubs']: obj.__dict__[name] = stub(a['key'], a['async'], getattr(obj, name) if a.get('pass') else None)
|
|
346
391
|
for name in S.get('inject') or []: setattr(obj, name, build({'store': name}, OBJ_STORES))
|
|
@@ -363,7 +408,7 @@ def call(req):
|
|
|
363
408
|
snap = state_of(obj, stores) if S.get('discard') and S['cls'] is not None else None
|
|
364
409
|
sys.settrace(tracer)
|
|
365
410
|
try:
|
|
366
|
-
out = run(fn(**kwargs))
|
|
411
|
+
with pinned(): out = run(fn(**kwargs))
|
|
367
412
|
err = None
|
|
368
413
|
except Exception as e:
|
|
369
414
|
out, err = None, f"{type(e).__name__}: {e}"[:300]
|