gdp-wired 0.50.0 → 0.50.1

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.
@@ -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) => `${r.field}.last${c ? `.${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[`${r.field}.last.${c}`];
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[`${reg.field}.last.${c}`].is(l))))));
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 -------------------------------------------------------------------------
@@ -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), x(`${p}${n}`))])),
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: x(`${p}${w.each}`) }) }];
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
+ }
@@ -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,6 +17,7 @@ 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";
@@ -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({ op: 'var', name }, scope?.vars[name]);
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) }, () => `k$${++boundCounter}`), g = f;
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 = `s$${++boundCounter}`;
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 = `some$${++boundCounter}`, value = kind.value(name), body = all(...kind.assume(name), f(value));
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$') && !vars.includes(n) && !/^some\$[ap]\d/.test(n));
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 probe = termOf(at(v('k$sum$'))), id = plain ? `sum$${map}` : `sum$${map}$${fnv(JSON.stringify(probe))}`, key = `${id}$k`;
931
- const term = substVarsE(probe, { 'k$sum$': { op: 'var', name: key } }), had = sumDecls.get(id);
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 v(id);
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 = `k$${++boundCounter}`; return { map: this.name, each, value: termOf(f(v(each))), concrete: { at: f } }; }
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 = `k$${++boundCounter}`, n = this.sorts.length, k = v(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 = `k$${++boundCounter}`;
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 = `k$${++boundCounter}`;
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) => [`key$${++keyCounter}`, Array.from({ length: Math.max(0, out.forall.length - 1) }, () => `key$${++keyCounter}`)];
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
- function prenex(c, what, key) {
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) => JSON.parse(JSON.stringify(c).replaceAll(`"op":"var","name":"${from}"`, `"op":"var","name":"${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 = /^(\d+):(.*)$/.exec(name); return m ? `${m[2]}@${m[1]}` : name; };
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 = `key$${++keyCounter}`;
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] ?? { op: 'var', name: 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
- return x;
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 = `key$${++keyCounter}`, src = { step: { then: then, ...(when ? { when: when } : {}) } };
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) => `${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 = `key$${++keyCounter}`;
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: marked(p), ...w } : { name, steps: k, then: marked(out.c), ...w });
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: marked(c), ...w } : { name, steps: k, forall: k1, then: marked(prenex(c, `step law ${name}`, k1) ?? c), ...w });
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) ? `key$${++keyCounter}` : undefined, key = (forall ? v(forall) : undefined);
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 = `k$${++boundCounter}`, best = env[n];
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,8 @@ 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
- return s.ghost ? s.ghost(out) : out;
2552
+ const encoded = encodeBinders(out, this.names().map(([n]) => n));
2553
+ return s.ghost ? s.ghost(encoded) : encoded;
2492
2554
  }
2493
2555
  // The same rule with ghosts its machine gains (the search's, over a law with "there exists" made plain: skolemOf).
2494
2556
  withGhosts(ghost) { return this.with({ ghost }); }
@@ -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, rule = isRule(target) ? target.withSumsOf(laws, stepLaws) : undefined;
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 (rule.withDivisors leaves the caller's rule as it was until a found law needs them).
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.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";
@@ -431,7 +432,7 @@ function val(e, c, names, dry) {
431
432
  if (one instanceof Int) {
432
433
  // (after the step: the sums over the map before it, as the state after it holds them, primed)
433
434
  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; };
435
+ 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
436
  return { t: 'num', v: new Int(sumOf('pos'), sumOf('neg')) };
436
437
  }
437
438
  return { t: 'num', v: Int.of(map.sum(cell => cell[fs[0]])) };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gdp-wired",
3
- "version": "0.50.0",
3
+ "version": "0.50.1",
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",