gdp-wired 0.31.1 → 0.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +95 -6
  2. package/dist/core/c/reader.d.ts +86 -0
  3. package/dist/core/c/reader.js +860 -0
  4. package/dist/core/check.js +20 -6
  5. package/dist/core/cli.d.ts +76 -0
  6. package/dist/core/cli.js +636 -0
  7. package/dist/core/dsl.d.ts +6 -4
  8. package/dist/core/dsl.js +30 -16
  9. package/dist/core/effect.d.ts +6 -4
  10. package/dist/core/effect.js +48 -10
  11. package/dist/core/ex/harness.exs +177 -0
  12. package/dist/core/ex/json.exs +46 -0
  13. package/dist/core/ex/reader.exs +462 -0
  14. package/dist/core/exists.d.ts +3 -0
  15. package/dist/core/exists.js +19 -5
  16. package/dist/core/extract-c.d.ts +35 -0
  17. package/dist/core/extract-c.js +424 -0
  18. package/dist/core/extract-check.js +27 -6
  19. package/dist/core/extract-ex.d.ts +16 -0
  20. package/dist/core/extract-ex.js +33 -0
  21. package/dist/core/extract-go-check.d.ts +28 -0
  22. package/dist/core/extract-go-check.js +639 -0
  23. package/dist/core/extract-go.d.ts +231 -0
  24. package/dist/core/extract-go.js +1166 -0
  25. package/dist/core/extract-jvm.d.ts +23 -0
  26. package/dist/core/extract-jvm.js +220 -0
  27. package/dist/core/extract-print.js +17 -7
  28. package/dist/core/extract-py.d.ts +15 -0
  29. package/dist/core/extract-py.js +31 -0
  30. package/dist/core/extract-rb.d.ts +17 -0
  31. package/dist/core/extract-rb.js +31 -0
  32. package/dist/core/extract-read.d.ts +20 -0
  33. package/dist/core/extract-read.js +46 -6
  34. package/dist/core/extract-rs.d.ts +12 -0
  35. package/dist/core/extract-rs.js +306 -0
  36. package/dist/core/extract-shapes.d.ts +2 -0
  37. package/dist/core/extract-shapes.js +6 -5
  38. package/dist/core/extract-step.d.ts +806 -0
  39. package/dist/core/extract-step.js +4141 -0
  40. package/dist/core/extract-swift.d.ts +27 -0
  41. package/dist/core/extract-swift.js +484 -0
  42. package/dist/core/extract-xstate.d.ts +10 -3
  43. package/dist/core/extract-xstate.js +50 -4
  44. package/dist/core/extract.d.ts +22 -3
  45. package/dist/core/extract.js +107 -18
  46. package/dist/core/go/go.mod +3 -0
  47. package/dist/core/go/reader.go +901 -0
  48. package/dist/core/infer.d.ts +4 -0
  49. package/dist/core/infer.js +1838 -69
  50. package/dist/core/jvm/Harness.java +361 -0
  51. package/dist/core/jvm/JavaReader.java +825 -0
  52. package/dist/core/jvm/Jvm.java +332 -0
  53. package/dist/core/jvm/KtReader.java +960 -0
  54. package/dist/core/jvm/Rt.java +10 -0
  55. package/dist/core/laws.d.ts +83 -0
  56. package/dist/core/laws.js +623 -0
  57. package/dist/core/machine.d.ts +2 -0
  58. package/dist/core/machine.js +87 -0
  59. package/dist/core/py/harness.py +328 -0
  60. package/dist/core/py/reader.py +447 -0
  61. package/dist/core/rb/harness.rb +233 -0
  62. package/dist/core/rb/reader.rb +375 -0
  63. package/dist/core/relational.d.ts +49 -0
  64. package/dist/core/relational.js +345 -0
  65. package/dist/core/rs/Cargo.lock +108 -0
  66. package/dist/core/rs/Cargo.toml +14 -0
  67. package/dist/core/rs/src/main.rs +681 -0
  68. package/dist/core/swift/Harness.swift +124 -0
  69. package/dist/core/swift/Main.swift +34 -0
  70. package/dist/core/swift/Package.swift +13 -0
  71. package/dist/core/swift/Sources/gdp-swiftreader/main.swift +1341 -0
  72. package/dist/interchange/check.d.ts +16 -0
  73. package/dist/interchange/check.js +111 -0
  74. package/dist/interchange/format.d.ts +150 -0
  75. package/dist/interchange/format.js +678 -0
  76. package/dist/kernel/epr.d.ts +40 -0
  77. package/dist/kernel/epr.js +1882 -0
  78. package/dist/kernel/kernel.d.ts +45 -1
  79. package/dist/kernel/kernel.js +138 -13
  80. package/dist/kernel/prove.d.ts +45 -0
  81. package/dist/kernel/prove.js +658 -51
  82. package/dist/lean-kernel/emit.d.ts +17 -2
  83. package/dist/lean-kernel/emit.js +87 -7
  84. package/package.json +57 -2
