gdp-wired 0.45.0 → 0.47.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 +61 -8
- package/dist/core/bitsets.d.ts +2 -0
- package/dist/core/bitsets.js +23 -0
- package/dist/core/bmc.js +6 -2
- package/dist/core/c/reader.d.ts +9 -1
- package/dist/core/c/reader.js +423 -31
- package/dist/core/calendar.d.ts +29 -0
- package/dist/core/calendar.js +82 -0
- package/dist/core/cli.d.ts +4 -0
- package/dist/core/cli.js +206 -40
- package/dist/core/compose.js +3 -1
- package/dist/core/counts.d.ts +4 -1
- package/dist/core/counts.js +314 -85
- package/dist/core/cycles.js +8 -1
- package/dist/core/cyclic.d.ts +1 -0
- package/dist/core/cyclic.js +13 -7
- package/dist/core/data-synth.d.ts +3 -0
- package/dist/core/data-synth.js +252 -0
- package/dist/core/data.d.ts +2 -1
- package/dist/core/data.js +223 -24
- package/dist/core/discover.js +3 -1
- package/dist/core/draft.d.ts +19 -0
- package/dist/core/draft.js +53 -0
- package/dist/core/dsl.d.ts +37 -3
- package/dist/core/dsl.js +167 -26
- package/dist/core/effect-schema.d.ts +90 -0
- package/dist/core/effect-schema.js +500 -0
- package/dist/core/effect.d.ts +4 -11
- package/dist/core/effect.js +3 -79
- package/dist/core/exists.d.ts +1 -0
- package/dist/core/exists.js +191 -16
- package/dist/core/extract-c.d.ts +2 -0
- package/dist/core/extract-c.js +169 -22
- package/dist/core/extract-check.d.ts +1 -0
- package/dist/core/extract-check.js +97 -6
- package/dist/core/extract-go-check.d.ts +1 -1
- package/dist/core/extract-go-check.js +26 -5
- package/dist/core/extract-go.d.ts +8 -0
- package/dist/core/extract-go.js +67 -6
- package/dist/core/extract-ir.d.ts +1 -0
- package/dist/core/extract-ir.js +15 -0
- package/dist/core/extract-jvm.d.ts +1 -1
- package/dist/core/extract-jvm.js +2 -0
- package/dist/core/extract-orm.d.ts +12 -0
- package/dist/core/extract-orm.js +244 -0
- package/dist/core/extract-print.js +20 -1
- package/dist/core/extract-py.d.ts +1 -0
- package/dist/core/extract-py.js +1 -1
- package/dist/core/extract-read.d.ts +26 -1
- package/dist/core/extract-read.js +14 -7
- package/dist/core/extract-rs.js +63 -15
- package/dist/core/extract-shapes.d.ts +1 -0
- package/dist/core/extract-shapes.js +84 -0
- package/dist/core/extract-sol.d.ts +10 -1
- package/dist/core/extract-sol.js +70 -22
- package/dist/core/extract-standalone.d.ts +3 -0
- package/dist/core/extract-standalone.js +221 -0
- package/dist/core/extract-step.d.ts +151 -1
- package/dist/core/extract-step.js +1232 -60
- package/dist/core/extract-swift.js +6 -2
- package/dist/core/extract.d.ts +9 -0
- package/dist/core/extract.js +77 -7
- package/dist/core/fiber-run.d.ts +5 -0
- package/dist/core/fiber-run.js +18 -0
- package/dist/core/infer.d.ts +4 -1
- package/dist/core/infer.js +918 -217
- package/dist/core/jvm/JavaReader.java +23 -6
- package/dist/core/jvm/Jvm.java +3 -0
- package/dist/core/jvm/KtReader.java +6 -5
- package/dist/core/laws.d.ts +10 -3
- package/dist/core/laws.js +226 -23
- package/dist/core/machine.d.ts +15 -1
- package/dist/core/machine.js +187 -15
- package/dist/core/nonterm.js +14 -1
- package/dist/core/orm/harness.js +61 -0
- package/dist/core/orm-fixtures/schema.prisma +5 -0
- package/dist/core/py/harness.py +183 -10
- package/dist/core/py/reader.py +234 -40
- package/dist/core/reader-fixtures/README.md +28 -0
- package/dist/core/reader-fixtures/c-693042.cpp +8 -0
- package/dist/core/reader-fixtures/go-685506.go +14 -0
- package/dist/core/reader-fixtures/jvm-724362.kt +8 -0
- package/dist/core/reader-fixtures/jvm-737430.kt +7 -0
- package/dist/core/reader-fixtures/jvm-765282.kt +3 -0
- package/dist/core/reader-fixtures/swift-735726.swift +15 -0
- package/dist/core/reader-fixtures/swift-735990.swift +15 -0
- package/dist/core/reader-fixtures/swift-739158.swift +4 -0
- package/dist/core/reader-fixtures/swift-744834.swift +15 -0
- package/dist/core/reader-fixtures/swift-746946.swift +31 -0
- package/dist/core/reader-fixtures/typescript-673062.ts.txt +2 -0
- package/dist/core/relation.d.ts +1 -1
- package/dist/core/relation.js +29 -2
- package/dist/core/relational.js +4 -2
- package/dist/core/rs/Cargo.toml +1 -1
- package/dist/core/rs/src/main.rs +466 -11
- package/dist/core/sample-cache.d.ts +8 -0
- package/dist/core/sample-cache.js +46 -0
- package/dist/core/security.d.ts +38 -0
- package/dist/core/security.js +88 -0
- package/dist/core/sol/harness.py +57 -4
- package/dist/core/sol-concrete.d.ts +23 -0
- package/dist/core/sol-concrete.js +195 -0
- package/dist/core/solver.js +3 -1
- package/dist/core/swift/Sources/gdp-swiftreader/main.swift +50 -7
- package/dist/core/system.js +1 -1
- package/dist/core/transfer.js +22 -9
- package/dist/core/translate.js +39 -10
- package/dist/core/watch.js +50 -5
- package/dist/interchange/format.js +11 -1
- package/dist/kernel/cdcl.d.ts +5 -0
- package/dist/kernel/cdcl.js +56 -9
- package/dist/kernel/epr.js +108 -26
- package/dist/kernel/kernel.d.ts +29 -1
- package/dist/kernel/kernel.js +325 -62
- package/dist/kernel/model-sequence.d.ts +3 -0
- package/dist/kernel/model-sequence.js +34 -0
- package/dist/kernel/prove.d.ts +10 -3
- package/dist/kernel/prove.js +332 -71
- package/dist/kernel/reader.d.ts +3 -0
- package/dist/kernel/reader.js +101 -14
- package/dist/kernel/share.d.ts +1 -0
- package/dist/kernel/share.js +27 -0
- package/dist/lean-kernel/emit.js +30 -37
- package/dist/lean-kernel/lean-terms.js +5 -0
- package/dist/lean-kernel/library.js +10 -10
- package/package.json +6 -1
|
@@ -7,6 +7,8 @@ import { node } from "./extract-go.js";
|
|
|
7
7
|
function harness(pkg, read, m, discard) {
|
|
8
8
|
const T = (t) => pkg.ttab[t] ?? { k: 'invalid' };
|
|
9
9
|
const imports = new Set(['bufio', 'encoding/json', 'fmt', 'os', 'reflect', 'strconv', 'math/big']);
|
|
10
|
+
if (read.clocks?.length)
|
|
11
|
+
imports.add('time');
|
|
10
12
|
const qual = (t) => { const x = T(t); if (x.pkg && !x.own && x.pkg !== '')
|
|
11
13
|
imports.add(x.pkg); };
|
|
12
14
|
const acc = (path) => `o.${path.join('.')}`;
|
|
@@ -61,7 +63,8 @@ function harness(pkg, read, m, discard) {
|
|
|
61
63
|
// A big.Int's nil flag and a map's are set with their values; a left-out field is compared, not set.
|
|
62
64
|
case 'bignil':
|
|
63
65
|
case 'mapnil':
|
|
64
|
-
case 'frame':
|
|
66
|
+
case 'frame':
|
|
67
|
+
case 'sink': break;
|
|
65
68
|
}
|
|
66
69
|
}
|
|
67
70
|
const frames = read.leaves.filter(l => l.kind === 'frame');
|
|
@@ -119,12 +122,17 @@ import (
|
|
|
119
122
|
${[...imports].sort().map(p => `\t${p.split('/')[0].includes('.') ? `${p.replace(/[^A-Za-z0-9]/g, '_').replace(/^/, 'gdp_')} ` : ''}${JSON.stringify(p)}`).join('\n')}
|
|
120
123
|
)
|
|
121
124
|
|
|
125
|
+
${read.clocks?.length ? `// Only the time source is substituted; Unix/UnixMilli run in Go unchanged.
|
|
126
|
+
var gdpNow int64
|
|
127
|
+
func gdpTimeNow(_ func() time.Time) time.Time { return time.UnixMilli(gdpNow) }
|
|
128
|
+
` : ''}
|
|
122
129
|
type gdpStep struct {
|
|
123
130
|
M string \`json:"m"\`
|
|
124
131
|
A []json.RawMessage \`json:"a"\`
|
|
125
132
|
}
|
|
126
133
|
type gdpCmd struct {
|
|
127
134
|
Op string \`json:"op"\`
|
|
135
|
+
Now int64 \`json:"now"\`
|
|
128
136
|
ID int \`json:"id"\`
|
|
129
137
|
State map[string]json.RawMessage \`json:"state"\`
|
|
130
138
|
M string \`json:"m"\`
|
|
@@ -279,7 +287,7 @@ func GdpHarnessMain(in, out string) {
|
|
|
279
287
|
case "get":
|
|
280
288
|
res = map[string]any{"state": gdpGet(objs[c.ID])}
|
|
281
289
|
case "call":
|
|
282
|
-
${read.answers?.length ? 'gdpAnswers = c.Answers\n\t\t\t' : ''}res = gdpRun(objs[c.ID], gdpStep{M: c.M, A: c.A})
|
|
290
|
+
${read.clocks?.length ? 'gdpNow = c.Now\n\t\t\t' : ''}${read.answers?.length ? 'gdpAnswers = c.Answers\n\t\t\t' : ''}res = gdpRun(objs[c.ID], gdpStep{M: c.M, A: c.A})
|
|
283
291
|
}
|
|
284
292
|
b, _ := json.Marshal(res)
|
|
285
293
|
wr.Write(b)
|
|
@@ -331,7 +339,18 @@ export function checkGo(dir, pkg, read, r, sorts, gopts) {
|
|
|
331
339
|
}
|
|
332
340
|
// (each answered call rewritten to the harness's answer in a copy of its file, the build told by an overlay)
|
|
333
341
|
const over = {};
|
|
334
|
-
|
|
342
|
+
const answers = read.answers ?? [], clocks = read.clocks ?? [];
|
|
343
|
+
// Go positions count UTF-8 bytes; explicit stub spans count JS code units.
|
|
344
|
+
const byteSpan = (p, end) => {
|
|
345
|
+
const m = /^(.*):(\d+):(\d+)$/.exec(p), lines = fs.readFileSync(`${dir}/${m[1]}`, 'utf8').split('\n');
|
|
346
|
+
const offset = (line, column) => lines.slice(0, line - 1).reduce((n, s) => n + s.length + 1, 0) + new TextDecoder('utf-8', { fatal: true }).decode(new TextEncoder().encode(lines[line - 1]).slice(0, column - 1)).length;
|
|
347
|
+
const e = end.split(':').map(Number);
|
|
348
|
+
return [offset(Number(m[2]), Number(m[3])), offset(e[0], e[1])];
|
|
349
|
+
};
|
|
350
|
+
const clockSites = clocks.map(c => ({ key: 'Go wall clock', at: [{ p: c.p, span: byteSpan(c.p, c.end) }] }));
|
|
351
|
+
// A Unicode clock prefix also moves any answer later on the same line.
|
|
352
|
+
const answerSites = !clocks.length ? answers : answers.map(a => ({ ...a, at: a.at?.map(s => s.span || !s.end ? s : { ...s, span: byteSpan(s.p, s.end) }) }));
|
|
353
|
+
for (const [f, t] of stubbed({ ...read, answers: [...answerSites, ...clockSites] }, f => fs.readFileSync(`${dir}/${f}`, 'utf8'), (a, i, t) => i >= answers.length ? `gdpTimeNow(${clocks[i - answers.length].callee})` : `gdpAnswer[${a.ty}](${JSON.stringify(a.key)}, ${t.slice(0, t.indexOf('('))}, ${t.slice(t.indexOf('(') + 1)}`)) {
|
|
335
354
|
const o = node('node:path').resolve(dir, f);
|
|
336
355
|
fs.writeFileSync(`${work}/${f}`, t);
|
|
337
356
|
over[o] = over[node('node:fs').realpathSync(o)] = `${work}/${f}`;
|
|
@@ -480,6 +499,7 @@ export function speak(work, bin, env, pkg, read, r, sorts, opts, count) {
|
|
|
480
499
|
return s;
|
|
481
500
|
};
|
|
482
501
|
let coverage;
|
|
502
|
+
let now = 0;
|
|
483
503
|
const r0 = performance.now();
|
|
484
504
|
const side = {
|
|
485
505
|
// (a constructor's arguments, C++'s: the rule's parameters)
|
|
@@ -494,7 +514,7 @@ export function speak(work, bin, env, pkg, read, r, sorts, opts, count) {
|
|
|
494
514
|
answers = Object.fromEntries(read.answers.map(a => { const x = v[a.inputs.name] ?? 0; if (a.fit && a.range && (Number(x) < a.range[0] || Number(x) > a.range[1]))
|
|
495
515
|
throw new Outside(`${a.key} answers ${String(x)}, outside its type`); return [a.key, a.inputs.none && v[a.inputs.none] === true ? { none: true } : { in: x }]; }));
|
|
496
516
|
}
|
|
497
|
-
const res = ask({ op: 'call', id: self, m: e.call, a: args, ...(answers ? { answers } : {}) });
|
|
517
|
+
const res = ask({ op: 'call', id: self, m: e.call, now, a: args, ...(answers ? { answers } : {}) });
|
|
498
518
|
if (res.frame)
|
|
499
519
|
throw new Error(`the code changes ${res.frame}, a field the rule leaves out`);
|
|
500
520
|
if (res.bad)
|
|
@@ -504,7 +524,8 @@ export function speak(work, bin, env, pkg, read, r, sorts, opts, count) {
|
|
|
504
524
|
return { ok: true, value: typeof res.out === 'string' && /^-?\d+$/.test(res.out) && m.results?.[e.call] && m.state.find(v => v.name === m.results[e.call].name)?.sort.k === 'num' ? Number(res.out) : res.out };
|
|
505
525
|
},
|
|
506
526
|
args: (inputs, e) => e.args.map(a => argJson(a, inputs)),
|
|
507
|
-
setNow:
|
|
527
|
+
setNow: n => { if (!Number.isSafeInteger(n))
|
|
528
|
+
throw new Outside('Go clock outside the exact integer range'); now = n; },
|
|
508
529
|
coverage: () => (coverage ??= closeAndCount()),
|
|
509
530
|
input: (v, x, rand) => { const y = rand(8) === 0 ? x : fit(x, v.name, rand); return typeof y === 'number' && y < 0 && sorts.get(v.name) === 'nat' ? -y : y; },
|
|
510
531
|
drawSnap: rand => {
|
|
@@ -7,6 +7,7 @@ export { proveRule, proveSteps } from './dsl.js';
|
|
|
7
7
|
export type TT = {
|
|
8
8
|
k: string;
|
|
9
9
|
go?: string;
|
|
10
|
+
nullflag?: boolean;
|
|
10
11
|
fixed?: boolean;
|
|
11
12
|
box?: boolean;
|
|
12
13
|
mutex?: boolean;
|
|
@@ -85,6 +86,7 @@ export type GX = {
|
|
|
85
86
|
v: GX;
|
|
86
87
|
}[];
|
|
87
88
|
i?: GX;
|
|
89
|
+
end?: string;
|
|
88
90
|
};
|
|
89
91
|
export type GS = {
|
|
90
92
|
s: string;
|
|
@@ -190,7 +192,13 @@ export type GoOptions = {
|
|
|
190
192
|
answers?: Record<string, string>;
|
|
191
193
|
skip?: string[];
|
|
192
194
|
};
|
|
195
|
+
export type GoClock = {
|
|
196
|
+
p: string;
|
|
197
|
+
end: string;
|
|
198
|
+
callee: string;
|
|
199
|
+
};
|
|
193
200
|
export type GoRead = {
|
|
201
|
+
clocks?: GoClock[];
|
|
194
202
|
answers?: (Answer & {
|
|
195
203
|
range?: [number, number];
|
|
196
204
|
})[];
|
package/dist/core/extract-go.js
CHANGED
|
@@ -9,7 +9,8 @@
|
|
|
9
9
|
//
|
|
10
10
|
// The subset: a named struct of the package and the methods given (pointer or value receivers), the object starting
|
|
11
11
|
// at Go's zero value; fields of integer types (every width, signed and unsigned, named ones such as time.Duration),
|
|
12
|
-
// bool, string,
|
|
12
|
+
// bool, string, direct time.Now().UnixMilli()/Unix() projections (one millisecond request tick; the check replaces
|
|
13
|
+
// only Now, not the native projection), *big.Int (an unbounded integer, nil a state of its own), nested structs, maps from
|
|
13
14
|
// integers or strings to integers, booleans or structs of them, and slices of integers or booleans as lists; locals,
|
|
14
15
|
// assignments (=, :=, op=, ++, --, tuples), if, switch (with a tag or without, fallthrough, break), early returns,
|
|
15
16
|
// calls of the package's functions and methods (inlined), pointers to the state's objects (an interior pointer &x.f
|
|
@@ -47,6 +48,7 @@ class Go {
|
|
|
47
48
|
opts;
|
|
48
49
|
g;
|
|
49
50
|
leaves = [];
|
|
51
|
+
clocks = new Map();
|
|
50
52
|
funcs = {};
|
|
51
53
|
constructor(pkg, opts, inf) {
|
|
52
54
|
this.pkg = pkg;
|
|
@@ -141,13 +143,18 @@ class Go {
|
|
|
141
143
|
if (tt.k === 'struct') {
|
|
142
144
|
return { e: 'struct', p: at.p, ty: String(t), fields: (tt.fields ?? []).map(g => {
|
|
143
145
|
const s = this.scalar(g.t);
|
|
144
|
-
return [g.name, typeof s === 'string' && !['ptr', 'struct', 'error'].includes(this.T(g.t).k) ? { e: 'opaque', p: at.p, why: `${g.name}: ${s}`, firm: true } : this.zero(g.t, at)];
|
|
146
|
+
return [g.name, typeof s === 'string' && !['ptr', 'struct', 'error'].includes(this.T(g.t).k) ? { e: 'opaque', p: at.p, why: `${g.name}: ${s}`, ...(this.floaty(g.t) ? { sink: true } : { firm: true }) } : this.zero(g.t, at)];
|
|
145
147
|
}) };
|
|
146
148
|
}
|
|
147
|
-
return { e: 'opaque', p: at.p, why: `a value of type ${this.tname(t)} (outside the subset)`, firm: true };
|
|
149
|
+
return { e: 'opaque', p: at.p, why: `a value of type ${this.tname(t)} (outside the subset)`, ...(this.floaty(t) ? { sink: true } : { firm: true }) };
|
|
148
150
|
}
|
|
151
|
+
// A float, or a fixed array of them: C's measurements, left out of the rule where they are only written (a value
|
|
152
|
+
// that is one, read into what the rule keeps, is refused there).
|
|
153
|
+
floaty(t) { const x = this.T(t); return x.k === 'float' || (x.k === 'array' && !!x.fixed && this.T(x.elem).k === 'float'); }
|
|
149
154
|
x(x) {
|
|
150
155
|
const at = this.at(x), c = x.c;
|
|
156
|
+
if (x.e === 'opaque')
|
|
157
|
+
return { e: 'opaque', ...at, why: x.why };
|
|
151
158
|
if (c) {
|
|
152
159
|
if (c.int !== undefined) {
|
|
153
160
|
const ty = this.intTy(x.t);
|
|
@@ -278,6 +285,17 @@ class Go {
|
|
|
278
285
|
if (f.e === 'sel' && f.k === 'qual')
|
|
279
286
|
return this.std(x);
|
|
280
287
|
if (f.e === 'sel' && f.k === 'method') {
|
|
288
|
+
// Keep Time opaque: only a direct Now projection is a scalar. Preserve
|
|
289
|
+
// the native projection in the check; substitute just its clock source.
|
|
290
|
+
const now = f.x;
|
|
291
|
+
if ((!this.pkg.lang || this.pkg.lang === 'go') && f.mpkg === 'time' && (f.n === 'Unix' || f.n === 'UnixMilli') && !a.length &&
|
|
292
|
+
now?.e === 'call' && !now.a?.length && now.f?.e === 'sel' && now.f.k === 'qual' && now.f.pkg === 'time' && now.f.n === 'Now') {
|
|
293
|
+
if (!now.end)
|
|
294
|
+
return this.no(x, 'time.Now(): the reader did not provide a clock source span');
|
|
295
|
+
this.clocks.set(now.p, { p: now.p, end: now.end, callee: now.f.text });
|
|
296
|
+
const clock = { e: 'clock', ...at };
|
|
297
|
+
return f.n === 'UnixMilli' ? clock : { e: 'bin', ...at, op: '//', x: clock, y: { e: 'int', p: x.p, v: 1000 } };
|
|
298
|
+
}
|
|
281
299
|
// A method promoted from an embedded field: its receiver is that field (through the embedded fields on the way).
|
|
282
300
|
let rt = this.T(f.x.t), base = rt.k === 'ptr' ? rt.elem : f.x.t, emb;
|
|
283
301
|
if ((f.path ?? []).length > 1) {
|
|
@@ -426,6 +444,8 @@ class Go {
|
|
|
426
444
|
return [{ s: 'ret', p: s.p, one: this.x(r[0]), why: 'a return of one value from a function of several' }];
|
|
427
445
|
if (!r.length && fn.results.length)
|
|
428
446
|
return [{ s: 'ret', p: s.p, bare: fn.results.map(x => x.id ?? null) }];
|
|
447
|
+
if (r.length !== fn.results.length)
|
|
448
|
+
return no(`return has ${r.length} values, but the function declares ${fn.results.length} results`);
|
|
429
449
|
return [{ s: 'ret', p: s.p, xs: r.map((e, i) => this.as(this.x(e), fn.results[i].t)) }];
|
|
430
450
|
}
|
|
431
451
|
case 'branch':
|
|
@@ -542,6 +562,12 @@ class Go {
|
|
|
542
562
|
heap.set(id, { k: 'list', decl, ops: [], origin: 'state' });
|
|
543
563
|
out.set(f.name, { t: 'list', id });
|
|
544
564
|
}
|
|
565
|
+
else if (this.floaty(f.t)) {
|
|
566
|
+
// (a float field: left out, written as the code writes it, never compared; a read of it is a float's)
|
|
567
|
+
out.set(f.name, { t: 'opaque', why: `${fp.join('.')}: a ${this.tname(f.t)} (a float, left out of the rule: nothing it keeps may read one)`, sink: true });
|
|
568
|
+
this.leaves.push({ name: '', path: fp, kind: 'sink', t: f.t, go: this.tname(f.t) });
|
|
569
|
+
g.notes.add(`${fp.join('.')}: a ${this.tname(f.t)}, a float, left out (the rule keeps nothing read from it; a float read into what it keeps is refused)`);
|
|
570
|
+
}
|
|
545
571
|
else {
|
|
546
572
|
out.set(f.name, { t: 'opaque', why: `${fp.join('.')} is a ${this.tname(f.t)}, a field outside the subset (left out of the rule)`, firm: true });
|
|
547
573
|
this.leaves.push({ name: '', path: fp, kind: 'frame', t: f.t, go: this.tname(f.t) });
|
|
@@ -639,6 +665,13 @@ class Go {
|
|
|
639
665
|
arg = { k: 'lit', value: 'context' };
|
|
640
666
|
g.notes.add(`${fn.name}(${pa.name ?? '_'}): a context.Context, passed on to the package's own functions only (the claim is for any context, the step never reading it)`);
|
|
641
667
|
}
|
|
668
|
+
else if (this.pkg.lang === 'c' || this.pkg.lang === 'cpp') {
|
|
669
|
+
// (C, C++: an argument outside the subset, a handle the code passes on to other code: the check gives a zeroed
|
|
670
|
+
// one; read here, it is refused where it is)
|
|
671
|
+
v = { t: 'opaque', why: `${fn.name}(${pa.name}): an argument of type ${pa.ts ?? this.tname(pa.t)} (${this.whyType(pa.t)}), only passed on` };
|
|
672
|
+
arg = { k: 'rec', fields: [] };
|
|
673
|
+
g.notes.add(`${fn.name}(${pa.name ?? '_'}): a ${pa.ts ?? this.tname(pa.t)}, outside the subset, only passed on to other code (the check gives a zeroed one)`);
|
|
674
|
+
}
|
|
642
675
|
else
|
|
643
676
|
return refuse(fn, `${fn.name}(${pa.name}): an argument of type ${pa.ts ?? this.tname(pa.t)} (${this.whyType(pa.t)})`);
|
|
644
677
|
if (pa.id)
|
|
@@ -740,12 +773,21 @@ function readGo1(pkg, o, go) {
|
|
|
740
773
|
const evL = { op: 'var', name: ev.name, values: names };
|
|
741
774
|
const outputs = [], results = {};
|
|
742
775
|
const finals = [], events = [], methods = [];
|
|
776
|
+
const lowered0 = (fn) => go.funcs[`${fn.recv?.type ?? ''}.${fn.name}`];
|
|
777
|
+
// (an out-parameter some path of the function returns without writing: not every statement writes *p)
|
|
778
|
+
const boxKept = (f, id) => !!id && !writesAll(f.body, id);
|
|
743
779
|
for (const fn of chosen) {
|
|
744
780
|
g.method = fn.name;
|
|
745
781
|
const sel = I.is(evL, fn.name);
|
|
746
782
|
let p = { pc: [sel], locals: new Map(), heap: new Map(heap), called: [], locks: [], defers: [] };
|
|
747
783
|
const bound = go.bindParams(fn, sel, p), args = bound.args, params = bound.params;
|
|
748
784
|
p = bound.p;
|
|
785
|
+
// (an out-parameter a path leaves as the caller gave it: what the caller gave, an input, read at the start)
|
|
786
|
+
for (const pa of fn.params) {
|
|
787
|
+
const pt = go.T(pa.t);
|
|
788
|
+
if (pt.k === 'ptr' && go.T(pt.elem).box && (go.T(pt.elem).fields ?? []).length === 1 && boxKept(lowered0(fn), pa.id))
|
|
789
|
+
g.lazyFieldIn(`in:${fn.name}_${pa.name ?? 'arg'}`, 'value', p, fn);
|
|
790
|
+
}
|
|
749
791
|
// The receiver.
|
|
750
792
|
if (fn.recv?.id)
|
|
751
793
|
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);
|
|
@@ -753,7 +795,7 @@ function readGo1(pkg, o, go) {
|
|
|
753
795
|
const kept = fn.results.filter((_, i) => i !== errAt);
|
|
754
796
|
if (kept.length > 1)
|
|
755
797
|
refuse(fn, `${fn.name} returns ${kept.length} values (a result kept is one value)`);
|
|
756
|
-
const lowered =
|
|
798
|
+
const lowered = lowered0(fn);
|
|
757
799
|
g.spans.set(`${opts.entry}.${fn.name}`, [fn.p.split(':')[0], fn.span[0], fn.span[1]]);
|
|
758
800
|
const flow = g.block(lowered.body, p);
|
|
759
801
|
if (flow.brk?.length)
|
|
@@ -839,6 +881,18 @@ function readGo1(pkg, o, go) {
|
|
|
839
881
|
if (answers.length)
|
|
840
882
|
for (const e of events)
|
|
841
883
|
e.args.push({ k: 'rec', fields: answers.flatMap(a => [a.inputs.name, ...(a.inputs.none ? [a.inputs.none] : [])]).map(n => [n, { k: 'input', name: n }]) });
|
|
884
|
+
// An answered outer call must not swallow a clock substitution or reuse its offsets.
|
|
885
|
+
for (const clock of go.clocks.values())
|
|
886
|
+
for (const answer of answers)
|
|
887
|
+
for (const site of answer.at ?? []) {
|
|
888
|
+
const c = /^(.*):(\d+):(\d+)$/.exec(clock.p), a = /^(.*):(\d+):(\d+)$/.exec(site.p);
|
|
889
|
+
if (!c || !a || c[1] !== a[1] || !site.end)
|
|
890
|
+
continue;
|
|
891
|
+
const cs = c.slice(2).map(Number), as = a.slice(2).map(Number), ce = clock.end.split(':').map(Number), ae = site.end.split(':').map(Number);
|
|
892
|
+
const before = (x, y) => x[0] < y[0] || (x[0] === y[0] && x[1] < y[1]);
|
|
893
|
+
if (before(cs, ae) && before(as, ce))
|
|
894
|
+
refuse(clock.p, 'a clock read inside an answered call (overlapping source substitutions)');
|
|
895
|
+
}
|
|
842
896
|
// (and the harness's: it makes the struct with the fields read)
|
|
843
897
|
for (const mt of methods)
|
|
844
898
|
mt.params = mt.params.map(pa => ({ ...pa, arg: recOf(pa.arg) }));
|
|
@@ -948,6 +1002,8 @@ function readGo1(pkg, o, go) {
|
|
|
948
1002
|
for (const d of maps)
|
|
949
1003
|
laws.push(`r.law(${JSON.stringify(`${d.name}: a nil map holds no key`)}, ({${d.name}, ${d.name}_nil}) => forall(k => any(${d.name}_nil.not(), ${d.name}.at(k).has.not())))`);
|
|
950
1004
|
const layout = { k: 'rec', fields: state.filter(v => !outputs.includes(v.name)).map(v => [v.name, { k: 'scalar', name: v.name }]) };
|
|
1005
|
+
if (g.now)
|
|
1006
|
+
g.notes.add('Go wall clock: UnixMilli and Unix projections use one millisecond request tick; multiple reads assume the step stays within that tick. General time.Time values and finer projections remain outside the subset.');
|
|
951
1007
|
const model = {
|
|
952
1008
|
name: opts.entry, shape: 'class', file: pkg.files[0]?.name ?? 'go', entry: opts.entry,
|
|
953
1009
|
params: cparams, inputs: g.inputs, state, maps, init, writes, mapWrites, outputs, ...(lists.length ? { lists, listWrites } : {}),
|
|
@@ -956,7 +1012,7 @@ function readGo1(pkg, o, go) {
|
|
|
956
1012
|
// Unsigned inputs are naturals (the input's kind); a state variable's sort is the printer's to decide (a natural where
|
|
957
1013
|
// every write is proven one: a wrap by cases may not be, though it stays within the type, which its law says).
|
|
958
1014
|
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);
|
|
959
|
-
return { ...(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 } : {}) };
|
|
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 } : {}) };
|
|
960
1016
|
}
|
|
961
1017
|
function termOf(v, at) {
|
|
962
1018
|
// (none: a path that ends without the value, which a reader of malformed source may join in)
|
|
@@ -977,7 +1033,7 @@ function materialize(go, p, at) {
|
|
|
977
1033
|
const self = p.heap.get('this');
|
|
978
1034
|
const seen = new Map();
|
|
979
1035
|
for (const l of go.leaves) {
|
|
980
|
-
if (l.kind === 'frame' || l.kind === 'bignil' || l.kind === 'mapnil')
|
|
1036
|
+
if (l.kind === 'frame' || l.kind === 'sink' || l.kind === 'bignil' || l.kind === 'mapnil')
|
|
981
1037
|
continue;
|
|
982
1038
|
let v = { t: 'struct', ty: self.ty, f: self.f };
|
|
983
1039
|
for (const s of l.path)
|
|
@@ -1179,3 +1235,8 @@ function probe(pkg, name) {
|
|
|
1179
1235
|
const writes = fn.params.some(x => go.T(x.t).k === 'ptr');
|
|
1180
1236
|
return { where: fn.p, what: `${name}: a function of its arguments${writes ? ' (the objects its pointers give are the caller\'s)' : ''}, not a step of a state the subset reads (a struct and its methods)` };
|
|
1181
1237
|
}
|
|
1238
|
+
// (whether a body's first statement sets *p, the out-parameter whose id is given: then no path leaves the caller's value)
|
|
1239
|
+
function writesAll(body, id) {
|
|
1240
|
+
const first = body[0];
|
|
1241
|
+
return !!first && first.s === 'assign' && JSON.stringify(first.l ?? []).includes(JSON.stringify(id));
|
|
1242
|
+
}
|
package/dist/core/extract-ir.js
CHANGED
|
@@ -198,3 +198,18 @@ export function varsOf(x, out = new Set(), maps = new Set()) {
|
|
|
198
198
|
go(x);
|
|
199
199
|
return { vars: out, maps };
|
|
200
200
|
}
|
|
201
|
+
// A numeric variable (a bound name: a pass i$, a key k$ or kl$, which no boolean or choice shares) replaced by a term
|
|
202
|
+
// everywhere in a term, structurally.
|
|
203
|
+
export function substN(x, name, by) {
|
|
204
|
+
const go = (o) => {
|
|
205
|
+
if (Array.isArray(o))
|
|
206
|
+
return o.map(go);
|
|
207
|
+
if (!o || typeof o !== 'object')
|
|
208
|
+
return o;
|
|
209
|
+
const r = o;
|
|
210
|
+
if (r.op === 'var' && r.name === name && !('values' in r))
|
|
211
|
+
return by;
|
|
212
|
+
return Object.fromEntries(Object.entries(r).map(([k, v]) => [k, go(v)]));
|
|
213
|
+
};
|
|
214
|
+
return go(x);
|
|
215
|
+
}
|
package/dist/core/extract-jvm.js
CHANGED
|
@@ -218,6 +218,8 @@ export function extractJvm(lang, at, opts = {}) {
|
|
|
218
218
|
const file = pathOf(at);
|
|
219
219
|
let mod;
|
|
220
220
|
try {
|
|
221
|
+
if (lang === 'kotlin' && typeof opts.ctor === 'string')
|
|
222
|
+
throw new Refusal(file, 'Kotlin ctor selection uses an arity, not a Java signature');
|
|
221
223
|
if (opts.stores && Object.keys(opts.stores).length)
|
|
222
224
|
throw new Refusal(file, `stores: not in the ${lang === 'java' ? 'Java' : 'Kotlin'} front end yet`);
|
|
223
225
|
// (a name or a string past the class file's 65,535 bytes: no compiler makes a class of it, javac and kotlinc throw)
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type StepOptions } from './extract-step.js';
|
|
2
|
+
/** Explicit boundary: the first argument is the injected Prisma client or TypeORM repository. */
|
|
3
|
+
export type OrmOptions = {
|
|
4
|
+
schema: string;
|
|
5
|
+
model: string;
|
|
6
|
+
kind?: 'prisma' | 'typeorm';
|
|
7
|
+
};
|
|
8
|
+
export declare function extractOrm(file: string, code: string, opts: StepOptions & {
|
|
9
|
+
orm: OrmOptions;
|
|
10
|
+
}): import("./extract.ts").Extraction & {
|
|
11
|
+
read?: import("./extract-step.ts").StepRead;
|
|
12
|
+
};
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
import ts from 'typescript';
|
|
2
|
+
import { Refusal } from "./extract-read.js";
|
|
3
|
+
import { asset, extractStep, node } from "./extract-step.js";
|
|
4
|
+
export function extractOrm(file, code, opts) {
|
|
5
|
+
const { readFileSync } = node('node:fs');
|
|
6
|
+
const { resolve, dirname, basename } = node('node:path');
|
|
7
|
+
const sf = ts.createSourceFile(file, code, ts.ScriptTarget.Latest, true);
|
|
8
|
+
const fail = (n, why) => { const p = sf.getLineAndCharacterOfPosition(n.getStart(sf)); throw new Refusal(`${file}:${p.line + 1}:${p.character + 1}`, why); };
|
|
9
|
+
try {
|
|
10
|
+
const names = typeof opts.entry === 'string' ? [opts.entry] : opts.entry;
|
|
11
|
+
if (!names?.length || new Set(names).size !== names.length)
|
|
12
|
+
throw new Refusal(file, 'ORM extraction requires distinct explicit entries');
|
|
13
|
+
const model = opts.orm.model, kind = opts.orm.kind ?? 'prisma';
|
|
14
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(model))
|
|
15
|
+
throw new Refusal(file, 'invalid ORM model name');
|
|
16
|
+
let schema;
|
|
17
|
+
try {
|
|
18
|
+
schema = readFileSync(resolve(dirname(file), opts.orm.schema), 'utf8');
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
throw new Refusal(file, 'ORM schema file cannot be read');
|
|
22
|
+
}
|
|
23
|
+
const fields = [], keys = [];
|
|
24
|
+
if (kind === 'prisma') {
|
|
25
|
+
// Mask comments and strings before locating a model; neither can declare one.
|
|
26
|
+
const masked = schema.replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*|"(?:\\.|[^"\\])*"/g, s => s.replace(/[^\n]/g, ' '));
|
|
27
|
+
const blocks = [...masked.matchAll(new RegExp(`\\bmodel\\s+${model}\\s*\\{([^{}]*)\\}`, 'g'))];
|
|
28
|
+
if (blocks.length !== 1)
|
|
29
|
+
throw new Refusal(file, `expected exactly one Prisma model ${model} in schema`);
|
|
30
|
+
const originalBlock = schema.slice(blocks[0].index, blocks[0].index + blocks[0][0].length).replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, '');
|
|
31
|
+
if (originalBlock.includes('"') || originalBlock.includes("'"))
|
|
32
|
+
throw new Refusal(file, `${model}: string syntax in model is unsupported`);
|
|
33
|
+
for (const raw of blocks[0][1].split('\n')) {
|
|
34
|
+
const line = raw.replace(/\/\/.*$/, '').trim();
|
|
35
|
+
if (!line)
|
|
36
|
+
continue;
|
|
37
|
+
const m = /^(\w+)\s+(Int|Boolean|String)\s*(.*)$/.exec(line);
|
|
38
|
+
if (!m || /@(?!id\b)/.test(m[3]) || /[^\s]/.test(m[3].replace('@id', '')))
|
|
39
|
+
throw new Refusal(file, `${model}: unsupported schema field ${line}`);
|
|
40
|
+
fields.push({ name: m[1], t: { k: m[2] === 'Int' ? 'int' : m[2] === 'Boolean' ? 'bool' : 'str' } });
|
|
41
|
+
if (m[3].includes('@id'))
|
|
42
|
+
keys.push(m[1]);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
else {
|
|
46
|
+
const entity = ts.createSourceFile(opts.orm.schema, schema, ts.ScriptTarget.Latest, true);
|
|
47
|
+
const imports = entity.statements.filter(ts.isImportDeclaration).filter(s => ts.isStringLiteral(s.moduleSpecifier) && s.moduleSpecifier.text === 'typeorm');
|
|
48
|
+
const imported = new Set(imports.flatMap(s => { const b = s.importClause?.namedBindings; return b && ts.isNamedImports(b) && !s.importClause?.isTypeOnly ? b.elements.filter(e => !e.isTypeOnly && !e.propertyName).map(e => e.name.text) : []; }));
|
|
49
|
+
if (!['Entity', 'Column', 'PrimaryColumn'].every(n => imported.has(n)))
|
|
50
|
+
throw new Refusal(file, `${model}: decorators must be direct named imports from typeorm`);
|
|
51
|
+
if (entity.statements.some(s => !ts.isImportDeclaration(s) && !(ts.isClassDeclaration(s) && s.name?.text === model)))
|
|
52
|
+
throw new Refusal(file, `${model}: unsupported entity module declaration`);
|
|
53
|
+
for (const s of entity.statements.filter(ts.isImportDeclaration)) {
|
|
54
|
+
const b = s.importClause?.namedBindings;
|
|
55
|
+
if (b && ts.isNamedImports(b) && b.elements.some(e => ['Entity', 'Column', 'PrimaryColumn'].includes(e.name.text) && (!ts.isStringLiteral(s.moduleSpecifier) || s.moduleSpecifier.text !== 'typeorm' || e.propertyName || e.isTypeOnly || s.importClause?.isTypeOnly)))
|
|
56
|
+
throw new Refusal(file, `${model}: ambiguous decorator binding`);
|
|
57
|
+
}
|
|
58
|
+
const classes = entity.statements.filter((s) => ts.isClassDeclaration(s) && s.name?.text === model);
|
|
59
|
+
const cls = classes.length === 1 ? classes[0] : undefined;
|
|
60
|
+
const decorators = (n) => ts.canHaveDecorators(n) ? ts.getDecorators(n) ?? [] : [];
|
|
61
|
+
const plain = (d, name) => ts.isCallExpression(d.expression) && ts.isIdentifier(d.expression.expression) && d.expression.expression.text === name && d.expression.arguments.length === 0;
|
|
62
|
+
if (entity.parseDiagnostics.length || !cls || cls.heritageClauses?.length || decorators(cls).length !== 1 || !plain(decorators(cls)[0], 'Entity'))
|
|
63
|
+
throw new Refusal(file, `${model}: expected a plain @Entity() class`);
|
|
64
|
+
for (const member of cls.members) {
|
|
65
|
+
if (!ts.isPropertyDeclaration(member) || !ts.isIdentifier(member.name) || member.initializer || member.questionToken || !member.type || member.modifiers?.some(m => m.kind !== ts.SyntaxKind.Decorator && m.kind !== ts.SyntaxKind.DeclareKeyword))
|
|
66
|
+
throw new Refusal(file, `${model}: unsupported entity member`);
|
|
67
|
+
const ds = decorators(member), primary = ds.length === 1 && plain(ds[0], 'PrimaryColumn');
|
|
68
|
+
if (!primary && !(ds.length === 1 && plain(ds[0], 'Column')))
|
|
69
|
+
throw new Refusal(file, `${model}.${member.name.text}: unsupported column decorator`);
|
|
70
|
+
const k = member.type.kind === ts.SyntaxKind.NumberKeyword ? 'int' : member.type.kind === ts.SyntaxKind.StringKeyword ? 'str' : member.type.kind === ts.SyntaxKind.BooleanKeyword ? 'bool' : undefined;
|
|
71
|
+
if (!k)
|
|
72
|
+
throw new Refusal(file, `${model}.${member.name.text}: unsupported column type`);
|
|
73
|
+
fields.push({ name: member.name.text, t: { k } });
|
|
74
|
+
if (primary)
|
|
75
|
+
keys.push(member.name.text);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
if (new Set(fields.map(f => f.name)).size !== fields.length || fields.some(f => ['__proto__', 'prototype', 'constructor'].includes(f.name)))
|
|
79
|
+
throw new Refusal(file, `${model}: duplicate or reserved column name`);
|
|
80
|
+
if (keys.length !== 1 || !fields.some(f => f.name !== keys[0]))
|
|
81
|
+
throw new Refusal(file, `${model}: requires one explicit primary key and a value column`);
|
|
82
|
+
const key = keys[0], rec = `orm.${model}`, funcs = {};
|
|
83
|
+
const loc = (n) => { const p = sf.getLineAndCharacterOfPosition(n.getStart(sf)); return `${basename(file)}:${p.line + 1}:${p.character + 1}`; };
|
|
84
|
+
const v = (n, p) => ({ e: 'var', n, p });
|
|
85
|
+
const get = (x, f, p) => ({ e: 'get', x, f, p });
|
|
86
|
+
const call = (x, f, kw, p) => ({ e: 'call', f: get(x, f, p), args: [], kw, p, text: f });
|
|
87
|
+
const manager = (p) => get({ e: 'cls', rec, p }, 'objects', p);
|
|
88
|
+
const object = (n) => {
|
|
89
|
+
if (!ts.isObjectLiteralExpression(n))
|
|
90
|
+
return fail(n, 'ORM arguments must be explicit object literals');
|
|
91
|
+
const out = new Map();
|
|
92
|
+
for (const prop of n.properties) {
|
|
93
|
+
if (ts.isShorthandPropertyAssignment(prop)) {
|
|
94
|
+
if (out.has(prop.name.text))
|
|
95
|
+
fail(prop, 'duplicate property');
|
|
96
|
+
out.set(prop.name.text, prop.name);
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
if (!ts.isPropertyAssignment(prop) || !ts.isIdentifier(prop.name))
|
|
100
|
+
return fail(prop, 'ORM properties must be explicit names');
|
|
101
|
+
if (out.has(prop.name.text))
|
|
102
|
+
fail(prop, 'duplicate property');
|
|
103
|
+
out.set(prop.name.text, prop.initializer);
|
|
104
|
+
}
|
|
105
|
+
return out;
|
|
106
|
+
};
|
|
107
|
+
let scalarNames = new Set(), rowName;
|
|
108
|
+
const expr = (n) => {
|
|
109
|
+
const p = loc(n);
|
|
110
|
+
if (ts.isIdentifier(n)) {
|
|
111
|
+
if (!scalarNames.has(n.text))
|
|
112
|
+
fail(n, 'only scalar inputs may be used as values');
|
|
113
|
+
return v(n.text, p);
|
|
114
|
+
}
|
|
115
|
+
if (ts.isNumericLiteral(n) && Number.isSafeInteger(Number(n.text)))
|
|
116
|
+
return { e: 'int', v: n.text, p };
|
|
117
|
+
if (ts.isStringLiteral(n))
|
|
118
|
+
return { e: 'str', v: n.text, p };
|
|
119
|
+
if (n.kind === ts.SyntaxKind.TrueKeyword || n.kind === ts.SyntaxKind.FalseKeyword)
|
|
120
|
+
return { e: 'bool', v: n.kind === ts.SyntaxKind.TrueKeyword, p };
|
|
121
|
+
if (ts.isPropertyAccessExpression(n) && !n.questionDotToken && ts.isIdentifier(n.expression) && n.expression.text === rowName && fields.some(f => f.name === n.name.text))
|
|
122
|
+
return get(v(rowName, p), n.name.text, p);
|
|
123
|
+
if (ts.isParenthesizedExpression(n))
|
|
124
|
+
return expr(n.expression);
|
|
125
|
+
return fail(n, 'expression outside the ORM subset');
|
|
126
|
+
};
|
|
127
|
+
for (const name of names) {
|
|
128
|
+
const parts = name.split('.');
|
|
129
|
+
let fn;
|
|
130
|
+
if (parts.length === 1) {
|
|
131
|
+
const found = sf.statements.filter((s) => ts.isFunctionDeclaration(s) && s.name?.text === name);
|
|
132
|
+
if (found.length === 1 && found[0].modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword))
|
|
133
|
+
fn = found[0];
|
|
134
|
+
}
|
|
135
|
+
else if (parts.length === 2) {
|
|
136
|
+
const classes = sf.statements.filter((s) => ts.isClassDeclaration(s) && s.name?.text === parts[0]);
|
|
137
|
+
const cls = classes.length === 1 ? classes[0] : undefined;
|
|
138
|
+
if (!cls || !cls.modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword) || cls.heritageClauses?.length || cls.members.some(m => !ts.isMethodDeclaration(m)) || (ts.canHaveDecorators(cls) && ts.getDecorators(cls)?.length))
|
|
139
|
+
throw new Refusal(file, `${name}: expected an exported plain class without constructor or fields`);
|
|
140
|
+
const methods = cls.members.filter((m) => ts.isMethodDeclaration(m) && ts.isIdentifier(m.name) && m.name.text === parts[1]);
|
|
141
|
+
if (methods.length === 1 && !methods[0].modifiers?.some(m => m.kind !== ts.SyntaxKind.AsyncKeyword && m.kind !== ts.SyntaxKind.PublicKeyword))
|
|
142
|
+
fn = methods[0];
|
|
143
|
+
}
|
|
144
|
+
if (!fn?.body || fn.asteriskToken || fn.modifiers?.some(m => m.kind === ts.SyntaxKind.DefaultKeyword || m.kind === ts.SyntaxKind.DeclareKeyword))
|
|
145
|
+
throw new Refusal(file, `${name}: expected an exported non-generator function or plain service method`);
|
|
146
|
+
const dep = fn.parameters[0];
|
|
147
|
+
if (!dep || !ts.isIdentifier(dep.name) || dep.dotDotDotToken || dep.initializer)
|
|
148
|
+
fail(fn, 'first argument must be the injected ORM client');
|
|
149
|
+
const client = dep.name.text;
|
|
150
|
+
if (dep.questionToken || client === 'this' || client.startsWith('__orm_'))
|
|
151
|
+
fail(dep, 'invalid ORM client binding');
|
|
152
|
+
const bindings = new Set([client]);
|
|
153
|
+
rowName = undefined;
|
|
154
|
+
const params = fn.parameters.slice(1).map(pa => {
|
|
155
|
+
if (!ts.isIdentifier(pa.name) || pa.initializer || pa.questionToken || pa.dotDotDotToken || !pa.type || (pa.name.text === 'this' || pa.name.text.startsWith('__orm_')) || bindings.has(pa.name.text))
|
|
156
|
+
return fail(pa, 'ORM inputs require distinct scalar type annotations');
|
|
157
|
+
bindings.add(pa.name.text);
|
|
158
|
+
const k = pa.type.kind === ts.SyntaxKind.NumberKeyword ? 'int' : pa.type.kind === ts.SyntaxKind.StringKeyword ? 'str' : pa.type.kind === ts.SyntaxKind.BooleanKeyword ? 'bool' : undefined;
|
|
159
|
+
if (!k)
|
|
160
|
+
return fail(pa, 'ORM inputs require number, string or boolean');
|
|
161
|
+
return { name: pa.name.text, t: { k } };
|
|
162
|
+
});
|
|
163
|
+
scalarNames = new Set([...bindings].filter(n => n !== client));
|
|
164
|
+
const body = [];
|
|
165
|
+
for (const [index, st] of fn.body.statements.entries()) {
|
|
166
|
+
if (ts.isReturnStatement(st)) {
|
|
167
|
+
body.push({ s: 'ret', p: loc(st), ...(st.expression ? { x: expr(st.expression) } : {}) });
|
|
168
|
+
continue;
|
|
169
|
+
}
|
|
170
|
+
let a, target;
|
|
171
|
+
if (ts.isVariableStatement(st) && st.declarationList.declarations.length === 1) {
|
|
172
|
+
const d = st.declarationList.declarations[0];
|
|
173
|
+
if (!ts.isIdentifier(d.name))
|
|
174
|
+
fail(d, 'expected a row variable');
|
|
175
|
+
target = d.name.text;
|
|
176
|
+
if (bindings.has(target) || target.startsWith('__orm_'))
|
|
177
|
+
fail(d, 'ORM row binding shadows another binding');
|
|
178
|
+
bindings.add(target);
|
|
179
|
+
a = d.initializer;
|
|
180
|
+
}
|
|
181
|
+
else if (ts.isExpressionStatement(st))
|
|
182
|
+
a = st.expression;
|
|
183
|
+
if (!a || !ts.isAwaitExpression(a) || !ts.isCallExpression(a.expression))
|
|
184
|
+
fail(st, 'only awaited ORM operations and scalar returns are supported');
|
|
185
|
+
const c = a.expression, p = loc(st);
|
|
186
|
+
if (!ts.isPropertyAccessExpression(c.expression) || c.questionDotToken || c.expression.questionDotToken || c.arguments.length !== 1)
|
|
187
|
+
fail(c, 'unsupported ORM call');
|
|
188
|
+
const access = c.expression, op = access.name.text;
|
|
189
|
+
const receiver = access.expression.getText(sf);
|
|
190
|
+
if (receiver !== (kind === 'prisma' ? `${client}.${model[0].toLowerCase()}${model.slice(1)}` : client))
|
|
191
|
+
fail(c, 'ORM receiver must be the injected client and selected model');
|
|
192
|
+
const args = object(c.arguments[0]);
|
|
193
|
+
const pair = (map) => [...map].map(([k, x]) => [k, expr(x)]);
|
|
194
|
+
if (kind === 'prisma' && op === 'create') {
|
|
195
|
+
if (target || args.size !== 1 || !args.has('data'))
|
|
196
|
+
fail(c, 'create result must be unused and only data supplied');
|
|
197
|
+
body.push({ s: 'expr', p, x: call(manager(p), 'create', pair(object(args.get('data'))), p) });
|
|
198
|
+
}
|
|
199
|
+
else if ((kind === 'prisma' && op === 'findUnique') || (kind === 'typeorm' && op === 'findOneBy')) {
|
|
200
|
+
const where = kind === 'prisma' ? (args.size === 1 && args.has('where') ? object(args.get('where')) : fail(c, 'findUnique requires only where')) : args;
|
|
201
|
+
if (!target || where.size !== 1 || !where.has(key))
|
|
202
|
+
fail(c, `read requires an assigned row and exactly its primary key ${JSON.stringify(key)}; received where fields: ${[...where.keys()].map(k => JSON.stringify(k)).join(', ') || '(none)'}`);
|
|
203
|
+
// findUnique/findOneBy return null, whereas the step IR's get fails on absence.
|
|
204
|
+
// This equivalence holds only when the very next operation dereferences the row.
|
|
205
|
+
const next = fn.body.statements[index + 1];
|
|
206
|
+
if (!next || !ts.isReturnStatement(next) || !next.expression || !ts.isPropertyAccessExpression(next.expression) || !ts.isIdentifier(next.expression.expression) || next.expression.expression.text !== target || index + 2 !== fn.body.statements.length)
|
|
207
|
+
fail(c, 'nullable ORM read must be immediately returned as a row field');
|
|
208
|
+
rowName = target;
|
|
209
|
+
body.push({ s: 'set', p, to: v(target, p), x: call(manager(p), 'get', pair(where), p) });
|
|
210
|
+
}
|
|
211
|
+
else if (kind === 'prisma' && op === 'update') {
|
|
212
|
+
if (target || args.size !== 2 || !args.has('where') || !args.has('data'))
|
|
213
|
+
fail(c, 'update requires where and data; its result must be unused');
|
|
214
|
+
const where = object(args.get('where')), data = object(args.get('data')), row = `__orm_row_${body.length}`;
|
|
215
|
+
if (where.size !== 1 || !where.has(key) || data.has(key) || !data.size || [...data.keys()].some(k => !fields.some(f => f.name === k)))
|
|
216
|
+
fail(c, `update requires primary key ${JSON.stringify(key)} and known non-key columns; received where fields: ${[...where.keys()].map(k => JSON.stringify(k)).join(', ') || '(none)'}; received data fields: ${[...data.keys()].map(k => JSON.stringify(k)).join(', ') || '(none)'}`);
|
|
217
|
+
body.push({ s: 'set', p, to: v(row, p), x: call(manager(p), 'get', pair(where), p) });
|
|
218
|
+
for (const [f, x] of data)
|
|
219
|
+
body.push({ s: 'set', p, to: get(v(row, p), f, p), x: expr(x) });
|
|
220
|
+
body.push({ s: 'expr', p, x: call(v(row, p), 'save', [], p) });
|
|
221
|
+
}
|
|
222
|
+
else if (kind === 'typeorm' && op === 'save') {
|
|
223
|
+
if (target)
|
|
224
|
+
fail(c, 'save result must be unused');
|
|
225
|
+
const row = `__orm_row_${body.length}`;
|
|
226
|
+
body.push({ s: 'set', p, to: v(row, p), x: { e: 'call', f: { e: 'cls', rec, p }, args: [], kw: pair(args), p } });
|
|
227
|
+
body.push({ s: 'expr', p, x: call(v(row, p), 'save', [], p) });
|
|
228
|
+
}
|
|
229
|
+
else
|
|
230
|
+
fail(c, `unsupported ORM operation ${op}`);
|
|
231
|
+
}
|
|
232
|
+
funcs[name] = { id: name, name, p: loc(fn), span: [basename(file), sf.getLineAndCharacterOfPosition(fn.getStart()).line + 1, sf.getLineAndCharacterOfPosition(fn.end).line + 1], params, ret: { k: 'any' }, body, decorators: [] };
|
|
233
|
+
}
|
|
234
|
+
const mod = { lang: 'TypeScript', file, path: resolve(file), root: resolve(dirname(file)), module: basename(file), entries: names.map(id => ({ k: 'func', id })), funcs, recs: { [rec]: { name: rec, short: model, fields, methods: {}, kinds: [], own: true, module: basename(file), p: file, orm: { framework: kind, key } } } };
|
|
235
|
+
const x = extractStep(mod, () => ({ cmd: 'bun', args: [asset('orm/harness.js')], hello: { path: resolve(file), model, kind } }), { ...opts, strict: true });
|
|
236
|
+
x.notes.push(`${kind}: injected client, explicit primary keys; database constraints, defaults and triggers are outside the boundary. Importing the original module executes its initialization and imported code with the checker's privileges; the check is not a sandbox and cannot prove absence of external side effects.`);
|
|
237
|
+
return x;
|
|
238
|
+
}
|
|
239
|
+
catch (e) {
|
|
240
|
+
if (e instanceof Refusal)
|
|
241
|
+
return { ok: false, refusals: [{ where: e.where, what: e.what }], notes: [] };
|
|
242
|
+
throw e;
|
|
243
|
+
}
|
|
244
|
+
}
|