gdp-wired 0.31.0 → 0.32.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +82 -6
- package/dist/core/c/reader.d.ts +86 -0
- package/dist/core/c/reader.js +860 -0
- package/dist/core/cli.d.ts +66 -0
- package/dist/core/cli.js +582 -0
- package/dist/core/dsl.d.ts +4 -2
- package/dist/core/dsl.js +22 -12
- package/dist/core/effect.d.ts +6 -4
- package/dist/core/effect.js +48 -10
- package/dist/core/ex/harness.exs +177 -0
- package/dist/core/ex/json.exs +46 -0
- package/dist/core/ex/reader.exs +462 -0
- package/dist/core/exists.d.ts +3 -0
- package/dist/core/exists.js +3 -1
- package/dist/core/extract-c.d.ts +35 -0
- package/dist/core/extract-c.js +424 -0
- package/dist/core/extract-check.js +27 -6
- package/dist/core/extract-ex.d.ts +16 -0
- package/dist/core/extract-ex.js +33 -0
- package/dist/core/extract-go-check.d.ts +28 -0
- package/dist/core/extract-go-check.js +639 -0
- package/dist/core/extract-go.d.ts +231 -0
- package/dist/core/extract-go.js +1166 -0
- package/dist/core/extract-jvm.d.ts +23 -0
- package/dist/core/extract-jvm.js +220 -0
- package/dist/core/extract-print.js +17 -7
- package/dist/core/extract-py.d.ts +15 -0
- package/dist/core/extract-py.js +31 -0
- package/dist/core/extract-rb.d.ts +17 -0
- package/dist/core/extract-rb.js +31 -0
- package/dist/core/extract-read.d.ts +20 -0
- package/dist/core/extract-read.js +46 -6
- package/dist/core/extract-rs.d.ts +12 -0
- package/dist/core/extract-rs.js +306 -0
- package/dist/core/extract-shapes.d.ts +2 -0
- package/dist/core/extract-shapes.js +6 -5
- package/dist/core/extract-step.d.ts +806 -0
- package/dist/core/extract-step.js +4141 -0
- package/dist/core/extract-swift.d.ts +27 -0
- package/dist/core/extract-swift.js +484 -0
- package/dist/core/extract-xstate.d.ts +10 -3
- package/dist/core/extract-xstate.js +50 -4
- package/dist/core/extract.d.ts +22 -3
- package/dist/core/extract.js +107 -18
- package/dist/core/go/go.mod +3 -0
- package/dist/core/go/reader.go +901 -0
- package/dist/core/infer.js +1770 -52
- package/dist/core/jvm/Harness.java +361 -0
- package/dist/core/jvm/JavaReader.java +825 -0
- package/dist/core/jvm/Jvm.java +332 -0
- package/dist/core/jvm/KtReader.java +960 -0
- package/dist/core/jvm/Rt.java +10 -0
- package/dist/core/laws.d.ts +66 -0
- package/dist/core/laws.js +522 -0
- package/dist/core/py/harness.py +328 -0
- package/dist/core/py/reader.py +447 -0
- package/dist/core/rb/harness.rb +233 -0
- package/dist/core/rb/reader.rb +375 -0
- package/dist/core/rs/Cargo.lock +108 -0
- package/dist/core/rs/Cargo.toml +14 -0
- package/dist/core/rs/src/main.rs +681 -0
- package/dist/core/swift/Harness.swift +124 -0
- package/dist/core/swift/Main.swift +34 -0
- package/dist/core/swift/Package.swift +13 -0
- package/dist/core/swift/Sources/gdp-swiftreader/main.swift +1341 -0
- package/dist/kernel/cdcl.js +43 -18
- package/dist/kernel/epr.d.ts +35 -0
- package/dist/kernel/epr.js +1676 -0
- package/dist/kernel/prove.d.ts +44 -0
- package/dist/kernel/prove.js +668 -54
- package/dist/lean-kernel/emit.d.ts +1 -0
- package/dist/lean-kernel/emit.js +21 -4
- package/package.json +53 -6
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// What the check's copy of the code calls where the original reads the clock or makes a call the caller answered
|
|
2
|
+
// (core/extract-jvm.ts rewrites those sites): the request's time and the request's answer, set by core/jvm/Harness.java.
|
|
3
|
+
package gdp;
|
|
4
|
+
|
|
5
|
+
public final class Rt {
|
|
6
|
+
public static volatile long NOW;
|
|
7
|
+
public static java.util.function.BiFunction<String, Class<?>, Object> ANSWER = (k, c) -> null;
|
|
8
|
+
public static long now() { return NOW; }
|
|
9
|
+
public static Object answer(String key, Class<?> c) { return ANSWER.apply(key, c); }
|
|
10
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import type { Extraction } from './extract.js';
|
|
2
|
+
export type LawText = {
|
|
3
|
+
name: string;
|
|
4
|
+
expr: string;
|
|
5
|
+
where?: string;
|
|
6
|
+
line?: number;
|
|
7
|
+
method?: string;
|
|
8
|
+
};
|
|
9
|
+
export type Built = {
|
|
10
|
+
kind: 'law' | 'step';
|
|
11
|
+
law: any;
|
|
12
|
+
method?: string;
|
|
13
|
+
};
|
|
14
|
+
export declare class LawError extends Error {
|
|
15
|
+
}
|
|
16
|
+
export declare function lawsIn(text: string, where?: string): LawText[];
|
|
17
|
+
type Seg = {
|
|
18
|
+
f: string;
|
|
19
|
+
} | {
|
|
20
|
+
i: X;
|
|
21
|
+
} | {
|
|
22
|
+
call: true;
|
|
23
|
+
args?: string;
|
|
24
|
+
};
|
|
25
|
+
type X = {
|
|
26
|
+
k: 'num';
|
|
27
|
+
v: number;
|
|
28
|
+
} | {
|
|
29
|
+
k: 'str';
|
|
30
|
+
v: string;
|
|
31
|
+
holes?: X[];
|
|
32
|
+
parts?: string[];
|
|
33
|
+
} | {
|
|
34
|
+
k: 'bool';
|
|
35
|
+
v: boolean;
|
|
36
|
+
} | {
|
|
37
|
+
k: 'null';
|
|
38
|
+
} | {
|
|
39
|
+
k: 'path';
|
|
40
|
+
head: string;
|
|
41
|
+
segs: Seg[];
|
|
42
|
+
} | {
|
|
43
|
+
k: 'un';
|
|
44
|
+
op: '-' | 'not';
|
|
45
|
+
x: X;
|
|
46
|
+
} | {
|
|
47
|
+
k: 'bin';
|
|
48
|
+
op: string;
|
|
49
|
+
a: X;
|
|
50
|
+
b: X;
|
|
51
|
+
} | {
|
|
52
|
+
k: 'old';
|
|
53
|
+
x: X;
|
|
54
|
+
} | {
|
|
55
|
+
k: 'fn';
|
|
56
|
+
f: string;
|
|
57
|
+
xs: X[];
|
|
58
|
+
} | {
|
|
59
|
+
k: 'forall';
|
|
60
|
+
v: string;
|
|
61
|
+
over: X;
|
|
62
|
+
body: X;
|
|
63
|
+
};
|
|
64
|
+
export declare function parse(s: string): X;
|
|
65
|
+
export declare function buildLaw(x: Extraction, l: LawText): Built;
|
|
66
|
+
export {};
|
|
@@ -0,0 +1,522 @@
|
|
|
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
|
+
export class LawError extends Error {
|
|
28
|
+
}
|
|
29
|
+
// --- reading the code's text -------------------------------------------------------------------------------------------
|
|
30
|
+
// Every law stated in a file's text, with its line.
|
|
31
|
+
const FORMS = [
|
|
32
|
+
/(?:#|\/\/|--|%|\/\*|^\s*\*)\s*gdp:\s*law\s+([^:]+?)\s*(?::\s*(.+?))?\s*(?:\*\/)?\s*$/,
|
|
33
|
+
/@(?:GdpLaw|gdp\.law|gdp_law)\s*\(?\s*(?:value\s*=\s*)?"((?:[^"\\]|\\.)*)"/,
|
|
34
|
+
/#\[doc\s*=\s*"\s*gdp:\s*law\s+((?:[^"\\]|\\.)*)"\s*\]/,
|
|
35
|
+
/@(?:GdpLaw|gdp\.law|gdp_law)\s*\(?\s*'((?:[^'\\]|\\.)*)'/,
|
|
36
|
+
];
|
|
37
|
+
export function lawsIn(text, where = '') {
|
|
38
|
+
const out = [];
|
|
39
|
+
text.split('\n').forEach((l, i) => {
|
|
40
|
+
for (const [k, re] of FORMS.entries()) {
|
|
41
|
+
const m = re.exec(l);
|
|
42
|
+
if (!m)
|
|
43
|
+
continue;
|
|
44
|
+
const body = k === 0 ? (m[2] ? `${m[1]}: ${m[2]}` : m[1]) : m[1].replace(/\\(.)/g, '$1').replace(/^\s*gdp:\s*law\s+/, '');
|
|
45
|
+
const c = body.indexOf(':');
|
|
46
|
+
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 });
|
|
47
|
+
break;
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
52
|
+
const WORDS = { '->': '.', '::': '.', and: '&&', or: '||', not: '!', implies: '=>', '∧': '&&', '∨': '||', '¬': '!', '→': '=>', '==>': '=>', '≤': '<=', '≥': '>=', '≠': '!=', '∀': 'forall', AND: '&&', OR: '||', NOT: '!' };
|
|
53
|
+
function tokens(s) {
|
|
54
|
+
const out = [], re = /\s*(f?"(?:[^"\\]|\\.)*"|f?'(?:[^'\\]|\\.)*'|`[^`]*`|\d+(?:\.\d+)?|@?[A-Za-z_][\w?]*|->|::|==>|=>|<=|>=|==|!=|&&|\|\||\/\/|[-+*%/<>()[\],.:!∧∨¬→≤≥≠∀])/y;
|
|
55
|
+
let m, at = 0;
|
|
56
|
+
while ((m = re.exec(s))) {
|
|
57
|
+
out.push(WORDS[m[1]] ?? m[1]);
|
|
58
|
+
at = re.lastIndex;
|
|
59
|
+
}
|
|
60
|
+
if (s.slice(at).trim())
|
|
61
|
+
throw new LawError(`can't read ${JSON.stringify(s.slice(at).trim())}`);
|
|
62
|
+
return out;
|
|
63
|
+
}
|
|
64
|
+
export function parse(s) {
|
|
65
|
+
const t = tokens(s);
|
|
66
|
+
let i = 0;
|
|
67
|
+
const peek = () => t[i], eat = (x) => { const v = t[i++]; if (x !== undefined && v !== x)
|
|
68
|
+
throw new LawError(`expected ${x} at ${JSON.stringify(v ?? 'the end')}`); return v; };
|
|
69
|
+
const operand = (p = t[i - 1]) => p !== undefined && /^[\w@"'`)\]]/.test(p) && !['&&', '||', '!', '=>', 'forall', 'in', 'is'].includes(p);
|
|
70
|
+
const top = () => {
|
|
71
|
+
if (peek() === 'forall' || peek() === 'all' && t[i + 2] === 'in') {
|
|
72
|
+
eat();
|
|
73
|
+
const v = eat();
|
|
74
|
+
eat('in');
|
|
75
|
+
const over = sum();
|
|
76
|
+
eat(':');
|
|
77
|
+
return { k: 'forall', v, over, body: top() };
|
|
78
|
+
}
|
|
79
|
+
const a = or();
|
|
80
|
+
return peek() === '=>' ? (eat(), { k: 'bin', op: '=>', a, b: top() }) : a;
|
|
81
|
+
};
|
|
82
|
+
// (a level of left-associative operators over the next level)
|
|
83
|
+
const left = (ops, next) => () => { let a = next(); while (ops.includes(peek())) {
|
|
84
|
+
const op = eat();
|
|
85
|
+
a = { k: 'bin', op, a, b: next() };
|
|
86
|
+
} return a; };
|
|
87
|
+
const or = left(['||'], () => and()), and = left(['&&'], () => neg());
|
|
88
|
+
const neg = () => (peek() === '!' ? (eat(), { k: 'un', op: 'not', x: neg() }) : cmp());
|
|
89
|
+
const cmp = () => {
|
|
90
|
+
const a = sum(), op = peek();
|
|
91
|
+
if (op === 'is') {
|
|
92
|
+
eat();
|
|
93
|
+
const n = peek() === '!' ? (eat(), true) : false;
|
|
94
|
+
const b = sum();
|
|
95
|
+
return n ? { k: 'un', op: 'not', x: { k: 'bin', op: '==', a, b } } : { k: 'bin', op: '==', a, b };
|
|
96
|
+
}
|
|
97
|
+
if (op === '!' && t[i + 1] === 'in') {
|
|
98
|
+
eat();
|
|
99
|
+
eat();
|
|
100
|
+
return { k: 'un', op: 'not', x: { k: 'bin', op: 'in', a, b: sum() } };
|
|
101
|
+
}
|
|
102
|
+
if (op && ['<', '<=', '>', '>=', '==', '!=', 'in'].includes(op)) {
|
|
103
|
+
eat();
|
|
104
|
+
return { k: 'bin', op, a, b: sum() };
|
|
105
|
+
}
|
|
106
|
+
return a;
|
|
107
|
+
};
|
|
108
|
+
const sum = left(['+', '-'], () => prod()), prod = left(['*', '//', '/', '%'], () => unary());
|
|
109
|
+
const unary = () => (peek() === '-' ? (eat(), { k: 'un', op: '-', x: unary() }) : atom());
|
|
110
|
+
const atom = () => {
|
|
111
|
+
const x = eat();
|
|
112
|
+
if (x === undefined)
|
|
113
|
+
throw new LawError('the expression ends early');
|
|
114
|
+
if (x === '(') {
|
|
115
|
+
const e = top();
|
|
116
|
+
eat(')');
|
|
117
|
+
return e;
|
|
118
|
+
}
|
|
119
|
+
if (/^\d/.test(x)) {
|
|
120
|
+
if (x.includes('.') && !/\.0+$/.test(x))
|
|
121
|
+
throw new LawError(`${x}: a number that isn't whole`);
|
|
122
|
+
return { k: 'num', v: Number(x) };
|
|
123
|
+
}
|
|
124
|
+
if (/^f?["'`]/.test(x))
|
|
125
|
+
return str(x);
|
|
126
|
+
if (x === ':' && /^[A-Za-z_]/.test(peek() ?? '') && !operand(t[i - 2]))
|
|
127
|
+
return { k: 'str', v: eat() };
|
|
128
|
+
if (['true', 'True'].includes(x))
|
|
129
|
+
return { k: 'bool', v: true };
|
|
130
|
+
if (['false', 'False'].includes(x))
|
|
131
|
+
return { k: 'bool', v: false };
|
|
132
|
+
if (['None', 'nil', 'null', 'undefined', 'NULL', 'nullptr'].includes(x))
|
|
133
|
+
return { k: 'null' };
|
|
134
|
+
if (!/^@?[A-Za-z_]/.test(x))
|
|
135
|
+
throw new LawError(`unexpected ${JSON.stringify(x)}`);
|
|
136
|
+
if (x === 'old' && peek() === '(') {
|
|
137
|
+
eat();
|
|
138
|
+
const e = top();
|
|
139
|
+
eat(')');
|
|
140
|
+
return { k: 'old', x: e };
|
|
141
|
+
}
|
|
142
|
+
if (['min', 'max', 'abs'].includes(x) && peek() === '(') {
|
|
143
|
+
eat();
|
|
144
|
+
const xs = [top()];
|
|
145
|
+
while (peek() === ',') {
|
|
146
|
+
eat();
|
|
147
|
+
xs.push(top());
|
|
148
|
+
}
|
|
149
|
+
eat(')');
|
|
150
|
+
return { k: 'fn', f: x, xs };
|
|
151
|
+
}
|
|
152
|
+
const p = { k: 'path', head: x, segs: [] };
|
|
153
|
+
for (;;) {
|
|
154
|
+
if (peek() === '.') {
|
|
155
|
+
eat();
|
|
156
|
+
p.segs.push({ f: eat() });
|
|
157
|
+
}
|
|
158
|
+
else if (peek() === '[') {
|
|
159
|
+
eat();
|
|
160
|
+
p.segs.push({ i: top() });
|
|
161
|
+
eat(']');
|
|
162
|
+
}
|
|
163
|
+
else if (peek() === '(') {
|
|
164
|
+
eat();
|
|
165
|
+
const from = i;
|
|
166
|
+
let d = 1;
|
|
167
|
+
while (d && i < t.length) {
|
|
168
|
+
const y = eat();
|
|
169
|
+
d += y === '(' ? 1 : y === ')' ? -1 : 0;
|
|
170
|
+
}
|
|
171
|
+
const inner = t.slice(from, i - 1).join('');
|
|
172
|
+
p.segs.push({ call: true, ...(inner && inner !== '...' ? { args: inner } : {}) });
|
|
173
|
+
}
|
|
174
|
+
else
|
|
175
|
+
break;
|
|
176
|
+
}
|
|
177
|
+
if ((p.head === 'before' || p.head === 'after') && p.segs.length && 'f' in p.segs[0]) {
|
|
178
|
+
const q = { k: 'path', head: p.segs[0].f, segs: p.segs.slice(1) };
|
|
179
|
+
return p.head === 'before' ? { k: 'old', x: q } : q;
|
|
180
|
+
}
|
|
181
|
+
return p;
|
|
182
|
+
};
|
|
183
|
+
// A string: a literal, or a template (f"rl:{k}", `rl:${k}`, "rl:#{k}") as its text and holes.
|
|
184
|
+
const str = (x) => {
|
|
185
|
+
const f = x.startsWith('f'), body = x.slice(f ? 2 : 1, -1);
|
|
186
|
+
const re = f ? /\{([^}]*)\}/g : x.startsWith('`') ? /\$\{([^}]*)\}/g : /#\{([^}]*)\}/g, parts = [], holes = [];
|
|
187
|
+
let last = 0;
|
|
188
|
+
for (const m of body.matchAll(re)) {
|
|
189
|
+
parts.push(body.slice(last, m.index));
|
|
190
|
+
holes.push(parse(m[1]));
|
|
191
|
+
last = m.index + m[0].length;
|
|
192
|
+
}
|
|
193
|
+
return holes.length ? { k: 'str', v: '', parts: [...parts, body.slice(last)], holes } : { k: 'str', v: body.replace(/\\(.)/g, '$1') };
|
|
194
|
+
};
|
|
195
|
+
const e = top();
|
|
196
|
+
if (i < t.length)
|
|
197
|
+
throw new LawError(`unexpected ${JSON.stringify(t[i])}`);
|
|
198
|
+
return e;
|
|
199
|
+
}
|
|
200
|
+
// The law a text states, built on the extraction's rule through its names.
|
|
201
|
+
export function buildLaw(x, l) {
|
|
202
|
+
const names = x.names ?? [], r = x.rule;
|
|
203
|
+
if (!r)
|
|
204
|
+
throw new LawError('the extraction has no rule');
|
|
205
|
+
if (!l.expr)
|
|
206
|
+
throw new LawError(`${l.name}: a law is stated as <name>: <expr>`);
|
|
207
|
+
const e = parse(l.expr);
|
|
208
|
+
// A first reading finds what the law reads: a request, a result, the failure or the state before make it a step law.
|
|
209
|
+
const probe = { b: {}, a: {}, step: true, method: l.method, keys: new Map(), roles: new Set(), methods: new Set() };
|
|
210
|
+
read(e, probe, names, true);
|
|
211
|
+
// (a law on a method, the line above it, is a law of its step: the state after it, old(x) before)
|
|
212
|
+
const step = !!l.method || ['input', 'answer', 'result', 'failed', 'clock', 'method', 'old'].some(k => probe.roles.has(k));
|
|
213
|
+
const method = probe.methods.size === 1 ? [...probe.methods][0] : l.method;
|
|
214
|
+
if (probe.methods.size > 1)
|
|
215
|
+
throw new LawError(`it reads the arguments of ${[...probe.methods].join(' and ')}: a law of one step is about one method`);
|
|
216
|
+
const gate = step && method && names.some(n => n.role === 'method') ? method : undefined;
|
|
217
|
+
const body = (b, a) => read(e, { b, a, step, method, keys: new Map(), roles: new Set(), methods: new Set() }, names, false);
|
|
218
|
+
if (!step)
|
|
219
|
+
return { kind: 'law', law: r.law(l.name, (env) => body(env, env)) };
|
|
220
|
+
const mname = names.find(n => n.role === 'method')?.rule;
|
|
221
|
+
return { kind: 'step', ...(gate ? { method: gate } : {}), law: r.stepLaw(l.name, (b, a) => body(b, a), gate ? (b) => b[mname].is(gate) : undefined) };
|
|
222
|
+
}
|
|
223
|
+
// The expression read: its value (`dry`: only which names it reads, nothing built).
|
|
224
|
+
function read(e, c, names, dry) {
|
|
225
|
+
if (e.k === 'forall') {
|
|
226
|
+
const over = val(e.over, c, names, dry);
|
|
227
|
+
if (over.t !== 'map')
|
|
228
|
+
throw new LawError(`forall ${e.v} in ...: over a map (a dict, a Map, a hash)`);
|
|
229
|
+
if (dry) {
|
|
230
|
+
c.keys.set(e.v, new Term({ op: 'const', value: 0 }));
|
|
231
|
+
return cond(val(e.body, c, names, true));
|
|
232
|
+
}
|
|
233
|
+
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))); });
|
|
234
|
+
}
|
|
235
|
+
return cond(val(e, c, names, dry));
|
|
236
|
+
}
|
|
237
|
+
const cond = (v) => {
|
|
238
|
+
if (v.t === 'cond')
|
|
239
|
+
return v.v;
|
|
240
|
+
if (v.t === 'opt' && v.v?.t === 'cond')
|
|
241
|
+
return v.v.v;
|
|
242
|
+
throw new LawError(`a ${v.t === 'num' ? 'number' : v.t} where a condition is read`);
|
|
243
|
+
};
|
|
244
|
+
const num = (v) => {
|
|
245
|
+
if (v.t === 'num')
|
|
246
|
+
return v.v;
|
|
247
|
+
if (v.t === 'opt' && v.v?.t === 'num')
|
|
248
|
+
return v.v.v;
|
|
249
|
+
if (v.t === 'cell' && v.fields.length === 1)
|
|
250
|
+
return Int.of(v.rec[v.fields[0]]);
|
|
251
|
+
if (v.t === 'key')
|
|
252
|
+
return Int.of(v.v);
|
|
253
|
+
throw new LawError(`a ${v.t} where a number is read`);
|
|
254
|
+
};
|
|
255
|
+
// A value of the rule's environment as the law reads it.
|
|
256
|
+
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 });
|
|
257
|
+
const DRY = { t: 'num', v: Int.of(0) };
|
|
258
|
+
function val(e, c, names, dry) {
|
|
259
|
+
const go = (x) => val(x, c, names, dry);
|
|
260
|
+
switch (e.k) {
|
|
261
|
+
case 'num': return { t: 'num', v: Int.of(e.v) };
|
|
262
|
+
case 'bool': return { t: 'cond', v: e.v ? yes : no };
|
|
263
|
+
case 'null': return { t: 'null' };
|
|
264
|
+
case 'str':
|
|
265
|
+
if (e.holes)
|
|
266
|
+
throw new LawError('a string template outside a store\'s key');
|
|
267
|
+
return { t: 'lit', v: e.v };
|
|
268
|
+
case 'old': {
|
|
269
|
+
c.roles.add('old');
|
|
270
|
+
return val(e.x, { ...c, a: c.b }, names, dry);
|
|
271
|
+
}
|
|
272
|
+
case 'fn': {
|
|
273
|
+
const xs = e.xs.map(go);
|
|
274
|
+
if (dry)
|
|
275
|
+
return DRY;
|
|
276
|
+
if (e.f === 'abs')
|
|
277
|
+
return { t: 'num', v: Int.of(num(xs[0]).abs) };
|
|
278
|
+
return { t: 'num', v: xs.slice(1).reduce((m, y) => (e.f === 'min' ? m.min(num(y)) : m.max(num(y))), num(xs[0])) };
|
|
279
|
+
}
|
|
280
|
+
case 'un': {
|
|
281
|
+
const v = go(e.x);
|
|
282
|
+
if (dry)
|
|
283
|
+
return v.t === 'cond' ? v : DRY;
|
|
284
|
+
return e.op === '-' ? { t: 'num', v: num(v).negate() } : { t: 'cond', v: not(cond(v)) };
|
|
285
|
+
}
|
|
286
|
+
case 'bin': {
|
|
287
|
+
if (e.op === 'in') {
|
|
288
|
+
const m = go(e.b);
|
|
289
|
+
if (m.t !== 'map')
|
|
290
|
+
throw new LawError('x in m: m a map');
|
|
291
|
+
const k = go(e.a);
|
|
292
|
+
return dry ? { t: 'cond', v: yes } : { t: 'cond', v: cellOf(m, key(k), c).rec.has };
|
|
293
|
+
}
|
|
294
|
+
// (a name the rule doesn't have, compared with a choice: the choice's value, Outcome.SLOW_ERROR)
|
|
295
|
+
const lit = (x) => { try {
|
|
296
|
+
return go(x);
|
|
297
|
+
}
|
|
298
|
+
catch (err) {
|
|
299
|
+
if (x.k !== 'path' || !(err instanceof LawError) || !['==', '!='].includes(e.op))
|
|
300
|
+
throw err;
|
|
301
|
+
return { t: 'lit', v: lastName(x) ?? '', err };
|
|
302
|
+
} };
|
|
303
|
+
const a = lit(e.a), b = lit(e.b);
|
|
304
|
+
if (a.t === 'lit' && a.err && b.t === 'lit' && b.err)
|
|
305
|
+
throw a.err;
|
|
306
|
+
if (['&&', '||', '=>'].includes(e.op))
|
|
307
|
+
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)) };
|
|
308
|
+
if (dry)
|
|
309
|
+
return ['+', '-', '*', '//', '/', '%'].includes(e.op) ? DRY : { t: 'cond', v: yes };
|
|
310
|
+
if (e.op === '+' || e.op === '-')
|
|
311
|
+
return { t: 'num', v: e.op === '+' ? num(a).plus(num(b)) : num(a).minus(num(b)) };
|
|
312
|
+
if (e.op === '*') {
|
|
313
|
+
const k = constOf(e.a) ?? constOf(e.b);
|
|
314
|
+
if (k === undefined)
|
|
315
|
+
throw new LawError('× by a constant only (a product of two values is outside linear arithmetic)');
|
|
316
|
+
return { t: 'num', v: num(constOf(e.a) === undefined ? a : b).times(k) };
|
|
317
|
+
}
|
|
318
|
+
if (e.op === '//' || e.op === '/' || e.op === '%') {
|
|
319
|
+
const k = constOf(e.b);
|
|
320
|
+
if (!k || k < 1)
|
|
321
|
+
throw new LawError(`${e.op} by a positive constant only`);
|
|
322
|
+
return e.op === '%' ? { t: 'num', v: Int.of(num(a).modBy(k)) } : { t: 'num', v: num(a).divBy(k) };
|
|
323
|
+
}
|
|
324
|
+
return { t: 'cond', v: compare(e.op, a, b, e) };
|
|
325
|
+
}
|
|
326
|
+
case 'path': return path(e, c, names, dry);
|
|
327
|
+
case 'forall': return fail('forall ... in ...: at the top of the law only');
|
|
328
|
+
}
|
|
329
|
+
return fail('an expression of no kind');
|
|
330
|
+
}
|
|
331
|
+
// (a path's last name: a choice's value written as one, Outcome.SLOW_ERROR)
|
|
332
|
+
const lastName = (x) => (x.segs.length ? x.segs.at(-1).f : x.head);
|
|
333
|
+
const constOf = (x) => (x.k === 'num' ? x.v : x.k === 'un' && x.op === '-' && x.x.k === 'num' ? -x.x.v : undefined);
|
|
334
|
+
function compare(op, a, b, e) {
|
|
335
|
+
if (b.t === 'null' || a.t === 'null') {
|
|
336
|
+
const o = a.t === 'null' ? b : a, none = o.t === 'opt' ? o.none : o.t === 'cell' ? not(o.rec.has) : undefined;
|
|
337
|
+
if (!none)
|
|
338
|
+
throw new LawError(`${show(a.t === 'null' ? e.b : e.a)} is never None here (the rule holds no None for it)`);
|
|
339
|
+
return op === '==' ? none : op === '!=' ? not(none) : fail(`${op} with None`);
|
|
340
|
+
}
|
|
341
|
+
const un = (v) => (v.t === 'opt' && v.v ? v.v : v);
|
|
342
|
+
a = un(a);
|
|
343
|
+
b = un(b);
|
|
344
|
+
// (a name the rule doesn't have is a choice's value only beside a choice)
|
|
345
|
+
for (const [v, o] of [[a, b], [b, a]])
|
|
346
|
+
if (v.t === 'lit' && v.err && o.t !== 'choice')
|
|
347
|
+
throw v.err;
|
|
348
|
+
const eq = (c) => (op === '==' ? c : op === '!=' ? not(c) : fail(`${op} of values that aren't numbers`));
|
|
349
|
+
if (a.t === 'choice' || b.t === 'choice') {
|
|
350
|
+
const [ch, o, ox] = a.t === 'choice' ? [a.v, b, e.b] : [b.v, a, e.a];
|
|
351
|
+
if (o.t === 'choice')
|
|
352
|
+
return eq(ch.eq(o.v));
|
|
353
|
+
const lit = o.t === 'lit' ? o.v : ox.k === 'path' ? lastName(ox) : undefined;
|
|
354
|
+
if (lit === undefined || !ch.values.includes(lit))
|
|
355
|
+
throw new LawError(`${show(ox)} isn't one of ${ch.values.join(', ')}`);
|
|
356
|
+
return eq(ch.is(lit));
|
|
357
|
+
}
|
|
358
|
+
if (a.t === 'str' || b.t === 'str') {
|
|
359
|
+
const [s, o] = a.t === 'str' ? [a.v, b] : [b.v, a];
|
|
360
|
+
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'));
|
|
361
|
+
}
|
|
362
|
+
if (a.t === 'cond' && b.t === 'cond')
|
|
363
|
+
return eq(a.v.iff(b.v));
|
|
364
|
+
const x = num(a), y = num(b);
|
|
365
|
+
return op === '<' ? x.lt(y) : op === '<=' ? x.atMost(y) : op === '>' ? x.gt(y) : op === '>=' ? x.atLeast(y) : op === '==' ? x.eq(y) : x.ne(y);
|
|
366
|
+
}
|
|
367
|
+
const fail = (s) => { throw new LawError(s); };
|
|
368
|
+
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);
|
|
369
|
+
// A map's key as the rule holds it: a string's id, a natural.
|
|
370
|
+
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; })());
|
|
371
|
+
function cellOf(m, k, c) {
|
|
372
|
+
const map = (c.a[m.n.rule] ?? c.b[m.n.rule]);
|
|
373
|
+
return { rec: map.at(k), fields: m.n.map.fields };
|
|
374
|
+
}
|
|
375
|
+
// A path: the longest prefix of it the code names (in the law's method first: its arguments shadow the fields, as in the
|
|
376
|
+
// code), then its fields, keys and calls.
|
|
377
|
+
function path(e, c, names, dry) {
|
|
378
|
+
if (c.keys.has(e.head) && !e.segs.length)
|
|
379
|
+
return { t: 'key', v: c.keys.get(e.head) };
|
|
380
|
+
if (e.head === 'result' || e.head === 'failed') {
|
|
381
|
+
const n = e.head === 'failed' ? names.find(x => x.role === 'failed') : results(names, c);
|
|
382
|
+
if (!n)
|
|
383
|
+
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');
|
|
384
|
+
c.roles.add(n.role);
|
|
385
|
+
if (n.method)
|
|
386
|
+
c.methods.add(n.method);
|
|
387
|
+
return rest(e.segs, leaf(n, c, dry), c, names, dry, e);
|
|
388
|
+
}
|
|
389
|
+
const explicit = ['self', 'this', 'state', 's'].includes(e.head) || e.head.startsWith('@');
|
|
390
|
+
const parts = [e.head.replace(/^@/, ''), ...e.segs.map(s => ('f' in s ? s.f : undefined))];
|
|
391
|
+
const heads = explicit && !e.head.startsWith('@') ? [parts.slice(1)] : [parts, ...(parts.length > 1 && parts[1] !== undefined ? [parts.slice(1)] : [])];
|
|
392
|
+
for (const [hi, p] of heads.entries()) {
|
|
393
|
+
const fields = [];
|
|
394
|
+
for (const s of p) {
|
|
395
|
+
if (s === undefined)
|
|
396
|
+
break;
|
|
397
|
+
fields.push(s);
|
|
398
|
+
}
|
|
399
|
+
const skip = parts.length - p.length;
|
|
400
|
+
for (let n = fields.length; n > 0; n--) {
|
|
401
|
+
const code = fields.slice(0, n).join('.'), next = e.segs[skip + n - 1];
|
|
402
|
+
const hit = find(code, names, c, explicit || hi > 0, next !== undefined && 'call' in next);
|
|
403
|
+
if (hit) {
|
|
404
|
+
c.roles.add(hit.role);
|
|
405
|
+
if (hit.method)
|
|
406
|
+
c.methods.add(hit.method);
|
|
407
|
+
// (an answered call is one value a step, whatever its arguments: written f(...) or f())
|
|
408
|
+
if (hit.role === 'answer' && next && 'call' in next && next.args)
|
|
409
|
+
throw new LawError(`${code}(${next.args}): an answered call's value is the request's, one a step: write it ${code}(...)`);
|
|
410
|
+
const segs = e.segs.slice(skip + n - 1 + (hit.role === 'answer' && next && 'call' in next ? 1 : 0));
|
|
411
|
+
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);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
// A method's argument by its method's name (charge.user), where several methods take one of that name.
|
|
416
|
+
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);
|
|
417
|
+
if (m) {
|
|
418
|
+
c.roles.add('input');
|
|
419
|
+
c.methods.add(m.method);
|
|
420
|
+
return rest(e.segs.slice(1), leaf(m, c, dry), c, names, dry, e);
|
|
421
|
+
}
|
|
422
|
+
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)))];
|
|
423
|
+
throw new LawError(`no ${show(e)} in the rule (its names: ${known.join(', ')})`);
|
|
424
|
+
}
|
|
425
|
+
// The name a code path is: the law's method's argument, a field of the state, a constructor's argument, an answered
|
|
426
|
+
// call (by its callee's last name), the rule's own name (as printed).
|
|
427
|
+
function find(code, names, c, stateOnly, called) {
|
|
428
|
+
const last = (n) => n.code.split('.').pop() === code.split('.').pop() && (code.split('.').length === 1 || n.code.endsWith(code));
|
|
429
|
+
const at = (n) => n.code.replace(/^@/, '') === code;
|
|
430
|
+
const inputs = names.filter(n => n.role === 'input' && n.code === code);
|
|
431
|
+
if (!stateOnly && !called && inputs.length) {
|
|
432
|
+
const here = inputs.filter(n => n.method === c.method);
|
|
433
|
+
if (here.length)
|
|
434
|
+
return here[0];
|
|
435
|
+
if (new Set(inputs.map(n => n.method)).size === 1)
|
|
436
|
+
return inputs[0];
|
|
437
|
+
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}`);
|
|
438
|
+
}
|
|
439
|
+
return names.find(n => n.role === 'state' && at(n) && !called)
|
|
440
|
+
?? (stateOnly ? undefined : names.find(n => (n.role === 'param' || n.role === 'const' || n.role === 'clock') && n.code === code && !called))
|
|
441
|
+
?? names.find(n => n.role === 'answer' && last(n))
|
|
442
|
+
?? (stateOnly ? undefined : names.find(n => n.rule === code && !called));
|
|
443
|
+
}
|
|
444
|
+
const results = (names, c) => {
|
|
445
|
+
const rs = names.filter(n => n.role === 'result' && n.code === 'result');
|
|
446
|
+
const r = rs.find(n => n.method === c.method) ?? (rs.length === 1 ? rs[0] : undefined);
|
|
447
|
+
if (!r && rs.length > 1)
|
|
448
|
+
throw new LawError(`result: of ${rs.map(n => n.method).join(', ')}: write the law on the method it is about (the line above it)`);
|
|
449
|
+
return r;
|
|
450
|
+
};
|
|
451
|
+
// A name's value: its variable in the environment (the state after the step where the law is a step's), its None-ness.
|
|
452
|
+
function leaf(n, c, dry) {
|
|
453
|
+
if (dry)
|
|
454
|
+
return n.none && !n.rule ? { t: 'opt', none: yes } : n.none ? { t: 'opt', none: yes, v: DRY } : DRY;
|
|
455
|
+
if (n.role === 'const')
|
|
456
|
+
return { t: 'num', v: Int.of(n.value) };
|
|
457
|
+
const env = c.step && (n.role === 'state' || n.role === 'result' || n.role === 'failed') ? c.a : c.b;
|
|
458
|
+
const get = (r) => { if (!(r in env) && !(r in c.b))
|
|
459
|
+
throw new LawError(`${n.code}: ${r} isn't in the rule's environment here`); return r in env ? env[r] : c.b[r]; };
|
|
460
|
+
const v = n.rule ? wrap(get(n.rule)) : undefined;
|
|
461
|
+
return n.none ? { t: 'opt', none: get(n.none), ...(v ? { v } : {}) } : v;
|
|
462
|
+
}
|
|
463
|
+
// 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.
|
|
464
|
+
function rest(segs, v, c, names, dry, e) {
|
|
465
|
+
for (let i = 0; i < segs.length; i++) {
|
|
466
|
+
const s = segs[i];
|
|
467
|
+
if (v.t === 'map') {
|
|
468
|
+
const isGet = 'f' in s && ['get', 'fetch', 'getOrDefault', 'lookup'].includes(s.f) && segs[i + 1] && 'call' in segs[i + 1];
|
|
469
|
+
const isHas = 'f' in s && ['has', 'contains', 'containsKey', 'has_key', 'key?', 'has_key?', 'include?'].includes(s.f);
|
|
470
|
+
if (isGet || isHas)
|
|
471
|
+
throw new LawError(`${show(e)}: write the key in brackets (m[k], or k in m)`);
|
|
472
|
+
if (!('i' in s))
|
|
473
|
+
throw new LawError(`${show(e)}: a map is read at a key (m[k])`);
|
|
474
|
+
const [m, k] = storeKey(v, s.i, c, names, dry);
|
|
475
|
+
if (dry) {
|
|
476
|
+
v = DRY;
|
|
477
|
+
continue;
|
|
478
|
+
}
|
|
479
|
+
const cell = cellOf(m, key(k), c);
|
|
480
|
+
v = { t: 'cell', ...cell };
|
|
481
|
+
continue;
|
|
482
|
+
}
|
|
483
|
+
if (v.t === 'cell' && 'f' in s) {
|
|
484
|
+
if (!v.fields.includes(s.f))
|
|
485
|
+
throw new LawError(`${show(e)}: its cells have ${v.fields.join(', ')}`);
|
|
486
|
+
v = wrap(v.rec[s.f]);
|
|
487
|
+
continue;
|
|
488
|
+
}
|
|
489
|
+
if (dry)
|
|
490
|
+
continue;
|
|
491
|
+
throw new LawError(`${show(e)}: can't read ${'f' in s ? `.${s.f}` : 'i' in s ? '[...]' : '(...)'} of a ${v.t}`);
|
|
492
|
+
}
|
|
493
|
+
return v;
|
|
494
|
+
}
|
|
495
|
+
// 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.
|
|
496
|
+
function storeKey(m, k, c, names, dry) {
|
|
497
|
+
if (!m.n.map?.store)
|
|
498
|
+
return [m, val(k, c, names, dry)];
|
|
499
|
+
const parts = [], holes = [];
|
|
500
|
+
const flat = (x) => { if (x.k === 'bin' && x.op === '+') {
|
|
501
|
+
flat(x.a);
|
|
502
|
+
flat(x.b);
|
|
503
|
+
}
|
|
504
|
+
else if (x.k === 'str' && !x.holes)
|
|
505
|
+
parts.push(x.v);
|
|
506
|
+
else if (x.k === 'str') {
|
|
507
|
+
x.parts.forEach((p, i) => { parts.push(p); if (x.holes[i]) {
|
|
508
|
+
holes.push(x.holes[i]);
|
|
509
|
+
parts.push('{}');
|
|
510
|
+
} });
|
|
511
|
+
}
|
|
512
|
+
else {
|
|
513
|
+
holes.push(x);
|
|
514
|
+
parts.push('{}');
|
|
515
|
+
} };
|
|
516
|
+
flat(k);
|
|
517
|
+
const tpl = parts.join('');
|
|
518
|
+
const hit = m.maps.find(x => x.map.tpl === tpl) ?? (holes.length === 1 && tpl === '{}' && m.maps.length === 1 ? m.maps[0] : undefined);
|
|
519
|
+
if (!hit || holes.length !== 1)
|
|
520
|
+
throw new LawError(`${m.n.code}[${tpl}]: its keys are ${m.maps.map(x => JSON.stringify(x.map.tpl.replace('{}', '<key>'))).join(', ')}`);
|
|
521
|
+
return [{ t: 'map', n: hit, maps: [hit] }, val(holes[0], c, names, dry)];
|
|
522
|
+
}
|