@@ -0,0 +1,623 @@
1
+ // Laws in the code's own terms, one syntax for every language the extractor reads: a comment (`# gdp: law <name>:
2
+ // <expr>`, `// gdp: law ...`, `-- ` or `%`), an annotation (`@GdpLaw("<name>: <expr>")`, `@gdp.law(...)`, `@gdp_law ...`)
3
+ // or a Rust doc attribute (`#[doc = "gdp: law ..."]`), read from the code's text as the boundary's `gdp:` tags are
4
+ // (core/extract-step.ts), so a macro can emit the same text later. Each is parsed here into the builders' law
5
+ // (core/dsl.ts) through the extraction's names (Extraction.names: each rule variable's path in the code), never guessed:
6
+ // a name the code doesn't have is refused with the names it has.
7
+ //
8
+ // The law's view of a step, the same in every language (and what a typed law could target later): the state after the
9
+ // step by its fields (or after.x), the state before it as old(x) or before.x, the request's arguments by name, `result`
10
+ // (the method's) and `failed` (with failures: 'kept'), the constructor's arguments (params) where no field shadows them,
11
+ // an answered call as f(...). A law that reads only the state, placed outside any method, holds in every state; any other
12
+ // is a law of one step (of the method it is written on). Anything else is refused with why, never dropped, and a law is
13
+ // known by its name: two of one name in a rule are refused.
14
+ //
15
+ // x <= cap and not failed comparisons (< <= > >= == !=), + − and × a constant, // and % by one, and or not
16
+ // failed implies spend >= budget implies (=>), parentheses, min max abs, true false None (nil, null)
17
+ // self.tokens <= self.capacity the state by its fields (self., this., @ or a receiver's name, or bare)
18
+ // result == (n <= old(tokens)) a request's arguments by name, `result`, `failed`, old(x) or before.x the state
19
+ // before the step (a law reading any of these is a law of one step)
20
+ // team.max_budget is None None-ness (is None, is not None, == nil, != null), an object's fields
21
+ // get_current_spend(...) >= 0 a call of other code answered by the request, by its name
22
+ // counts[user] < limit, user in m a map at a key as the code reads it (m.get(k), k in m, m[k] is None)
23
+ // cache["hits:" + s] <= limit a store at its key's template ("hits:" + s, f"hits:{s}")
24
+ // forall k in budgets: budgets[k].spent <= budgets[k].limit every key the map holds (at the top of the law)
25
+ // mode == "closed", outcome == SLOW_ERROR, mode == :closed a choice by its value
26
+ import { Choice, Int, Str, Term, all, any, forall, no, not, yes } from "./dsl.js";
27
+ import { agreement, isolation, noninterference } from "./relational.js";
28
+ export class LawError extends Error {
29
+ }
30
+ // --- reading the code's text -------------------------------------------------------------------------------------------
31
+ // Every law stated in a file's text, with its line.
32
+ const FORMS = [
33
+ /(?:#|\/\/|--|%|\/\*|^\s*\*)\s*gdp:\s*law\s+([^:]+?)\s*(?::\s*(.+?))?\s*(?:\*\/)?\s*$/,
34
+ /@(?:GdpLaw|gdp\.law|gdp_law)\s*\(?\s*(?:value\s*=\s*)?"((?:[^"\\]|\\.)*)"/,
35
+ /#\[doc\s*=\s*"\s*gdp:\s*law\s+((?:[^"\\]|\\.)*)"\s*\]/,
36
+ /@(?:GdpLaw|gdp\.law|gdp_law)\s*\(?\s*'((?:[^'\\]|\\.)*)'/,
37
+ ];
38
+ export function lawsIn(text, where = '') {
39
+ const out = [];
40
+ text.split('\n').forEach((l, i) => {
41
+ for (const [k, re] of FORMS.entries()) {
42
+ const m = re.exec(l);
43
+ if (!m)
44
+ continue;
45
+ const body = k === 0 ? (m[2] ? `${m[1]}: ${m[2]}` : m[1]) : m[1].replace(/\\(.)/g, '$1').replace(/^\s*gdp:\s*law\s+/, '');
46
+ const c = body.indexOf(':');
47
+ out.push(c > 0 ? { name: body.slice(0, c).trim(), expr: body.slice(c + 1).trim(), where: `${where}:${i + 1}`, line: i + 1 } : { name: body.trim(), expr: '', where: `${where}:${i + 1}`, line: i + 1 });
48
+ break;
49
+ }
50
+ });
51
+ return out;
52
+ }
53
+ const WORDS = { '->': '.', '::': '.', and: '&&', or: '||', not: '!', implies: '=>', '∧': '&&', '∨': '||', '¬': '!', '→': '=>', '==>': '=>', '≤': '<=', '≥': '>=', '≠': '!=', '∀': 'forall', AND: '&&', OR: '||', NOT: '!' };
54
+ function tokens(s) {
55
+ const out = [], re = /\s*(f?"(?:[^"\\]|\\.)*"|f?'(?:[^'\\]|\\.)*'|`[^`]*`|\d+(?:\.\d+)?|@?[A-Za-z_][\w?]*|->|::|==>|=>|<=|>=|==|!=|&&|\|\||\/\/|[-+*%/<>()[\],.:!∧∨¬→≤≥≠∀])/y;
56
+ let m, at = 0;
57
+ while ((m = re.exec(s))) {
58
+ out.push(WORDS[m[1]] ?? m[1]);
59
+ at = re.lastIndex;
60
+ }
61
+ if (s.slice(at).trim())
62
+ throw new LawError(`can't read ${JSON.stringify(s.slice(at).trim())}`);
63
+ return out;
64
+ }
65
+ // Durations, as many seconds: linear over the clock (a day is 86,400 s: the request's time counts seconds, with no
66
+ // time zone, leap second or daylight saving). A month, a year, a business day or the end of a day isn't a fixed number
67
+ // of seconds, so a law reading one is refused: state it in days.
68
+ const SECONDS = { ms: 0.001, millisecond: 0.001, milliseconds: 0.001, second: 1, seconds: 1, sec: 1, secs: 1, minute: 60, minutes: 60, min: 60, mins: 60,
69
+ hour: 3600, hours: 3600, day: 86_400, days: 86_400, week: 604_800, weeks: 604_800 };
70
+ const NOT_LINEAR = /^(months?|years?|quarters?|business|working|weekdays?|fortnights?)$/i;
71
+ function seconds(unit) {
72
+ const u = unit.toLowerCase();
73
+ if (NOT_LINEAR.test(u))
74
+ throw new LawError(`${unit}: not a fixed number of seconds (a month or a year has several lengths, a business day depends on the calendar): state it in days, hours or seconds`);
75
+ return SECONDS[u];
76
+ }
77
+ // A duration in the clock's units ('s': time.time(), 'ms': Date.now()): duration('30 days') is 2,592,000.
78
+ export function duration(text, clock = 's') {
79
+ const m = /^\s*(\d+)\s*(?:calendar\s+)?([A-Za-z]+)(?:\s+days?)?\s*$/.exec(text);
80
+ if (!m)
81
+ throw new LawError(`${text}: a duration is a whole number and a unit (30 days, 15 minutes)`);
82
+ if (!Object.hasOwn(SECONDS, m[2].toLowerCase()) && !NOT_LINEAR.test(m[2]))
83
+ throw new LawError(`${m[2]}: a unit of ${Object.keys(SECONDS).join(', ')}`);
84
+ const v = Number(m[1]) * seconds(m[2]) * (clock === 'ms' ? 1000 : 1);
85
+ if (!Number.isInteger(v))
86
+ throw new LawError(`${text}: not a whole number of the clock's units`);
87
+ return v;
88
+ }
89
+ export function parse(s) {
90
+ const t = tokens(s);
91
+ let i = 0;
92
+ const peek = () => t[i], eat = (x) => { const v = t[i++]; if (x !== undefined && v !== x)
93
+ throw new LawError(`expected ${x} at ${JSON.stringify(v ?? 'the end')}`); return v; };
94
+ const operand = (p = t[i - 1]) => p !== undefined && /^[\w@"'`)\]]/.test(p) && !['&&', '||', '!', '=>', 'forall', 'in', 'is'].includes(p);
95
+ const top = () => {
96
+ if (peek() === 'forall' || peek() === 'all' && t[i + 2] === 'in') {
97
+ eat();
98
+ const v = eat();
99
+ eat('in');
100
+ const over = sum();
101
+ eat(':');
102
+ return { k: 'forall', v, over, body: top() };
103
+ }
104
+ const a = or();
105
+ return peek() === '=>' ? (eat(), { k: 'bin', op: '=>', a, b: top() }) : a;
106
+ };
107
+ // (a level of left-associative operators over the next level)
108
+ const left = (ops, next) => () => { let a = next(); while (ops.includes(peek())) {
109
+ const op = eat();
110
+ a = { k: 'bin', op, a, b: next() };
111
+ } return a; };
112
+ const or = left(['||'], () => and()), and = left(['&&'], () => neg());
113
+ const neg = () => (peek() === '!' ? (eat(), { k: 'un', op: 'not', x: neg() }) : cmp());
114
+ const cmp = () => {
115
+ const a = sum(), op = peek();
116
+ if (op === 'is') {
117
+ eat();
118
+ const n = peek() === '!' ? (eat(), true) : false;
119
+ const b = sum();
120
+ return n ? { k: 'un', op: 'not', x: { k: 'bin', op: '==', a, b } } : { k: 'bin', op: '==', a, b };
121
+ }
122
+ if (op === '!' && t[i + 1] === 'in') {
123
+ eat();
124
+ eat();
125
+ return { k: 'un', op: 'not', x: { k: 'bin', op: 'in', a, b: sum() } };
126
+ }
127
+ if (op && ['<', '<=', '>', '>=', '==', '!=', 'in'].includes(op)) {
128
+ eat();
129
+ return { k: 'bin', op, a, b: sum() };
130
+ }
131
+ return a;
132
+ };
133
+ const sum = left(['+', '-'], () => prod()), prod = left(['*', '//', '/', '%'], () => unary());
134
+ const unary = () => (peek() === '-' ? (eat(), { k: 'un', op: '-', x: unary() }) : atom());
135
+ const atom = () => {
136
+ const x = eat();
137
+ if (x === undefined)
138
+ throw new LawError('the expression ends early');
139
+ if (x === '(') {
140
+ const e = top();
141
+ eat(')');
142
+ return e;
143
+ }
144
+ if (/^\d/.test(x)) {
145
+ if (x.includes('.') && !/\.0+$/.test(x))
146
+ throw new LawError(`${x}: a number that isn't whole`);
147
+ // (a duration: 30 days, 15 minutes, in seconds until the clock's unit is known)
148
+ const u = peek()?.toLowerCase(), calendar = u === 'calendar' && /^days?$/i.test(t[i + 1] ?? '');
149
+ if (u && (calendar || Object.hasOwn(SECONDS, u) || NOT_LINEAR.test(u))) {
150
+ eat();
151
+ if (calendar)
152
+ eat();
153
+ return { k: 'dur', v: Number(x) * seconds(calendar ? 'days' : u), text: `${x} ${u}${calendar ? ' days' : ''}` };
154
+ }
155
+ return { k: 'num', v: Number(x) };
156
+ }
157
+ if (/^f?["'`]/.test(x))
158
+ return str(x);
159
+ if (x === ':' && /^[A-Za-z_]/.test(peek() ?? '') && !operand(t[i - 2]))
160
+ return { k: 'str', v: eat() };
161
+ if (['true', 'True'].includes(x))
162
+ return { k: 'bool', v: true };
163
+ if (['false', 'False'].includes(x))
164
+ return { k: 'bool', v: false };
165
+ if (['None', 'nil', 'null', 'undefined', 'NULL', 'nullptr'].includes(x))
166
+ return { k: 'null' };
167
+ if (!/^@?[A-Za-z_]/.test(x))
168
+ throw new LawError(`unexpected ${JSON.stringify(x)}`);
169
+ if (x === 'old' && peek() === '(') {
170
+ eat();
171
+ const e = top();
172
+ eat(')');
173
+ return { k: 'old', x: e };
174
+ }
175
+ if (['min', 'max', 'abs'].includes(x) && peek() === '(') {
176
+ eat();
177
+ const xs = [top()];
178
+ while (peek() === ',') {
179
+ eat();
180
+ xs.push(top());
181
+ }
182
+ eat(')');
183
+ return { k: 'fn', f: x, xs };
184
+ }
185
+ const p = { k: 'path', head: x, segs: [] };
186
+ for (;;) {
187
+ if (peek() === '.') {
188
+ eat();
189
+ p.segs.push({ f: eat() });
190
+ }
191
+ else if (peek() === '[') {
192
+ eat();
193
+ p.segs.push({ i: top() });
194
+ eat(']');
195
+ }
196
+ else if (peek() === '(') {
197
+ eat();
198
+ const from = i;
199
+ let d = 1;
200
+ while (d && i < t.length) {
201
+ const y = eat();
202
+ d += y === '(' ? 1 : y === ')' ? -1 : 0;
203
+ }
204
+ const inner = t.slice(from, i - 1).join('');
205
+ p.segs.push({ call: true, ...(inner && inner !== '...' ? { args: inner } : {}) });
206
+ }
207
+ else
208
+ break;
209
+ }
210
+ if ((p.head === 'before' || p.head === 'after') && p.segs.length && 'f' in p.segs[0]) {
211
+ const q = { k: 'path', head: p.segs[0].f, segs: p.segs.slice(1) };
212
+ return p.head === 'before' ? { k: 'old', x: q } : q;
213
+ }
214
+ return p;
215
+ };
216
+ // A string: a literal, or a template (f"rl:{k}", `rl:${k}`, "rl:#{k}") as its text and holes.
217
+ const str = (x) => {
218
+ const f = x.startsWith('f'), body = x.slice(f ? 2 : 1, -1);
219
+ const re = f ? /\{([^}]*)\}/g : x.startsWith('`') ? /\$\{([^}]*)\}/g : /#\{([^}]*)\}/g, parts = [], holes = [];
220
+ let last = 0;
221
+ for (const m of body.matchAll(re)) {
222
+ parts.push(body.slice(last, m.index));
223
+ holes.push(parse(m[1]));
224
+ last = m.index + m[0].length;
225
+ }
226
+ return holes.length ? { k: 'str', v: '', parts: [...parts, body.slice(last)], holes } : { k: 'str', v: body.replace(/\\(.)/g, '$1') };
227
+ };
228
+ const e = top();
229
+ if (i < t.length)
230
+ throw new LawError(`unexpected ${JSON.stringify(t[i])}`);
231
+ return e;
232
+ }
233
+ // The law a text states, built on the extraction's rule through its names.
234
+ // The extraction's names, with the request's time as `now` where the rule reads it and no name says so (a TypeScript
235
+ // class's Date.now()).
236
+ export function namesWithClock(x) {
237
+ const ns = x.names ?? [], ins = x.rule?.parts?.inputs.map(([n]) => n) ?? [];
238
+ return ns.some(n => n.role === 'clock') || !ins.includes('now') || ns.some(n => n.code === 'now') ? ns : [...ns, { code: 'now', rule: 'now', role: 'clock' }];
239
+ }
240
+ export function buildLaw(x, l, opts = {}) {
241
+ const names = namesWithClock(x), r = x.rule;
242
+ if (!r)
243
+ throw new LawError('the extraction has no rule');
244
+ if (!l.expr)
245
+ throw new LawError(`${l.name}: a law is stated as <name>: <expr>`);
246
+ const e = parse(l.expr);
247
+ // A first reading finds what the law reads: a request, a result, the failure or the state before make it a step law.
248
+ const probe = { b: {}, a: {}, step: true, method: l.method, keys: new Map(), roles: new Set(), methods: new Set(), clock: opts.clock };
249
+ read(e, probe, names, true);
250
+ // (a law on a method, the line above it, is a law of its step: the state after it, old(x) before)
251
+ const step = !!l.method || ['input', 'answer', 'result', 'failed', 'clock', 'method', 'old'].some(k => probe.roles.has(k));
252
+ const method = probe.methods.size === 1 ? [...probe.methods][0] : l.method;
253
+ if (probe.methods.size > 1)
254
+ throw new LawError(`it reads the arguments of ${[...probe.methods].join(' and ')}: a law of one step is about one method`);
255
+ const gate = step && method && names.some(n => n.role === 'method') ? method : undefined;
256
+ const body = (b, a) => read(e, { b, a, step, method, keys: new Map(), roles: new Set(), methods: new Set(), clock: opts.clock }, names, false);
257
+ if (!step)
258
+ return { kind: 'law', law: r.law(l.name, (env) => body(env, env)) };
259
+ const mname = names.find(n => n.role === 'method')?.rule;
260
+ return { kind: 'step', ...(gate ? { method: gate } : {}), law: r.stepLaw(l.name, (b, a) => body(b, a), gate ? (b) => b[mname].is(gate) : undefined) };
261
+ }
262
+ // The expression read: its value (`dry`: only which names it reads, nothing built).
263
+ function read(e, c, names, dry) {
264
+ if (e.k === 'forall') {
265
+ const over = val(e.over, c, names, dry);
266
+ if (over.t !== 'map')
267
+ throw new LawError(`forall ${e.v} in ...: over a map (a dict, a Map, a hash)`);
268
+ if (dry) {
269
+ c.keys.set(e.v, new Term({ op: 'const', value: 0 }));
270
+ return cond(val(e.body, c, names, true));
271
+ }
272
+ return forall(k => { c.keys.set(e.v, k); const m = (c.step ? c.a : c.b)[over.n.rule]; return m.at(k).has.implies(cond(val(e.body, c, names, false))); });
273
+ }
274
+ return cond(val(e, c, names, dry));
275
+ }
276
+ const cond = (v) => {
277
+ if (v.t === 'cond')
278
+ return v.v;
279
+ if (v.t === 'opt' && v.v?.t === 'cond')
280
+ return v.v.v;
281
+ throw new LawError(`a ${v.t === 'num' ? 'number' : v.t} where a condition is read`);
282
+ };
283
+ const num = (v) => {
284
+ if (v.t === 'num')
285
+ return v.v;
286
+ if (v.t === 'opt' && v.v?.t === 'num')
287
+ return v.v.v;
288
+ if (v.t === 'cell' && v.fields.length === 1)
289
+ return Int.of(v.rec[v.fields[0]]);
290
+ if (v.t === 'key')
291
+ return Int.of(v.v);
292
+ throw new LawError(`a ${v.t} where a number is read`);
293
+ };
294
+ // A value of the rule's environment as the law reads it.
295
+ const wrap = (x) => (x instanceof Int ? { t: 'num', v: x } : x instanceof Term ? { t: 'num', v: Int.of(x) } : x instanceof Choice ? { t: 'choice', v: x } : x instanceof Str ? { t: 'str', v: x } : { t: 'cond', v: x });
296
+ const DRY = { t: 'num', v: Int.of(0) };
297
+ function val(e, c, names, dry) {
298
+ const go = (x) => val(x, c, names, dry);
299
+ switch (e.k) {
300
+ case 'num': return { t: 'num', v: Int.of(e.v) };
301
+ case 'dur':
302
+ if (c.clock === undefined)
303
+ throw new LawError(`${e.text}: the clock's unit isn't known here (clock = "s" or "ms" in gdp.toml)`);
304
+ if (!Number.isInteger(e.v * c.clock))
305
+ throw new LawError(`${e.text}: not a whole number of the clock's units`);
306
+ return { t: 'num', v: Int.of(e.v * c.clock) };
307
+ case 'bool': return { t: 'cond', v: e.v ? yes : no };
308
+ case 'null': return { t: 'null' };
309
+ case 'str':
310
+ if (e.holes)
311
+ throw new LawError('a string template outside a store\'s key');
312
+ return { t: 'lit', v: e.v };
313
+ case 'old': {
314
+ c.roles.add('old');
315
+ return val(e.x, { ...c, a: c.b }, names, dry);
316
+ }
317
+ case 'fn': {
318
+ const xs = e.xs.map(go);
319
+ if (dry)
320
+ return DRY;
321
+ if (e.f === 'abs')
322
+ return { t: 'num', v: Int.of(num(xs[0]).abs) };
323
+ return { t: 'num', v: xs.slice(1).reduce((m, y) => (e.f === 'min' ? m.min(num(y)) : m.max(num(y))), num(xs[0])) };
324
+ }
325
+ case 'un': {
326
+ const v = go(e.x);
327
+ if (dry)
328
+ return v.t === 'cond' ? v : DRY;
329
+ return e.op === '-' ? { t: 'num', v: num(v).negate() } : { t: 'cond', v: not(cond(v)) };
330
+ }
331
+ case 'bin': {
332
+ if (e.op === 'in') {
333
+ const m = go(e.b);
334
+ if (m.t !== 'map')
335
+ throw new LawError('x in m: m a map');
336
+ const k = go(e.a);
337
+ return dry ? { t: 'cond', v: yes } : { t: 'cond', v: cellOf(m, key(k), c).rec.has };
338
+ }
339
+ // (a name the rule doesn't have, compared with a choice: the choice's value, Outcome.SLOW_ERROR)
340
+ const lit = (x) => { try {
341
+ return go(x);
342
+ }
343
+ catch (err) {
344
+ if (x.k !== 'path' || !(err instanceof LawError) || !['==', '!='].includes(e.op))
345
+ throw err;
346
+ return { t: 'lit', v: lastName(x) ?? '', err };
347
+ } };
348
+ const a = lit(e.a), b = lit(e.b);
349
+ if (a.t === 'lit' && a.err && b.t === 'lit' && b.err)
350
+ throw a.err;
351
+ if (['&&', '||', '=>'].includes(e.op))
352
+ return dry ? { t: 'cond', v: yes } : { t: 'cond', v: e.op === '&&' ? all(cond(a), cond(b)) : e.op === '||' ? any(cond(a), cond(b)) : cond(a).implies(cond(b)) };
353
+ if (dry)
354
+ return ['+', '-', '*', '//', '/', '%'].includes(e.op) ? DRY : { t: 'cond', v: yes };
355
+ if (e.op === '+' || e.op === '-')
356
+ return { t: 'num', v: e.op === '+' ? num(a).plus(num(b)) : num(a).minus(num(b)) };
357
+ if (e.op === '*') {
358
+ const k = constOf(e.a) ?? constOf(e.b);
359
+ if (k === undefined)
360
+ throw new LawError('× by a constant only (a product of two values is outside linear arithmetic)');
361
+ return { t: 'num', v: num(constOf(e.a) === undefined ? a : b).times(k) };
362
+ }
363
+ if (e.op === '//' || e.op === '/' || e.op === '%') {
364
+ const k = constOf(e.b);
365
+ if (!k || k < 1)
366
+ throw new LawError(`${e.op} by a positive constant only`);
367
+ return e.op === '%' ? { t: 'num', v: Int.of(num(a).modBy(k)) } : { t: 'num', v: num(a).divBy(k) };
368
+ }
369
+ return { t: 'cond', v: compare(e.op, a, b, e) };
370
+ }
371
+ case 'path': return path(e, c, names, dry);
372
+ case 'forall': return fail('forall ... in ...: at the top of the law only');
373
+ }
374
+ return fail('an expression of no kind');
375
+ }
376
+ // (a path's last name: a choice's value written as one, Outcome.SLOW_ERROR)
377
+ const lastName = (x) => (x.segs.length ? x.segs.at(-1).f : x.head);
378
+ const constOf = (x) => (x.k === 'num' ? x.v : x.k === 'un' && x.op === '-' && x.x.k === 'num' ? -x.x.v : undefined);
379
+ function compare(op, a, b, e) {
380
+ if (b.t === 'null' || a.t === 'null') {
381
+ const o = a.t === 'null' ? b : a, none = o.t === 'opt' ? o.none : o.t === 'cell' ? not(o.rec.has) : undefined;
382
+ if (!none)
383
+ throw new LawError(`${show(a.t === 'null' ? e.b : e.a)} is never None here (the rule holds no None for it)`);
384
+ return op === '==' ? none : op === '!=' ? not(none) : fail(`${op} with None`);
385
+ }
386
+ const un = (v) => (v.t === 'opt' && v.v ? v.v : v);
387
+ a = un(a);
388
+ b = un(b);
389
+ // (a name the rule doesn't have is a choice's value only beside a choice)
390
+ for (const [v, o] of [[a, b], [b, a]])
391
+ if (v.t === 'lit' && v.err && o.t !== 'choice')
392
+ throw v.err;
393
+ const eq = (c) => (op === '==' ? c : op === '!=' ? not(c) : fail(`${op} of values that aren't numbers`));
394
+ if (a.t === 'choice' || b.t === 'choice') {
395
+ const [ch, o, ox] = a.t === 'choice' ? [a.v, b, e.b] : [b.v, a, e.a];
396
+ if (o.t === 'choice')
397
+ return eq(ch.eq(o.v));
398
+ const lit = o.t === 'lit' ? o.v : ox.k === 'path' ? lastName(ox) : undefined;
399
+ if (lit === undefined || !ch.values.includes(lit))
400
+ throw new LawError(`${show(ox)} isn't one of ${ch.values.join(', ')}`);
401
+ return eq(ch.is(lit));
402
+ }
403
+ if (a.t === 'str' || b.t === 'str') {
404
+ const [s, o] = a.t === 'str' ? [a.v, b] : [b.v, a];
405
+ return eq(o.t === 'str' ? s.eq(o.v) : o.t === 'lit' ? s.eq(o.v) : fail('a string compared with what isn\'t one'));
406
+ }
407
+ if (a.t === 'cond' && b.t === 'cond')
408
+ return eq(a.v.iff(b.v));
409
+ const x = num(a), y = num(b);
410
+ return op === '<' ? x.lt(y) : op === '<=' ? x.atMost(y) : op === '>' ? x.gt(y) : op === '>=' ? x.atLeast(y) : op === '==' ? x.eq(y) : x.ne(y);
411
+ }
412
+ const fail = (s) => { throw new LawError(s); };
413
+ const show = (x) => (x.k === 'path' ? [x.head, ...x.segs.map(s => ('f' in s ? `.${s.f}` : 'i' in s ? '[...]' : '(...)'))].join('') : x.k === 'str' ? JSON.stringify(x.v) : x.k);
414
+ // A map's key as the rule holds it: a string's id, a natural.
415
+ const key = (k) => (k.t === 'opt' && k.v ? key(k.v) : k.t === 'key' ? k.v : k.t === 'str' ? k.v.id : k.t === 'lit' ? fail('a literal key (the rule keys a map by the request\'s values)') : (() => { const n = num(k); return n.neg.e.op === 'const' && n.neg.e.value === 0 ? n.pos : n.clamped; })());
416
+ function cellOf(m, k, c) {
417
+ const map = (c.a[m.n.rule] ?? c.b[m.n.rule]);
418
+ return { rec: map.at(k), fields: m.n.map.fields };
419
+ }
420
+ // A path: the longest prefix of it the code names (in the law's method first: its arguments shadow the fields, as in the
421
+ // code), then its fields, keys and calls.
422
+ function path(e, c, names, dry) {
423
+ if (c.keys.has(e.head) && !e.segs.length)
424
+ return { t: 'key', v: c.keys.get(e.head) };
425
+ if (e.head === 'result' || e.head === 'failed') {
426
+ const n = e.head === 'failed' ? names.find(x => x.role === 'failed') : results(names, c);
427
+ if (!n)
428
+ throw new LawError(e.head === 'failed' ? 'the rule keeps no failure (with failures: \'kept\' it does: `failures = "kept"` in gdp.toml or --failures kept)' : 'the method returns nothing the rule keeps');
429
+ c.roles.add(n.role);
430
+ if (n.method)
431
+ c.methods.add(n.method);
432
+ return rest(e.segs, leaf(n, c, dry), c, names, dry, e);
433
+ }
434
+ const explicit = ['self', 'this', 'state', 's'].includes(e.head) || e.head.startsWith('@');
435
+ const parts = [e.head.replace(/^@/, ''), ...e.segs.map(s => ('f' in s ? s.f : undefined))];
436
+ const heads = explicit && !e.head.startsWith('@') ? [parts.slice(1)] : [parts, ...(parts.length > 1 && parts[1] !== undefined ? [parts.slice(1)] : [])];
437
+ for (const [hi, p] of heads.entries()) {
438
+ const fields = [];
439
+ for (const s of p) {
440
+ if (s === undefined)
441
+ break;
442
+ fields.push(s);
443
+ }
444
+ const skip = parts.length - p.length;
445
+ for (let n = fields.length; n > 0; n--) {
446
+ const code = fields.slice(0, n).join('.'), next = e.segs[skip + n - 1];
447
+ const hit = find(code, names, c, explicit || hi > 0, next !== undefined && 'call' in next);
448
+ if (hit) {
449
+ c.roles.add(hit.role);
450
+ if (hit.method)
451
+ c.methods.add(hit.method);
452
+ // (an answered call is one value a step, whatever its arguments: written f(...) or f())
453
+ if (hit.role === 'answer' && next && 'call' in next && next.args)
454
+ throw new LawError(`${code}(${next.args}): an answered call's value is the request's, one a step: write it ${code}(...)`);
455
+ const segs = e.segs.slice(skip + n - 1 + (hit.role === 'answer' && next && 'call' in next ? 1 : 0));
456
+ return rest(segs, hit.map ? { t: 'map', n: hit, maps: names.filter(x => x.map && x.code === hit.code) } : leaf(hit, c, dry), c, names, dry, e);
457
+ }
458
+ }
459
+ }
460
+ // A method's argument by its method's name (charge.user), where several methods take one of that name.
461
+ const m = names.find(n => n.role === 'input' && n.method === e.head && e.segs[0] && 'f' in e.segs[0] && n.code === e.segs[0].f);
462
+ if (m) {
463
+ c.roles.add('input');
464
+ c.methods.add(m.method);
465
+ return rest(e.segs.slice(1), leaf(m, c, dry), c, names, dry, e);
466
+ }
467
+ const known = [...new Set(names.filter(n => n.rule || n.none).map(n => (n.role === 'answer' ? `${n.code.split('.').pop()}()` : n.method && n.role === 'input' ? `${n.code} (${n.method})` : n.code)))];
468
+ throw new LawError(`no ${show(e)} in the rule (its names: ${known.join(', ')})`);
469
+ }
470
+ // The name a code path is: the law's method's argument, a field of the state, a constructor's argument, an answered
471
+ // call (by its callee's last name), the rule's own name (as printed).
472
+ function find(code, names, c, stateOnly, called) {
473
+ const last = (n) => n.code.split('.').pop() === code.split('.').pop() && (code.split('.').length === 1 || n.code.endsWith(code));
474
+ const at = (n) => n.code.replace(/^@/, '') === code;
475
+ const inputs = names.filter(n => n.role === 'input' && n.code === code);
476
+ if (!stateOnly && !called && inputs.length) {
477
+ const here = inputs.filter(n => n.method === c.method);
478
+ if (here.length)
479
+ return here[0];
480
+ if (new Set(inputs.map(n => n.method)).size === 1)
481
+ return inputs[0];
482
+ throw new LawError(`${code} is an argument of ${inputs.map(n => n.method).join(', ')}: write the law on the method it is about (the line above it), or as <method>.${code}`);
483
+ }
484
+ return names.find(n => n.role === 'state' && at(n) && !called)
485
+ ?? (stateOnly ? undefined : names.find(n => (n.role === 'param' || n.role === 'const' || n.role === 'clock') && n.code === code && !called))
486
+ ?? names.find(n => n.role === 'answer' && last(n))
487
+ ?? (stateOnly ? undefined : names.find(n => n.rule === code && !called));
488
+ }
489
+ const results = (names, c) => {
490
+ const rs = names.filter(n => n.role === 'result' && n.code === 'result');
491
+ const r = rs.find(n => n.method === c.method) ?? (rs.length === 1 ? rs[0] : undefined);
492
+ if (!r && rs.length > 1)
493
+ throw new LawError(`result: of ${rs.map(n => n.method).join(', ')}: write the law on the method it is about (the line above it)`);
494
+ return r;
495
+ };
496
+ // A name's value: its variable in the environment (the state after the step where the law is a step's), its None-ness.
497
+ function leaf(n, c, dry) {
498
+ if (dry)
499
+ return n.none && !n.rule ? { t: 'opt', none: yes } : n.none ? { t: 'opt', none: yes, v: DRY } : DRY;
500
+ if (n.role === 'const')
501
+ return { t: 'num', v: Int.of(n.value) };
502
+ const env = c.step && (n.role === 'state' || n.role === 'result' || n.role === 'failed') ? c.a : c.b;
503
+ const get = (r) => { if (!(r in env) && !(r in c.b))
504
+ throw new LawError(`${n.code}: ${r} isn't in the rule's environment here`); return r in env ? env[r] : c.b[r]; };
505
+ const v = n.rule ? wrap(get(n.rule)) : undefined;
506
+ return n.none ? { t: 'opt', none: get(n.none), ...(v ? { v } : {}) } : v;
507
+ }
508
+ // The rest of a path: a map at a key (m[k], m.get(k)), a cell's field, has/contains/key? of a map.
509
+ function rest(segs, v, c, names, dry, e) {
510
+ for (let i = 0; i < segs.length; i++) {
511
+ const s = segs[i];
512
+ if (v.t === 'map') {
513
+ const isGet = 'f' in s && ['get', 'fetch', 'getOrDefault', 'lookup'].includes(s.f) && segs[i + 1] && 'call' in segs[i + 1];
514
+ const isHas = 'f' in s && ['has', 'contains', 'containsKey', 'has_key', 'key?', 'has_key?', 'include?'].includes(s.f);
515
+ if (isGet || isHas)
516
+ throw new LawError(`${show(e)}: write the key in brackets (m[k], or k in m)`);
517
+ if (!('i' in s))
518
+ throw new LawError(`${show(e)}: a map is read at a key (m[k])`);
519
+ const [m, k] = storeKey(v, s.i, c, names, dry);
520
+ if (dry) {
521
+ v = DRY;
522
+ continue;
523
+ }
524
+ const cell = cellOf(m, key(k), c);
525
+ v = { t: 'cell', ...cell };
526
+ continue;
527
+ }
528
+ if (v.t === 'cell' && 'f' in s) {
529
+ if (!v.fields.includes(s.f))
530
+ throw new LawError(`${show(e)}: its cells have ${v.fields.join(', ')}`);
531
+ v = wrap(v.rec[s.f]);
532
+ continue;
533
+ }
534
+ if (dry)
535
+ continue;
536
+ throw new LawError(`${show(e)}: can't read ${'f' in s ? `.${s.f}` : 'i' in s ? '[...]' : '(...)'} of a ${v.t}`);
537
+ }
538
+ return v;
539
+ }
540
+ // A store's map by its key's template ("hits:" + s, f"hits:{s}"), and the key's value; any other map at the key read.
541
+ function storeKey(m, k, c, names, dry) {
542
+ if (!m.n.map?.store)
543
+ return [m, val(k, c, names, dry)];
544
+ const parts = [], holes = [];
545
+ const flat = (x) => { if (x.k === 'bin' && x.op === '+') {
546
+ flat(x.a);
547
+ flat(x.b);
548
+ }
549
+ else if (x.k === 'str' && !x.holes)
550
+ parts.push(x.v);
551
+ else if (x.k === 'str') {
552
+ x.parts.forEach((p, i) => { parts.push(p); if (x.holes[i]) {
553
+ holes.push(x.holes[i]);
554
+ parts.push('{}');
555
+ } });
556
+ }
557
+ else {
558
+ holes.push(x);
559
+ parts.push('{}');
560
+ } };
561
+ flat(k);
562
+ const tpl = parts.join('');
563
+ const hit = m.maps.find(x => x.map.tpl === tpl) ?? (holes.length === 1 && tpl === '{}' && m.maps.length === 1 ? m.maps[0] : undefined);
564
+ if (!hit || holes.length !== 1)
565
+ throw new LawError(`${m.n.code}[${tpl}]: its keys are ${m.maps.map(x => JSON.stringify(x.map.tpl.replace('{}', '<key>'))).join(', ')}`);
566
+ return [{ t: 'map', n: hit, maps: [hit] }, val(holes[0], c, names, dry)];
567
+ }
568
+ const CITE = /(?:#|\/\/|--|%|\/\*|^\s*\*)\s*gdp:\s*cite\s+([^:]+?)\s*:\s*(.+?)\s*(?:\*\/)?\s*$/;
569
+ export function citesIn(text, where = '') {
570
+ return text.split('\n').flatMap((l, i) => { const m = CITE.exec(l); return m ? [{ law: m[1].trim(), text: m[2], where: `${where}:${i + 1}` }] : []; });
571
+ }
572
+ // --- laws about two runs -------------------------------------------------------------------------------------------------
573
+ // Three forms of a stated law (core/relational.ts), over the code's names:
574
+ // <secret>[, ...] never reaches <visible>[, ...] noninterference: the secret arguments (or params, answers) never
575
+ // change the visible fields or results, nor which calls fail
576
+ // isolated by <owner> [seeing <name>[, ...]] isolation: what the caller whose <owner> argument is B sees (the
577
+ // maps' cells at B, the results of B's calls, B's failures) is the
578
+ // same whatever the other callers do; by default every map, result
579
+ // agrees with <Entry> [on <name>[, ...]] a migration: this rule and <Entry> (another rule of the same
580
+ // target) keep the same fields after the same calls, fail alike
581
+ const TWO = [/^(.+?)\s+never\s+reach(?:es)?\s+(.+)$/i, /^isolated\s+by\s+([\w.]+)(?:\s+seeing\s+(.+))?$/i, /^agrees\s+with\s+([\w.]+)(?:\s+on\s+(.+))?$/i];
582
+ export const isTwoRuns = (expr) => TWO.some(re => re.test(expr.trim()));
583
+ const list = (s) => (s ? s.split(/\s*,\s*|\s+and\s+/).map(x => x.trim()).filter(Boolean) : []);
584
+ export function buildTwoRuns(x, l, others = {}) {
585
+ const names = namesWithClock(x), e = l.expr.trim(), r = x.rule;
586
+ if (!r)
587
+ throw new LawError('the extraction has no rule');
588
+ const known = () => [...new Set(names.filter(n => n.rule).map(n => n.code))].join(', ');
589
+ const ruleNames = (ns, code, roles, what) => {
590
+ const hit = ns.filter(n => n.code.replace(/^@/, '') === code.replace(/^(self|this)\./, '') && roles.includes(n.role));
591
+ if (!hit.length)
592
+ throw new LawError(`no ${code} ${what} (its names: ${known()})`);
593
+ return [...new Set(hit.flatMap(n => [n.rule, ...(n.none ? [n.none] : [])]).filter(Boolean))];
594
+ };
595
+ const STATE = ['state', 'result', 'failed'];
596
+ let m = TWO[0].exec(e);
597
+ if (m) {
598
+ const secret = list(m[1]).flatMap(c => ruleNames(names, c, ['input', 'param', 'answer', 'clock'], 'among the arguments, params or answered calls'));
599
+ const visible = list(m[2]).flatMap(c => ruleNames(names, c, STATE, 'among the fields and results'));
600
+ return { ...noninterference(r, { secret, visible, name: l.name }), name: l.name };
601
+ }
602
+ if ((m = TWO[1].exec(e))) {
603
+ const owners = names.filter(n => n.role === 'input' && n.code === m[1] && n.rule);
604
+ if (!owners.length)
605
+ throw new LawError(`no argument ${m[1]} (its names: ${known()})`);
606
+ const method = names.find(n => n.role === 'method')?.rule, methods = new Set(owners.map(n => n.method));
607
+ const key = (v) => (v instanceof Term ? v : v instanceof Int ? v.pos : v.id);
608
+ // (a call is B's where its method takes the owner argument and it is B; with one rule input for every method, that)
609
+ const owner = (env, b) => any(...owners.map(n => all(key(env[n.rule]).eq(b), ...(method && methods.size && n.method ? [env[method].is(n.method)] : []))));
610
+ const seen = m[2] ? list(m[2]).flatMap(c => ruleNames(names, c, STATE, 'among the fields and results')) : undefined;
611
+ const maps = new Set(names.filter(n => n.map).map(n => n.rule));
612
+ const sees = seen?.filter(n => maps.has(n)), results = seen ? seen.filter(n => !maps.has(n)) : names.filter(n => n.role === 'result' || n.role === 'failed').flatMap(n => [n.rule, ...(n.none ? [n.none] : [])]).filter(Boolean);
613
+ return { ...isolation(r, { owner, ...(sees ? { sees } : {}), results: [...new Set(results)], name: l.name }), name: l.name };
614
+ }
615
+ if ((m = TWO[2].exec(e))) {
616
+ const o = others[m[1]];
617
+ if (!o?.rule)
618
+ throw new LawError(`no rule ${m[1]} read beside this one (${Object.keys(others).join(', ') || 'none'}): agrees with names another class of the same target`);
619
+ const visible = m[2] ? list(m[2]).flatMap(c => { const mine = ruleNames(names, c, STATE, 'among the fields and results'); ruleNames(o.names ?? [], c, STATE, `in ${m[1]}`); return mine; }) : undefined;
620
+ return { ...agreement(o.rule, r, { ...(visible ? { visible } : {}), name: l.name }), name: l.name };
621
+ }
622
+ throw new LawError('not a law about two runs');
623
+ }
@@ -205,6 +205,8 @@ export declare const pairE: (a: E, b: E) => E;
205
205
  export declare const argsKey: (args: E[]) => E;
206
206
  export declare function pairedArgs(key: E, n: number): E[] | undefined;
207
207
  export declare function evalC(c: C, env: Env, st: State, m: Machine): boolean;
208
+ export declare function compileE(e: E, m: Machine): (env: Env, st: State) => number;
209
+ export declare function compileC(c: C, m: Machine): (env: Env, st: State) => boolean;
208
210
  export declare function carriedView(m: Machine, st: State, input: Request, rename?: (map: string) => string): State;
209
211
  export declare const numbersOf: (input: Request) => Record<string, number>;
210
212
  export declare function interpret(m: Machine): {