gdp-wired 0.55.1 → 0.56.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +48 -0
- package/dist/core/agent-consult/cli.js +11 -0
- package/dist/core/agent-consult/worker.js +9 -0
- package/dist/core/c/reader.d.ts +74 -2
- package/dist/core/c/reader.js +3144 -121
- package/dist/core/c/safety.d.ts +98 -0
- package/dist/core/c/safety.js +642 -0
- package/dist/core/cli.d.ts +9 -0
- package/dist/core/cli.js +215 -8
- package/dist/core/extract-c.d.ts +8 -0
- package/dist/core/extract-c.js +114 -15
- package/dist/core/extract-check.js +124 -12
- package/dist/core/extract-go-check.js +6 -0
- package/dist/core/extract-go.d.ts +15 -1
- package/dist/core/extract-go.js +102 -4
- package/dist/core/extract-print.js +4 -2
- package/dist/core/extract-step.d.ts +22 -0
- package/dist/core/extract-step.js +261 -9
- package/dist/core/extract.d.ts +10 -0
- package/dist/core/extract.js +37 -3
- package/dist/core/law-answer.d.ts +1 -0
- package/dist/core/law-answer.js +23 -0
- package/dist/core/laws.js +3 -16
- package/dist/core/native-law.js +11 -3
- package/dist/interchange/cli.js +13 -0
- package/package.json +1 -1
|
@@ -92,6 +92,67 @@ export function instrument(code, file, tail = '', extra = []) {
|
|
|
92
92
|
const js = ts.transpileModule(out, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022, esModuleInterop: true, jsx: ts.JsxEmit.React }, fileName: file.replace(/\.js$/, '.ts').replace(/\.jsx$/, '.tsx') }).outputText;
|
|
93
93
|
return { js, arms };
|
|
94
94
|
}
|
|
95
|
+
// Cooperative deadline instrumentation for Bun, where node:vm's `timeout` option leaks a watchdog timer that can kill
|
|
96
|
+
// later host JavaScript on affected versions (e.g. Bun 1.3.14). Node keeps node:vm's native timeout unchanged.
|
|
97
|
+
const isBun = typeof globalThis.Bun !== 'undefined';
|
|
98
|
+
class SandboxTimeout extends Error {
|
|
99
|
+
code = 'ERR_SCRIPT_EXECUTION_TIMEOUT';
|
|
100
|
+
constructor(ms) { super(`Script execution timed out after ${ms}ms`); }
|
|
101
|
+
}
|
|
102
|
+
function instrumentTicks(js, file) {
|
|
103
|
+
const sf = ts.createSourceFile(file, js, ts.ScriptTarget.ES2022, true, ts.ScriptKind.JS);
|
|
104
|
+
const edits = [];
|
|
105
|
+
const isLoop = (n) => ts.isForStatement(n) || ts.isForInStatement(n) || ts.isForOfStatement(n) || ts.isWhileStatement(n) || ts.isDoStatement(n);
|
|
106
|
+
const isFn = (n) => ts.isFunctionDeclaration(n) || ts.isFunctionExpression(n) || ts.isMethodDeclaration(n) ||
|
|
107
|
+
ts.isGetAccessorDeclaration(n) || ts.isSetAccessorDeclaration(n) || ts.isConstructorDeclaration(n) || ts.isArrowFunction(n);
|
|
108
|
+
const blockInsert = (b) => {
|
|
109
|
+
const start = b.getStart(sf) + 1;
|
|
110
|
+
let pos = start;
|
|
111
|
+
for (const st of b.statements) {
|
|
112
|
+
if (ts.isExpressionStatement(st) && ts.isStringLiteral(st.expression))
|
|
113
|
+
pos = st.end;
|
|
114
|
+
else
|
|
115
|
+
break;
|
|
116
|
+
}
|
|
117
|
+
return [pos, pos > start ? ';__gdp_tick();' : '__gdp_tick();'];
|
|
118
|
+
};
|
|
119
|
+
const visit = (n) => {
|
|
120
|
+
if (isLoop(n)) {
|
|
121
|
+
const body = n.statement;
|
|
122
|
+
if (ts.isBlock(body)) {
|
|
123
|
+
edits.push([body.getStart(sf) + 1, '__gdp_tick();']);
|
|
124
|
+
ts.forEachChild(n, visit);
|
|
125
|
+
}
|
|
126
|
+
else {
|
|
127
|
+
edits.push([body.getStart(sf), '{__gdp_tick();']);
|
|
128
|
+
ts.forEachChild(n, visit);
|
|
129
|
+
edits.push([body.end, '}']);
|
|
130
|
+
}
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
if (isFn(n) && n.body) {
|
|
134
|
+
if (ts.isBlock(n.body)) {
|
|
135
|
+
edits.push(blockInsert(n.body));
|
|
136
|
+
ts.forEachChild(n, visit);
|
|
137
|
+
}
|
|
138
|
+
else {
|
|
139
|
+
edits.push([n.body.getStart(sf), '(__gdp_tick(), (']);
|
|
140
|
+
ts.forEachChild(n, visit);
|
|
141
|
+
edits.push([n.body.end, '))']);
|
|
142
|
+
}
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
ts.forEachChild(n, visit);
|
|
146
|
+
};
|
|
147
|
+
visit(sf);
|
|
148
|
+
if (!edits.length)
|
|
149
|
+
return js;
|
|
150
|
+
const order = edits.map((e, i) => [...e, i]).sort((a, b) => b[0] - a[0] || b[2] - a[2]);
|
|
151
|
+
let out = js;
|
|
152
|
+
for (const [pos, txt] of order)
|
|
153
|
+
out = out.slice(0, pos) + txt + out.slice(pos);
|
|
154
|
+
return out;
|
|
155
|
+
}
|
|
95
156
|
export function sandbox(code, file, expose, modules = {}, init, files = {}, extra = [], nativeMethods = []) {
|
|
96
157
|
const vm = vmOf();
|
|
97
158
|
// A final arrow can end exactly where a factory appends fields. Its capture
|
|
@@ -100,6 +161,19 @@ export function sandbox(code, file, expose, modules = {}, init, files = {}, extr
|
|
|
100
161
|
const captured = new Map(), captureErrors = new Map();
|
|
101
162
|
const counts = arms.map(() => 0);
|
|
102
163
|
let now = 0, invocation = 0, observedClock, observing = false;
|
|
164
|
+
let ticks = 0, deadline = Infinity, limitMs = 0, timedOut = false;
|
|
165
|
+
const startBudget = (ms) => { ticks = 0; limitMs = ms; timedOut = false; deadline = performance.now() + ms; };
|
|
166
|
+
const stopBudget = () => { deadline = Infinity; timedOut = false; };
|
|
167
|
+
const tick = () => {
|
|
168
|
+
if (timedOut)
|
|
169
|
+
throw new SandboxTimeout(limitMs);
|
|
170
|
+
if (deadline === Infinity)
|
|
171
|
+
return;
|
|
172
|
+
if ((++ticks & 15) === 0 && performance.now() >= deadline) {
|
|
173
|
+
timedOut = true;
|
|
174
|
+
throw new SandboxTimeout(limitMs);
|
|
175
|
+
}
|
|
176
|
+
};
|
|
103
177
|
const stub = (name) => new Proxy({}, {
|
|
104
178
|
get: (_, k) => { if (k === '__esModule' || typeof k === 'symbol')
|
|
105
179
|
return undefined; throw new Error(`the check loads no module ${name} (its ${String(k)} was read)`); },
|
|
@@ -125,6 +199,8 @@ export function sandbox(code, file, expose, modules = {}, init, files = {}, extr
|
|
|
125
199
|
require: (name) => (name in modules ? modules[name] : name.startsWith('.') && Object.keys(files).length ? load(ENTRY, name) : stub(name)),
|
|
126
200
|
console: { log() { }, warn() { }, error() { }, info() { }, debug() { } },
|
|
127
201
|
});
|
|
202
|
+
if (isBun)
|
|
203
|
+
Object.defineProperty(ctx, '__gdp_tick', { value: tick, writable: false, configurable: false, enumerable: false });
|
|
128
204
|
// The files given, by their place beside the entry's; each loaded once.
|
|
129
205
|
const ENTRY = `/v/${file.split('/').pop()}`, abs = Object.fromEntries(Object.entries(files).map(([p, c]) => [normalize(`/v/${p}`), c])), loaded = new Map();
|
|
130
206
|
const load = (from, spec) => {
|
|
@@ -142,10 +218,13 @@ export function sandbox(code, file, expose, modules = {}, init, files = {}, extr
|
|
|
142
218
|
// A file that doesn't load here (it reads import.meta, a browser's globals): a stub that throws when read, so a step
|
|
143
219
|
// that reads it fails the check rather than running without it.
|
|
144
220
|
try {
|
|
145
|
-
const
|
|
221
|
+
const body = isBun ? instrumentTicks(js, at) : js;
|
|
222
|
+
const f = vm.runInContext(`(function (module, exports, require) {${body}\n})`, ctx);
|
|
146
223
|
f(m, m.exports, (s2) => (s2 in modules ? modules[s2] : s2.startsWith('.') ? load(at, s2) : stub(s2)));
|
|
147
224
|
}
|
|
148
225
|
catch (e) {
|
|
226
|
+
if (timedOut)
|
|
227
|
+
throw e;
|
|
149
228
|
const st = stub(`${spec} (${e.message})`);
|
|
150
229
|
loaded.set(at, st);
|
|
151
230
|
return st;
|
|
@@ -155,8 +234,22 @@ export function sandbox(code, file, expose, modules = {}, init, files = {}, extr
|
|
|
155
234
|
};
|
|
156
235
|
// The clock is the request's: Date.now() and new Date() read it.
|
|
157
236
|
vm.runInContext('globalThis.Date = new Proxy(Date, {construct: (D, a) => (a.length ? new D(...a) : new D(__now())), get: (D, k) => (k === "now" ? () => __now() : D[k])}); Math.random = () => { throw new Error("Math.random in a step") }', ctx);
|
|
158
|
-
|
|
159
|
-
return 'default: module.exports.default'; const [h, ...rest] = n.split('.'); return `${JSON.stringify(n)}: (typeof ${h} !== 'undefined' ? ${h} : module.exports.${h})${rest.map(x => `.${x}`).join('')}`; }).join(', ')}}
|
|
237
|
+
const loadCode = `${isBun ? instrumentTicks(js, file) : js}\n;globalThis.__gdp = {${expose.map(n => { if (n === 'default')
|
|
238
|
+
return 'default: module.exports.default'; const [h, ...rest] = n.split('.'); return `${JSON.stringify(n)}: (typeof ${h} !== 'undefined' ? ${h} : module.exports.${h})${rest.map(x => `.${x}`).join('')}`; }).join(', ')}};`;
|
|
239
|
+
if (isBun) {
|
|
240
|
+
startBudget(2000);
|
|
241
|
+
try {
|
|
242
|
+
vm.runInContext(loadCode, ctx, { filename: file });
|
|
243
|
+
if (timedOut)
|
|
244
|
+
throw new SandboxTimeout(2000);
|
|
245
|
+
}
|
|
246
|
+
finally {
|
|
247
|
+
stopBudget();
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
else {
|
|
251
|
+
vm.runInContext(loadCode, ctx, { timeout: 2000, filename: file });
|
|
252
|
+
}
|
|
160
253
|
const script = new vm.Script('globalThis.__r = (() => { try { return {ok: true, value: __gdp[__f].apply(__self, __args)} } catch (e) { return {ok: false, error: String(e && e.message || e)} } })()');
|
|
161
254
|
const call = (f, self, args, housekeeping = false) => {
|
|
162
255
|
// Reading/restoring a factory's closure is harness work, not a new request.
|
|
@@ -169,16 +262,35 @@ export function sandbox(code, file, expose, modules = {}, init, files = {}, extr
|
|
|
169
262
|
}
|
|
170
263
|
observing = request;
|
|
171
264
|
Object.assign(ctx, { __f: f, __self: self, __args: args });
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
265
|
+
if (isBun) {
|
|
266
|
+
startBudget(1000);
|
|
267
|
+
try {
|
|
268
|
+
script.runInContext(ctx);
|
|
269
|
+
if (timedOut)
|
|
270
|
+
throw new SandboxTimeout(1000);
|
|
271
|
+
}
|
|
272
|
+
catch (e) {
|
|
273
|
+
if (timedOut || e.code === 'ERR_SCRIPT_EXECUTION_TIMEOUT')
|
|
274
|
+
throw new HarnessFailure(`a request ran past the check's 1000 ms (${e.message})`);
|
|
275
|
+
throw e;
|
|
276
|
+
}
|
|
277
|
+
finally {
|
|
278
|
+
stopBudget();
|
|
279
|
+
observing = false;
|
|
280
|
+
}
|
|
179
281
|
}
|
|
180
|
-
|
|
181
|
-
|
|
282
|
+
else {
|
|
283
|
+
try {
|
|
284
|
+
script.runInContext(ctx, { timeout: 1000 });
|
|
285
|
+
}
|
|
286
|
+
catch (e) {
|
|
287
|
+
if (e.code === 'ERR_SCRIPT_EXECUTION_TIMEOUT')
|
|
288
|
+
throw new HarnessFailure(`a request ran past the check's 1000 ms (${e.message})`);
|
|
289
|
+
throw e;
|
|
290
|
+
}
|
|
291
|
+
finally {
|
|
292
|
+
observing = false;
|
|
293
|
+
}
|
|
182
294
|
}
|
|
183
295
|
return ctx.__r;
|
|
184
296
|
};
|
|
@@ -2,6 +2,7 @@ import { Outside, constantsOf, draw, drive, evalTerm } from "./extract-check.js"
|
|
|
2
2
|
import { buildCheck, builtEvidence, compileLimit, openHarness, stopped, stubbed } from "./extract-step.js";
|
|
3
3
|
import { node } from "./extract-go.js";
|
|
4
4
|
import { nativeWireDecoder, snapshotNativeBindings } from "./native-wire.js";
|
|
5
|
+
import { nativeObservationSequence } from "./native-observations.js";
|
|
5
6
|
// --- the harness ------------------------------------------------------------------------------------------------------
|
|
6
7
|
// Go source beside the package: a state set from JSON and read back as JSON, leaf by leaf; each method called with its
|
|
7
8
|
// arguments made from JSON; a panic recovered; the left-out fields compared before and after.
|
|
@@ -549,6 +550,8 @@ export function speak(work, bin, env, pkg, read, r, sorts, opts, count) {
|
|
|
549
550
|
const capabilities = ask({ op: 'hello' });
|
|
550
551
|
const decode = capabilities.nativeSnapshot === 1 || capabilities.nativeBindings === 1 ? nativeWireDecoder() : undefined;
|
|
551
552
|
let bindings;
|
|
553
|
+
const acceptObservation = capabilities.nativeObservations === 1 ? nativeObservationSequence(new Set(read.answers?.map(a => a.key))) : undefined;
|
|
554
|
+
let observations, observedCache;
|
|
552
555
|
// A state from the harness as a snapshot (a number past the safe integers: the code leaves the rule's numbers).
|
|
553
556
|
const toSnap = (s) => {
|
|
554
557
|
const leaves = {}, maps = {}, lists = {};
|
|
@@ -630,6 +633,8 @@ export function speak(work, bin, env, pkg, read, r, sorts, opts, count) {
|
|
|
630
633
|
}
|
|
631
634
|
const res = ask({ op: 'call', id: self, m: e.call, now, a: args, ...(answers ? { answers } : {}) });
|
|
632
635
|
bindings = res.nativeBindings;
|
|
636
|
+
observations = res.nativeObservations;
|
|
637
|
+
observedCache = undefined;
|
|
633
638
|
if (res.frame)
|
|
634
639
|
throw new Error(`the code changes ${res.frame}, a field the rule leaves out`);
|
|
635
640
|
if (res.bad)
|
|
@@ -649,6 +654,7 @@ export function speak(work, bin, env, pkg, read, r, sorts, opts, count) {
|
|
|
649
654
|
throw new Error(`native parameter capture: ${bindings.error}`);
|
|
650
655
|
return bindings?.snapshot ? snapshotNativeBindings(decode, bindings.snapshot) : undefined;
|
|
651
656
|
} } : {}),
|
|
657
|
+
...(acceptObservation ? { nativeObservations: () => (observedCache ??= acceptObservation(observations)) } : {}),
|
|
652
658
|
args: (inputs, e) => e.args.map(a => argJson(a, inputs)),
|
|
653
659
|
setNow: n => { if (!Number.isSafeInteger(n))
|
|
654
660
|
throw new Outside('Go clock outside the exact integer range'); now = n; },
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { B } from './extract-ir.js';
|
|
2
2
|
import { type Arg, type Model, type FileURL } from './extract-read.js';
|
|
3
3
|
import { type Extraction, type Name } from './extract.js';
|
|
4
|
-
import { type Answer } from './extract-step.js';
|
|
4
|
+
import { type Answer, type SafetySite } from './extract-step.js';
|
|
5
5
|
import { type GoCheckOptions, type GoLeaf } from './extract-go-check.js';
|
|
6
6
|
export { minimizeRun, minimizeRunDetailed, proveRule, proveSteps } from './dsl.js';
|
|
7
7
|
export type TT = {
|
|
@@ -87,6 +87,12 @@ export type GX = {
|
|
|
87
87
|
}[];
|
|
88
88
|
i?: GX;
|
|
89
89
|
end?: string;
|
|
90
|
+
site?: SafetySite;
|
|
91
|
+
sites?: SafetySite[];
|
|
92
|
+
checkedType?: number;
|
|
93
|
+
dims?: number[];
|
|
94
|
+
vals?: number[];
|
|
95
|
+
indices?: GX[];
|
|
90
96
|
};
|
|
91
97
|
export type GS = {
|
|
92
98
|
s: string;
|
|
@@ -145,10 +151,12 @@ export type GoFunc = {
|
|
|
145
151
|
params: GoParam[];
|
|
146
152
|
results: GoParam[];
|
|
147
153
|
body?: GS[];
|
|
154
|
+
safetySites?: SafetySite[];
|
|
148
155
|
};
|
|
149
156
|
export type GoPkg = {
|
|
150
157
|
dir?: string;
|
|
151
158
|
lang?: string;
|
|
159
|
+
safety?: true;
|
|
152
160
|
ctor?: GoFunc;
|
|
153
161
|
package: string;
|
|
154
162
|
files: {
|
|
@@ -189,6 +197,7 @@ export type GoOptions = {
|
|
|
189
197
|
check?: GoCheckOptions;
|
|
190
198
|
fails?: Record<string, string>;
|
|
191
199
|
strict?: boolean;
|
|
200
|
+
safety?: boolean;
|
|
192
201
|
answers?: Record<string, string>;
|
|
193
202
|
skip?: string[];
|
|
194
203
|
};
|
|
@@ -198,6 +207,11 @@ export type GoClock = {
|
|
|
198
207
|
callee: string;
|
|
199
208
|
};
|
|
200
209
|
export type GoRead = {
|
|
210
|
+
safety?: {
|
|
211
|
+
sites: (SafetySite & {
|
|
212
|
+
condition: B;
|
|
213
|
+
})[];
|
|
214
|
+
};
|
|
201
215
|
clocks?: GoClock[];
|
|
202
216
|
answers?: (Answer & {
|
|
203
217
|
range?: [number, number];
|
package/dist/core/extract-go.js
CHANGED
|
@@ -55,6 +55,8 @@ class Go {
|
|
|
55
55
|
this.opts = opts;
|
|
56
56
|
const mod = { lang: pkg.lang ?? 'go', file: pkg.files[0]?.name ?? 'go', path: pkg.dir ? `${pkg.dir}/${pkg.files[0]?.name ?? ''}` : '', module: pkg.package, root: pkg.dir ?? '', entries: [], recs: {}, funcs: this.funcs, split: false };
|
|
57
57
|
this.g = new Stepper(mod, { entry: opts.entry, ...(opts.onError ? { onError: opts.onError } : {}), ...(opts.answers ? { answers: opts.answers } : {}), ...(opts.skip ? { skip: opts.skip } : {}) }, inf);
|
|
58
|
+
if (opts.safety)
|
|
59
|
+
this.g.safety = new Map();
|
|
58
60
|
for (const f of pkg.funcs)
|
|
59
61
|
this.funcs[`${f.recv?.type ?? ''}.${f.name}`] = this.fn(f);
|
|
60
62
|
}
|
|
@@ -121,7 +123,10 @@ class Go {
|
|
|
121
123
|
const k = this.T(x.t).k, it = this.intTy(x.t), ret = it ? { k: 'int', bits: it.bits, signed: it.signed } : k === 'bool' ? { k: 'bool' } : k === 'string' ? { k: 'str' } : undefined;
|
|
122
124
|
return this.no(x, why, { ext: name, args: (x.a ?? []).map(y => this.x(y)), kw: [], ...(recv ? { recv: this.x(recv) } : {}), ...(ret ? { ret, ty: this.tname(x.t) } : {}), ...(x.end ? { end: x.end } : {}) });
|
|
123
125
|
}
|
|
124
|
-
at(x) {
|
|
126
|
+
at(x) {
|
|
127
|
+
const ity = this.opts.safety && x.checkedType !== undefined ? this.intTy(x.checkedType) ?? refuse(x, 'missing integer operation type in C safety source') : undefined;
|
|
128
|
+
return { p: x.p, text: x.text, ...(this.opts.safety && x.site ? { site: x.site } : {}), ...(ity ? { ity } : {}) };
|
|
129
|
+
}
|
|
125
130
|
// A value as the type it is assigned to: an untyped constant takes the type; an integer stays itself.
|
|
126
131
|
as(v, t) {
|
|
127
132
|
const ty = this.intTy(t), k = this.T(t).k;
|
|
@@ -208,6 +213,7 @@ class Go {
|
|
|
208
213
|
return { e: 'lidx', ...at, s: this.x(x.x), i: this.x(x.i), ty: this.intTy(xt.elem) };
|
|
209
214
|
return this.no(x, `${x.text}: an index into a ${this.tname(x.x.t)}`, { pre: [this.x(x.x), this.x(x.i)] });
|
|
210
215
|
}
|
|
216
|
+
case 'table': return { e: 'table', ...at, sites: x.sites, dims: x.dims, vals: x.vals, indices: (x.indices ?? []).map(y => this.x(y)), ity: this.intTy(x.t), isBool: this.T(x.t).k === 'bool' };
|
|
211
217
|
case 'slice': {
|
|
212
218
|
// s[:len(s)-1] of a slice of the state: its last item taken off (put back in s's own place).
|
|
213
219
|
const h = x.hi, ok = !x.lo && !x.three && h?.e === 'bin' && h.op === '-' && h.y?.c?.int === '1' && h.x?.e === 'call' && h.x.builtin === 'len' && h.x.a?.[0]?.text === x.x.text;
|
|
@@ -685,6 +691,18 @@ class Go {
|
|
|
685
691
|
// Read with the boundary inferred unless strict (core/extract-step.ts's readStep: each refused run adds what the next
|
|
686
692
|
// infers): Go's check can't stub a call, so a call of another package is left out where nothing reads its value.
|
|
687
693
|
export function readGo(pkg, opts) {
|
|
694
|
+
if (opts.safety) {
|
|
695
|
+
const at = pkg.files[0]?.name ?? '?';
|
|
696
|
+
if (!pkg.safety || pkg.lang !== 'c')
|
|
697
|
+
refuse(at, 'C safety requires the checked source reader');
|
|
698
|
+
if (Object.keys(opts.answers ?? {}).length || opts.skip?.length || Object.keys(opts.domains ?? {}).length)
|
|
699
|
+
refuse(at, 'safety does not allow inferred boundaries or custom domains');
|
|
700
|
+
if (opts.onError === 'discard')
|
|
701
|
+
refuse(at, 'C safety does not allow discarding state writes on failure');
|
|
702
|
+
return readGo1(pkg, { ...opts, onError: 'refuse' }, new Go(pkg, { ...opts, onError: 'refuse' }));
|
|
703
|
+
}
|
|
704
|
+
if (pkg.safety)
|
|
705
|
+
refuse(pkg.files[0]?.name ?? '?', 'checked C source requires safety lowering');
|
|
688
706
|
if (!opts.entry && !opts.strict) {
|
|
689
707
|
// No entry: the package's one struct whose exported methods write it (core/extract-step.ts's writesState).
|
|
690
708
|
const g = new Go(pkg, opts).g, writing = (t) => pkg.funcs.filter(f => f.recv?.type === t && f.body && (pkg.lang === 'c' || pkg.lang === 'cpp' || /^[A-Z]/.test(f.name)) && g.writesState(`${t}.${f.name}`, new Set([g.mod.funcs[`${t}.${f.name}`]?.recv ?? ''])));
|
|
@@ -756,7 +774,30 @@ function readGo1(pkg, o, go) {
|
|
|
756
774
|
p = g.bindLocal(pa.id, it ? { t: 'num', e: I.nvar(v.name), ty: it } : { t: 'bool', e: I.bvar(v.name) }, fn, p);
|
|
757
775
|
}
|
|
758
776
|
p = g.bindLocal('this', { t: 'ptr', to: { k: 'obj', id: 'this', path: [] } }, fn, p);
|
|
777
|
+
const ctorCut = g.safety ? new Set() : undefined, ctorDead = g.safety ? new Set() : undefined;
|
|
778
|
+
if (g.safety) {
|
|
779
|
+
if (fn.safetySites === undefined)
|
|
780
|
+
refuse(fn, 'missing pre-lowering C safety site inventory on initializer');
|
|
781
|
+
g.safetyCutSites = ctorCut;
|
|
782
|
+
g.safetyDeadSites = ctorDead;
|
|
783
|
+
}
|
|
759
784
|
const flow = g.block(go.fn(fn).body, p), ends = [...flow.rets.map(([q]) => q), ...(flow.live ? [flow.live] : [])];
|
|
785
|
+
if (g.safety) {
|
|
786
|
+
const expected = new Set((fn.safetySites ?? []).map(s => `${s.kind}:${s.where}`));
|
|
787
|
+
for (const s of fn.safetySites ?? []) {
|
|
788
|
+
const key = `${s.kind}:${s.where}`;
|
|
789
|
+
if (!ctorCut.has(key) && !ctorDead.has(key))
|
|
790
|
+
refuse(fn, `unaccounted C safety initializer site (${s.kind} at ${s.where})`);
|
|
791
|
+
}
|
|
792
|
+
for (const k of ctorCut)
|
|
793
|
+
if (!expected.has(k))
|
|
794
|
+
refuse(fn, `uninventoried C safety initializer cut (${k})`);
|
|
795
|
+
if ([...g.safety.values()].some(s => !(s.condition.op === 'const' && !s.condition.v)))
|
|
796
|
+
refuse(fn, 'a constructor with a possible C safety fault');
|
|
797
|
+
g.safety.clear();
|
|
798
|
+
g.safetyCutSites = undefined;
|
|
799
|
+
g.safetyDeadSites = undefined;
|
|
800
|
+
}
|
|
760
801
|
if (g.refusals.length > n0 || !ends.length)
|
|
761
802
|
refuse(fn, 'a constructor that can fail (the rule\'s start is where it leaves the object)');
|
|
762
803
|
const m = materialize(go, g.join(ends, fn), fn);
|
|
@@ -780,6 +821,7 @@ function readGo1(pkg, o, go) {
|
|
|
780
821
|
g.method = fn.name;
|
|
781
822
|
const sel = I.is(evL, fn.name);
|
|
782
823
|
let p = { pc: [sel], locals: new Map(), heap: new Map(heap), called: [], locks: [], defers: [] };
|
|
824
|
+
const beforeInput = g.refusals.length;
|
|
783
825
|
const bound = go.bindParams(fn, sel, p), args = bound.args, params = bound.params;
|
|
784
826
|
p = bound.p;
|
|
785
827
|
// (an out-parameter a path leaves as the caller gave it: what the caller gave, an input, read at the start)
|
|
@@ -788,6 +830,8 @@ function readGo1(pkg, o, go) {
|
|
|
788
830
|
if (pt.k === 'ptr' && go.T(pt.elem).box && (go.T(pt.elem).fields ?? []).length === 1 && boxKept(lowered0(fn), pa.id))
|
|
789
831
|
g.lazyFieldIn(`in:${fn.name}_${pa.name ?? 'arg'}`, 'value', p, fn);
|
|
790
832
|
}
|
|
833
|
+
if (g.safety)
|
|
834
|
+
p = g.assume(p, I.not(I.or(...g.refusals.slice(beforeInput))));
|
|
791
835
|
// The receiver.
|
|
792
836
|
if (fn.recv?.id)
|
|
793
837
|
p = g.bindLocal(fn.recv.id, fn.recv.ptr ? { t: 'ptr', to: { k: 'obj', id: 'this', path: [] } } : { t: 'struct', ty: String(td.t), f: fields }, fn, p);
|
|
@@ -797,13 +841,45 @@ function readGo1(pkg, o, go) {
|
|
|
797
841
|
refuse(fn, `${fn.name} returns ${kept.length} values (a result kept is one value)`);
|
|
798
842
|
const lowered = lowered0(fn);
|
|
799
843
|
g.spans.set(`${opts.entry}.${fn.name}`, [fn.p.split(':')[0], fn.span[0], fn.span[1]]);
|
|
844
|
+
const methodCut = g.safety ? new Set() : undefined, methodDead = g.safety ? new Set() : undefined;
|
|
845
|
+
if (g.safety) {
|
|
846
|
+
if (fn.safetySites === undefined)
|
|
847
|
+
refuse(fn, 'missing pre-lowering C safety site inventory');
|
|
848
|
+
g.safetyCutSites = methodCut;
|
|
849
|
+
g.safetyDeadSites = methodDead;
|
|
850
|
+
}
|
|
851
|
+
const beforeBody = g.refusals.length;
|
|
800
852
|
const flow = g.block(lowered.body, p);
|
|
853
|
+
if (g.safety) {
|
|
854
|
+
g.safetyCutSites = undefined;
|
|
855
|
+
g.safetyDeadSites = undefined;
|
|
856
|
+
const expected = new Set(fn.safetySites.map(s => `${s.kind}:${s.where}`));
|
|
857
|
+
for (const s of fn.safetySites) {
|
|
858
|
+
const key = `${s.kind}:${s.where}`;
|
|
859
|
+
if (!methodCut.has(key) && !methodDead.has(key))
|
|
860
|
+
refuse(fn, `unaccounted C safety source site (${s.kind} at ${s.where})`);
|
|
861
|
+
g.registerSafety(s);
|
|
862
|
+
}
|
|
863
|
+
for (const k of methodCut)
|
|
864
|
+
if (!expected.has(k))
|
|
865
|
+
refuse(fn, `uninventoried C safety cut (${k})`);
|
|
866
|
+
}
|
|
867
|
+
if (g.safety && g.refusals.length !== beforeBody)
|
|
868
|
+
refuse(fn, 'an untracked refusal on a C safety source path');
|
|
869
|
+
if (g.safety && flow.live && fn.results.length) {
|
|
870
|
+
const c = g.cond(flow.live);
|
|
871
|
+
if (!(c.op === 'const' && !c.v))
|
|
872
|
+
refuse(fn, 'a non-void C method with a reachable fallthrough');
|
|
873
|
+
}
|
|
801
874
|
if (flow.brk?.length)
|
|
802
875
|
refuse(fn, 'a break outside a switch');
|
|
803
876
|
const rets = [...flow.rets.map(([q, v]) => [q, v.xs]), ...(flow.live ? [[flow.live, []]] : [])];
|
|
804
877
|
// An error returned: a refusal (where it isn't nil), the state as it was there.
|
|
805
878
|
const ok = [];
|
|
806
879
|
for (const [q0, vs] of rets) {
|
|
880
|
+
const prefix = g.cond(q0);
|
|
881
|
+
if (g.safety && prefix.op === 'const' && !prefix.v)
|
|
882
|
+
continue;
|
|
807
883
|
const q = { ...q0, locks: q0.locks.filter(k => !q0.defers.includes(k)) };
|
|
808
884
|
if (q.locks.length)
|
|
809
885
|
refuse(fn, `${fn.name} returns with a mutex locked`);
|
|
@@ -812,6 +888,8 @@ function readGo1(pkg, o, go) {
|
|
|
812
888
|
// A result the caller states is the failure where it compares so: a refusal there, as an error is.
|
|
813
889
|
const m = /^\s*(==|!=|<=|>=|<|>)\s*(-?\d+|true|false)\s*$/.exec(fails) ?? refuse(fn, `fails: ${JSON.stringify(fails)} (a comparison with a constant: '< 0', '!= 0', '== false')`);
|
|
814
890
|
const r = vs[0] ?? refuse(fn, `${fn.name} returns nothing to compare (fails: ${fails})`);
|
|
891
|
+
if (g.safety && !['true', 'false'].includes(m[2]) && !Number.isSafeInteger(Number(m[2])))
|
|
892
|
+
refuse(fn, 'an inexact configured failure constant');
|
|
815
893
|
const k = m[2] === 'true' || m[2] === 'false' ? { t: 'bool', e: m[2] === 'true' ? I.T : I.F } : { t: 'num', e: I.num(Number(m[2])) };
|
|
816
894
|
// (no failure where the result's bounds and the path's facts exclude it: an item of a uint8_t is never < 0)
|
|
817
895
|
const kv = Number(m[2]), e = r.t === 'num' ? r.e : undefined, op = m[1];
|
|
@@ -832,8 +910,25 @@ function readGo1(pkg, o, go) {
|
|
|
832
910
|
else
|
|
833
911
|
ok.push([q, vs]);
|
|
834
912
|
}
|
|
835
|
-
if (!ok.length)
|
|
836
|
-
|
|
913
|
+
if (!ok.length) {
|
|
914
|
+
if (!g.safety)
|
|
915
|
+
refuse(fn, `${fn.name} always fails`);
|
|
916
|
+
// This method still exists as an event: a fault can be its only exit.
|
|
917
|
+
// Its normal slot values are immaterial on faults (the monitor stutters).
|
|
918
|
+
const vs = fn.results.map(r => go.T(r.t).k === 'bool' ? { t: 'bool', e: I.F } : { t: 'num', e: I.num(0), ty: go.intTy(r.t) });
|
|
919
|
+
const dummy = g.assume(p, I.F);
|
|
920
|
+
for (const pa of params) {
|
|
921
|
+
const pt = go.T(pa.t);
|
|
922
|
+
if (pt.k !== 'ptr' || !go.T(pt.elem).box)
|
|
923
|
+
continue;
|
|
924
|
+
const id = `in:${fn.name}_${pa.name}`, obj = dummy.heap.get(id);
|
|
925
|
+
if (obj?.k === 'rec' && !obj.f.has('value')) {
|
|
926
|
+
const et = go.T(pt.elem).fields[0].t;
|
|
927
|
+
dummy.heap.set(id, { ...obj, f: new Map(obj.f).set('value', go.T(et).k === 'bool' ? { t: 'bool', e: I.F } : { t: 'num', e: I.num(0), ty: go.intTy(et) }) });
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
ok.push([dummy, vs]);
|
|
931
|
+
}
|
|
837
932
|
// The kept result: by the path that returned it (a local the join merges).
|
|
838
933
|
const ri = fn.results.findIndex((_, i) => i !== errAt);
|
|
839
934
|
const final = g.join(ok.map(([q, vs]) => (kept.length ? { ...q, locals: new Map(q.locals).set('$ret', vs[ri]) } : q)), fn), acc = final.locals.get('$ret');
|
|
@@ -955,6 +1050,9 @@ function readGo1(pkg, o, go) {
|
|
|
955
1050
|
}
|
|
956
1051
|
const refuseB = I.or(...g.refusals);
|
|
957
1052
|
mention(refuseB);
|
|
1053
|
+
const safety = g.safety ? { sites: [...g.safety.values()] } : undefined;
|
|
1054
|
+
for (const s of safety?.sites ?? [])
|
|
1055
|
+
mention(s.condition);
|
|
958
1056
|
for (const n of Object.keys(writes))
|
|
959
1057
|
used.add(n);
|
|
960
1058
|
// A map's nil flag and a big.Int's go with their value.
|
|
@@ -1012,7 +1110,7 @@ function readGo1(pkg, o, go) {
|
|
|
1012
1110
|
// Unsigned inputs are naturals (the input's kind); a state variable's sort is the printer's to decide (a natural where
|
|
1013
1111
|
// every write is proven one: a wrap by cases may not be, though it stays within the type, which its law says).
|
|
1014
1112
|
const unsigned = [...g.ints].filter(([n, ty]) => { const [lo, hi] = rangeOf(ty); return lo === 0 && hi > 0 && (g.inputs.some(v => v.name === n) || cparams.some(v => v.name === n)); }).map(([n]) => n);
|
|
1015
|
-
return { ...(g.now ? { clocks: [...go.clocks.values()] } : {}), ...(pkg.ctor ? { ctor: ctorArgs } : {}), ...(g.leftOut.size ? { leftOut: [...g.leftOut] } : {}), model, edges: g.edges, unsigned, leaves: go.leaves.filter(l => l.kind === 'frame' || state.some(v => v.name === l.name) || maps.some(d => d.name === l.name) || lists.some(d => d.name === l.name)), spans: [...g.spans.values()], entry: opts.entry, methods, ...(answers.length ? { answers } : {}) };
|
|
1113
|
+
return { ...(safety ? { safety } : {}), ...(g.now ? { clocks: [...go.clocks.values()] } : {}), ...(pkg.ctor ? { ctor: ctorArgs } : {}), ...(g.leftOut.size ? { leftOut: [...g.leftOut] } : {}), model, edges: g.edges, unsigned, leaves: go.leaves.filter(l => l.kind === 'frame' || state.some(v => v.name === l.name) || maps.some(d => d.name === l.name) || lists.some(d => d.name === l.name)), spans: [...g.spans.values()], entry: opts.entry, methods, ...(answers.length ? { answers } : {}) };
|
|
1016
1114
|
}
|
|
1017
1115
|
function termOf(v, at) {
|
|
1018
1116
|
// (none: a path that ends without the value, which a reader of malformed source may join in)
|
|
@@ -370,7 +370,8 @@ function pn(e, P, ctx, mode, recv = false) {
|
|
|
370
370
|
const prod = `${f(e.a, true)}.mul(${f(e.b, false)})`;
|
|
371
371
|
return nat ? prod : `Int.of(${prod})`;
|
|
372
372
|
}
|
|
373
|
-
|
|
373
|
+
const prod = `${pn(e.a, P, ctx, 'nat', true)}.mul(${pn(e.b, P, ctx, 'nat')})`;
|
|
374
|
+
return !nat && recv ? `Int.of(${prod})` : prod;
|
|
374
375
|
case 'min': return nat ? `min(${A(e.a)}, ${A(e.b)})` : `${R(e.a)}.min(${A(e.b)})`;
|
|
375
376
|
case 'max':
|
|
376
377
|
if (nat) {
|
|
@@ -389,7 +390,8 @@ function pn(e, P, ctx, mode, recv = false) {
|
|
|
389
390
|
// where the dividend is at least 0.
|
|
390
391
|
if (!natOK(e.a, ctx) && !nonneg(e.a, ctx))
|
|
391
392
|
throw new Refusal(P.m.file, 'x % k where x may be negative (JavaScript\'s remainder takes the sign of x)');
|
|
392
|
-
|
|
393
|
+
const rem = `${pn(e.a, P, ctx, natOK(e.a, ctx) ? 'nat' : 'int', true)}.modBy(${e.k})`;
|
|
394
|
+
return !nat && recv ? `Int.of(${rem})` : rem;
|
|
393
395
|
case 'ite': {
|
|
394
396
|
const d = decided(e.c, ctx);
|
|
395
397
|
if (d !== undefined)
|
|
@@ -246,6 +246,7 @@ type V = {
|
|
|
246
246
|
cmp?: [N, N];
|
|
247
247
|
slen?: K;
|
|
248
248
|
bits?: Bits;
|
|
249
|
+
range?: [number, number];
|
|
249
250
|
} | {
|
|
250
251
|
t: 'bool';
|
|
251
252
|
e: B;
|
|
@@ -614,6 +615,10 @@ type Pend = Bound & {
|
|
|
614
615
|
at: string;
|
|
615
616
|
end?: string;
|
|
616
617
|
};
|
|
618
|
+
export type SafetySite = {
|
|
619
|
+
where: string;
|
|
620
|
+
kind: 'bounds' | 'overflow' | 'division';
|
|
621
|
+
};
|
|
617
622
|
export declare class Stepper {
|
|
618
623
|
readonly mod: SModule;
|
|
619
624
|
readonly opts: StepOptions;
|
|
@@ -623,6 +628,16 @@ export declare class Stepper {
|
|
|
623
628
|
readonly params: Var[];
|
|
624
629
|
readonly notes: Set<string>;
|
|
625
630
|
readonly refusals: B[];
|
|
631
|
+
safety?: Map<string, SafetySite & {
|
|
632
|
+
condition: B;
|
|
633
|
+
}>;
|
|
634
|
+
safetyCutSites?: Set<string>;
|
|
635
|
+
safetyDeadSites?: Set<string>;
|
|
636
|
+
registerSafety(site: SafetySite): (SafetySite & {
|
|
637
|
+
condition: B;
|
|
638
|
+
}) | undefined;
|
|
639
|
+
markSafetyDead(node: unknown, seenFns?: Set<string>): void;
|
|
640
|
+
safetyCut(p: Path, at: SX, kind: SafetySite['kind'], bad: B): Path;
|
|
626
641
|
fails: B[];
|
|
627
642
|
failPaths: Path[];
|
|
628
643
|
readonly maps: MapDecl[];
|
|
@@ -1074,6 +1089,13 @@ export declare class Stepper {
|
|
|
1074
1089
|
eq(a: V, b: V, x: {
|
|
1075
1090
|
p: string;
|
|
1076
1091
|
}, p?: Path): B;
|
|
1092
|
+
safetyRange(ty: IntTy | undefined, at: SX): [number, number];
|
|
1093
|
+
safetyBounds(v: Extract<V, {
|
|
1094
|
+
t: 'num';
|
|
1095
|
+
}>, at: SX): [number, number];
|
|
1096
|
+
safetyModulo(e: N, m: number, lo?: number): N;
|
|
1097
|
+
safetyWrapUnsigned(e: N, lo: bigint, hi: bigint, mod: number): N;
|
|
1098
|
+
safetyArith(op: string, a: V, b: V, at: SX, p: Path): [V, Path];
|
|
1077
1099
|
arith(op: string, a: V, b: V, x: {
|
|
1078
1100
|
p: string;
|
|
1079
1101
|
}, p: Path): V;
|