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.
- package/README.md +95 -6
- package/dist/core/c/reader.d.ts +86 -0
- package/dist/core/c/reader.js +860 -0
- package/dist/core/check.js +20 -6
- package/dist/core/cli.d.ts +76 -0
- package/dist/core/cli.js +636 -0
- package/dist/core/dsl.d.ts +6 -4
- package/dist/core/dsl.js +30 -16
- 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 +19 -5
- 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.d.ts +4 -0
- package/dist/core/infer.js +1838 -69
- 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 +83 -0
- package/dist/core/laws.js +623 -0
- package/dist/core/machine.d.ts +2 -0
- package/dist/core/machine.js +87 -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/relational.d.ts +49 -0
- package/dist/core/relational.js +345 -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/interchange/check.d.ts +16 -0
- package/dist/interchange/check.js +111 -0
- package/dist/interchange/format.d.ts +150 -0
- package/dist/interchange/format.js +678 -0
- package/dist/kernel/epr.d.ts +40 -0
- package/dist/kernel/epr.js +1882 -0
- package/dist/kernel/kernel.d.ts +45 -1
- package/dist/kernel/kernel.js +138 -13
- package/dist/kernel/prove.d.ts +45 -0
- package/dist/kernel/prove.js +658 -51
- package/dist/lean-kernel/emit.d.ts +17 -2
- package/dist/lean-kernel/emit.js +87 -7
- package/package.json +57 -2
package/dist/core/cli.js
ADDED
|
@@ -0,0 +1,636 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
3
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
4
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
5
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
6
|
+
});
|
|
7
|
+
}
|
|
8
|
+
return path;
|
|
9
|
+
};
|
|
10
|
+
import { proveRule, proveSteps } from "./dsl.js";
|
|
11
|
+
import { LawError, buildLaw, buildTwoRuns, citesIn, isTwoRuns, lawsIn, namesWithClock } from "./laws.js";
|
|
12
|
+
import { certify, proveTwoRuns } from "./relational.js";
|
|
13
|
+
const proc = globalThis.process;
|
|
14
|
+
const fs = proc.getBuiltinModule('node:fs'), path = proc.getBuiltinModule('node:path');
|
|
15
|
+
const out = (s = '') => proc.stdout.write(`${s}\n`);
|
|
16
|
+
// Color, plain ANSI: only on a terminal, never with --json, NO_COLOR (any value) or TERM=dumb; FORCE_COLOR turns it on.
|
|
17
|
+
// Uncolored, the text is the same byte for byte.
|
|
18
|
+
export const colors = (env, tty, json = false) => !json && (env.FORCE_COLOR !== undefined && !['0', 'false'].includes(env.FORCE_COLOR) ? true : env.NO_COLOR === undefined && env.TERM !== 'dumb' && tty);
|
|
19
|
+
let tint = false;
|
|
20
|
+
const SGR = { green: 32, red: 31, yellow: 33, dim: 2 };
|
|
21
|
+
const paint = (c, s) => (tint && s !== '' ? `\x1b[${SGR[c]}m${s}\x1b[0m` : String(s));
|
|
22
|
+
const VERDICT = { proven: 'green', broken: 'red', unknown: 'yellow', 'not read': 'yellow' };
|
|
23
|
+
function args(argv) {
|
|
24
|
+
const o = { ms: 10_000, propose: true }, targets = [];
|
|
25
|
+
let cmd = '';
|
|
26
|
+
for (let i = 0; i < argv.length; i++) {
|
|
27
|
+
const a = argv[i];
|
|
28
|
+
if (a === '--json')
|
|
29
|
+
o.json = true;
|
|
30
|
+
else if (a === '--no-propose')
|
|
31
|
+
o.propose = false;
|
|
32
|
+
else if (a.startsWith('--')) {
|
|
33
|
+
const [k, inline] = a.slice(2).split('='), v = inline ?? argv[++i] ?? '';
|
|
34
|
+
const key = k.replace(/-(\w)/g, (_, c) => c.toUpperCase());
|
|
35
|
+
o[key] = key === 'methods' ? v.split(',') : key === 'ms' ? Number(v) : v;
|
|
36
|
+
}
|
|
37
|
+
else if (!cmd)
|
|
38
|
+
cmd = a;
|
|
39
|
+
else
|
|
40
|
+
targets.push(a);
|
|
41
|
+
}
|
|
42
|
+
return { cmd, targets, o };
|
|
43
|
+
}
|
|
44
|
+
const EXT = { '.py': 'python', '.rb': 'ruby', '.ex': 'elixir', '.exs': 'elixir', '.java': 'java', '.kt': 'kotlin', '.go': 'go', '.rs': 'rust', '.swift': 'swift', '.c': 'c', '.h': 'c',
|
|
45
|
+
'.cpp': 'cpp', '.cc': 'cpp', '.cxx': 'cpp', '.hpp': 'cpp', '.ts': 'ts', '.mts': 'ts', '.tsx': 'ts', '.js': 'ts', '.mjs': 'ts' };
|
|
46
|
+
const COMMENT = { python: '#', ruby: '#', elixir: '#', java: '//', kotlin: '//', go: '//', rust: '//', swift: '//', c: '//', cpp: '//', ts: '//' };
|
|
47
|
+
export const LANG_NAME = { python: 'Python', ruby: 'Ruby', elixir: 'Elixir', java: 'Java', kotlin: 'Kotlin', go: 'Go', rust: 'Rust', swift: 'Swift', c: 'C', cpp: 'C++', ts: 'TypeScript' };
|
|
48
|
+
function targetsOf(p) {
|
|
49
|
+
const abs = path.resolve(p);
|
|
50
|
+
if (!fs.existsSync(abs))
|
|
51
|
+
throw new Error(`${p}: no such file or directory`);
|
|
52
|
+
const src = (d, ext) => fs.readdirSync(d).filter(f => ext.test(f) && !/_test\.go$|\.test\.|_spec\./.test(f)).map(f => path.join(d, f));
|
|
53
|
+
if (fs.statSync(abs).isDirectory()) {
|
|
54
|
+
if (fs.existsSync(path.join(abs, 'Cargo.toml')))
|
|
55
|
+
return [{ lang: 'rust', at: abs, files: rustFiles(abs) }];
|
|
56
|
+
if (fs.existsSync(path.join(abs, 'Package.swift')))
|
|
57
|
+
return [{ lang: 'swift', at: abs, files: swiftFiles(path.join(abs, 'Sources')) }];
|
|
58
|
+
if (fs.existsSync(path.join(abs, 'go.mod')) || src(abs, /\.go$/).length)
|
|
59
|
+
return [{ lang: 'go', at: abs, files: src(abs, /\.go$/) }];
|
|
60
|
+
return fs.readdirSync(abs).filter(f => EXT[path.extname(f)] && !/\.test\.|_test\.|_spec\.|\.d\.ts$/.test(f)).flatMap(f => targetsOf(path.join(abs, f)));
|
|
61
|
+
}
|
|
62
|
+
const lang = EXT[path.extname(abs)];
|
|
63
|
+
if (!lang)
|
|
64
|
+
throw new Error(`${p}: not a language gdp-wired reads (${Object.keys(EXT).join(' ')})`);
|
|
65
|
+
if (lang === 'go')
|
|
66
|
+
return [{ lang, at: path.dirname(abs), files: src(path.dirname(abs), /\.go$/) }];
|
|
67
|
+
if (lang === 'rust') {
|
|
68
|
+
const crate = up(path.dirname(abs), d => fs.existsSync(path.join(d, 'Cargo.toml')));
|
|
69
|
+
return [{ lang, at: crate ?? path.dirname(abs), files: crate ? rustFiles(crate) : [abs] }];
|
|
70
|
+
}
|
|
71
|
+
return [{ lang, at: abs, files: [abs] }];
|
|
72
|
+
}
|
|
73
|
+
const swiftFiles = (d) => (fs.existsSync(d) ? fs.readdirSync(d).flatMap(f => { const p = path.join(d, f); return fs.statSync(p).isDirectory() ? swiftFiles(p) : f.endsWith('.swift') ? [p] : []; }) : []);
|
|
74
|
+
const rustFiles = (crate) => { const d = path.join(crate, 'src'); return fs.existsSync(d) ? fs.readdirSync(d).filter(f => f.endsWith('.rs')).map(f => path.join(d, f)) : []; };
|
|
75
|
+
// The nearest directory from `d` up where `ok` holds.
|
|
76
|
+
export function up(d, ok) {
|
|
77
|
+
for (let x = d;; x = path.dirname(x)) {
|
|
78
|
+
if (ok(x))
|
|
79
|
+
return x;
|
|
80
|
+
if (path.dirname(x) === x)
|
|
81
|
+
return undefined;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
// A front end run on a target with the options (each loaded only when its language is read).
|
|
85
|
+
async function extractOne(t, o) {
|
|
86
|
+
try {
|
|
87
|
+
return await extractWith(t, o);
|
|
88
|
+
}
|
|
89
|
+
catch (e) {
|
|
90
|
+
// (every front end is read through the TypeScript extractor's terms: the typescript package beside gdp-wired)
|
|
91
|
+
if (/typescript/.test(String(e.message)) && /find|resolve/i.test(String(e.message)))
|
|
92
|
+
throw new Error('the extractors need the typescript package beside gdp-wired: npx gdp-wired-cli check ... (gdp-wired with TypeScript beside it), or npm i -D gdp-wired typescript');
|
|
93
|
+
throw e;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
async function extractWith(t, o) {
|
|
97
|
+
const f = t.at, dir = path.dirname(f);
|
|
98
|
+
switch (t.lang) {
|
|
99
|
+
case 'python': {
|
|
100
|
+
const { extractPython } = await import("./extract-py.js");
|
|
101
|
+
// (the repository's root: the project's (pyproject.toml, setup.py), else above the outermost package the file is
|
|
102
|
+
// in; the Python of a virtualenv beside it)
|
|
103
|
+
const root = o.root ?? up(dir, d => ['pyproject.toml', 'setup.py', 'setup.cfg'].some(m => fs.existsSync(path.join(d, m)))) ?? up(dir, d => !fs.existsSync(path.join(d, '__init__.py'))) ?? dir;
|
|
104
|
+
const venv = up(root, d => fs.existsSync(path.join(d, '.venv', 'bin', 'python')));
|
|
105
|
+
return extractPython(f, { root, ...(venv ? { python: path.join(venv, '.venv', 'bin', 'python') } : {}), ...o });
|
|
106
|
+
}
|
|
107
|
+
case 'ruby': {
|
|
108
|
+
const { extractRuby } = await import("./extract-rb.js");
|
|
109
|
+
return extractRuby(f, { root: up(dir, d => path.basename(d) === 'lib') ?? dir, ...o });
|
|
110
|
+
}
|
|
111
|
+
case 'elixir': {
|
|
112
|
+
const { extractElixir } = await import("./extract-ex.js");
|
|
113
|
+
return extractElixir(f, o);
|
|
114
|
+
}
|
|
115
|
+
case 'java': {
|
|
116
|
+
const { extractJava } = await import("./extract-jvm.js");
|
|
117
|
+
return extractJava(f, o);
|
|
118
|
+
}
|
|
119
|
+
case 'kotlin': {
|
|
120
|
+
const { extractKotlin } = await import("./extract-jvm.js");
|
|
121
|
+
return extractKotlin(f, o);
|
|
122
|
+
}
|
|
123
|
+
case 'go': {
|
|
124
|
+
const { extractGo } = await import("./extract-go.js");
|
|
125
|
+
return extractGo(f, o);
|
|
126
|
+
}
|
|
127
|
+
case 'rust': {
|
|
128
|
+
const { extractRust } = await import("./extract-rs.js");
|
|
129
|
+
return extractRust(f, o);
|
|
130
|
+
}
|
|
131
|
+
case 'swift': {
|
|
132
|
+
const { extractSwift } = await import("./extract-swift.js");
|
|
133
|
+
return extractSwift(f, o);
|
|
134
|
+
}
|
|
135
|
+
case 'c':
|
|
136
|
+
case 'cpp': {
|
|
137
|
+
const { extractC } = await import("./extract-c.js");
|
|
138
|
+
return extractC(f, o, t.lang === 'cpp');
|
|
139
|
+
}
|
|
140
|
+
case 'ts': {
|
|
141
|
+
// (Effect and XState run on the package the file's own project has, imported here as the code imports it)
|
|
142
|
+
const code = fs.readFileSync(f, 'utf8'), file = path.relative(proc.cwd(), f) || f, { createRequire } = proc.getBuiltinModule('node:module');
|
|
143
|
+
const own = async (spec) => { try {
|
|
144
|
+
return await import(__rewriteRelativeImportExtension(createRequire(f).resolve(spec)));
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
return undefined;
|
|
148
|
+
} };
|
|
149
|
+
if (/from\s+['"]effect(\/\w+)?['"]/.test(code)) {
|
|
150
|
+
const { extractEffect } = await import("./effect.js"), effect = await own('effect');
|
|
151
|
+
return extractEffect(file, { ...(effect ? { effect } : {}), ...o });
|
|
152
|
+
}
|
|
153
|
+
if (/from\s+['"]xstate['"]/.test(code) && /\bcreateMachine\b/.test(code)) {
|
|
154
|
+
const { extractXState } = await import("./extract-xstate.js"), xstate = await own('xstate');
|
|
155
|
+
return extractXState(file, { ...(xstate ? { xstate } : {}), ...o });
|
|
156
|
+
}
|
|
157
|
+
const { extract } = await import("./extract.js");
|
|
158
|
+
return extract(file, o);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
export function configFor(from) {
|
|
163
|
+
// (the first of the three in a directory that holds gdp's options)
|
|
164
|
+
const holder = (d) => ['gdp.toml', 'pyproject.toml', 'package.json'].find(f => fs.existsSync(path.join(d, f)) && (f === 'gdp.toml' || (f === 'pyproject.toml' ? /^\[tool\.gdp\b/m : /"gdp"\s*:/).test(fs.readFileSync(path.join(d, f), 'utf8'))));
|
|
165
|
+
const dir = up(from, d => !!holder(d));
|
|
166
|
+
if (!dir)
|
|
167
|
+
return { all: {}, rules: {} };
|
|
168
|
+
const f = holder(dir);
|
|
169
|
+
const text = fs.readFileSync(path.join(dir, f), 'utf8');
|
|
170
|
+
let c;
|
|
171
|
+
if (f === 'package.json')
|
|
172
|
+
c = JSON.parse(text).gdp ?? {};
|
|
173
|
+
else if (f === 'pyproject.toml') {
|
|
174
|
+
// (only its [tool.gdp...] tables, read as a gdp.toml's)
|
|
175
|
+
let on = false;
|
|
176
|
+
c = toml(text.split('\n').filter(l => { const h = /^\s*\[([^\]]*)\]/.exec(l); if (h)
|
|
177
|
+
on = /^tool\.gdp\b/.test(h[1].trim()); return on; }).join('\n')).tool?.gdp ?? {};
|
|
178
|
+
}
|
|
179
|
+
else
|
|
180
|
+
c = toml(text);
|
|
181
|
+
const { rules, ...all } = c;
|
|
182
|
+
return { all, rules: rules ?? {}, at: path.join(dir, f) };
|
|
183
|
+
}
|
|
184
|
+
// TOML's subset a gdp.toml needs: tables ([a.b."c.d"]), dotted and quoted keys, strings, integers, booleans, arrays and
|
|
185
|
+
// inline tables on one line, # comments.
|
|
186
|
+
export function toml(text) {
|
|
187
|
+
const root = {};
|
|
188
|
+
let table = root;
|
|
189
|
+
const keys = (s) => [...s.matchAll(/\s*(?:"((?:[^"\\]|\\.)*)"|'([^']*)'|([\w-]+))\s*(?:\.|$)/g)].map(m => m[1] ?? m[2] ?? m[3]);
|
|
190
|
+
const at = (o, ks) => ks.reduce((t, k) => (t[k] ??= {}), o);
|
|
191
|
+
// (a dotted key = value set in a table; what follows it)
|
|
192
|
+
const pair = (s, into) => {
|
|
193
|
+
const eq = /^((?:"(?:[^"\\]|\\.)*"|'[^']*'|[\w.-]+|\s)+?)\s*=/.exec(s) ?? fail(`gdp.toml: can't read ${s.slice(0, 40)}`);
|
|
194
|
+
const ks = keys(eq[1]), [v, r] = value(s.slice(eq[0].length));
|
|
195
|
+
at(into, ks.slice(0, -1))[ks.at(-1)] = v;
|
|
196
|
+
return r;
|
|
197
|
+
};
|
|
198
|
+
const value = (s) => {
|
|
199
|
+
s = s.trimStart();
|
|
200
|
+
const str = /^"((?:[^"\\]|\\.)*)"|^'([^']*)'/.exec(s);
|
|
201
|
+
if (str) {
|
|
202
|
+
const v = str[1] !== undefined ? JSON.parse(`"${str[1]}"`) : str[2];
|
|
203
|
+
return [['None', 'null', 'nil'].includes(v) ? null : v, s.slice(str[0].length)];
|
|
204
|
+
}
|
|
205
|
+
if (s[0] === '[' || s[0] === '{') {
|
|
206
|
+
const arr = s[0] === '[', out = [], obj = {};
|
|
207
|
+
s = s.slice(1);
|
|
208
|
+
for (;;) {
|
|
209
|
+
s = s.trimStart();
|
|
210
|
+
if (s[0] === (arr ? ']' : '}'))
|
|
211
|
+
return [arr ? out : obj, s.slice(1)];
|
|
212
|
+
if (s[0] === ',') {
|
|
213
|
+
s = s.slice(1);
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
if (arr) {
|
|
217
|
+
const [v, r] = value(s);
|
|
218
|
+
out.push(v);
|
|
219
|
+
s = r;
|
|
220
|
+
}
|
|
221
|
+
else
|
|
222
|
+
s = pair(s, obj);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
const m = /^(true|false|-?\d+)/.exec(s) ?? fail(`gdp.toml: can't read ${s.slice(0, 40)}`);
|
|
226
|
+
return [m[1] === 'true' ? true : m[1] === 'false' ? false : Number(m[1]), s.slice(m[0].length)];
|
|
227
|
+
};
|
|
228
|
+
for (const raw of text.split('\n')) {
|
|
229
|
+
const l = raw.trim();
|
|
230
|
+
if (!l || l.startsWith('#'))
|
|
231
|
+
continue;
|
|
232
|
+
const h = /^\[([^\]]+)\]\s*(?:#.*)?$/.exec(l);
|
|
233
|
+
if (h) {
|
|
234
|
+
table = at(root, keys(h[1]));
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
const r = pair(l, table).trim();
|
|
238
|
+
if (r && !r.startsWith('#'))
|
|
239
|
+
fail(`gdp.toml: can't read ${l}`);
|
|
240
|
+
}
|
|
241
|
+
return root;
|
|
242
|
+
}
|
|
243
|
+
const fail = (s) => { throw new Error(s); };
|
|
244
|
+
// Two option objects merged, the second's winning (objects merged key by key: a store's attrs beside its methods).
|
|
245
|
+
const merge = (a, b) => {
|
|
246
|
+
const out = { ...a };
|
|
247
|
+
for (const [k, v] of Object.entries(b))
|
|
248
|
+
out[k] = v && typeof v === 'object' && !Array.isArray(v) && out[k] && typeof out[k] === 'object' && !Array.isArray(out[k]) ? merge(out[k], v) : v;
|
|
249
|
+
return out;
|
|
250
|
+
};
|
|
251
|
+
// The entries to read: the one given, else the one inferred; where several classes or structs qualify, each of them; a
|
|
252
|
+
// file of functions, each function a law is stated on.
|
|
253
|
+
async function rulesOf(t, o, laws) {
|
|
254
|
+
const { json: _j, ms: _m, propose: _p, clock: _c, cert: _t, ...flags } = o;
|
|
255
|
+
void _j;
|
|
256
|
+
void _m;
|
|
257
|
+
void _p;
|
|
258
|
+
void _c;
|
|
259
|
+
void _t;
|
|
260
|
+
// (the options: gdp.toml's for every rule, then the rule's own, then the flags; a rule found with no entry named is
|
|
261
|
+
// read again where gdp.toml has options of its own for it)
|
|
262
|
+
const cfg = configFor(t.lang === 'go' || t.lang === 'rust' || fs.statSync(t.at).isDirectory() ? t.at : path.dirname(t.at));
|
|
263
|
+
const { clock: _k, ...shared } = cfg.all;
|
|
264
|
+
void _k;
|
|
265
|
+
const optsFor = (entry) => merge(merge(shared, (entry && cfg.rules[entry]) || {}), flags);
|
|
266
|
+
const one = async (entry) => {
|
|
267
|
+
const x = await extractOne(t, { ...optsFor(entry), ...(entry ? { entry } : {}) }), found = x.model?.name;
|
|
268
|
+
return !entry && found && cfg.rules[found] ? { entry: found, x: await extractOne(t, { ...optsFor(found), entry: found }) } : { entry, x };
|
|
269
|
+
};
|
|
270
|
+
const given = o.entry ?? cfg.all.entry;
|
|
271
|
+
if (given)
|
|
272
|
+
return [await one(given)];
|
|
273
|
+
if (t.lang === 'ts' || t.lang === 'cpp') {
|
|
274
|
+
const code = t.files.map(f => fs.readFileSync(f, 'utf8')).join('\n');
|
|
275
|
+
const re = t.lang === 'cpp' ? /^\s*(?:class|struct)\s+(\w+)\s*(?::[^{]*)?\{/gm : /export\s+(?:default\s+)?(?:abstract\s+)?class\s+(\w+)|export\s+(?:const|function)\s+(\w+)/g;
|
|
276
|
+
const cands = [...new Set([...code.matchAll(re)].map(m => m[1] ?? m[2]))];
|
|
277
|
+
const all = await Promise.all(cands.map(c => one(c)));
|
|
278
|
+
const good = all.filter(r => r.x.ok);
|
|
279
|
+
return good.length ? good : all.length ? all : [{ x: { ok: false, refusals: [{ where: t.at, what: 'no class or exported function to read: name the entry (--entry)' }], notes: [] } }];
|
|
280
|
+
}
|
|
281
|
+
const first = await one();
|
|
282
|
+
if (first.x.ok)
|
|
283
|
+
return [first];
|
|
284
|
+
// (refused with no entry named: the rules gdp.toml names that the code has, each with its options)
|
|
285
|
+
const named = Object.keys(cfg.rules).filter(k => t.files.some(f => new RegExp(`\\b${k.replace(/[^\w]/g, '\\$&')}\\b`).test(fs.readFileSync(f, 'utf8'))));
|
|
286
|
+
if (named.length)
|
|
287
|
+
return Promise.all(named.map(k => one(k)));
|
|
288
|
+
// (else each class the refusal names, and each function outside a class a law is stated on)
|
|
289
|
+
const what = first.x.refusals[0]?.what ?? '';
|
|
290
|
+
const several = /several (?:classes|structs) (?:write their state|written by the file's functions) \(([^)]*)\)/.exec(what)?.[1].split(', ') ?? [];
|
|
291
|
+
const fns = [...new Set(laws.filter(l => !l.cls && l.fn).map(l => l.fn))];
|
|
292
|
+
return several.length || fns.length ? Promise.all([...several, ...fns].map(c => one(c))) : [first];
|
|
293
|
+
}
|
|
294
|
+
function scoped(file) {
|
|
295
|
+
const text = fs.readFileSync(file, 'utf8'), lines = text.split('\n');
|
|
296
|
+
return lawsIn(text, path.basename(file)).map(l => {
|
|
297
|
+
let cls, fn;
|
|
298
|
+
for (let i = l.line - 1; i >= 0 && !cls; i--) {
|
|
299
|
+
const m = /\b(?:class|struct|actor|defmodule|module|object|impl|record|interface)\s+([\w.:]+)|\btype\s+(\w+)\s+struct\b/.exec(lines[i].replace(/(#|\/\/).*$/, ''));
|
|
300
|
+
if (m)
|
|
301
|
+
cls = (m[1] ?? m[2]).split(/[.:]/).pop();
|
|
302
|
+
}
|
|
303
|
+
for (let i = l.line - 1; i < lines.length && !fn; i++) {
|
|
304
|
+
const code = i === l.line - 1 ? lines[i].replace(/(#|\/\/|--).*$/, '') : lines[i];
|
|
305
|
+
const m = /\b(?:def|defp|fn|fun|func|function)\s+(?:\([^)]*\)\s*)?(?:self\.)?(\w+)|^\s*(?:(?:public|private|protected|static|final|synchronized|async|override|open|suspend|inline|virtual|const|[\w<>[\],?]+)\s+)*(\w+)\s*\(/.exec(code);
|
|
306
|
+
if (m && !/^(if|for|while|switch|return|catch|new)$/.test(m[1] ?? m[2]))
|
|
307
|
+
fn = m[1] ?? m[2];
|
|
308
|
+
}
|
|
309
|
+
// (a Python function at the module's top level is in no class, whatever precedes it)
|
|
310
|
+
if (fn && file.endsWith('.py') && lines.slice(l.line - 1).some(x => new RegExp(`^(?:async\\s+)?def\\s+${fn}\\b`).test(x)))
|
|
311
|
+
cls = undefined;
|
|
312
|
+
return { ...l, ...(cls ? { cls } : {}), ...(fn ? { fn } : {}) };
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
export async function checkTarget(t, o) {
|
|
316
|
+
const laws = t.files.flatMap(scoped), cites = t.files.flatMap(f => citesIn(fs.readFileSync(f, 'utf8'), path.basename(f)));
|
|
317
|
+
const rules = await rulesOf(t, o, laws);
|
|
318
|
+
const outs = [];
|
|
319
|
+
// (the clock's unit, for durations in a law: the language's clock, or clock = "s" | "ms" in gdp.toml or --clock)
|
|
320
|
+
const unit = o.clock ?? configFor(t.lang === 'go' || t.lang === 'rust' || fs.statSync(t.at).isDirectory() ? t.at : path.dirname(t.at)).all.clock ?? CLOCK[t.lang];
|
|
321
|
+
const others = Object.fromEntries(rules.filter(r => r.x.ok).map(r => [r.entry ?? r.x.model?.name ?? '', r.x]));
|
|
322
|
+
const ctx = { ms: o.ms, clock: unit === 's' ? 1 : unit === 'ms' ? 1000 : undefined, others, cites, cert: o.cert, file: path.relative(proc.cwd(), t.at) || t.at };
|
|
323
|
+
for (const { entry, x } of rules) {
|
|
324
|
+
const name = entry ?? (x.model?.name || undefined);
|
|
325
|
+
// (a target that is the working directory, a crate's or a package's: `.`)
|
|
326
|
+
const r = { file: path.relative(proc.cwd(), t.at) || '.', lang: LANG_NAME[t.lang], ...(name ? { entry: name } : {}), ok: x.ok, refusals: x.refusals, notes: x.notes, names: x.names ?? [], laws: [], proposed: [], ...(x.source ? { source: x.source } : {}) };
|
|
327
|
+
outs.push(r);
|
|
328
|
+
// (the laws of this rule: all where it is the file's one, else those in its class or on it or its methods, and those
|
|
329
|
+
// outside every class and function)
|
|
330
|
+
const ms0 = new Set((x.names ?? []).map(n => n.method));
|
|
331
|
+
const mine = rules.length === 1 ? laws : laws.filter(l => (!l.cls && !l.fn) || (l.cls ? l.cls === name : l.fn === name || ms0.has(l.fn)));
|
|
332
|
+
if (!x.ok || !x.rule) {
|
|
333
|
+
r.laws = mine.map(l => ({ name: l.name, expr: l.expr, where: l.where, verdict: 'not read', why: 'the rule was refused', ms: 0 }));
|
|
334
|
+
continue;
|
|
335
|
+
}
|
|
336
|
+
const ev = x.evidence;
|
|
337
|
+
if (ev)
|
|
338
|
+
r.checked = `checked against ${'probes' in ev ? `the code: ${ev.requests} requests from the start, ${ev.fromStates} from drawn states, ${ev.probes.steps} from the prover's witnesses` : `XState's own actor: ${ev.events} events`}${ev.coverage.arms ? `, ${ev.coverage.hit} of ${ev.coverage.arms} branch arms` : ''}`;
|
|
339
|
+
// (the rule's methods: the choice of method where it has several, else the one each name says)
|
|
340
|
+
const evSort = x.model?.inputs.find(v => v.name === x.model?.event)?.sort;
|
|
341
|
+
const methods = new Set([...(x.names ?? []).filter(n => n.method).map(n => n.method), ...(evSort?.k === 'choice' ? evSort.values : [])]);
|
|
342
|
+
const stated = mine.map(l => ({ ...l, ...(l.fn && methods.has(l.fn) ? { method: l.fn } : {}) }));
|
|
343
|
+
const proven = [];
|
|
344
|
+
// (a law is known by its name: a name stated twice in one rule is refused, both times)
|
|
345
|
+
const twice = (l) => stated.filter(m => m.name === l.name).map(m => m.where);
|
|
346
|
+
r.laws = stated.map(l => (twice(l).length > 1 ? { name: l.name, expr: l.expr, where: l.where, verdict: 'not read', why: `a law of this name is stated twice (${twice(l).join(', ')}): a law is known by its name`, ms: 0 } : prove(x, l, o.ms, proven, { ...ctx, entry: name })));
|
|
347
|
+
if (o.propose && x.model) {
|
|
348
|
+
const p = propose(x, t.lang, o, proven, new Set(stated.map(l => l.expr.replace(/\s+/g, ''))));
|
|
349
|
+
r.proposed = p.shown;
|
|
350
|
+
r.brokenProposed = p.broken;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
// (a citation of no law stated in the target: refused, as a law not read is)
|
|
354
|
+
const named = new Set(laws.map(l => l.name));
|
|
355
|
+
for (const c of cites.filter(c => !named.has(c.law)))
|
|
356
|
+
outs[0]?.laws.push({ name: c.law, expr: '', where: c.where, verdict: 'not read', why: `a citation of no law stated here (gdp: cite <law name>: <clause>): ${c.text}`, ms: 0 });
|
|
357
|
+
return outs;
|
|
358
|
+
}
|
|
359
|
+
// The unit of each language's clock (Date.now() and a Clock's millis count milliseconds; time.time(), DateTime.diff in
|
|
360
|
+
// seconds and Instant's as_secs count seconds); the others say it in gdp.toml (clock = "s" or "ms").
|
|
361
|
+
const CLOCK = { python: 's', elixir: 's', rust: 's', ts: 'ms', java: 'ms', kotlin: 'ms' };
|
|
362
|
+
// A law proven: an invariant with the rule's own invariants beside it, a step law with them and the invariants proven
|
|
363
|
+
// so far (each holds in every reachable state, so the step laws may assume them); a law about two runs with the rule's
|
|
364
|
+
// invariants holding of each run (core/relational.ts). Its citations go beside it, and with --cert <dir> the proof, as
|
|
365
|
+
// an interchange document whose meta holds them.
|
|
366
|
+
function prove(x, l, ms, proven, ctx) {
|
|
367
|
+
const t0 = Date.now(), cites = ctx?.cites.filter(c => c.law === l.name).map(c => c.text) ?? [];
|
|
368
|
+
const base = { name: l.name, expr: l.expr, ...(l.where ? { where: l.where } : {}), ...(cites.length ? { cites } : {}) };
|
|
369
|
+
const inv = x.invariants ?? [], search = { search: { ms } };
|
|
370
|
+
let b, two;
|
|
371
|
+
try {
|
|
372
|
+
if (isTwoRuns(l.expr))
|
|
373
|
+
two = buildTwoRuns(x, l, ctx?.others);
|
|
374
|
+
else
|
|
375
|
+
b = buildLaw(x, l, { clock: ctx?.clock });
|
|
376
|
+
}
|
|
377
|
+
catch (e) {
|
|
378
|
+
if (e instanceof LawError || two === undefined && isTwoRuns(l.expr))
|
|
379
|
+
return { ...base, verdict: 'not read', why: e.message, ms: 0 };
|
|
380
|
+
throw e;
|
|
381
|
+
}
|
|
382
|
+
const kind = two ? 'two runs' : b.kind;
|
|
383
|
+
let v;
|
|
384
|
+
try {
|
|
385
|
+
v = two ? proveTwoRuns(two, { ...search, invariants: [two.sides[0] === x.rule ? inv : (ctx?.others && Object.values(ctx.others).find(o => o.rule === two.sides[0])?.invariants) ?? [], inv] }) : b.kind === 'law' ? proveRule(x.rule, [...inv, b.law], search) : proveSteps(x.rule, [...inv, ...proven], [b.law], search);
|
|
386
|
+
}
|
|
387
|
+
catch (e) {
|
|
388
|
+
return { ...base, kind, verdict: 'unknown', why: e.message, ms: Date.now() - t0 };
|
|
389
|
+
}
|
|
390
|
+
const verdict = v.proven && v.checked ? 'proven' : v.run ? 'broken' : 'unknown';
|
|
391
|
+
// (a state the laws allow from which a step breaks the law, no run from the start reaching it: shown, not a break)
|
|
392
|
+
const at = !v.run && v.witness && !two ? (x.names ?? []).filter(n => n.rule && n.rule in v.witness && n.role !== 'const').map(n => `${label(n)} = ${shownValue(x, n.rule, v.witness, n.none)}`) : [];
|
|
393
|
+
if (verdict === 'proven' && b?.kind === 'law')
|
|
394
|
+
proven.push(b.law);
|
|
395
|
+
const found = v.found?.laws?.map(f => f.text);
|
|
396
|
+
let cert;
|
|
397
|
+
if (verdict === 'proven' && ctx?.cert) {
|
|
398
|
+
const more = v.found?.laws?.map(f => f.law) ?? [];
|
|
399
|
+
const meta = { producer: 'gdp-wired check', file: ctx.file, ...(ctx.entry ? { entry: ctx.entry } : {}), law: l.name, expr: l.expr, ...(l.where ? { where: l.where } : {}), cites };
|
|
400
|
+
const doc = v.k ? undefined : two ? certify(two.rule, [...v.given ?? [], ...more, ...two.laws], two.stepLaws, meta)
|
|
401
|
+
: b.kind === 'law' ? certify(x.rule, [...inv, ...more, b.law], [], meta) : certify(x.rule, [...inv, ...proven, ...more], [b.law], meta);
|
|
402
|
+
if (doc) {
|
|
403
|
+
fs.mkdirSync(ctx.cert, { recursive: true });
|
|
404
|
+
cert = path.join(ctx.cert, `${[ctx.entry ?? path.basename(ctx.file), l.name].join('.').replace(/[^\w.-]+/g, '-')}.json`);
|
|
405
|
+
fs.writeFileSync(cert, JSON.stringify(doc));
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
return { ...base, kind, verdict, ...(v.run ? { run: two ? pairRunOf(x, v.run, two) : runOf(x, v.run) } : {}), ...(verdict === 'unknown' ? { why: [v.why ?? v.stuck ?? 'not proven', ...(at.length ? [`a state the laws allow where a step breaks it, no run from the start found reaching it: ${at.join(', ')}`] : [])].join('; ') } : {}),
|
|
409
|
+
...(v.run && !two ? { assumes: assumedOf(x, v.run) } : {}), ...(found?.length ? { found } : {}), ...(cert ? { cert } : {}), ms: Date.now() - t0 };
|
|
410
|
+
}
|
|
411
|
+
// Two runs as calls of the code: each request once, the values the two runs take apart as `a | b`, and the run b leaves
|
|
412
|
+
// out (isolation's: the others' calls) marked.
|
|
413
|
+
function pairRunOf(x, run, two) {
|
|
414
|
+
const sideOf = (vars, p) => Object.fromEntries(Object.entries(vars).flatMap(([k, val]) => (k.startsWith(p) ? [[k.slice(2), val]] : /^[ab]_/.test(k) ? [] : [[k, val]])));
|
|
415
|
+
const a = runOf(x, { params: sideOf(run.params, 'a_'), trace: run.trace.map(q => sideOf(q, 'a_')) });
|
|
416
|
+
const b = runOf(x, { params: sideOf(run.params, 'b_'), trace: run.trace.map(q => sideOf(q, 'b_')) });
|
|
417
|
+
const tenant = 'tenant' in run.params && !two.shared.every(n => n !== 'tenant') ? [`B is ${run.params.tenant} (run b takes only B's calls)`] : [];
|
|
418
|
+
return [...tenant, ...a.map((s, i) => (s === b[i] ? s : `${s} | ${b[i]}`))];
|
|
419
|
+
}
|
|
420
|
+
// What a refutation assumes of the answers inferred (core/extract-step.ts's `assumed`), at the run's last request.
|
|
421
|
+
function assumedOf(x, run) {
|
|
422
|
+
const last = run.trace.at(-1), out = [];
|
|
423
|
+
for (const n of (x.names ?? []).filter(m => m.role === 'answer')) {
|
|
424
|
+
if (!last || !(n.rule in last))
|
|
425
|
+
continue;
|
|
426
|
+
const how = x.read?.answers.find(a => a.key === n.code);
|
|
427
|
+
if (how?.how)
|
|
428
|
+
out.push(`assumes ${n.code.split('.').pop()}(...) may return ${shownValue(x, n.rule, last, n.none)} (${how.how}: any ${how.sort})`);
|
|
429
|
+
}
|
|
430
|
+
return out;
|
|
431
|
+
}
|
|
432
|
+
function kindOf(x, rule) {
|
|
433
|
+
const r = x.rule;
|
|
434
|
+
return [...r.parts.params, ...r.parts.inputs, ...r.kindsOfState()].find(([n]) => n === rule)?.[1];
|
|
435
|
+
}
|
|
436
|
+
function shownValue(x, rule, vars, none) {
|
|
437
|
+
if (none && (vars[none] === 1 || vars[none] === true))
|
|
438
|
+
return 'None';
|
|
439
|
+
const k = kindOf(x, rule);
|
|
440
|
+
try {
|
|
441
|
+
const v = k ? k.decode(rule, vars) : vars[rule];
|
|
442
|
+
return typeof v === 'string' ? JSON.stringify(v) : String(v);
|
|
443
|
+
}
|
|
444
|
+
catch {
|
|
445
|
+
return `a string (#${String(vars[rule])})`;
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
// A run as calls of the code: the constructor's arguments, then each request (the method, its arguments by the code's
|
|
449
|
+
// names, the answers and the clock), the last the one that breaks the law.
|
|
450
|
+
export function runOf(x, run) {
|
|
451
|
+
const names = namesWithClock(x), code = (n) => n.code;
|
|
452
|
+
const ps = names.filter(n => n.role === 'param' && n.rule && n.rule in run.params);
|
|
453
|
+
const lines = ps.length ? [`made with ${ps.map(n => `${code(n)} = ${shownValue(x, n.rule, run.params, n.none)}`).join(', ')}`] : [];
|
|
454
|
+
const ev = names.find(n => n.role === 'method');
|
|
455
|
+
for (const req of run.trace) {
|
|
456
|
+
const m = ev ? String(kindOf(x, ev.rule)?.decode(ev.rule, req) ?? '') : names.find(n => n.method)?.method ?? '';
|
|
457
|
+
// (an object the caller gives: None, or its fields read; a field of an object that is None not shown)
|
|
458
|
+
const none = (n) => !!n.none && (req[n.none] === 1 || req[n.none] === true);
|
|
459
|
+
const objs = names.filter(n => n.role === 'input' && n.method === m && !n.rule && n.none && n.none in req);
|
|
460
|
+
const as = names.filter(n => n.role === 'input' && n.method === m && (n.rule ? n.rule in req : none(n)) && !objs.some(o => none(o) && n.code.startsWith(`${o.code}.`)));
|
|
461
|
+
const call = `${m || 'step'}(${as.map(n => `${code(n)}=${n.rule ? shownValue(x, n.rule, req, n.none) : 'None'}`).join(', ')})`;
|
|
462
|
+
const extra = names.filter(n => (n.role === 'answer' || n.role === 'clock') && n.rule in req).map(n => `${label(n)} = ${shownValue(x, n.rule, req, n.none)}`);
|
|
463
|
+
lines.push(extra.length ? `${call} with ${extra.join(', ')}` : call);
|
|
464
|
+
}
|
|
465
|
+
return lines;
|
|
466
|
+
}
|
|
467
|
+
// --- laws proposed: the rule's own comparisons, as laws in the code's terms ----------------------------------------------
|
|
468
|
+
// From each comparison, min or max of the step between a number of the state and another number of the state or the
|
|
469
|
+
// params, or two fields of one map's cells: that one is at most the other (both ways); an integer of the state never
|
|
470
|
+
// below 0; a number of the state that never goes down, or up. Each proven or broken by the prover; the broken ones only
|
|
471
|
+
// counted (they are guesses, not claims).
|
|
472
|
+
function propose(x, lang, o, proven, stated) {
|
|
473
|
+
const m = x.rule.machine, names = x.names ?? [], model = x.model;
|
|
474
|
+
const nums = new Set([...model.state, ...model.params].filter(v => v.sort.k === 'num' && !model.outputs.includes(v.name) && v.name !== 'made_at').map(v => v.name));
|
|
475
|
+
const state = new Set(model.state.filter(v => nums.has(v.name)).map(v => v.name));
|
|
476
|
+
// (the code's name for a variable, or the rule's where the code's names another first)
|
|
477
|
+
const codeOf = (rule) => { const n = names.find(y => y.rule === rule && (y.role === 'state' || y.role === 'param')); if (!n)
|
|
478
|
+
return rule; const first = names.find(y => y.code === n.code && (y.role === 'state' || y.role === 'param')); return first === n ? n.code : rule; };
|
|
479
|
+
const base = (v) => v.replace(/\$neg$/, '');
|
|
480
|
+
const sides = (e) => { const s = new Set(); JSON.stringify(e, (k, v) => { if (k === 'name' && typeof v === 'string')
|
|
481
|
+
s.add(base(v)); if (k === 'map' && typeof v === 'string')
|
|
482
|
+
s.add(base(v)); return v; }); return s; };
|
|
483
|
+
const pairs = new Set();
|
|
484
|
+
JSON.stringify(m.step, (_, v) => {
|
|
485
|
+
if (v && typeof v === 'object' && ['<', '<=', 'min', 'max'].includes(v.op ?? '') && 'a' in v && 'b' in v) {
|
|
486
|
+
const a = sides(v.a), b = sides(v.b);
|
|
487
|
+
for (const p of a)
|
|
488
|
+
for (const q of b)
|
|
489
|
+
if (p !== q) {
|
|
490
|
+
pairs.add(`${p}\0${q}`);
|
|
491
|
+
pairs.add(`${q}\0${p}`);
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
return v;
|
|
495
|
+
});
|
|
496
|
+
const cands = [];
|
|
497
|
+
const add = (name, expr) => { if (!stated.has(expr.replace(/\s+/g, '')) && !cands.some(c => c.expr === expr))
|
|
498
|
+
cands.push({ name, expr }); };
|
|
499
|
+
for (const pq of pairs) {
|
|
500
|
+
const [p, q] = pq.split('\0');
|
|
501
|
+
if (state.has(p) && nums.has(q))
|
|
502
|
+
add(`${codeOf(p)} stays at most ${codeOf(q)}`, `${codeOf(p)} <= ${codeOf(q)}`);
|
|
503
|
+
const mp = /^(.+)\.(\w+)$/.exec(p), mq = /^(.+)\.(\w+)$/.exec(q);
|
|
504
|
+
if (mp && mq && mp[1] === mq[1] && mp[2] !== mq[2] && mp[2] !== 'has' && mq[2] !== 'has') {
|
|
505
|
+
const map = names.find(n => n.rule === mp[1] && n.map);
|
|
506
|
+
if (map && map.map.fields.includes(mp[2]) && map.map.fields.includes(mq[2]))
|
|
507
|
+
add(`every ${map.code}'s ${mp[2]} stays at most its ${mq[2]}`, `forall k in ${map.code}: ${map.code}[k].${mp[2]} <= ${map.code}[k].${mq[2]}`);
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
for (const v of state) {
|
|
511
|
+
if (`${v}$neg` in m.state)
|
|
512
|
+
add(`${codeOf(v)} is never negative`, `${codeOf(v)} >= 0`);
|
|
513
|
+
add(`${codeOf(v)} never changes`, `${codeOf(v)} == old(${codeOf(v)})`);
|
|
514
|
+
add(`${codeOf(v)} never goes down`, `${codeOf(v)} >= old(${codeOf(v)})`);
|
|
515
|
+
add(`${codeOf(v)} never goes up`, `${codeOf(v)} <= old(${codeOf(v)})`);
|
|
516
|
+
}
|
|
517
|
+
const shown = [], until = Date.now() + Math.max(5000, o.ms * 2);
|
|
518
|
+
let broken = 0;
|
|
519
|
+
const fixed = new Set();
|
|
520
|
+
for (const c of cands.slice(0, 40)) {
|
|
521
|
+
if (Date.now() > until)
|
|
522
|
+
break;
|
|
523
|
+
const v = /^(.+) never (?:changes|goes (?:down|up))$/.exec(c.name)?.[1];
|
|
524
|
+
if (v && fixed.has(v))
|
|
525
|
+
continue;
|
|
526
|
+
const r = prove(x, c, Math.min(o.ms, 2000), proven);
|
|
527
|
+
if (r.verdict === 'broken' || r.verdict === 'not read')
|
|
528
|
+
broken++;
|
|
529
|
+
else {
|
|
530
|
+
shown.push({ ...r, where: `${COMMENT[lang]} gdp: law ${c.name}: ${c.expr}` });
|
|
531
|
+
if (v && r.verdict === 'proven' && c.name.endsWith('changes'))
|
|
532
|
+
fixed.add(v);
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
return { shown, broken };
|
|
536
|
+
}
|
|
537
|
+
// The laws `check` proposes for an extraction with nothing stated, each proven (`shown`: those not broken by a run).
|
|
538
|
+
export const proposedLaws = (x, lang, ms = 2000) => propose(x, lang, { ms, propose: true }, [], new Set());
|
|
539
|
+
// --- printing ------------------------------------------------------------------------------------------------------------
|
|
540
|
+
const ROLE = { state: 'state', param: 'made with', input: 'request', answer: 'answered', result: 'result', failed: 'failed', method: 'method', clock: 'clock', const: 'constant' };
|
|
541
|
+
function printRule(r, o) {
|
|
542
|
+
out(`${r.file}${r.entry ? `: ${r.entry}` : ''} (${r.lang})`);
|
|
543
|
+
if (!r.ok) {
|
|
544
|
+
for (const f of r.refusals)
|
|
545
|
+
out(` ${paint('yellow', `refused at ${f.where}:`)} ${f.what}`);
|
|
546
|
+
}
|
|
547
|
+
else {
|
|
548
|
+
if (r.checked)
|
|
549
|
+
out(` ${paint('dim', r.checked)}`);
|
|
550
|
+
const inferred = r.notes.filter(n => /inferred|tagged|left out|answered|injected|the entry/.test(n));
|
|
551
|
+
for (const n of inferred.slice(0, 12))
|
|
552
|
+
out(` ${n}`);
|
|
553
|
+
out(` ${paint('dim', 'names (the code\'s, then the rule\'s):')}`);
|
|
554
|
+
const w = Math.min(36, Math.max(...r.names.map(n => label(n).length), 8));
|
|
555
|
+
for (const n of r.names)
|
|
556
|
+
out(` ${paint('dim', `${label(n).padEnd(w)} ${ROLE[n.role].padEnd(9)} ${n.rule}${n.none ? `${n.rule ? ', ' : ''}None: ${n.none}` : ''}${n.map ? ` (cells: ${n.map.fields.join(', ')}${n.map.tpl ? `; key ${JSON.stringify(n.map.tpl)}` : ''})` : ''}${n.role === 'const' ? String(n.value) : ''}`)}`);
|
|
557
|
+
}
|
|
558
|
+
const law = (l, proposed) => {
|
|
559
|
+
out(` ${paint(VERDICT[l.verdict], l.verdict)}${' '.repeat(Math.max(0, 9 - l.verdict.length))}${l.name}${proposed ? '' : ` ${paint('dim', `(${l.where})`)}`}`);
|
|
560
|
+
if (!proposed && l.verdict !== 'proven')
|
|
561
|
+
out(` ${l.expr}`);
|
|
562
|
+
for (const c of l.cites ?? [])
|
|
563
|
+
out(` cites: ${c}`);
|
|
564
|
+
if (l.cert)
|
|
565
|
+
out(` ${paint('dim', `certificate: ${l.cert}`)}`);
|
|
566
|
+
if (l.run)
|
|
567
|
+
for (const [i, s] of l.run.entries())
|
|
568
|
+
out(` ${i === 0 ? 'run: ' : ' '}${paint('red', s)}`);
|
|
569
|
+
for (const a of l.assumes ?? [])
|
|
570
|
+
out(` ${a}`);
|
|
571
|
+
if (l.found)
|
|
572
|
+
out(` proven with what the search found: ${l.found.join('; ')}`);
|
|
573
|
+
if (l.why && l.verdict !== 'proven')
|
|
574
|
+
out(` ${l.why}`);
|
|
575
|
+
if (proposed)
|
|
576
|
+
out(` ${l.where}`);
|
|
577
|
+
};
|
|
578
|
+
if (r.laws.length) {
|
|
579
|
+
out(' laws stated in the code:');
|
|
580
|
+
for (const l of r.laws)
|
|
581
|
+
law(l, false);
|
|
582
|
+
}
|
|
583
|
+
if (r.proposed.length || r.brokenProposed) {
|
|
584
|
+
out(' laws proposed (nothing written; state one with the comment under it):');
|
|
585
|
+
for (const l of r.proposed)
|
|
586
|
+
law(l, true);
|
|
587
|
+
if (r.brokenProposed)
|
|
588
|
+
out(` (${r.brokenProposed} more proposed and broken by a run: not shown)`);
|
|
589
|
+
}
|
|
590
|
+
if (r.ok && !r.laws.length)
|
|
591
|
+
out(` no law stated: write one as \`${COMMENT[Object.keys(LANG_NAME).find(k => LANG_NAME[k] === r.lang)]} gdp: law <name>: <expr>\` over the names above`);
|
|
592
|
+
void o;
|
|
593
|
+
out();
|
|
594
|
+
}
|
|
595
|
+
const label = (n) => (n.role === 'answer' ? `${n.code.split('.').pop()}(...)` : n.role === 'input' && n.method ? `${n.method}(${n.code})` : n.role === 'result' && n.method ? `${n.method}() result` : n.code);
|
|
596
|
+
const USAGE = `gdp-wired check <file|dir>... [--entry X] [--methods a,b] [--failures kept] [--on-error discard] [--json] [--ms 10000] [--no-propose] [--clock s|ms] [--cert <dir>]
|
|
597
|
+
|
|
598
|
+
Reads the rule in each file (Python, Ruby, Elixir, Java, Kotlin, Go, Rust, Swift, C, C++, TypeScript, Effect, XState), checks it
|
|
599
|
+
against the code by running both, proves the laws stated in the code (\`# gdp: law <name>: <expr>\`, \`// gdp: law ...\`,
|
|
600
|
+
@GdpLaw("<name>: <expr>")) and proposes others. Laws about two runs: \`<secret> never reaches <fields>\`, \`isolated by <argument>\`,
|
|
601
|
+
\`agrees with <Class>\`; a duration over the clock: \`now - t < 30 days\`; the clause a law answers: \`gdp: cite <law name>: <clause>\`;
|
|
602
|
+
--cert <dir> writes each proven law's certificate (its meta the citations). Exit code: 1 when a stated law is broken, 2 when
|
|
603
|
+
one couldn't be checked.`;
|
|
604
|
+
// Every target's rules and their laws, and the exit code (1: a stated law broken; 2: one not checked).
|
|
605
|
+
export async function check(targets, given = {}, each) {
|
|
606
|
+
const o = { ms: 10_000, propose: true, ...given }, all = [];
|
|
607
|
+
for (const p of targets)
|
|
608
|
+
for (const t of targetsOf(p)) {
|
|
609
|
+
const rs = await checkTarget(t, o);
|
|
610
|
+
all.push(...rs);
|
|
611
|
+
if (each)
|
|
612
|
+
rs.forEach(each);
|
|
613
|
+
}
|
|
614
|
+
const stated = all.flatMap(r => r.laws);
|
|
615
|
+
return { rules: all, exit: stated.some(l => l.verdict === 'broken') ? 1 : stated.some(l => l.verdict === 'not read') ? 2 : 0 };
|
|
616
|
+
}
|
|
617
|
+
export async function main(argv) {
|
|
618
|
+
const { cmd, targets, o } = args(argv);
|
|
619
|
+
if (cmd !== 'check' || !targets.length) {
|
|
620
|
+
out(USAGE);
|
|
621
|
+
return cmd === 'help' || cmd === '--help' || cmd === '-h' || !cmd ? 0 : 2;
|
|
622
|
+
}
|
|
623
|
+
tint = colors(proc.env, !!proc.stdout.isTTY, !!o.json);
|
|
624
|
+
const { rules: all, exit: code } = await check(targets, o, o.json ? undefined : r => printRule(r, o));
|
|
625
|
+
const stated = all.flatMap(r => r.laws);
|
|
626
|
+
if (o.json)
|
|
627
|
+
out(JSON.stringify({ rules: all.map(({ source: _s, ...r }) => r), exit: code }, null, 1));
|
|
628
|
+
else if (stated.length) {
|
|
629
|
+
const n = (v) => stated.filter(l => l.verdict === v).length;
|
|
630
|
+
out(`${paint('green', n('proven'))} of ${stated.length} stated laws proven, ${paint('red', n('broken'))} broken, ${paint('yellow', n('unknown'))} unknown, ${paint('yellow', n('not read'))} not read`);
|
|
631
|
+
}
|
|
632
|
+
return code;
|
|
633
|
+
}
|
|
634
|
+
if (import.meta.url === `file://${proc.argv[1]}` || /\/(cli\.(ts|js)|gdp-wired)$/.test(proc.argv[1] ?? '')) {
|
|
635
|
+
main(proc.argv.slice(2)).then(c => { proc.exitCode = c; }, e => { out(`gdp-wired: ${e.message}`); proc.exitCode = 2; });
|
|
636
|
+
}
|