gdp-wired 0.50.0 → 0.50.2
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/dist/core/chart.js +28 -4
- package/dist/core/cli.js +2 -1
- package/dist/core/compose.js +4 -3
- package/dist/core/dsl-binders.d.ts +15 -0
- package/dist/core/dsl-binders.js +129 -0
- package/dist/core/dsl.d.ts +5 -0
- package/dist/core/dsl.js +101 -37
- package/dist/core/extract-c.js +1 -1
- package/dist/core/extract-go-check.js +3 -2
- package/dist/core/extract-step.js +11 -2
- package/dist/core/extract.d.ts +1 -0
- package/dist/core/infer.js +6 -2
- package/dist/core/laws.d.ts +4 -0
- package/dist/core/laws.js +10 -1
- package/dist/core/native-wire.d.ts +1 -0
- package/dist/core/native-wire.js +85 -0
- package/dist/core/py/harness.py +35 -1
- package/dist/core/source-check.d.ts +2 -0
- package/dist/core/source-check.js +21 -0
- package/dist/kernel/reader.js +5 -1
- package/dist/lean-kernel/axiom-audit.js +5 -2
- package/dist/lean-kernel/emit.d.ts +1 -0
- package/dist/lean-kernel/emit.js +22 -4
- package/package.json +4 -2
package/dist/core/chart.js
CHANGED
|
@@ -19,6 +19,7 @@
|
|
|
19
19
|
import { Choice, Cond, Term, all, any, no, oneOf, proveRule, proveSteps, rule, when, yes } from "./dsl.js";
|
|
20
20
|
import { interpret, numbersOf } from "./machine.js";
|
|
21
21
|
import { allowed } from "./watch.js";
|
|
22
|
+
import { reservedName } from "./dsl-binders.js";
|
|
22
23
|
export class Chart {
|
|
23
24
|
s;
|
|
24
25
|
constructor(s) {
|
|
@@ -71,8 +72,31 @@ export class Chart {
|
|
|
71
72
|
}
|
|
72
73
|
};
|
|
73
74
|
walk('', root);
|
|
74
|
-
return { name, field: single ? s.field ?? 'state' : name, leaves, finals, compounds };
|
|
75
|
+
return { name, field: single ? s.field ?? 'state' : name, leaves, finals, compounds, historyFields: new Map() };
|
|
75
76
|
});
|
|
77
|
+
// Allocate readable legacy names first, before fallbacks, so an encoded name cannot steal one.
|
|
78
|
+
// Include every declared field and generated flag: history is storage, never an alias for user data.
|
|
79
|
+
const usedNames = new Set([...regions.map(r => r.field), ...Object.keys(s.params), ...Object.keys(s.inputs),
|
|
80
|
+
...Object.keys(s.context), ...Object.keys(s.outputs), 'event', ...s.on.flatMap((_, i) => [`on${i}`, `take${i}`])]);
|
|
81
|
+
const histories = regions.flatMap(r => [...r.compounds].filter(([c, v]) => c && v.history).map(([c]) => ({ r, c })));
|
|
82
|
+
for (const { r, c } of histories) {
|
|
83
|
+
const legacy = `${r.field}.last.${c}`;
|
|
84
|
+
if (!reservedName(legacy) && !usedNames.has(legacy)) {
|
|
85
|
+
r.historyFields.set(c, legacy);
|
|
86
|
+
usedNames.add(legacy);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
// Encode UTF-16 code units (including lone surrogates) injectively, in a namespace outside `.last.`.
|
|
90
|
+
const hex = (x) => Array.from({ length: x.length }, (_, i) => x.charCodeAt(i).toString(16).padStart(4, '0')).join('');
|
|
91
|
+
for (const { r, c } of histories)
|
|
92
|
+
if (!r.historyFields.has(c)) {
|
|
93
|
+
const base = `gdp$chart$history$${hex(r.field)}$${hex(c)}`;
|
|
94
|
+
let name = base, n = 0;
|
|
95
|
+
while (usedNames.has(name))
|
|
96
|
+
name = `${base}$${++n}`;
|
|
97
|
+
r.historyFields.set(c, name);
|
|
98
|
+
usedNames.add(name);
|
|
99
|
+
}
|
|
76
100
|
// A path as the region and the state within it.
|
|
77
101
|
const locate = (path) => {
|
|
78
102
|
if (single)
|
|
@@ -107,7 +131,7 @@ export class Chart {
|
|
|
107
131
|
});
|
|
108
132
|
// Most specific source first, then the order declared: the first enabled in this order is taken.
|
|
109
133
|
placed.sort((a, b) => b.depth - a.depth || a.order - b.order);
|
|
110
|
-
const lastOf = (r, c) =>
|
|
134
|
+
const lastOf = (r, c) => r.historyFields.get(c);
|
|
111
135
|
const state = {};
|
|
112
136
|
for (const r of regions) {
|
|
113
137
|
const kind = oneOf(...r.leaves), enter = (path) => { const c = r.compounds.get(path); return c ? enter(path ? `${path}.${c.initial}` : c.initial) : path; };
|
|
@@ -188,7 +212,7 @@ export class Chart {
|
|
|
188
212
|
const [head, ...rest] = single ? ['state', ...compound.split('.')] : compound.split('.'), r = regions.find(x => x.name === head), c = rest.join('.');
|
|
189
213
|
if (!r?.compounds.get(c)?.history)
|
|
190
214
|
throw new Error(`${this.s.name}: ${compound} keeps no history`);
|
|
191
|
-
return env[
|
|
215
|
+
return env[r.historyFields.get(c)];
|
|
192
216
|
}
|
|
193
217
|
wrap(env) { return Object.assign(Object.create(null), env, { in: (p) => this.in(env, p), last: (c) => this.last(env, c) }); }
|
|
194
218
|
law(name, f) { return this.rule.law(name, (env) => f(this.wrap(env))); }
|
|
@@ -199,7 +223,7 @@ export class Chart {
|
|
|
199
223
|
// laws `prove` and `check` are given (as a rule's kind laws are), since a law about entering a compound may need it.
|
|
200
224
|
chartLaws() {
|
|
201
225
|
const { rule: r, regions } = this.build();
|
|
202
|
-
return regions.flatMap(reg => [...reg.compounds].filter(([c, { history }]) => history && c).map(([c]) => r.law(`${reg.name === 'state' ? '' : `${reg.name}.`}${c} remembers one of its own states`, (env) => any(...reg.leaves.filter(l => l.startsWith(`${c}.`)).map(l => env[
|
|
226
|
+
return regions.flatMap(reg => [...reg.compounds].filter(([c, { history }]) => history && c).map(([c]) => r.law(`${reg.name === 'state' ? '' : `${reg.name}.`}${c} remembers one of its own states`, (env) => any(...reg.leaves.filter(l => l.startsWith(`${c}.`)).map(l => env[reg.historyFields.get(c)].is(l))))));
|
|
203
227
|
}
|
|
204
228
|
prove(laws = [], stepLaws = [], opts = {}) { const given = [...this.chartLaws(), ...laws]; return stepLaws.length ? proveSteps(this.rule, given, stepLaws, opts) : proveRule(this.rule, given, opts); }
|
|
205
229
|
// --- the checks a chart's author expects -------------------------------------------------------------------------
|
package/dist/core/cli.js
CHANGED
|
@@ -1128,7 +1128,8 @@ export async function check(targets, given = {}, each) {
|
|
|
1128
1128
|
rs.forEach(each);
|
|
1129
1129
|
}
|
|
1130
1130
|
const stated = all.flatMap(r => r.laws);
|
|
1131
|
-
|
|
1131
|
+
// A sampled source translation cannot turn an unknown proof into a successful check.
|
|
1132
|
+
return { rules: all, exit: stated.some(l => l.verdict === 'unknown' || l.translation === 'unchecked' || l.translation === 'error') ? 2 : stated.some(l => l.verdict === 'broken') ? 1 : stated.some(l => l.verdict === 'not read') || o.security && all.some(r => !r.ok) ? 2 : 0 };
|
|
1132
1133
|
}
|
|
1133
1134
|
// --- draft: laws from a clause, for a person to review ----------------------------------------------------------------
|
|
1134
1135
|
// gdp-wired draft <file> --clause <text> | --clause-file <f> --cite <ref> [--llm <command> | --answer <file>] [--by <who>]:
|
package/dist/core/compose.js
CHANGED
|
@@ -14,9 +14,10 @@
|
|
|
14
14
|
import { all, any, bit, not, same, unreachable, x } from "./machine.js";
|
|
15
15
|
import { substC, substE } from "../kernel/kernel.js";
|
|
16
16
|
import { nameQuantifiers } from "./dsl.js";
|
|
17
|
+
import { copyVariable, generatedVariable } from "./dsl-binders.js";
|
|
17
18
|
function rename(e, prefix, m, inputs) {
|
|
18
19
|
switch (e.op) {
|
|
19
|
-
case 'var': return m.params.includes(e.name) ? e : m.inputs.includes(e.name) ? (inputs[e.name] ?? e) : x(`${prefix}${e.name}`);
|
|
20
|
+
case 'var': return m.params.includes(e.name) ? e : m.inputs.includes(e.name) ? (inputs[e.name] ?? e) : copyVariable(e, x(`${prefix}${e.name}`));
|
|
20
21
|
case 'const': return e;
|
|
21
22
|
case 'mul': return { ...e, a: rename(e.a, prefix, m, inputs) };
|
|
22
23
|
case 'if': return { op: 'if', c: renameC(e.c, prefix, m, inputs), then: rename(e.then, prefix, m, inputs), else: rename(e.else, prefix, m, inputs) };
|
|
@@ -54,10 +55,10 @@ function renamed(m, p, inputs, stays) {
|
|
|
54
55
|
maps: Object.fromEntries(Object.entries(m.maps ?? {}).map(([n, v]) => [`${p}${n}`, v])),
|
|
55
56
|
step: {
|
|
56
57
|
flags: Object.fromEntries(Object.entries(m.step.flags ?? {}).map(([n, c]) => [`${p}${n}`, renameC(c, p, m, inputs)])),
|
|
57
|
-
state: Object.fromEntries(Object.entries(m.step.state ?? {}).map(([n, e]) => [`${p}${n}`, keep(rename(e, p, m, inputs),
|
|
58
|
+
state: Object.fromEntries(Object.entries(m.step.state ?? {}).map(([n, e]) => [`${p}${n}`, keep(rename(e, p, m, inputs), generatedVariable(`${p}${n}`))])),
|
|
58
59
|
maps: Object.fromEntries(Object.entries(m.step.maps ?? {}).map(([n, w]) => {
|
|
59
60
|
if ('each' in w)
|
|
60
|
-
return [`${p}${n}`, { each: `${p}${w.each}`, value: keep(rename(w.value, p, m, inputs), { op: 'get', map: `${p}${n}`, key:
|
|
61
|
+
return [`${p}${n}`, { each: `${p}${w.each}`, value: keep(rename(w.value, p, m, inputs), { op: 'get', map: `${p}${n}`, key: generatedVariable(`${p}${w.each}`) }) }];
|
|
61
62
|
const key = rename(w.key, p, m, inputs);
|
|
62
63
|
return [`${p}${n}`, { key, value: keep(rename(w.value, p, m, inputs), { op: 'get', map: `${p}${n}`, key }) }];
|
|
63
64
|
})),
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export declare const internalName: (token: string, legacy: string) => string;
|
|
2
|
+
export declare const binder: (kind: string, index: number) => string;
|
|
3
|
+
export declare function variable(name: string): {
|
|
4
|
+
op: 'var';
|
|
5
|
+
name: string;
|
|
6
|
+
};
|
|
7
|
+
export declare function generatedVariable(name: string): {
|
|
8
|
+
op: 'var';
|
|
9
|
+
name: string;
|
|
10
|
+
};
|
|
11
|
+
export declare function copyVariable<T extends object>(from: object, to: T): T;
|
|
12
|
+
export declare const reservedName: (name: string) => boolean;
|
|
13
|
+
export declare function plainDeclaration(what: string, name: string): void;
|
|
14
|
+
export declare function guardReserved(value: unknown, allowedFree?: string[]): void;
|
|
15
|
+
export declare function encodeBinders<T>(value: T, declared: string[], allowedFree?: string[]): T;
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
// Private generated identities carry provenance in memory, not in their spelling.
|
|
2
|
+
// At the public machine/law boundary retain the historical readable name unless
|
|
3
|
+
// it collides with a declared or free identifier. Symbols never enter JSON/Lean.
|
|
4
|
+
const origin = Symbol('generated variable');
|
|
5
|
+
const issued = new Map();
|
|
6
|
+
export const internalName = (token, legacy) => { issued.set(token, legacy); return token; };
|
|
7
|
+
export const binder = (kind, index) => internalName(`?${kind}${index}`, `${kind}$${index}`);
|
|
8
|
+
const identity = (name) => {
|
|
9
|
+
const end = name.search(/[.$]/), root = end < 0 ? name : name.slice(0, end), legacy = issued.get(root);
|
|
10
|
+
return legacy === undefined ? undefined : { root, legacy, suffix: name.slice(root.length) };
|
|
11
|
+
};
|
|
12
|
+
export function variable(name) {
|
|
13
|
+
const out = { op: 'var', name };
|
|
14
|
+
if (identity(name))
|
|
15
|
+
Object.defineProperty(out, origin, { value: true, enumerable: true });
|
|
16
|
+
return out;
|
|
17
|
+
}
|
|
18
|
+
// Only generator sites may issue this mark; a matching name is not provenance.
|
|
19
|
+
export function generatedVariable(name) {
|
|
20
|
+
const out = { op: 'var', name };
|
|
21
|
+
Object.defineProperty(out, origin, { value: true, enumerable: true });
|
|
22
|
+
return out;
|
|
23
|
+
}
|
|
24
|
+
export function copyVariable(from, to) {
|
|
25
|
+
if (from[origin]) {
|
|
26
|
+
Object.defineProperty(to, origin, { value: true, enumerable: true });
|
|
27
|
+
const a = from.name, b = to.name;
|
|
28
|
+
// Composition prefixes an issued identity. Preserve its readable alias too,
|
|
29
|
+
// but only a marked source node can authorize this renamed identity.
|
|
30
|
+
if (typeof a === 'string' && typeof b === 'string' && b.endsWith(a)) {
|
|
31
|
+
const id = identity(a), prefix = b.slice(0, b.length - a.length);
|
|
32
|
+
if (id && prefix)
|
|
33
|
+
internalName(prefix + id.root, prefix + id.legacy);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return to;
|
|
37
|
+
}
|
|
38
|
+
export const reservedName = (name) => name === '1' || /[*[\],:#?~'⟦⟧⟨⟩|]/.test(name);
|
|
39
|
+
export function plainDeclaration(what, name) {
|
|
40
|
+
if (reservedName(name))
|
|
41
|
+
throw new Error(`${what}: the name ${name} is reserved (1, or * [ ] , : # ? ~ ' ⟦ ⟧ ⟨ ⟩ |)`);
|
|
42
|
+
}
|
|
43
|
+
const bindings = (node) => [
|
|
44
|
+
...(node.op === 'all' && typeof node.key === 'string' ? [node.key, ...Array.isArray(node.keys) ? node.keys : []] : []),
|
|
45
|
+
...(typeof node.forall === 'string' ? [node.forall, ...Array.isArray(node.keys) ? node.keys : []] : []),
|
|
46
|
+
...(typeof node.each === 'string' ? [node.each] : []),
|
|
47
|
+
...(typeof node.key === 'string' && 'where' in node && 'by' in node ? [node.key] : []),
|
|
48
|
+
...(Array.isArray(node.some) ? node.some.filter((n) => typeof n === 'string') : []),
|
|
49
|
+
];
|
|
50
|
+
export function guardReserved(value, allowedFree = []) {
|
|
51
|
+
const allowed = new Set(allowedFree);
|
|
52
|
+
const check = (x) => {
|
|
53
|
+
if (!x || typeof x !== 'object')
|
|
54
|
+
return;
|
|
55
|
+
if (Array.isArray(x)) {
|
|
56
|
+
x.forEach(check);
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
const node = x;
|
|
60
|
+
if (node.op === 'var' && typeof node.name === 'string' && reservedName(node.name) && !allowed.has(node.name) && !node[origin])
|
|
61
|
+
throw Error(`law or rule reads free reserved name ${node.name}`);
|
|
62
|
+
Object.values(node).forEach(check);
|
|
63
|
+
};
|
|
64
|
+
check(value);
|
|
65
|
+
}
|
|
66
|
+
export function encodeBinders(value, declared, allowedFree = []) {
|
|
67
|
+
guardReserved(value, allowedFree);
|
|
68
|
+
const used = new Set([...declared, ...allowedFree]), groups = new Map();
|
|
69
|
+
const generated = (name) => {
|
|
70
|
+
const id = identity(name);
|
|
71
|
+
if (!id)
|
|
72
|
+
return false;
|
|
73
|
+
const group = groups.get(id.root) ?? { legacy: id.legacy, parts: new Set() };
|
|
74
|
+
group.parts.add(id.suffix);
|
|
75
|
+
groups.set(id.root, group);
|
|
76
|
+
return true;
|
|
77
|
+
};
|
|
78
|
+
const collect = (x) => {
|
|
79
|
+
if (!x || typeof x !== 'object')
|
|
80
|
+
return;
|
|
81
|
+
if (Array.isArray(x)) {
|
|
82
|
+
x.forEach(collect);
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
const node = x;
|
|
86
|
+
for (const n of bindings(node))
|
|
87
|
+
if (!generated(n))
|
|
88
|
+
used.add(n);
|
|
89
|
+
if (node.op === 'var' && typeof node.name === 'string') {
|
|
90
|
+
if (!node[origin] || !generated(node.name))
|
|
91
|
+
used.add(node.name);
|
|
92
|
+
}
|
|
93
|
+
if (typeof node.map === 'string')
|
|
94
|
+
used.add(node.map);
|
|
95
|
+
if (node.op === 'flag' && typeof node.name === 'string')
|
|
96
|
+
used.add(node.name);
|
|
97
|
+
Object.values(node).forEach(collect);
|
|
98
|
+
};
|
|
99
|
+
collect(value);
|
|
100
|
+
if (!groups.size)
|
|
101
|
+
return value;
|
|
102
|
+
const names = new Map();
|
|
103
|
+
let next = 0;
|
|
104
|
+
for (const [root, group] of groups) {
|
|
105
|
+
const suffixes = [...group.parts];
|
|
106
|
+
let fresh = group.legacy;
|
|
107
|
+
if (suffixes.some(s => used.has(fresh + s)))
|
|
108
|
+
do {
|
|
109
|
+
fresh = `gdp$bound$${++next}`;
|
|
110
|
+
} while (used.has(fresh) || suffixes.some(s => used.has(fresh + s)));
|
|
111
|
+
for (const suffix of suffixes) {
|
|
112
|
+
const alias = fresh + suffix;
|
|
113
|
+
used.add(alias);
|
|
114
|
+
names.set(root + suffix, alias);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
const rewrite = (x) => {
|
|
118
|
+
if (typeof x === 'string')
|
|
119
|
+
return names.get(x) ?? x;
|
|
120
|
+
if (!x || typeof x !== 'object')
|
|
121
|
+
return x;
|
|
122
|
+
if (Array.isArray(x))
|
|
123
|
+
return x.map(rewrite);
|
|
124
|
+
if (Object.getPrototypeOf(x) !== Object.prototype && Object.getPrototypeOf(x) !== null)
|
|
125
|
+
return x;
|
|
126
|
+
return Object.fromEntries(Object.entries(x).map(([k, v]) => [names.get(k) ?? k, rewrite(v)]));
|
|
127
|
+
};
|
|
128
|
+
return rewrite(value);
|
|
129
|
+
}
|
package/dist/core/dsl.d.ts
CHANGED
|
@@ -501,6 +501,11 @@ export type Relation = {
|
|
|
501
501
|
};
|
|
502
502
|
export declare const relation: (holds: Cond, whenever?: Cond) => Relation;
|
|
503
503
|
export declare function nameQuantifiers(m: Machine): Machine;
|
|
504
|
+
export declare class QuantifierAdmissionError extends Error {
|
|
505
|
+
readonly code: 'nested-universal' | 'binder-capture';
|
|
506
|
+
readonly kind: "quantifier-admission";
|
|
507
|
+
constructor(code: 'nested-universal' | 'binder-capture', reason: string);
|
|
508
|
+
}
|
|
504
509
|
export type FnDef = {
|
|
505
510
|
arity: number;
|
|
506
511
|
js: string | ((...args: number[]) => number);
|
package/dist/core/dsl.js
CHANGED
|
@@ -17,10 +17,11 @@ import { searchNow as countedSearchNow } from "./wall.js";
|
|
|
17
17
|
//
|
|
18
18
|
// A step returns its updates as one object: every right-hand side reads the state before the step, as the kernel and
|
|
19
19
|
// both runtimes do.
|
|
20
|
+
import { binder, copyVariable, encodeBinders, generatedVariable, guardReserved, internalName, plainDeclaration, variable } from "./dsl-binders.js";
|
|
20
21
|
import { candidates, cone, searchCounted } from "./counts.js";
|
|
21
22
|
import { proveCandidateSeeds } from "./candidate-seeds.js";
|
|
22
23
|
import { proveCountedCandidateSeeds } from "./counted-candidate-seeds.js";
|
|
23
|
-
import { inheritSource, translationVerdict } from "./source-check.js";
|
|
24
|
+
import { bindSourceMachine, inheritSource, translationVerdict } from "./source-check.js";
|
|
24
25
|
import { env as knobs } from "./solver.js";
|
|
25
26
|
import { argsKey, bindDirect, directOf, machineTerms, part, tuple, carriedView, compileFunction, divName, divisor, divisorsIn, evalC, evalE, fnCall, hasFinite, interpret, isArithmetic, loadJs, modName, numbersOf, pairedArgs, seeded, sourceFreeFn, withArithmetic } from "./machine.js";
|
|
26
27
|
import { allowed, keysOf, requestEnv, watch, watchWork } from "./watch.js";
|
|
@@ -224,7 +225,7 @@ export class Kind {
|
|
|
224
225
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
225
226
|
from(init) { return { kind: this, init }; }
|
|
226
227
|
}
|
|
227
|
-
const v = (name) => new Term(
|
|
228
|
+
const v = (name) => new Term(variable(name), scope?.vars[name]);
|
|
228
229
|
let scope;
|
|
229
230
|
const inScope = (s, f) => { const outer = scope; scope = s; try {
|
|
230
231
|
return f();
|
|
@@ -877,7 +878,7 @@ let boundCounter = 0;
|
|
|
877
878
|
// on its own, and compared with another only plainly (i < j, i <= j, i = j); the runtimes decide it on every tuple of
|
|
878
879
|
// a few keys per breakpoint, so it costs the square of the cells (the cube, over three keys).
|
|
879
880
|
export const everyKey = (f) => {
|
|
880
|
-
const names = Array.from({ length: Math.max(1, f.length) }, () =>
|
|
881
|
+
const names = Array.from({ length: Math.max(1, f.length) }, () => binder('k', ++boundCounter)), g = f;
|
|
881
882
|
const ok = (picked) => (picked.length === names.length ? g(...picked).ok : everyOk(scope?.keys, k => ok([...picked, keyTerm(k)])));
|
|
882
883
|
return new Cond({ op: 'all', key: names[0], ...(names.length > 1 ? { keys: names.slice(1) } : {}), c: g(...names.map(v)).c }, ok([]));
|
|
883
884
|
};
|
|
@@ -886,13 +887,13 @@ export const desc = (t) => ({ desc: t });
|
|
|
886
887
|
// Some key where f holds, in a law or a step law's conclusion (¬∀k. ¬f(k)): proven through a witness, a term naming the
|
|
887
888
|
// key, given here or found by the prover among a few candidates (kernel/prove.ts).
|
|
888
889
|
export const someKey = (f, witness) => {
|
|
889
|
-
const key =
|
|
890
|
+
const key = binder('s', ++boundCounter);
|
|
890
891
|
const none = everyOk(scope?.keys, k => f(keyTerm(k)).not().ok);
|
|
891
892
|
return new Cond({ op: 'not', x: { op: 'all', key, c: f(v(key)).not().c, ...(witness === undefined ? {} : { witness: termOf(witness) }) } }, none === undefined ? undefined : !none);
|
|
892
893
|
};
|
|
893
894
|
export function exists(a, b, c) {
|
|
894
895
|
const [kind, f, w] = (a instanceof Kind ? [a, b, c] : [nat, a, b]);
|
|
895
|
-
const name =
|
|
896
|
+
const name = binder('some', ++boundCounter), value = kind.value(name), body = all(...kind.assume(name), f(value));
|
|
896
897
|
const store = (x) => Object.fromEntries(Object.entries(kind.store(name, x)).map(([n, t]) => [n, termOf(t)]));
|
|
897
898
|
const ghost = typeof w === 'object' && w !== null && 'step' in w && 'start' in w && typeof w.step === 'function';
|
|
898
899
|
const given = w === undefined ? {} : ghost
|
|
@@ -911,7 +912,7 @@ function pulledOut(cs, what, prefix) {
|
|
|
911
912
|
bs.forEach((b, i) => b.vars.forEach(n => { ren[n] = { op: 'var', name: n.endsWith('$neg') ? `${prefix}${i}$neg` : `${prefix}${i}` }; }));
|
|
912
913
|
const r = (c) => (prefix === undefined ? c : substVars(c, ren));
|
|
913
914
|
const vars = bs.flatMap(b => b.vars.map(n => (prefix === undefined ? n : ren[n].name)));
|
|
914
|
-
const out = cs.map(c => r(c.c)), stray = out.flatMap(c => namesIn(c)).filter(n => n.startsWith('some
|
|
915
|
+
const out = cs.map(c => r(c.c)), stray = out.flatMap(c => namesIn(c)).filter(n => n.startsWith('?some') && !vars.includes(n) && !/^some\$[ap]\d/.test(n));
|
|
915
916
|
if (stray.length)
|
|
916
917
|
throw new Error(`${what}: ${stray[0]} is bound by an exists(...) whose condition was taken apart; keep it whole (and, or, not, implies)`);
|
|
917
918
|
return { cs: out, vars, bodies: bs.map(b => ({ vars: b.vars.map(n => (prefix === undefined ? n : ren[n].name)), body: r(b.body) })) };
|
|
@@ -927,12 +928,17 @@ export const declaredSum = (name) => sumDecls.get(name);
|
|
|
927
928
|
const fnv = (text) => { let h = 0x811c9dc5; for (let i = 0; i < text.length; i++)
|
|
928
929
|
h = Math.imul(h ^ text.charCodeAt(i), 0x01000193) >>> 0; return h.toString(36); };
|
|
929
930
|
function sumOver(map, at, plain) {
|
|
930
|
-
const
|
|
931
|
-
const
|
|
931
|
+
const placeholder = internalName('?sumKey', 'k$sum$');
|
|
932
|
+
const probe = termOf(at(v(placeholder)));
|
|
933
|
+
// Hash the old spelling, never the private token; the actual substitution
|
|
934
|
+
// still distinguishes a same-spelled free user parameter.
|
|
935
|
+
const legacyProbe = substVarsE(probe, { [placeholder]: { op: 'var', name: 'k$sum$' } });
|
|
936
|
+
const id = plain ? `sum$${map}` : `sum$${map}$${fnv(JSON.stringify(legacyProbe))}`, key = `${id}$k`;
|
|
937
|
+
const term = substVarsE(probe, { [placeholder]: generatedVariable(key) }), had = sumDecls.get(id);
|
|
932
938
|
if (had && JSON.stringify(had.term) !== JSON.stringify(term))
|
|
933
939
|
throw new Error(`${id}: two sums by one name`);
|
|
934
940
|
sumDecls.set(id, { key, term });
|
|
935
|
-
return
|
|
941
|
+
return new Term(generatedVariable(id), scope?.vars[id]);
|
|
936
942
|
}
|
|
937
943
|
// The sums a set of terms reads (by name), declared.
|
|
938
944
|
export const sumsIn = (ts, more = []) => {
|
|
@@ -958,7 +964,7 @@ export class MapRef {
|
|
|
958
964
|
// key's cell plus `by` where `c` holds (the counter every cap keeps).
|
|
959
965
|
bump(key, c = yes, by = 1) { return this.set(key, when(c, this.at(key).plus(by), this.at(key))); }
|
|
960
966
|
// Every key at once: the value at each key, the key read only as a map's key (Other.at(k)).
|
|
961
|
-
each(f) { const each =
|
|
967
|
+
each(f) { const each = binder('k', ++boundCounter); return { map: this.name, each, value: termOf(f(v(each))), concrete: { at: f } }; }
|
|
962
968
|
// As a set (cells 0 or 1): a member, and, as whole flags, every member of this one in another, none shared, the same.
|
|
963
969
|
has(key) { return this.at(key).atLeast(1); }
|
|
964
970
|
subsetOf(other) { return everyKey(k => this.at(k).atMost(other.at(k))); }
|
|
@@ -993,7 +999,7 @@ export class RelRef {
|
|
|
993
999
|
has(...xs) { return this.at(...xs).atLeast(1); }
|
|
994
1000
|
// The relation after the step: each tuple in it where f holds (its parts as f reads them).
|
|
995
1001
|
each(f) {
|
|
996
|
-
const each =
|
|
1002
|
+
const each = binder('k', ++boundCounter), n = this.sorts.length, k = v(each);
|
|
997
1003
|
const parts = n === 1 ? [k] : Array.from({ length: n }, (_, i) => new Term(part(k.e, i, n)));
|
|
998
1004
|
return { map: this.name, each, value: when(f(...parts), 1, 0).e };
|
|
999
1005
|
}
|
|
@@ -1023,7 +1029,7 @@ export class ListRef {
|
|
|
1023
1029
|
removeAt(i, when = yes) { return { when, at: k => when_(k.lt(i), this.at(k), this.at(k.plus(1))), len: this.len.minus(1) }; }
|
|
1024
1030
|
// The updates for the step: the first operation whose condition holds, else the list as it was.
|
|
1025
1031
|
apply(...ops) {
|
|
1026
|
-
const each =
|
|
1032
|
+
const each = binder('k', ++boundCounter);
|
|
1027
1033
|
const at = (k) => ops.reduceRight((acc, op) => when_(op.when, op.at(k), acc), this.at(k));
|
|
1028
1034
|
const len = ops.reduceRight((acc, op) => when_(op.when, op.len, acc), this.len);
|
|
1029
1035
|
return { [this.name]: { map: this.name, each, value: at(v(each)).e, concrete: { at } }, [`${this.name}_len`]: len };
|
|
@@ -1077,7 +1083,7 @@ export function sizedSort(name, size) {
|
|
|
1077
1083
|
throw new Error('a sized sort needs a name');
|
|
1078
1084
|
const below = termOf(size);
|
|
1079
1085
|
const every = (f) => {
|
|
1080
|
-
const key =
|
|
1086
|
+
const key = binder('k', ++boundCounter);
|
|
1081
1087
|
const body = f(v(key));
|
|
1082
1088
|
if (body.ex?.length || hasAll(body.c))
|
|
1083
1089
|
throw new Error('a finite sort body must be unquantified in this slice');
|
|
@@ -1367,7 +1373,7 @@ const termAt = (t) => (t instanceof Term ? t : lit(t));
|
|
|
1367
1373
|
// With two parameters or more, about every two keys or more: forall((i, j) => i.lt(j).implies(...)).
|
|
1368
1374
|
export function forall(f) { return { forall: f }; }
|
|
1369
1375
|
// The keys a law's callback names: one, or two when it takes two.
|
|
1370
|
-
const keysFor = (out) => [
|
|
1376
|
+
const keysFor = (out) => [binder('key', ++keyCounter), Array.from({ length: Math.max(0, out.forall.length - 1) }, () => binder('key', ++keyCounter))];
|
|
1371
1377
|
// For histories: `holds` (a <= b, homogeneous over sums and queries) wherever `when` (params and plain inputs) holds.
|
|
1372
1378
|
export const relation = (holds, whenever = yes) => ({ when: whenever, holds });
|
|
1373
1379
|
// --- quantifiers anywhere ---------------------------------------------------------------------------------------------
|
|
@@ -1517,25 +1523,50 @@ export function nameQuantifiers(m) {
|
|
|
1517
1523
|
// is two keys at once. A quantifier under a not is some key (someKey), left for the prover's witness.
|
|
1518
1524
|
const hasForall = (c, positive = true) => c.op === 'all' ? positive || hasForall(c.c, positive) : c.op === 'not' ? hasForall(c.x, !positive) : c.op === 'and' || c.op === 'or' ? c.xs.some(y => hasForall(y, positive)) : false;
|
|
1519
1525
|
const hasAll = (c) => JSON.stringify(c).includes('"op":"all"');
|
|
1520
|
-
|
|
1526
|
+
export class QuantifierAdmissionError extends Error {
|
|
1527
|
+
code;
|
|
1528
|
+
kind = 'quantifier-admission';
|
|
1529
|
+
constructor(code, reason) {
|
|
1530
|
+
super(reason);
|
|
1531
|
+
this.code = code;
|
|
1532
|
+
this.name = 'QuantifierAdmissionError';
|
|
1533
|
+
}
|
|
1534
|
+
}
|
|
1535
|
+
function freeKey(value, name) {
|
|
1536
|
+
if (!value || typeof value !== 'object')
|
|
1537
|
+
return false;
|
|
1538
|
+
if (Array.isArray(value))
|
|
1539
|
+
return value.some(v => freeKey(v, name));
|
|
1540
|
+
const node = value;
|
|
1541
|
+
if (node.op === 'var')
|
|
1542
|
+
return node.name === name;
|
|
1543
|
+
if (node.op === 'all' && [node.key, ...(Array.isArray(node.keys) ? node.keys : [])].includes(name))
|
|
1544
|
+
return false;
|
|
1545
|
+
return Object.values(node).some(v => freeKey(v, name));
|
|
1546
|
+
}
|
|
1547
|
+
function prenex(c, what, key, alreadyBound = false) {
|
|
1521
1548
|
if (hasFinite(c) && (what.startsWith('step law') || (c.op !== 'all' && hasForall(c))))
|
|
1522
1549
|
throw new Error(`${what}: a finite universal is one whole law in this slice (not nested or a step law)`);
|
|
1550
|
+
if (!alreadyBound && hasForall(c) && freeKey(c, key))
|
|
1551
|
+
throw new QuantifierAdmissionError('binder-capture', `${what}: generated law key ${key} would capture a free variable; rename it`);
|
|
1523
1552
|
let found = false;
|
|
1524
|
-
const walk = (d, positive) => {
|
|
1553
|
+
const walk = (d, positive, insideUniversal) => {
|
|
1525
1554
|
switch (d.op) {
|
|
1526
1555
|
case 'all':
|
|
1527
1556
|
if (d.keys?.length)
|
|
1528
1557
|
throw new Error(`${what}: a condition at every two keys in a law is the law's own keys (forall((i, j) => ...))`);
|
|
1529
1558
|
if (!positive)
|
|
1530
1559
|
return d;
|
|
1560
|
+
if (insideUniversal)
|
|
1561
|
+
throw new QuantifierAdmissionError('nested-universal', `${what}: nested universal keys are two keys at once; name them together with forall((i, j) => ...), not nested everyKey calls`);
|
|
1531
1562
|
found = true;
|
|
1532
|
-
return walk(substKey(d.c, d.key, key), positive);
|
|
1533
|
-
case 'not': return { op: 'not', x: walk(d.x, !positive) };
|
|
1563
|
+
return walk(substKey(d.c, d.key, key), positive, true);
|
|
1564
|
+
case 'not': return { op: 'not', x: walk(d.x, !positive, insideUniversal) };
|
|
1534
1565
|
case 'and':
|
|
1535
1566
|
case 'or': {
|
|
1536
1567
|
if ((d.op === 'or') === positive && d.xs.some(y => hasForall(y, positive)) && d.xs.filter(y => hasForall(y, positive) || namesIn(y).includes(key)).length > 1)
|
|
1537
1568
|
throw new Error(`${what}: a condition at every key in an or beside another part that reads a key is two keys at once`);
|
|
1538
|
-
return { op: d.op, xs: d.xs.map(y => walk(y, positive)) };
|
|
1569
|
+
return { op: d.op, xs: d.xs.map(y => walk(y, positive, insideUniversal)) };
|
|
1539
1570
|
}
|
|
1540
1571
|
case 'flag': return d;
|
|
1541
1572
|
case '<':
|
|
@@ -1546,10 +1577,33 @@ function prenex(c, what, key) {
|
|
|
1546
1577
|
return d;
|
|
1547
1578
|
}
|
|
1548
1579
|
};
|
|
1549
|
-
const out = walk(c, true);
|
|
1580
|
+
const out = walk(c, true, alreadyBound);
|
|
1550
1581
|
return found ? out : undefined;
|
|
1551
1582
|
}
|
|
1552
|
-
const substKey = (c, from, to) =>
|
|
1583
|
+
const substKey = (c, from, to) => {
|
|
1584
|
+
const walk = (value) => {
|
|
1585
|
+
if (!value || typeof value !== 'object')
|
|
1586
|
+
return value;
|
|
1587
|
+
if (Array.isArray(value))
|
|
1588
|
+
return value.map(walk);
|
|
1589
|
+
const node = value;
|
|
1590
|
+
if (node.op === 'all') {
|
|
1591
|
+
const bound = [node.key, ...(Array.isArray(node.keys) ? node.keys : [])];
|
|
1592
|
+
if (bound.includes(from))
|
|
1593
|
+
return value; // An inner binder shadows this occurrence.
|
|
1594
|
+
if (bound.includes(to) && freeKey(node.c, from))
|
|
1595
|
+
throw new QuantifierAdmissionError('binder-capture', `renaming ${from} to ${to} would capture an inner binder; use forall((i, j) => ...)`);
|
|
1596
|
+
}
|
|
1597
|
+
if (node.op === 'var') {
|
|
1598
|
+
if (node.name !== from)
|
|
1599
|
+
return node;
|
|
1600
|
+
guardReserved(node); // A user-written reserved name must not be laundered by substitution.
|
|
1601
|
+
return variable(to);
|
|
1602
|
+
}
|
|
1603
|
+
return Object.fromEntries(Object.entries(node).map(([k, v]) => [k, walk(v)]));
|
|
1604
|
+
};
|
|
1605
|
+
return walk(c);
|
|
1606
|
+
};
|
|
1553
1607
|
// The definitions actually flattened into a rule may have changed since recur captured its inlined helpers.
|
|
1554
1608
|
const sourceFreeDef = (d) => sourceFreeFn(d) && Object.values(d.uses ?? {}).every(sourceFreeDef);
|
|
1555
1609
|
export const fn = (arity, js, opts = {}) => {
|
|
@@ -1818,10 +1872,10 @@ const skolemsOf = new WeakMap();
|
|
|
1818
1872
|
const withSource = (x, src) => (sources.set(x, src), x);
|
|
1819
1873
|
// A k-step law's later requests are built over marked names (j:name, which no rule can declare: ':' is reserved); the
|
|
1820
1874
|
// kernel reads them as name@j.
|
|
1821
|
-
const markedName = (name) => { const m =
|
|
1875
|
+
const markedName = (name) => { const m = /^\?step(\d+):(.*)$/.exec(name); return m ? `${m[2]}@${m[1]}` : name; };
|
|
1822
1876
|
const markedE = (e) => {
|
|
1823
1877
|
switch (e.op) {
|
|
1824
|
-
case 'var': return { op: 'var', name: markedName(e.name) };
|
|
1878
|
+
case 'var': return copyVariable(e, { op: 'var', name: markedName(e.name) });
|
|
1825
1879
|
case 'const': return e;
|
|
1826
1880
|
case 'mul': return { ...e, a: markedE(e.a) };
|
|
1827
1881
|
case 'if': return { op: 'if', c: marked(e.c), then: markedE(e.then), else: markedE(e.else) };
|
|
@@ -1835,7 +1889,7 @@ const markedE = (e) => {
|
|
|
1835
1889
|
case 'proj': return { ...e, a: markedE(e.a) };
|
|
1836
1890
|
}
|
|
1837
1891
|
};
|
|
1838
|
-
const marked = (c) => c.op === 'flag' ? c : c.op === 'all' ? { ...c, c: marked(c.c) } : c.op === 'not' ? { op: 'not', x: marked(c.x) } : c.op === 'and' || c.op === 'or' ? { op: c.op, xs: c.xs.map(marked) } : { ...c, a: markedE(c.a), b: markedE(c.b) };
|
|
1892
|
+
const marked = (c) => c.op === 'flag' ? c : c.op === 'all' ? { ...c, c: marked(c.c), ...(c.witness ? { witness: markedE(c.witness) } : {}) } : c.op === 'not' ? { op: 'not', x: marked(c.x) } : c.op === 'and' || c.op === 'or' ? { op: c.op, xs: c.xs.map(marked) } : { ...c, a: markedE(c.a), b: markedE(c.b) };
|
|
1839
1893
|
// P params, I inputs, S state, M maps, F flags, R a history's record, Su its sums, Q its queries: each a record of the
|
|
1840
1894
|
// values the builders hand out, grown by each call.
|
|
1841
1895
|
export class Rule {
|
|
@@ -2062,7 +2116,7 @@ export class Rule {
|
|
|
2062
2116
|
// A law about the params, the state, the maps and the sums (not a request): `forall` for every key of a map.
|
|
2063
2117
|
law(name, f) { return withSource(this.lawOf(name, f(this.env({ flags: false, inputs: false, queries: false }))), { law: f }); }
|
|
2064
2118
|
lawOf(name, out) {
|
|
2065
|
-
const key =
|
|
2119
|
+
const key = binder('key', ++keyCounter);
|
|
2066
2120
|
if (out instanceof Cond) {
|
|
2067
2121
|
const p = prenex(out.c, `law ${name}`, key);
|
|
2068
2122
|
return this.divides(this.someOf(name, out, p ? { name, forall: key, holds: p, ...(out.c.op === 'all' && out.c.finite !== undefined ? { finite: out.c.finite } : {}) } : { name, holds: out.c }));
|
|
@@ -2070,7 +2124,7 @@ export class Rule {
|
|
|
2070
2124
|
const [k1, more] = keysFor(out), inner = out.forall(v(k1), ...more.map(v)), holds = inner.c;
|
|
2071
2125
|
if (hasFinite(holds))
|
|
2072
2126
|
throw new Error(`law ${name}: a finite universal is one whole law, not inside forall`);
|
|
2073
|
-
return this.divides(this.someOf(name, inner, more.length ? { name, forall: k1, keys: more, holds } : { name, forall: k1, holds: prenex(holds, `law ${name}`, k1) ?? holds }));
|
|
2127
|
+
return this.divides(this.someOf(name, inner, more.length ? { name, forall: k1, keys: more, holds } : { name, forall: k1, holds: prenex(holds, `law ${name}`, k1, true) ?? holds }));
|
|
2074
2128
|
}
|
|
2075
2129
|
// A law's existentials (exists), pulled out before it: `some` its naturals, `witness` the ones given (a ghost's step
|
|
2076
2130
|
// read with the step's own values).
|
|
@@ -2085,7 +2139,7 @@ export class Rule {
|
|
|
2085
2139
|
if (b.start && b.step) {
|
|
2086
2140
|
const st = b.step(env);
|
|
2087
2141
|
for (const n of b.vars)
|
|
2088
|
-
ghost[n] = { start: b.start[n] ?? { op: 'const', value: 0 }, step: st[n] ??
|
|
2142
|
+
ghost[n] = { start: b.start[n] ?? { op: 'const', value: 0 }, step: st[n] ?? variable(n) };
|
|
2089
2143
|
}
|
|
2090
2144
|
const witness = { ...(Object.keys(terms).length ? { terms } : {}), ...(Object.keys(ghost).length ? { ghost } : {}) };
|
|
2091
2145
|
return { ...law, some: vars, ...(Object.keys(witness).length ? { witness } : {}) };
|
|
@@ -2094,7 +2148,8 @@ export class Rule {
|
|
|
2094
2148
|
divides(x) {
|
|
2095
2149
|
if (this.spec.arith)
|
|
2096
2150
|
divisorsIn([x], this.spec.arith);
|
|
2097
|
-
|
|
2151
|
+
const names = this.names().map(([n]) => n);
|
|
2152
|
+
return encodeBinders(x, names, 'then' in x ? names.map(n => `${n}'`) : []);
|
|
2098
2153
|
}
|
|
2099
2154
|
// The same rule declaring every sum over a map's keys these read (laws, step laws, a liveness, a decision's goal), as
|
|
2100
2155
|
// each prover entry takes it; this rule itself unchanged. The rule where they read none it doesn't already declare.
|
|
@@ -2140,13 +2195,13 @@ export class Rule {
|
|
|
2140
2195
|
const env = this.env();
|
|
2141
2196
|
const after = this.afterEnv();
|
|
2142
2197
|
const out = then(env, after), w = when ? { when: when(env).c } : {};
|
|
2143
|
-
const key =
|
|
2198
|
+
const key = binder('key', ++keyCounter), src = { step: { then: then, ...(when ? { when: when } : {}) } };
|
|
2144
2199
|
if (out instanceof Cond) {
|
|
2145
2200
|
const p = prenex(out.c, `step law ${name}`, key);
|
|
2146
2201
|
return withSource(this.divides(p ? { name, forall: key, then: p, ...w } : { name, then: out.c, ...w }), src);
|
|
2147
2202
|
}
|
|
2148
2203
|
const [k1, more] = keysFor(out), c = out.forall(v(k1), ...more.map(v)).c;
|
|
2149
|
-
return withSource(this.divides(more.length ? { name, forall: k1, keys: more, then: c, ...w } : { name, forall: k1, then: prenex(c, `step law ${name}`, k1) ?? c, ...w }), src);
|
|
2204
|
+
return withSource(this.divides(more.length ? { name, forall: k1, keys: more, then: c, ...w } : { name, forall: k1, then: prenex(c, `step law ${name}`, k1, true) ?? c, ...w }), src);
|
|
2150
2205
|
}
|
|
2151
2206
|
// A law about k steps in a row (k from 2 to 64): `then(first, last, requests)` relates what the first step reads to the
|
|
2152
2207
|
// state, maps and sums after the last, with each step's request and queries (requests[0] is the first's); `when(before,
|
|
@@ -2156,7 +2211,7 @@ export class Rule {
|
|
|
2156
2211
|
const env = this.env();
|
|
2157
2212
|
const after = this.afterEnv();
|
|
2158
2213
|
// The j-th request's values over marked names, renamed to the kernel's input@j once built.
|
|
2159
|
-
const mark = (j) =>
|
|
2214
|
+
const mark = (j) => `?step${j}:`;
|
|
2160
2215
|
const requests = Array.from({ length: k }, (_, j) => {
|
|
2161
2216
|
if (j === 0)
|
|
2162
2217
|
return Object.fromEntries([...this.spec.inputs.map(([n]) => n), ...this.spec.queries.map(([n]) => n)].map(n => [n, env[n]]));
|
|
@@ -2167,13 +2222,18 @@ export class Rule {
|
|
|
2167
2222
|
while (whens.length && whens.at(-1) === undefined)
|
|
2168
2223
|
whens.pop();
|
|
2169
2224
|
const w = whens.length ? { when: whens.map(c => (c ?? lit(0).atMost(0)).c) } : {};
|
|
2170
|
-
const key =
|
|
2225
|
+
const key = binder('key', ++keyCounter);
|
|
2226
|
+
const allowedMarks = [...this.names().map(([n]) => `${n}'`), ...namesIn(requests)];
|
|
2227
|
+
const markLaw = (c, keys = []) => {
|
|
2228
|
+
guardReserved({ ...(keys.length ? { forall: keys[0], keys: keys.slice(1) } : {}), then: c }, allowedMarks);
|
|
2229
|
+
return marked(c);
|
|
2230
|
+
};
|
|
2171
2231
|
if (out instanceof Cond) {
|
|
2172
2232
|
const p = prenex(out.c, `step law ${name}`, key);
|
|
2173
|
-
return this.divides(p ? { name, steps: k, forall: key, then:
|
|
2233
|
+
return this.divides(p ? { name, steps: k, forall: key, then: markLaw(p, [key]), ...w } : { name, steps: k, then: markLaw(out.c), ...w });
|
|
2174
2234
|
}
|
|
2175
2235
|
const [k1, more] = keysFor(out), c = out.forall(v(k1), ...more.map(v)).c;
|
|
2176
|
-
return this.divides(more.length ? { name, steps: k, forall: k1, keys: more, then:
|
|
2236
|
+
return this.divides(more.length ? { name, steps: k, forall: k1, keys: more, then: markLaw(c, [k1, ...more]), ...w } : { name, steps: k, forall: k1, then: markLaw(prenex(c, `step law ${name}`, k1, true) ?? c, [k1]), ...w });
|
|
2177
2237
|
}
|
|
2178
2238
|
// "Whenever `from` holds, `to` holds later", in every run that takes each helpful request infinitely often: proven by
|
|
2179
2239
|
// a rank (a natural over the state and params, or several compared in order) that no step raises while `from` holds
|
|
@@ -2197,7 +2257,7 @@ export class Rule {
|
|
|
2197
2257
|
leadsTo(name, spec) {
|
|
2198
2258
|
const env = this.env({ flags: false, inputs: false, queries: false });
|
|
2199
2259
|
const fs = [spec.from, spec.to, spec.rank, ...(typeof spec.helpful === 'function' ? [spec.helpful] : spec.helpful.flatMap(h => [h.when, h.request]))];
|
|
2200
|
-
const forall = fs.some(f => f && f.length > 1) ?
|
|
2260
|
+
const forall = fs.some(f => f && f.length > 1) ? binder('key', ++keyCounter) : undefined, key = (forall ? v(forall) : undefined);
|
|
2201
2261
|
const req = (f) => Object.fromEntries(Object.entries(f(env, key)).map(([n, t]) => [n, termOf(t)]));
|
|
2202
2262
|
const r = spec.rank ? spec.rank(env, key) : [], rank = Array.isArray(r) ? r.map(termOf) : termOf(r);
|
|
2203
2263
|
const base = { name, from: spec.from(env, key).c, to: spec.to(env, key).c, rank, ...(spec.fairness === 'strong' ? { fairness: 'strong' } : {}), ...(spec.levels ? { levels: spec.levels } : {}), ...(forall ? { forall } : {}) };
|
|
@@ -2363,6 +2423,7 @@ export class Rule {
|
|
|
2363
2423
|
distinct() {
|
|
2364
2424
|
const seen = new Map();
|
|
2365
2425
|
for (const [n, what] of this.names()) {
|
|
2426
|
+
plainDeclaration(this.spec.name, n);
|
|
2366
2427
|
const had = seen.get(n);
|
|
2367
2428
|
if (had)
|
|
2368
2429
|
throw new Error(`${this.spec.name}: ${n} is ${had} and ${had === what ? 'declared again' : what}; give each a name of its own`);
|
|
@@ -2432,7 +2493,7 @@ export class Rule {
|
|
|
2432
2493
|
// The least keys: inputs the runtimes find, assumed least.
|
|
2433
2494
|
const leasts = {}, leastAssume = [];
|
|
2434
2495
|
for (const [n, f] of s.leasts ?? []) {
|
|
2435
|
-
const d = f(env), key =
|
|
2496
|
+
const d = f(env), key = binder('k', ++boundCounter), best = env[n];
|
|
2436
2497
|
const parts = (k) => d.by(k).map(b => (typeof b === 'object' && !(b instanceof Term) && !(b instanceof Int) && 'desc' in b ? { t: Int.of(b.desc), desc: true } : { t: Int.of(b), desc: false }));
|
|
2437
2498
|
const zero = (e) => e.op === 'const' && e.value === 0;
|
|
2438
2499
|
leasts[n] = { some: `${n}$some`, key, where: d.where(v(key)).c, by: parts(v(key)).map(b => ({ e: b.t.pos.e, ...(zero(b.t.neg.e) ? {} : { neg: b.t.neg.e }), ...(b.desc ? { desc: true } : {}) })) };
|
|
@@ -2488,7 +2549,10 @@ export class Rule {
|
|
|
2488
2549
|
// (each sum a state variable from 0 the step never sets: sumMachine sets it, exact)
|
|
2489
2550
|
const sums = sumsIn(machineTerms(m), s.sumsRead ?? []);
|
|
2490
2551
|
const out = withArithmetic(sums ? { ...m, state: { ...m.state, ...Object.fromEntries(Object.keys(sums).map(n => [n, { op: 'const', value: 0 }])) }, sums } : m, [], s.arith ?? []);
|
|
2491
|
-
|
|
2552
|
+
const encoded = encodeBinders(out, this.names().map(([n]) => n));
|
|
2553
|
+
const machine = s.ghost ? s.ghost(encoded) : encoded;
|
|
2554
|
+
bindSourceMachine(this, machine);
|
|
2555
|
+
return machine;
|
|
2492
2556
|
}
|
|
2493
2557
|
// The same rule with ghosts its machine gains (the search's, over a law with "there exists" made plain: skolemOf).
|
|
2494
2558
|
withGhosts(ghost) { return this.with({ ghost }); }
|
package/dist/core/extract-c.js
CHANGED
|
@@ -569,7 +569,7 @@ export function checkC(file, flags, c, read, r, sorts, opts, cpp) {
|
|
|
569
569
|
return { ...empty, mismatch: `the check's harness doesn't start: ${why(x).split('\n').filter(Boolean).slice(0, 3).join(' | ')}` };
|
|
570
570
|
}
|
|
571
571
|
const buildMs = Math.round(performance.now() - b0), none = () => ({ arms: 0, hit: 0, missed: [] });
|
|
572
|
-
return
|
|
572
|
+
return Object.assign(speak(work, `${work}/harness`, globalThis.process?.env, c.pkg, read, r, sorts, opts.check ?? {}, none), { buildMs });
|
|
573
573
|
}
|
|
574
574
|
finally {
|
|
575
575
|
try {
|
|
@@ -386,7 +386,7 @@ export function checkGo(dir, pkg, read, r, sorts, gopts) {
|
|
|
386
386
|
return { arms: 0, hit: 0, missed: [] };
|
|
387
387
|
}
|
|
388
388
|
};
|
|
389
|
-
return
|
|
389
|
+
return Object.assign(speak(work, `${work}/harness`, { ...goEnv(), GOCOVERDIR: `${work}/cov` }, pkg, read, r, sorts, opts, count), { buildMs });
|
|
390
390
|
}
|
|
391
391
|
finally {
|
|
392
392
|
try {
|
|
@@ -581,7 +581,8 @@ export function speak(work, bin, env, pkg, read, r, sorts, opts, count) {
|
|
|
581
581
|
ev = { runs: 0, requests: 0, fromStates: 0, probes: { conditions: 0, witnesses: 0, steps: 0 }, refusedBoth: 0, outside: 0, edge: 0, compiledAgreed: 0, coverage: { arms: 0, hit: 0, missed: [] }, ms: 0,
|
|
582
582
|
mismatch: `the check's harness: ${e.message}` };
|
|
583
583
|
}
|
|
584
|
-
|
|
584
|
+
// The native journal is keyed by this exact evidence object.
|
|
585
|
+
return Object.assign(ev, { runMs: Math.round(performance.now() - r0) });
|
|
585
586
|
}
|
|
586
587
|
finally {
|
|
587
588
|
if (wi >= 0)
|
|
@@ -27,6 +27,7 @@
|
|
|
27
27
|
import * as I from "./extract-ir.js";
|
|
28
28
|
import { Refusal, mergeOps, mergeWrites } from "./extract-read.js";
|
|
29
29
|
import { fromModel } from "./extract.js";
|
|
30
|
+
import { nativeWireDecoder } from "./native-wire.js";
|
|
30
31
|
import { nonneg } from "./extract-print.js";
|
|
31
32
|
import { HarnessFailure, Outside, constantsOf, draw, drive, evalTerm, noEvidence, retried, tiesIn } from "./extract-check.js";
|
|
32
33
|
// Bitwise and, or and xor of two naturals below 2^53 (JavaScript's operators stop at 32 bits).
|
|
@@ -6632,6 +6633,7 @@ function checkStepOnce(h, read, r, sorts, opts) {
|
|
|
6632
6633
|
const hi = ask({ op: 'hello', ...h.hello, naiveUtc: read.naiveUtc, leaves: read.leaves, ctor: read.ctor, answers: read.answers, kept: read.kept, cls: read.cls ?? null, stores: read.stores, arms: read.arms, discard: opts.onError === 'discard', ...(read.inject ? { inject: read.inject } : {}), ...(read.globals ? { globals: read.globals } : {}), ...(read.inert ? { inert: read.inert } : {}), ...(opts.fields ? { fields: opts.fields } : {}) });
|
|
6633
6634
|
if (hi.error)
|
|
6634
6635
|
return { ...empty, mismatch: `the code doesn't load with the check's harness: ${JSON.stringify(hi.error)}` };
|
|
6636
|
+
const native = hi.nativeSnapshot === 1 && read.leaves.some(l => l.ordered) ? nativeWireDecoder() : undefined;
|
|
6635
6637
|
const num = (x, at) => { const n = Number(x); if (typeof x === 'string' && Number.isSafeInteger(n) && String(n) === x)
|
|
6636
6638
|
return n; throw new Outside(`${at} is ${String(x)}`); };
|
|
6637
6639
|
const toSnap = (s) => {
|
|
@@ -6712,6 +6714,12 @@ function checkStepOnce(h, read, r, sorts, opts) {
|
|
|
6712
6714
|
}
|
|
6713
6715
|
return { ok: true, value: o };
|
|
6714
6716
|
},
|
|
6717
|
+
...(native ? { nativeState: (self) => {
|
|
6718
|
+
const result = ask({ op: 'native', id: self });
|
|
6719
|
+
if (result.error)
|
|
6720
|
+
throw new Error(`native snapshot: ${JSON.stringify(result.error)}`);
|
|
6721
|
+
return native(result.snapshot);
|
|
6722
|
+
} } : {}),
|
|
6715
6723
|
args: (inputs, e) => { inputsNow = inputs; return (read.args[e.call] ?? []).map(([n, a]) => [n, build(a, inputs)]); },
|
|
6716
6724
|
setNow: n => { now = n; },
|
|
6717
6725
|
coverage: () => (coverage ??= closeAndCount()),
|
|
@@ -6775,7 +6783,8 @@ function checkStepOnce(h, read, r, sorts, opts) {
|
|
|
6775
6783
|
return { arms: arms.length, hit: arms.filter(a => hit.has(a)).length, missed: arms.filter(a => !hit.has(a)).map(a => `the arm at ${a}`) };
|
|
6776
6784
|
}
|
|
6777
6785
|
const ev = drive(m, r, sorts, side, o);
|
|
6778
|
-
|
|
6786
|
+
// The native journal is keyed by this exact evidence object.
|
|
6787
|
+
return Object.assign(ev, { runMs: Math.round(performance.now() - r0) });
|
|
6779
6788
|
}
|
|
6780
6789
|
catch (x) {
|
|
6781
6790
|
if (x instanceof HarnessFailure)
|
|
@@ -6874,7 +6883,7 @@ export function stepNames(read) {
|
|
|
6874
6883
|
for (const l of read.leaves) {
|
|
6875
6884
|
const code = l.path.join('.');
|
|
6876
6885
|
if (l.kind === 'map')
|
|
6877
|
-
out.push({ code: l.orm ? l.name : l.store ?? code, rule: l.name, role: 'state', map: { fields: m.maps.find(d => d.name === l.name)?.fields.map(f => f.name) ?? [], ...(l.orm ? { store: l.orm.rec, tpl: '{}' } : l.store ? { store: l.store, tpl: l.tpl ?? '{}' } : {}), ...(l.ordered ? { ordered: true } : {}) } });
|
|
6886
|
+
out.push({ code: l.orm ? l.name : l.store ?? code, rule: l.name, role: 'state', map: { fields: m.maps.find(d => d.name === l.name)?.fields.map(f => f.name) ?? [], ...(l.orm ? { store: l.orm.rec, tpl: '{}' } : l.store ? { store: l.store, tpl: l.tpl ?? '{}' } : {}), ...(l.ordered ? { ordered: true, scalar: m.maps.find(d => d.name === l.name)?.scalar === true } : {}) } });
|
|
6878
6887
|
else if (l.kind === 'none') {
|
|
6879
6888
|
const n = at(code);
|
|
6880
6889
|
if (n)
|
package/dist/core/extract.d.ts
CHANGED
package/dist/core/infer.js
CHANGED
|
@@ -1035,7 +1035,11 @@ function inferLawsSearchIn(target, laws, stepLaws, opts) {
|
|
|
1035
1035
|
// (GDP_INFER_TRACE=2: each phase's progress too, to stderr)
|
|
1036
1036
|
if (env.GDP_INFER_TRACE === '2' && !opts.progress)
|
|
1037
1037
|
opts = { ...opts, progress: (phase, info) => globalThis.process.stderr.write(`[infer ${phase}] ${JSON.stringify(info)}\n`) };
|
|
1038
|
-
const t0 = countedSearchNow(), ms = opts.ms ?? 20000, wallUntil = opts.wall ?? t0 + ms
|
|
1038
|
+
const t0 = countedSearchNow(), ms = opts.ms ?? 20000, wallUntil = opts.wall ?? t0 + ms;
|
|
1039
|
+
// Divisor declarations are mutable rule metadata. Keep a private copy even
|
|
1040
|
+
// when withSumsOf would return the original rule: candidate search and returned
|
|
1041
|
+
// remainder laws must not add arithmetic facts to the caller's next proof.
|
|
1042
|
+
const rule = isRule(target) ? target.withDivisors().withSumsOf(laws, stepLaws) : undefined;
|
|
1039
1043
|
// The clock the budgets read (counted milliseconds since the start, or wall time where `timed`), and the stop.
|
|
1040
1044
|
const timed = !!opts.timed, w0 = work.n, used = { tries: 0, rows: 0, evals: 0, watched: 0, erows: 0, etries: 0 };
|
|
1041
1045
|
const now = () => (timed ? countedSearchNow() - t0
|
|
@@ -1071,7 +1075,7 @@ function inferLawsSearchIn(target, laws, stepLaws, opts) {
|
|
|
1071
1075
|
const m = rule ? rule.machine : target;
|
|
1072
1076
|
let proofs = 0;
|
|
1073
1077
|
// The rule (or machine) the kernel proves the candidates with: once a remainder is among them, one that declares
|
|
1074
|
-
// div$k and mod$k for its divisors (
|
|
1078
|
+
// div$k and mod$k for its divisors (all declarations stay on the private rule copy).
|
|
1075
1079
|
// Only the laws proven read: a search none of whose chosen candidates is a remainder proves with the rule as it is.
|
|
1076
1080
|
const byDivisors = new Map();
|
|
1077
1081
|
const forLaws = (ls) => {
|
package/dist/core/laws.d.ts
CHANGED
|
@@ -16,6 +16,10 @@ export type Built = {
|
|
|
16
16
|
};
|
|
17
17
|
export declare class LawError extends Error {
|
|
18
18
|
}
|
|
19
|
+
export declare class ScalarListQuantifierError extends LawError {
|
|
20
|
+
readonly shape = "scalar-ordered-list-quantification";
|
|
21
|
+
constructor();
|
|
22
|
+
}
|
|
19
23
|
export declare function lawsIn(text: string, where?: string): LawText[];
|
|
20
24
|
type Seg = {
|
|
21
25
|
f: string;
|
package/dist/core/laws.js
CHANGED
|
@@ -28,6 +28,7 @@
|
|
|
28
28
|
// in it, the same item, not an equal one), at every two (or three) at once
|
|
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
|
+
import { copyVariable } from "./dsl-binders.js";
|
|
31
32
|
import { attachNativeLaw } from "./source-check.js";
|
|
32
33
|
import { nativeLaw } from "./native-law.js";
|
|
33
34
|
import { agreement, isolation, noninterference } from "./relational.js";
|
|
@@ -35,6 +36,10 @@ import { CalendarError, businessDays } from "./calendar.js";
|
|
|
35
36
|
export { businessDays } from "./calendar.js";
|
|
36
37
|
export class LawError extends Error {
|
|
37
38
|
}
|
|
39
|
+
export class ScalarListQuantifierError extends LawError {
|
|
40
|
+
shape = 'scalar-ordered-list-quantification';
|
|
41
|
+
constructor() { super('forall over a scalar ordered list is not supported: list values and membership must not be replaced by position keys'); }
|
|
42
|
+
}
|
|
38
43
|
// --- reading the code's text -------------------------------------------------------------------------------------------
|
|
39
44
|
// Every law stated in a file's text, with its line.
|
|
40
45
|
const FORMS = [
|
|
@@ -349,6 +354,10 @@ function read(e, c, names, dry) {
|
|
|
349
354
|
const over = val(f.over, c, names, dry);
|
|
350
355
|
if (over.t !== 'map')
|
|
351
356
|
throw new LawError(`forall ${f.v} in ...: over a map (a dict, a Map, a hash) or a list`);
|
|
357
|
+
// Record identity is represented by its stable key. A scalar value is not:
|
|
358
|
+
// neither its comparisons nor membership may silently use that position.
|
|
359
|
+
if (over.n.map?.ordered && over.n.map.scalar !== false)
|
|
360
|
+
throw new ScalarListQuantifierError();
|
|
352
361
|
return { over, env: f.over.k === 'old' || !c.step ? c.b : c.a };
|
|
353
362
|
});
|
|
354
363
|
if (dry) {
|
|
@@ -431,7 +440,7 @@ function val(e, c, names, dry) {
|
|
|
431
440
|
if (one instanceof Int) {
|
|
432
441
|
// (after the step: the sums over the map before it, as the state after it holds them, primed)
|
|
433
442
|
const after = (m.env ?? c.a) === c.a && c.step && c.a !== c.b, src = (after ? c.b[m.n.rule] : map);
|
|
434
|
-
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; };
|
|
443
|
+
const sumOf = (part) => { const t = src.sum(cell => cell[fs[0]][part]); return after && t.e.op === 'var' ? new Term(copyVariable(t.e, { op: 'var', name: `${t.e.name}'` })) : t; };
|
|
435
444
|
return { t: 'num', v: new Int(sumOf('pos'), sumOf('neg')) };
|
|
436
445
|
}
|
|
437
446
|
return { t: 'num', v: Int.of(map.sum(cell => cell[fs[0]])) };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function nativeWireDecoder(maxObjects?: number, maxNodes?: number): (wire: unknown) => unknown;
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// Decode identity-bearing snapshots returned by the real native harness. This
|
|
2
|
+
// is observation transport only: no model values or proof results are supplied.
|
|
3
|
+
export function nativeWireDecoder(maxObjects = 100000, maxNodes = 10000) {
|
|
4
|
+
if (!Number.isSafeInteger(maxObjects) || maxObjects < 1 || !Number.isSafeInteger(maxNodes) || maxNodes < 1)
|
|
5
|
+
throw Error('invalid native snapshot bounds');
|
|
6
|
+
const objects = new Map();
|
|
7
|
+
return wire => {
|
|
8
|
+
let nodes = 0;
|
|
9
|
+
const seen = new Set();
|
|
10
|
+
const record = (value) => {
|
|
11
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
12
|
+
throw Error('invalid native snapshot node');
|
|
13
|
+
return value;
|
|
14
|
+
};
|
|
15
|
+
const decode = (value) => {
|
|
16
|
+
if (++nodes > maxNodes)
|
|
17
|
+
throw Error('native snapshot exceeds node bound');
|
|
18
|
+
if (value === null || typeof value === 'string' || typeof value === 'boolean')
|
|
19
|
+
return value;
|
|
20
|
+
if (typeof value === 'number') {
|
|
21
|
+
if (!Number.isSafeInteger(value))
|
|
22
|
+
throw Error('unsafe native snapshot number');
|
|
23
|
+
return value;
|
|
24
|
+
}
|
|
25
|
+
const node = record(value), id = node.id, kind = node.kind;
|
|
26
|
+
if (typeof id !== 'string' || !/^[1-9][0-9]*$/.test(id))
|
|
27
|
+
throw Error('invalid native snapshot identity');
|
|
28
|
+
if (kind === 'ref') {
|
|
29
|
+
if (!seen.has(id))
|
|
30
|
+
throw Error('unbound native snapshot reference');
|
|
31
|
+
return objects.get(id).value;
|
|
32
|
+
}
|
|
33
|
+
if (kind !== 'object' && kind !== 'array' && kind !== 'map')
|
|
34
|
+
throw Error('unsupported native snapshot kind');
|
|
35
|
+
if (seen.has(id))
|
|
36
|
+
throw Error('duplicate native snapshot identity');
|
|
37
|
+
seen.add(id);
|
|
38
|
+
let kept = objects.get(id);
|
|
39
|
+
if (kept && kept.kind !== kind)
|
|
40
|
+
throw Error('native snapshot identity changed kind');
|
|
41
|
+
if (!kept) {
|
|
42
|
+
if (objects.size >= maxObjects)
|
|
43
|
+
throw Error('native snapshot exceeds identity bound');
|
|
44
|
+
const fresh = kind === 'array' ? [] : kind === 'map' ? new Map() : Object.create(null);
|
|
45
|
+
kept = { kind, value: fresh };
|
|
46
|
+
objects.set(id, kept);
|
|
47
|
+
}
|
|
48
|
+
if (!Array.isArray(node.items))
|
|
49
|
+
throw Error('invalid native snapshot entries');
|
|
50
|
+
if (kind === 'array') {
|
|
51
|
+
const target = kept.value;
|
|
52
|
+
target.length = 0;
|
|
53
|
+
for (const item of node.items)
|
|
54
|
+
target.push(decode(item));
|
|
55
|
+
}
|
|
56
|
+
else if (kind === 'map') {
|
|
57
|
+
const target = kept.value;
|
|
58
|
+
target.clear();
|
|
59
|
+
for (const item of node.items) {
|
|
60
|
+
if (!Array.isArray(item) || item.length !== 2 || (typeof item[0] !== 'string' && typeof item[0] !== 'number'))
|
|
61
|
+
throw Error('invalid native snapshot map entry');
|
|
62
|
+
const key = decode(item[0]);
|
|
63
|
+
if (target.has(key))
|
|
64
|
+
throw Error('duplicate native snapshot map key');
|
|
65
|
+
target.set(key, decode(item[1]));
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
else {
|
|
69
|
+
const target = kept.value;
|
|
70
|
+
for (const key of Object.keys(target))
|
|
71
|
+
delete target[key];
|
|
72
|
+
for (const item of node.items) {
|
|
73
|
+
if (!Array.isArray(item) || item.length !== 2 || typeof item[0] !== 'string' || Object.hasOwn(target, item[0]))
|
|
74
|
+
throw Error('invalid native snapshot object entry');
|
|
75
|
+
Object.defineProperty(target, item[0], { value: decode(item[1]), writable: true, enumerable: true, configurable: true });
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return kept.value;
|
|
79
|
+
};
|
|
80
|
+
const envelope = record(wire);
|
|
81
|
+
if (envelope.version !== 1)
|
|
82
|
+
throw Error('unsupported native snapshot version');
|
|
83
|
+
return decode(envelope.root);
|
|
84
|
+
};
|
|
85
|
+
}
|
package/dist/core/py/harness.py
CHANGED
|
@@ -12,6 +12,7 @@ CUR = {}
|
|
|
12
12
|
EFF = {}
|
|
13
13
|
HIT = set()
|
|
14
14
|
S = {}
|
|
15
|
+
NATIVE_OBJECTS = {}
|
|
15
16
|
|
|
16
17
|
def datetime_in(v, unit):
|
|
17
18
|
epoch = datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc if unit == 'datetime-utc' else None)
|
|
@@ -591,7 +592,7 @@ def hello(req):
|
|
|
591
592
|
S['cls'] = getattr(mod, req['cls'].rpartition('.')[2]) if req.get('cls') else None
|
|
592
593
|
S['loop'] = asyncio.new_event_loop()
|
|
593
594
|
asyncio.set_event_loop(S['loop'])
|
|
594
|
-
return {'ok': True}
|
|
595
|
+
return {'ok': True, 'nativeSnapshot': 1}
|
|
595
596
|
|
|
596
597
|
def make(args):
|
|
597
598
|
global OBJ_STORES
|
|
@@ -659,6 +660,38 @@ def call(req):
|
|
|
659
660
|
if after.get(k) != before[k]: return {'frame': k}
|
|
660
661
|
return {'out': tag(out), **({'err': err} if err is not None else {}), **({'effects': dict(EFF)} if EFF else {})}
|
|
661
662
|
|
|
663
|
+
# Native observation transport for ordered containers. Retain real references
|
|
664
|
+
# so Python cannot recycle an address and manufacture cross-snapshot identity.
|
|
665
|
+
def native_state(obj):
|
|
666
|
+
seen = set()
|
|
667
|
+
count = [0]
|
|
668
|
+
def encode(value, names=None):
|
|
669
|
+
count[0] += 1
|
|
670
|
+
if count[0] > 10000: raise ValueError('native snapshot exceeds node bound')
|
|
671
|
+
if value is None or isinstance(value, (str, bool)): return value
|
|
672
|
+
if isinstance(value, (int, float)):
|
|
673
|
+
if not (-9007199254740991 <= value <= 9007199254740991) or int(value) != value:
|
|
674
|
+
raise ValueError('native snapshot number is outside exact integer range')
|
|
675
|
+
return int(value)
|
|
676
|
+
address = id(value)
|
|
677
|
+
if address not in NATIVE_OBJECTS:
|
|
678
|
+
if len(NATIVE_OBJECTS) >= 100000: raise ValueError('native snapshot exceeds identity bound')
|
|
679
|
+
NATIVE_OBJECTS[address] = (value, str(len(NATIVE_OBJECTS) + 1))
|
|
680
|
+
ident = NATIVE_OBJECTS[address][1]
|
|
681
|
+
if ident in seen: return {'kind': 'ref', 'id': ident}
|
|
682
|
+
seen.add(ident)
|
|
683
|
+
if isinstance(value, list):
|
|
684
|
+
return {'kind': 'array', 'id': ident, 'items': [encode(x) for x in value]}
|
|
685
|
+
if isinstance(value, dict):
|
|
686
|
+
if any(not isinstance(k, (str, int, float)) or isinstance(k, bool) for k in value):
|
|
687
|
+
raise ValueError('unsupported native snapshot map key')
|
|
688
|
+
return {'kind': 'map', 'id': ident, 'items': [[encode(k), encode(v)] for k, v in value.items()]}
|
|
689
|
+
fields = vars(value)
|
|
690
|
+
if names is not None: fields = {name: fields[name] for name in names}
|
|
691
|
+
return {'kind': 'object', 'id': ident, 'items': [[k, encode(v)] for k, v in fields.items()]}
|
|
692
|
+
roots = sorted({l['path'][0] for l in S['leaves'] if l.get('path') and l['kind'] != 'frame'})
|
|
693
|
+
return {'version': 1, 'root': encode(obj, roots)}
|
|
694
|
+
|
|
662
695
|
def main():
|
|
663
696
|
fin = open(sys.argv[1], 'r'); fout = open(sys.argv[2], 'w')
|
|
664
697
|
for line in fin:
|
|
@@ -683,6 +716,7 @@ def main():
|
|
|
683
716
|
elif op == 'get':
|
|
684
717
|
obj, stores = OBJS[req['id']]
|
|
685
718
|
res = {'state': state_of(obj, stores)}
|
|
719
|
+
elif op == 'native': res = {'snapshot': native_state(OBJS[req['id']][0])}
|
|
686
720
|
elif op == 'call': res = call(req)
|
|
687
721
|
elif op == 'coverage': res = {'hit': sorted(HIT)}
|
|
688
722
|
else: res = {'error': f"no op {op}"}
|
|
@@ -26,6 +26,7 @@ export type TranslationFields = {
|
|
|
26
26
|
kernelProven?: boolean;
|
|
27
27
|
};
|
|
28
28
|
export declare function inheritSource(from: object, to: object, transparent?: boolean): void;
|
|
29
|
+
export declare function bindSourceMachine(rule: object, machine: object): void;
|
|
29
30
|
export declare function rememberNative(e: object, journal: NativeJournal): void;
|
|
30
31
|
export declare function attachSource(rule: object, e: object, generated: object[]): void;
|
|
31
32
|
export declare function attachNativeLaw(rule: object, law: object, name: string, method: string | undefined, evaluate: (observation: NativeObservation) => boolean): void;
|
|
@@ -39,6 +40,7 @@ export declare function translationVerdict<V extends {
|
|
|
39
40
|
why?: string;
|
|
40
41
|
stuck?: string;
|
|
41
42
|
}>(rule: object, laws: object[], verdict: V): TranslatedVerdict<V>;
|
|
43
|
+
export declare function requireSourceTranslation(rule: object, laws: object[]): void;
|
|
42
44
|
export declare const nativeSame: (a: unknown, b: unknown) => boolean;
|
|
43
45
|
export declare function nativeSnapshot(value: unknown, seen?: Map<object, unknown>): unknown;
|
|
44
46
|
export {};
|
|
@@ -19,6 +19,19 @@ export function inheritSource(from, to, transparent = false) {
|
|
|
19
19
|
if (transparent && source)
|
|
20
20
|
sources.set(to, source);
|
|
21
21
|
}
|
|
22
|
+
// Rule.machine makes a fresh structural model. Carry source provenance onto that
|
|
23
|
+
// exact model so public consumers that receive only a Machine still fail closed.
|
|
24
|
+
// The marker is enumerable here: spread/reconstruction keeps the warning, but
|
|
25
|
+
// never the private WeakMap journal (a copied machine is therefore rejected).
|
|
26
|
+
export function bindSourceMachine(rule, machine) {
|
|
27
|
+
const source = sources.get(rule);
|
|
28
|
+
if (source) {
|
|
29
|
+
mark(machine, true);
|
|
30
|
+
sources.set(machine, source);
|
|
31
|
+
}
|
|
32
|
+
else if (marked(rule))
|
|
33
|
+
mark(machine, true);
|
|
34
|
+
}
|
|
22
35
|
const evidence = new WeakMap();
|
|
23
36
|
const sources = new WeakMap();
|
|
24
37
|
const nativeLaws = new WeakMap();
|
|
@@ -69,6 +82,14 @@ export function translationVerdict(rule, laws, verdict) {
|
|
|
69
82
|
}
|
|
70
83
|
return { ...verdict, translation: journal.scope, translationChecks: checks };
|
|
71
84
|
}
|
|
85
|
+
// Lean export is a public proof boundary. It must repeat source admission from
|
|
86
|
+
// the bound machine and laws instead of trusting caller-supplied fields or an
|
|
87
|
+
// old verdict: the journal and native-law identities live only in these maps.
|
|
88
|
+
export function requireSourceTranslation(rule, laws) {
|
|
89
|
+
const verdict = translationVerdict(rule, laws, { proven: true, checked: true });
|
|
90
|
+
if (!verdict.proven || !verdict.checked)
|
|
91
|
+
throw new Error(verdict.why ?? 'source translation was not checked');
|
|
92
|
+
}
|
|
72
93
|
const sourceIdentity = new WeakMap(), cloneIdentity = new WeakMap();
|
|
73
94
|
let nextIdentity = 0;
|
|
74
95
|
const identify = (original, clone) => {
|
package/dist/kernel/reader.js
CHANGED
|
@@ -228,7 +228,7 @@ export class Reader {
|
|
|
228
228
|
break;
|
|
229
229
|
case 'mul': {
|
|
230
230
|
const a = this.linear(e.a);
|
|
231
|
-
lin = a.lin && same(0, e, a.lin, 0, 0, () => scale(a.lin, e.k));
|
|
231
|
+
lin = a.lin && Number.isSafeInteger(e.k) ? same(0, e, a.lin, 0, 0, () => scale(a.lin, e.k)) : undefined;
|
|
232
232
|
r = a;
|
|
233
233
|
break;
|
|
234
234
|
}
|
|
@@ -312,6 +312,10 @@ export class Reader {
|
|
|
312
312
|
break;
|
|
313
313
|
}
|
|
314
314
|
}
|
|
315
|
+
// Match kernel.ts's linearOf: an unsafe intermediate form is no form,
|
|
316
|
+
// even if later arithmetic would cancel it back into the safe range.
|
|
317
|
+
if (lin && !everyLinearCell(lin, (_key, coefficient) => Number.isSafeInteger(coefficient), 'reader linear safety'))
|
|
318
|
+
lin = undefined;
|
|
315
319
|
// (an open value's reason is what its decided parts need: only the column's own value is open)
|
|
316
320
|
const out = { lin, w: r.w, fin: r.fin, pos: r.pos, stamp: r.pos < 0 ? 0 : this.trail.stamp(r.pos), node: this.node };
|
|
317
321
|
this.ls.set(e, out);
|
|
@@ -7,8 +7,11 @@ export function asked(source) {
|
|
|
7
7
|
return [...code.matchAll(/^#print axioms\s+(\S+)/gm)].map(m => m[1]);
|
|
8
8
|
}
|
|
9
9
|
export function answers(out) {
|
|
10
|
-
|
|
11
|
-
|
|
10
|
+
// Lake prefixes native informational output with its source location. Strip
|
|
11
|
+
// only that exact envelope; arbitrary diagnostic text is not an axiom answer.
|
|
12
|
+
const plain = out.replace(/^info: [^\r\n]+\.lean:\d+:\d+: /gm, '');
|
|
13
|
+
const deps = [...plain.matchAll(/^'([^\r\n]+)' depends on axioms: \[([^\]]*)\]\r?$/gm)].map(m => ({ name: m[1], axioms: m[2].split(',').map(a => a.trim()).filter(Boolean) }));
|
|
14
|
+
const none = [...plain.matchAll(/^'([^\r\n]+)' does not depend on any axioms\r?$/gm)].map(m => ({ name: m[1], axioms: [] }));
|
|
12
15
|
return [...deps, ...none];
|
|
13
16
|
}
|
|
14
17
|
export function gate(out, sources, native = false) {
|
|
@@ -116,6 +116,7 @@ export declare function readable(id: string, laws: Law[], vars: string[], maps:
|
|
|
116
116
|
eLit?: (e: E) => string;
|
|
117
117
|
ghosts?: boolean;
|
|
118
118
|
explicitExistentials?: ReadonlySet<string>;
|
|
119
|
+
lawDef?: (j: number) => string;
|
|
119
120
|
}): string;
|
|
120
121
|
export type ProgressCase = {
|
|
121
122
|
id: string;
|
package/dist/lean-kernel/emit.js
CHANGED
|
@@ -12,6 +12,7 @@ import { legacyFamilyOrder } from "./legacy-family-order.js";
|
|
|
12
12
|
import { proveKInduction } from "../core/kind.js";
|
|
13
13
|
import { quantifiedRenames } from "./qalpha.js";
|
|
14
14
|
import { countsForReads } from "../core/count-facts.js";
|
|
15
|
+
import { requireSourceTranslation } from "../core/source-check.js";
|
|
15
16
|
export { leanLibrary };
|
|
16
17
|
// --- to Lean ------------------------------------------------------------------------------------------------------------
|
|
17
18
|
const varsOf = (c) => [...JSON.stringify(c).matchAll(/"op":"var","name":"([^"]+)"/g)].map(m => m[1]);
|
|
@@ -1002,6 +1003,7 @@ theorem ${id}_laws : ∀ maps ρ, evalC ρ maps ${id}_fold.pre = true → ∀ t,
|
|
|
1002
1003
|
// abbreviation for its column), proven from the machine's theorem by unfolding the law's own definition. The statement
|
|
1003
1004
|
// is what a Lean development cites; the column numbers stay inside the namespace.
|
|
1004
1005
|
// `have`: the line that gives each law as a hypothesis hl (an SEntry's Holds by default; a cyclic proof's, holdsOver).
|
|
1006
|
+
// `lawDef`: the separate condition definition wrapped by a cyclic MLaw; other exporters inline the condition.
|
|
1005
1007
|
// A law with "there exists" (core/exists.ts, `ex` on the law the kernel proved) is stated as the existential it is:
|
|
1006
1008
|
// `<id>_someN`, ∃ w1 .. wn, P with the bound naturals set to them (updAll, Ghost.lean), from the law proven with its
|
|
1007
1009
|
// witness terms in place (some_of_subst) or over the machine's ghosts at every reachable state of the machine without
|
|
@@ -1216,7 +1218,7 @@ ${laws.map((law, j) => {
|
|
|
1216
1218
|
return `-- ${law.name}: its terms read an if, so no plain statement here (${id}_laws holds it)`;
|
|
1217
1219
|
const hyps = arithBinders(law), names = arithIn(law).map(hypName);
|
|
1218
1220
|
// Proof terms retain neutral Boolean children; surface statements omit them.
|
|
1219
|
-
const surfaceProof = `by simpa [${id}_l${j}, holdsC, evalE, upd] using hl'`;
|
|
1221
|
+
const surfaceProof = `by simpa [${id}_l${j}${reach.lawDef ? `, ${reach.lawDef(j)}` : ''}, holdsC, evalE, upd] using hl'`;
|
|
1220
1222
|
const rw = names.length ? `have hμ : ${statement(law, false)} := ${surfaceProof}\n rw [${names.join(', ')}] at hμ\n exact hμ` : `exact ${surfaceProof}`;
|
|
1221
1223
|
const own = law.keys?.length ? `${reach.have ? reach.have(j) : `have hl : ${id}_e${j}.Holds ρ μ := ${reach.call} ${id}_e${j} (by simp [${id}_proof])`}
|
|
1222
1224
|
have hl' := fun k ${law.keys.map((_, i) => `k${i + 2}`).join(' ')} => (evalC_iff (upd (${law.keys.reduce((acc, key, i) => `upd (${acc}) ${vars.indexOf(key)} k${i + 2}`, 'ρ')}) ${vars.indexOf(law.forall)} k) μ ${id}_l${j}.holds).mp (hl ${law.keys.map((_, i) => `k${i + 2}`).join(' ')} k)
|
|
@@ -2117,7 +2119,7 @@ theorem ${id}_laws : ∀ ρ M, SReach ${id}_machine ρ M → ∀ e ∈ ${id}_mla
|
|
|
2117
2119
|
theorem ${id}_hcheck : checkHMachine ${id}_hist [] ${id}_records = true := by ${checkBy}
|
|
2118
2120
|
theorem ${id}_hlaws : ∀ ρ M hist, HReach ${id}_hist ρ M hist → ∀ e ∈ ${id}_mlaws, holdsOver e.1 M e.2 ρ :=
|
|
2119
2121
|
fun ρ M hist h => ${id}_laws ρ M (hreach_plain ${id}_hist ${id}_records ${id}_hcheck ρ M hist h)
|
|
2120
|
-
${readable(id, laws, vars, maps, { binders: '(ρ : Nat → Nat) (μ : Nat → Nat → Nat) (hist : List (Nat → Nat))', hyp: `HReach ${id}_hist ρ μ hist`, call: '',
|
|
2122
|
+
${readable(id, laws, vars, maps, { binders: '(ρ : Nat → Nat) (μ : Nat → Nat → Nat) (hist : List (Nat → Nat))', hyp: `HReach ${id}_hist ρ μ hist`, call: '', lawDef: j => `${id}_law${j}`,
|
|
2121
2123
|
have: j => `have hl : holdsOver ${id}_l${j} μ ${keys2(laws[j])} ρ := cyc_machine_holds (${id}_law${j}_holds ρ μ ${reach('h')})` })}`;
|
|
2122
2124
|
};
|
|
2123
2125
|
// The machine's own step laws, one step or k (BridgeRules.lean's cyc_kstep_sound): the SKStep as the usual export
|
|
@@ -2208,7 +2210,7 @@ ${cycProofText(id, p, [], vars, maps)}
|
|
|
2208
2210
|
${okLemmas}
|
|
2209
2211
|
${lawBlocks}
|
|
2210
2212
|
${lawsThm}
|
|
2211
|
-
${hm ? histBlock() : readable(id, laws, vars, maps, { binders: '(ρ : Nat → Nat) (μ : Nat → Nat → Nat)', hyp: `SReach ${id}_machine ρ μ`, call: '', lit: c, eLit: e, ghosts: !rf && gv.length > 0,
|
|
2213
|
+
${hm ? histBlock() : readable(id, laws, vars, maps, { binders: '(ρ : Nat → Nat) (μ : Nat → Nat → Nat)', hyp: `SReach ${id}_machine ρ μ`, call: '', lit: c, eLit: e, ghosts: !rf && gv.length > 0, lawDef: j => `${id}_law${j}`,
|
|
2212
2214
|
have: j => `have hl : holdsOver ${id}_l${j} μ ${keys2(laws[j])} ρ := cyc_machine_holds (${id}_law${j}_holds ρ μ h)` })}${opts.noFacts ? '' : factsProof(id, m, maps, vars, opts.simp)}${records.length ? `\n\n${records.join('\n\n')}` : ''}${opts.after ? `\n\n${opts.after(ix)}` : ''}` };
|
|
2213
2215
|
}
|
|
2214
2216
|
// A fold from its cyclic proof (Bridge.lean's cyc_fold_sound): the fold numbered as foldToLean numbers it, each law's
|
|
@@ -2500,6 +2502,22 @@ export function hmachineToLean(id, m, laws, tampers = [], corollary) {
|
|
|
2500
2502
|
// `cyclic`: each machine, loop and fold the cyclic route covers from cyclic certificates (see cycMachineToLean); defaults
|
|
2501
2503
|
// to GDP_CERT=cyclic. `certReport` then says which items went which way.
|
|
2502
2504
|
export function toLean(items, opts = {}) {
|
|
2505
|
+
// Admit source-derived models before changing exporter state or emitting any text.
|
|
2506
|
+
// Ordinary typed DSL machines have no provenance entry and pass unchanged.
|
|
2507
|
+
for (const item of items) {
|
|
2508
|
+
if ('machine' in item)
|
|
2509
|
+
requireSourceTranslation(item.machine, [...item.laws, ...(item.stepLaws ?? []), ...(item.liveness ?? [])]);
|
|
2510
|
+
else if ('kInduction' in item)
|
|
2511
|
+
requireSourceTranslation(item.kInduction.machine, [...item.kInduction.laws, item.kInduction.law]);
|
|
2512
|
+
else if ('countedMachine' in item)
|
|
2513
|
+
requireSourceTranslation(item.countedMachine, item.laws);
|
|
2514
|
+
else if ('refinement' in item) {
|
|
2515
|
+
requireSourceTranslation(item.refinement.impl, item.refinement.relation);
|
|
2516
|
+
requireSourceTranslation(item.refinement.spec, item.refinement.relation);
|
|
2517
|
+
}
|
|
2518
|
+
else if ('cyclic' in item && item.bridge)
|
|
2519
|
+
requireSourceTranslation(item.bridge.machine, item.bridge.laws);
|
|
2520
|
+
}
|
|
2503
2521
|
const outer = checkBy, outerCerts = certsOn;
|
|
2504
2522
|
const env = globalThis.process?.env;
|
|
2505
2523
|
checkBy = (opts.native ?? env?.GDP_LEAN_NATIVE === '1') ? 'native_decide' : 'decide +kernel';
|
|
@@ -2930,6 +2948,6 @@ theorem ${id}_law${j}_holds : ∀ ρ M, SReach ${id}_machine ρ M → ∀ ρ' :
|
|
|
2930
2948
|
${(b.tampered ?? []).map((tm, j) => `-- TAMPERED: ${tm.what}. Lean computes the check against the proof to false.
|
|
2931
2949
|
def ${id}_tamperedm${j} : SMachine := ${machineLit(tm.machine, t, ix, mx)}
|
|
2932
2950
|
example : cycMOk ${id}_tamperedm${j} ${id}_enc ${id}_facts ${id}_law0 ${keysL(b.laws[0])} ${id}_node0 = false := by ${checkBy}`).join('\n')}
|
|
2933
|
-
${readable(id, b.laws, vars, maps, { binders: '(ρ : Nat → Nat) (μ : Nat → Nat → Nat)', hyp: `SReach ${id}_machine ρ μ`, call: '',
|
|
2951
|
+
${readable(id, b.laws, vars, maps, { binders: '(ρ : Nat → Nat) (μ : Nat → Nat → Nat)', hyp: `SReach ${id}_machine ρ μ`, call: '', lawDef: j => `${id}_law${j}`,
|
|
2934
2952
|
have: j => `have hl : holdsOver ${id}_l${j} μ ${list((b.laws[j].keys ?? []).map(k2 => String(ix(k2))))} ρ := cyc_machine_holds (${id}_law${j}_holds ρ μ h)` })}`;
|
|
2935
2953
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "gdp-wired",
|
|
3
|
-
"version": "0.50.
|
|
3
|
+
"version": "0.50.2",
|
|
4
4
|
"description": "An automatic prover for stateful rules (budgets, caps, windows, workflows, policies): laws proven with no proof to write, checked again in Lean, counterexamples found on the GPU, the rule shipped as code",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"verification",
|
|
@@ -207,7 +207,9 @@
|
|
|
207
207
|
"smoke": "sh scripts/smoke.sh",
|
|
208
208
|
"bar": "bun gates/bar.ts",
|
|
209
209
|
"test:bar": "bun test ./gates/bar.test.ts",
|
|
210
|
-
"test": "bun scripts/test-shards.ts"
|
|
210
|
+
"test": "bun scripts/test-shards.ts",
|
|
211
|
+
"release:full-gate": "bun scripts/release-ci/full-gate-runner.ts",
|
|
212
|
+
"release:verify-gate": "bun scripts/release-ci/verify-publish-gate.ts"
|
|
211
213
|
},
|
|
212
214
|
"devDependencies": {
|
|
213
215
|
"@gdp-ts/core": "0.1.0",
|