gdp-wired 0.31.1 → 0.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +95 -6
  2. package/dist/core/c/reader.d.ts +86 -0
  3. package/dist/core/c/reader.js +860 -0
  4. package/dist/core/check.js +20 -6
  5. package/dist/core/cli.d.ts +76 -0
  6. package/dist/core/cli.js +636 -0
  7. package/dist/core/dsl.d.ts +6 -4
  8. package/dist/core/dsl.js +30 -16
  9. package/dist/core/effect.d.ts +6 -4
  10. package/dist/core/effect.js +48 -10
  11. package/dist/core/ex/harness.exs +177 -0
  12. package/dist/core/ex/json.exs +46 -0
  13. package/dist/core/ex/reader.exs +462 -0
  14. package/dist/core/exists.d.ts +3 -0
  15. package/dist/core/exists.js +19 -5
  16. package/dist/core/extract-c.d.ts +35 -0
  17. package/dist/core/extract-c.js +424 -0
  18. package/dist/core/extract-check.js +27 -6
  19. package/dist/core/extract-ex.d.ts +16 -0
  20. package/dist/core/extract-ex.js +33 -0
  21. package/dist/core/extract-go-check.d.ts +28 -0
  22. package/dist/core/extract-go-check.js +639 -0
  23. package/dist/core/extract-go.d.ts +231 -0
  24. package/dist/core/extract-go.js +1166 -0
  25. package/dist/core/extract-jvm.d.ts +23 -0
  26. package/dist/core/extract-jvm.js +220 -0
  27. package/dist/core/extract-print.js +17 -7
  28. package/dist/core/extract-py.d.ts +15 -0
  29. package/dist/core/extract-py.js +31 -0
  30. package/dist/core/extract-rb.d.ts +17 -0
  31. package/dist/core/extract-rb.js +31 -0
  32. package/dist/core/extract-read.d.ts +20 -0
  33. package/dist/core/extract-read.js +46 -6
  34. package/dist/core/extract-rs.d.ts +12 -0
  35. package/dist/core/extract-rs.js +306 -0
  36. package/dist/core/extract-shapes.d.ts +2 -0
  37. package/dist/core/extract-shapes.js +6 -5
  38. package/dist/core/extract-step.d.ts +806 -0
  39. package/dist/core/extract-step.js +4141 -0
  40. package/dist/core/extract-swift.d.ts +27 -0
  41. package/dist/core/extract-swift.js +484 -0
  42. package/dist/core/extract-xstate.d.ts +10 -3
  43. package/dist/core/extract-xstate.js +50 -4
  44. package/dist/core/extract.d.ts +22 -3
  45. package/dist/core/extract.js +107 -18
  46. package/dist/core/go/go.mod +3 -0
  47. package/dist/core/go/reader.go +901 -0
  48. package/dist/core/infer.d.ts +4 -0
  49. package/dist/core/infer.js +1838 -69
  50. package/dist/core/jvm/Harness.java +361 -0
  51. package/dist/core/jvm/JavaReader.java +825 -0
  52. package/dist/core/jvm/Jvm.java +332 -0
  53. package/dist/core/jvm/KtReader.java +960 -0
  54. package/dist/core/jvm/Rt.java +10 -0
  55. package/dist/core/laws.d.ts +83 -0
  56. package/dist/core/laws.js +623 -0
  57. package/dist/core/machine.d.ts +2 -0
  58. package/dist/core/machine.js +87 -0
  59. package/dist/core/py/harness.py +328 -0
  60. package/dist/core/py/reader.py +447 -0
  61. package/dist/core/rb/harness.rb +233 -0
  62. package/dist/core/rb/reader.rb +375 -0
  63. package/dist/core/relational.d.ts +49 -0
  64. package/dist/core/relational.js +345 -0
  65. package/dist/core/rs/Cargo.lock +108 -0
  66. package/dist/core/rs/Cargo.toml +14 -0
  67. package/dist/core/rs/src/main.rs +681 -0
  68. package/dist/core/swift/Harness.swift +124 -0
  69. package/dist/core/swift/Main.swift +34 -0
  70. package/dist/core/swift/Package.swift +13 -0
  71. package/dist/core/swift/Sources/gdp-swiftreader/main.swift +1341 -0
  72. package/dist/interchange/check.d.ts +16 -0
  73. package/dist/interchange/check.js +111 -0
  74. package/dist/interchange/format.d.ts +150 -0
  75. package/dist/interchange/format.js +678 -0
  76. package/dist/kernel/epr.d.ts +40 -0
  77. package/dist/kernel/epr.js +1882 -0
  78. package/dist/kernel/kernel.d.ts +45 -1
  79. package/dist/kernel/kernel.js +138 -13
  80. package/dist/kernel/prove.d.ts +45 -0
  81. package/dist/kernel/prove.js +658 -51
  82. package/dist/lean-kernel/emit.d.ts +17 -2
  83. package/dist/lean-kernel/emit.js +87 -7
  84. package/package.json +57 -2
@@ -0,0 +1,639 @@
1
+ import { Outside, constantsOf, draw, drive, evalTerm } from "./extract-check.js";
2
+ import { stubbed } from "./extract-step.js";
3
+ import { node } from "./extract-go.js";
4
+ // --- the harness ------------------------------------------------------------------------------------------------------
5
+ // Go source beside the package: a state set from JSON and read back as JSON, leaf by leaf; each method called with its
6
+ // arguments made from JSON; a panic recovered; the left-out fields compared before and after.
7
+ function harness(pkg, read, m, discard) {
8
+ const T = (t) => pkg.ttab[t] ?? { k: 'invalid' };
9
+ const imports = new Set(['bufio', 'encoding/json', 'fmt', 'os', 'reflect', 'strconv', 'math/big']);
10
+ const qual = (t) => { const x = T(t); if (x.pkg && !x.own && x.pkg !== '')
11
+ imports.add(x.pkg); };
12
+ const acc = (path) => `o.${path.join('.')}`;
13
+ const get = [], set = [];
14
+ const intGet = (e, t) => (T(t).signed === false ? `strconv.FormatUint(uint64(${e}), 10)` : `strconv.FormatInt(int64(${e}), 10)`);
15
+ const intSet = (dst, raw, t) => {
16
+ qual(t);
17
+ const bits = T(t).bits ?? 64, fn = T(t).signed === false ? 'gdpUint' : 'gdpInt';
18
+ return `if gv, ok := ${fn}(${raw}, ${bits}); ok { ${dst} = ${T(t).go}(gv) } else { return fmt.Errorf("%s outside its type", ${JSON.stringify(dst)}) }`;
19
+ };
20
+ for (const l of read.leaves) {
21
+ const a = acc(l.path), k = JSON.stringify(l.name);
22
+ switch (l.kind) {
23
+ case 'int':
24
+ get.push(`s[${k}] = ${intGet(a, l.t)}`);
25
+ set.push(`if r, ok := s[${k}]; ok { ${intSet(a, 'r', l.t)} }`);
26
+ break;
27
+ case 'bool':
28
+ get.push(`s[${k}] = ${a}`);
29
+ set.push(`if r, ok := s[${k}]; ok { if err := json.Unmarshal(r, &${a}); err != nil { return err } }`);
30
+ break;
31
+ case 'str':
32
+ get.push(`s[${k}] = ${a}`);
33
+ set.push(`if r, ok := s[${k}]; ok { if err := json.Unmarshal(r, &${a}); err != nil { return err } }`);
34
+ break;
35
+ case 'big': {
36
+ const nk = JSON.stringify(`${l.name}_nil`);
37
+ get.push(`if ${a} == nil { s[${k}] = "0"; s[${nk}] = true } else { s[${k}] = ${a}.String(); s[${nk}] = false }`);
38
+ set.push(`{ var isNil bool; if r, ok := s[${nk}]; ok { json.Unmarshal(r, &isNil) }; if isNil { ${a} = nil } else if r, ok := s[${k}]; ok { var t string; json.Unmarshal(r, &t); z, ok := new(big.Int).SetString(t, 10); if !ok { return fmt.Errorf("bad big") }; ${a} = z } }`);
39
+ break;
40
+ }
41
+ case 'map': {
42
+ const d = m.maps.find(x => x.name === l.name), mt = T(l.t), kt = mt.key, vt = mt.elem, nk = JSON.stringify(`${l.name}_nil`);
43
+ qual(l.t);
44
+ const keyOut = T(kt).k === 'int' ? intGet('key', kt) : 'string(key)';
45
+ const cellOut = d.scalar ? (T(vt).k === 'int' ? `map[string]any{"value": ${intGet('val', vt)}}` : 'map[string]any{"value": val}')
46
+ : `map[string]any{${d.fields.map(f => { const ft = T(vt).fields.find(g => g.name === f.name).t; return `${JSON.stringify(f.name)}: ${T(ft).k === 'int' ? intGet(`val.${f.name}`, ft) : `val.${f.name}`}`; }).join(', ')}}`;
47
+ get.push(`{ s[${nk}] = ${a} == nil; cells := map[string]any{}; for key, val := range ${a} { cells[${keyOut}] = ${cellOut} }; s[${k}] = cells }`);
48
+ const keyIn = T(kt).k === 'int' ? `var key ${T(kt).go}; ${intSet('key', 'json.RawMessage(strconv.Quote(ks))', kt)}` : `key := ${T(kt).go}(ks)`;
49
+ const cellIn = d.scalar ? (T(vt).k === 'int' ? `var val ${T(vt).go}; ${intSet('val', 'c["value"]', vt)}` : `var val ${T(vt).go}; json.Unmarshal(c["value"], &val)`)
50
+ : `var val ${T(vt).go}; ${d.fields.map(f => { const ft = T(vt).fields.find(g => g.name === f.name).t; return T(ft).k === 'int' ? intSet(`val.${f.name}`, `c[${JSON.stringify(f.name)}]`, ft) : `json.Unmarshal(c[${JSON.stringify(f.name)}], &val.${f.name})`; }).join('; ')}`;
51
+ set.push(`{ var isNil bool; if r, ok := s[${nk}]; ok { json.Unmarshal(r, &isNil) }; var cells map[string]map[string]json.RawMessage; if r, ok := s[${k}]; ok { json.Unmarshal(r, &cells) }; if isNil { ${a} = nil; if len(cells) > 0 { return fmt.Errorf("a nil map with keys") } } else { ${a} = ${T(l.t).go}{}; for ks, c := range cells { ${keyIn}; ${cellIn}; ${a}[key] = val } } }`);
52
+ break;
53
+ }
54
+ case 'list': {
55
+ const et = T(l.t).elem;
56
+ qual(l.t);
57
+ get.push(`{ xs := []any{}; for _, x := range ${a} { xs = append(xs, ${T(et).k === 'int' ? intGet('x', et) : 'x'}) }; s[${k}] = xs }`);
58
+ set.push(`if r, ok := s[${k}]; ok { var xs []json.RawMessage; json.Unmarshal(r, &xs); ${a} = nil; for _, x := range xs { var v ${T(et).go}; ${T(et).k === 'int' ? intSet('v', 'x', et) : 'json.Unmarshal(x, &v)'}; ${a} = append(${a}, v) } }`);
59
+ break;
60
+ }
61
+ // A big.Int's nil flag and a map's are set with their values; a left-out field is compared, not set.
62
+ case 'bignil':
63
+ case 'mapnil':
64
+ case 'frame': break;
65
+ }
66
+ }
67
+ const frames = read.leaves.filter(l => l.kind === 'frame');
68
+ // The methods: their arguments made from JSON (a struct the caller gives: a fresh one with the fields given).
69
+ const calls = [];
70
+ for (const meth of read.methods) {
71
+ const lines = [];
72
+ meth.params.forEach((pa, i) => {
73
+ const t = T(pa.t), raw = `a[${i}]`;
74
+ if (pa.arg.k === 'lit' && pa.arg.value === 'context') {
75
+ imports.add('context');
76
+ lines.push(`var a${i} context.Context = context.Background()`);
77
+ }
78
+ else if (pa.arg.k === 'input') {
79
+ if (t.k === 'int') {
80
+ lines.push(`var a${i} ${t.go}`);
81
+ lines.push(intSet(`a${i}`, raw, pa.t).replace('return fmt.Errorf', 'return nil, fmt.Errorf'));
82
+ }
83
+ else if (t.k === 'ptr')
84
+ lines.push(`a${i}, ok${i} := new(big.Int).SetString(gdpStr(${raw}), 10); if !ok${i} { return nil, fmt.Errorf("bad big") }`);
85
+ else {
86
+ lines.push(`var a${i} ${t.go}`);
87
+ lines.push(`if err := json.Unmarshal(${raw}, &a${i}); err != nil { return nil, err }`);
88
+ }
89
+ }
90
+ else if (pa.arg.k === 'rec') {
91
+ // (a pointer to a struct the caller gives, or a struct given by value)
92
+ const byValue = t.k !== 'ptr', st = byValue ? t : T(t.elem);
93
+ qual(byValue ? pa.t : t.elem);
94
+ lines.push(`a${i} := ${byValue ? '' : '&'}${st.go}{}`);
95
+ lines.push(`var f${i} map[string]json.RawMessage; json.Unmarshal(${raw}, &f${i})`);
96
+ for (const [f] of pa.arg.fields) {
97
+ const ft = (st.fields ?? st.xfields).find(g => g.name === f).t, fx = T(ft);
98
+ if (fx.k === 'int')
99
+ lines.push(`if r, ok := f${i}[${JSON.stringify(f)}]; ok { ${intSet(`a${i}.${f}`, 'r', ft).replace('return fmt.Errorf', 'return nil, fmt.Errorf')} }`);
100
+ else if (fx.k === 'ptr')
101
+ lines.push(`if r, ok := f${i}[${JSON.stringify(f)}]; ok { z, ok := new(big.Int).SetString(gdpStr(r), 10); if !ok { return nil, fmt.Errorf("bad big") }; a${i}.${f} = z }`);
102
+ else
103
+ lines.push(`if r, ok := f${i}[${JSON.stringify(f)}]; ok { json.Unmarshal(r, &a${i}.${f}) }`);
104
+ }
105
+ }
106
+ });
107
+ const argList = meth.params.map((_, i) => `a${i}`).join(', ');
108
+ const kept = meth.results.filter((_, i) => !(meth.err && i === meth.results.length - 1));
109
+ const outs = [...kept.map((_, i) => `r${i}`), ...(meth.err ? ['err'] : [])];
110
+ const recv = meth.ptr ? 'o' : '(*o)';
111
+ const invoke = outs.length ? `${outs.join(', ')} := ${recv}.${meth.name}(${argList})` : `${recv}.${meth.name}(${argList})`;
112
+ const keptOut = kept.length ? (T(kept[0]).k === 'int' ? `res.Out = ${intGet('r0', kept[0])}; res.HasOut = true` : 'res.Out = r0; res.HasOut = true') : '';
113
+ calls.push(`case ${JSON.stringify(meth.name)}:\n\t\t${lines.join('\n\t\t')}\n\t\treturn func(res *gdpRes) { ${invoke}; ${keptOut}${meth.err ? '; if err != nil { res.Err = err.Error() }' : ''} }, nil`);
114
+ }
115
+ const code = `// Generated by gdp-wired's Go check (core/extract-go-check.ts): the package's code is called as it is.
116
+ package ${pkg.package}
117
+
118
+ import (
119
+ ${[...imports].sort().map(p => `\t${p.split('/')[0].includes('.') ? `${p.replace(/[^A-Za-z0-9]/g, '_').replace(/^/, 'gdp_')} ` : ''}${JSON.stringify(p)}`).join('\n')}
120
+ )
121
+
122
+ type gdpStep struct {
123
+ M string \`json:"m"\`
124
+ A []json.RawMessage \`json:"a"\`
125
+ }
126
+ type gdpCmd struct {
127
+ Op string \`json:"op"\`
128
+ ID int \`json:"id"\`
129
+ State map[string]json.RawMessage \`json:"state"\`
130
+ M string \`json:"m"\`
131
+ A []json.RawMessage \`json:"a"\`
132
+ Answers map[string]json.RawMessage \`json:"answers"\`
133
+ }
134
+ ${read.answers?.length ? `
135
+ // The stub point of an answered call, by the callee's name (each call rewritten to it in the package's copy, the
136
+ // callee and its arguments still evaluated): the request's input for it, the zero value where it is none.
137
+ var gdpAnswers map[string]json.RawMessage
138
+
139
+ func gdpAnswer[T any](name string, _ ...any) T {
140
+ var v T
141
+ var a struct {
142
+ In json.RawMessage \`json:"in"\`
143
+ }
144
+ if json.Unmarshal(gdpAnswers[name], &a) != nil || len(a.In) == 0 {
145
+ return v
146
+ }
147
+ var s string
148
+ if json.Unmarshal(a.In, &s) == nil {
149
+ if p, ok := any(&v).(*string); ok {
150
+ *p = s
151
+ } else {
152
+ json.Unmarshal([]byte(s), &v)
153
+ }
154
+ return v
155
+ }
156
+ json.Unmarshal(a.In, &v)
157
+ return v
158
+ }
159
+ ` : ''}
160
+ type gdpRes struct {
161
+ State map[string]any \`json:"state,omitempty"\`
162
+ Out any \`json:"out,omitempty"\`
163
+ HasOut bool \`json:"hasOut,omitempty"\`
164
+ Err string \`json:"err,omitempty"\`
165
+ Panic string \`json:"panic,omitempty"\`
166
+ Bad string \`json:"bad,omitempty"\`
167
+ Frame string \`json:"frame,omitempty"\`
168
+ }
169
+
170
+ var _ = reflect.DeepEqual
171
+ var _ = big.NewInt
172
+ var _ = strconv.Itoa
173
+
174
+ func gdpInt(r json.RawMessage, bits int) (int64, bool) {
175
+ v, err := strconv.ParseInt(gdpStr(r), 10, bits)
176
+ return v, err == nil
177
+ }
178
+ func gdpUint(r json.RawMessage, bits int) (uint64, bool) {
179
+ v, err := strconv.ParseUint(gdpStr(r), 10, bits)
180
+ return v, err == nil
181
+ }
182
+ func gdpStr(r json.RawMessage) string {
183
+ var s string
184
+ if json.Unmarshal(r, &s) == nil {
185
+ return s
186
+ }
187
+ return string(r)
188
+ }
189
+ func gdpGet(o *${read.entry}) map[string]any {
190
+ s := map[string]any{}
191
+ ${get.join('\n\t')}
192
+ return s
193
+ }
194
+ func gdpSet(o *${read.entry}, s map[string]json.RawMessage) error {
195
+ ${set.join('\n\t')}
196
+ return nil
197
+ }
198
+ func gdpFrame(o *${read.entry}) []any {
199
+ return []any{${frames.map(l => acc(l.path)).join(', ')}}
200
+ }
201
+
202
+ var gdpFrameNames = []string{${frames.map(l => JSON.stringify(l.path.join('.'))).join(', ')}}
203
+
204
+ func gdpCall(o *${read.entry}, m string, a []json.RawMessage) (func(*gdpRes), error) {
205
+ switch m {
206
+ ${calls.join('\n\t')}
207
+ }
208
+ return nil, fmt.Errorf("no method %s", m)
209
+ }
210
+ func gdpRoundTrip(o *${read.entry}) map[string]json.RawMessage {
211
+ b, _ := json.Marshal(gdpGet(o))
212
+ var s map[string]json.RawMessage
213
+ json.Unmarshal(b, &s)
214
+ return s
215
+ }
216
+ func gdpRun(o *${read.entry}, st gdpStep) (res gdpRes) {
217
+ call, err := gdpCall(o, st.M, st.A)
218
+ if err != nil {
219
+ res.Bad = err.Error()
220
+ return
221
+ }
222
+ before := gdpFrame(o)
223
+ pre := gdpRoundTrip(o)
224
+ func() {
225
+ defer func() {
226
+ if r := recover(); r != nil {
227
+ res.Panic = fmt.Sprint(r)
228
+ }
229
+ }()
230
+ call(&res)
231
+ }()
232
+ after := gdpFrame(o)
233
+ for i := range before {
234
+ if !reflect.DeepEqual(before[i], after[i]) {
235
+ res.Frame = gdpFrameNames[i]
236
+ }
237
+ }
238
+ if ${discard ? 'true' : 'false'} && (res.Err != "" || res.Panic != "") {
239
+ gdpSet(o, pre)
240
+ }
241
+ res.State = gdpGet(o)
242
+ return
243
+ }
244
+
245
+ // GdpHarnessMain answers the requests read from the named pipe in, a JSON line each, on the named pipe out.
246
+ func GdpHarnessMain(in, out string) {
247
+ inf, err := os.Open(in)
248
+ if err != nil {
249
+ panic(err)
250
+ }
251
+ outf, err := os.OpenFile(out, os.O_WRONLY, 0)
252
+ if err != nil {
253
+ panic(err)
254
+ }
255
+ rd, wr := bufio.NewReaderSize(inf, 1<<20), bufio.NewWriter(outf)
256
+ objs := map[int]*${read.entry}{}
257
+ for {
258
+ line, err := rd.ReadBytes('\\n')
259
+ if err != nil {
260
+ break
261
+ }
262
+ var c gdpCmd
263
+ var res any
264
+ if err := json.Unmarshal(line, &c); err != nil {
265
+ panic(err)
266
+ }
267
+ switch c.Op {
268
+ case "new":
269
+ objs[len(objs)+1] = new(${read.entry})
270
+ res = map[string]any{"id": len(objs)}
271
+ case "at":
272
+ o := new(${read.entry})
273
+ if err := gdpSet(o, c.State); err != nil {
274
+ res = map[string]any{"bad": err.Error()}
275
+ } else {
276
+ objs[len(objs)+1] = o
277
+ res = map[string]any{"id": len(objs)}
278
+ }
279
+ case "get":
280
+ res = map[string]any{"state": gdpGet(objs[c.ID])}
281
+ 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})
283
+ }
284
+ b, _ := json.Marshal(res)
285
+ wr.Write(b)
286
+ wr.WriteByte('\\n')
287
+ wr.Flush()
288
+ }
289
+ }
290
+ `;
291
+ return { code, imports };
292
+ }
293
+ // --- the module the package is in -------------------------------------------------------------------------------------
294
+ function moduleOf(dir) {
295
+ const fs = node('node:fs');
296
+ let d = dir.replace(/\/$/, '');
297
+ const parts = [];
298
+ for (;;) {
299
+ if (fs.existsSync(`${d}/go.mod`)) {
300
+ const mod = /^module\s+(\S+)/m.exec(fs.readFileSync(`${d}/go.mod`, 'utf8'))?.[1];
301
+ if (!mod)
302
+ throw new Error(`${d}/go.mod names no module`);
303
+ return { root: d, path: [mod, ...parts].join('/'), module: mod };
304
+ }
305
+ const up = d.split('/').slice(0, -1).join('/');
306
+ if (!up || up === d)
307
+ throw new Error(`no go.mod above ${dir}`);
308
+ parts.unshift(d.split('/').pop());
309
+ d = up;
310
+ }
311
+ }
312
+ const goEnv = () => ({ ...globalThis.process?.env, GOFLAGS: '-mod=mod -buildvcs=false', GOWORK: 'off' });
313
+ // --- the check --------------------------------------------------------------------------------------------------------
314
+ // core/extract-check.ts's `drive`, with the Go code's side: the harness built once and spoken to through two named
315
+ // pipes, a JSON line a request (make an object, set it to a state, read it, call a method on it).
316
+ export function checkGo(dir, pkg, read, r, sorts, gopts) {
317
+ const opts = gopts.check ?? {}, m = read.model;
318
+ const fs = node('node:fs'), cp = node('node:child_process'), os = node('node:os');
319
+ const mod = moduleOf(dir), work = fs.mkdtempSync(`${os.tmpdir()}/gdp-gocheck-`);
320
+ const hfile = `${dir.replace(/\/$/, '')}/zz_gdp_harness_gen.go`, mainDir = `${mod.root}/gdpharness_${Date.now().toString(36)}`;
321
+ const { code } = harness(pkg, read, m, gopts.onError === 'discard');
322
+ const importPath = mod.path, empty = { runs: 0, requests: 0, fromStates: 0, probes: { conditions: 0, witnesses: 0, steps: 0 }, refusedBoth: 0, outside: 0, edge: 0, compiledAgreed: 0, coverage: { arms: 0, hit: 0, missed: [] }, ms: 0, buildMs: 0, runMs: 0 };
323
+ const b0 = performance.now();
324
+ try {
325
+ fs.writeFileSync(hfile, code);
326
+ fs.mkdirSync(mainDir, { recursive: true });
327
+ fs.writeFileSync(`${mainDir}/main.go`, `package main\n\nimport (\n\t"os"\n\n\tpkg ${JSON.stringify(importPath)}\n)\n\nfunc main() { pkg.GdpHarnessMain(os.Args[1], os.Args[2]) }\n`);
328
+ if (opts.keep) {
329
+ fs.mkdirSync(opts.keep, { recursive: true });
330
+ fs.writeFileSync(`${opts.keep}/harness.go`, code);
331
+ }
332
+ // (each answered call rewritten to the harness's answer in a copy of its file, the build told by an overlay)
333
+ const over = {};
334
+ for (const [f, t] of stubbed(read, f => fs.readFileSync(`${dir}/${f}`, 'utf8'), (a, _i, t) => `gdpAnswer[${a.ty}](${JSON.stringify(a.key)}, ${t.slice(0, t.indexOf('('))}, ${t.slice(t.indexOf('(') + 1)}`)) {
335
+ const o = node('node:path').resolve(dir, f);
336
+ fs.writeFileSync(`${work}/${f}`, t);
337
+ over[o] = over[node('node:fs').realpathSync(o)] = `${work}/${f}`;
338
+ }
339
+ if (Object.keys(over).length)
340
+ fs.writeFileSync(`${work}/overlay.json`, JSON.stringify({ Replace: over }));
341
+ try {
342
+ // The harness's own package in -coverpkg too: the counters are written only where main is instrumented.
343
+ // (a rewritten copy isn't instrumented with -cover, which reads the files as they are: no arms counted then)
344
+ cp.execFileSync('go', ['build', ...(fs.existsSync(`${work}/overlay.json`) ? [`-overlay=${work}/overlay.json`] : ['-cover', `-coverpkg=${importPath},${mod.module}/${mainDir.split('/').pop()}`]), '-o', `${work}/harness`, `./${mainDir.split('/').pop()}`], { cwd: mod.root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], env: goEnv(), maxBuffer: 1 << 26 });
345
+ }
346
+ catch (x) {
347
+ const err = String(x.stderr ?? x.message);
348
+ return { ...empty, mismatch: `the package doesn't build with the check's harness: ${err.split('\n').filter(Boolean).slice(0, 6).join(' | ')}` };
349
+ }
350
+ const buildMs = Math.round(performance.now() - b0);
351
+ fs.mkdirSync(`${work}/cov`, { recursive: true });
352
+ // The blocks of the code the step reads that the requests reached (the harness's counters, written as it exits).
353
+ const count = () => {
354
+ try {
355
+ cp.execFileSync('go', ['tool', 'covdata', 'textfmt', `-i=${work}/cov`, `-o=${work}/cov.txt`], { cwd: mod.root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], env: goEnv() });
356
+ const blocks = new Map();
357
+ for (const l of fs.readFileSync(`${work}/cov.txt`, 'utf8').split('\n').slice(1)) {
358
+ const mm = /^(.*):(\d+)\.\d+,(\d+)\.\d+ \d+ (\d+)$/.exec(l);
359
+ if (!mm)
360
+ continue;
361
+ const file = mm[1].split('/').pop(), from = Number(mm[2]), to = Number(mm[3]), n = Number(mm[4]);
362
+ if (!read.spans.some(([f, a, b]) => f === file && from >= a && to <= b))
363
+ continue;
364
+ const k = `${file}:${mm[2]}-${mm[3]}:${l.split(' ')[0]}`;
365
+ blocks.set(k, { file, from, to, hit: (blocks.get(k)?.hit ?? false) || n > 0 });
366
+ }
367
+ return { arms: blocks.size, hit: [...blocks.values()].filter(b => b.hit).length, missed: [...blocks.values()].filter(b => !b.hit).map(b => `the block at ${b.file}:${b.from}-${b.to}`) };
368
+ }
369
+ catch {
370
+ return { arms: 0, hit: 0, missed: [] };
371
+ }
372
+ };
373
+ return { ...speak(work, `${work}/harness`, { ...goEnv(), GOCOVERDIR: `${work}/cov` }, pkg, read, r, sorts, opts, count), buildMs };
374
+ }
375
+ finally {
376
+ try {
377
+ fs.rmSync(hfile);
378
+ }
379
+ catch { /* gone */ }
380
+ try {
381
+ fs.rmSync(mainDir, { recursive: true, force: true });
382
+ }
383
+ catch { /* gone */ }
384
+ try {
385
+ fs.rmSync(work, { recursive: true, force: true });
386
+ }
387
+ catch { /* gone */ }
388
+ }
389
+ }
390
+ // The code's side of core/extract-check.ts's `drive`, for a harness built in the code's language (Go's, C's): the
391
+ // harness spoken to through two named pipes in `work`, a JSON line a request (make an object, set it to a state, read
392
+ // it, call a method on it), every state compared; `count` reads the coverage after the harness exits.
393
+ export function speak(work, bin, env, pkg, read, r, sorts, opts, count) {
394
+ const m = read.model, bound = opts.bound ?? 12;
395
+ const fs = node('node:fs'), cp = node('node:child_process');
396
+ let child, wi = -1, ro = -1;
397
+ try {
398
+ cp.execFileSync('mkfifo', [`${work}/in`, `${work}/out`], {});
399
+ child = node('node:child_process').spawn(bin, [`${work}/in`, `${work}/out`], { stdio: 'ignore', env });
400
+ wi = fs.openSync(`${work}/in`, 'w');
401
+ ro = fs.openSync(`${work}/out`, 'r');
402
+ const buf = new Uint8Array(1 << 20), dec = new TextDecoder();
403
+ let pend = '';
404
+ const line = () => {
405
+ for (;;) {
406
+ const k = pend.indexOf('\n');
407
+ if (k >= 0) {
408
+ const l = pend.slice(0, k);
409
+ pend = pend.slice(k + 1);
410
+ return l;
411
+ }
412
+ const n = fs.readSync(ro, buf, 0, buf.length, null);
413
+ if (n === 0)
414
+ return undefined;
415
+ pend += dec.decode(buf.subarray(0, n), { stream: true });
416
+ }
417
+ };
418
+ const ask = (cmd) => {
419
+ fs.writeSync(wi, `${JSON.stringify(cmd)}\n`);
420
+ const l = line();
421
+ if (l === undefined)
422
+ throw new Error('the harness stopped');
423
+ return JSON.parse(l);
424
+ };
425
+ // A state from the harness as a snapshot (a number past the safe integers: the code leaves the rule's numbers).
426
+ const toSnap = (s) => {
427
+ const leaves = {}, maps = {}, lists = {};
428
+ const num = (x, at) => { const n = Number(x); if (Number.isSafeInteger(n) && String(n) === String(x))
429
+ return n; throw new Outside(`${at} is ${String(x)}`); };
430
+ for (const v of m.state)
431
+ if (!m.outputs.includes(v.name))
432
+ leaves[v.name] = v.sort.k === 'num' ? num(s[v.name], v.name) : s[v.name];
433
+ for (const d of m.maps)
434
+ maps[d.name] = Object.fromEntries(Object.entries((s[d.name] ?? {})).map(([k, c]) => [k, Object.fromEntries(d.fields.map(f => [f.name, f.sort.k === 'num' ? num(c[f.name], `${d.name}[${k}].${f.name}`) : c[f.name]]))]));
435
+ for (const d of m.lists ?? [])
436
+ lists[d.name] = (s[d.name] ?? []).map(x => (d.fields[0].sort.k === 'num' ? num(x, d.name) : x));
437
+ return { leaves, maps, ...(m.lists?.length ? { lists } : {}) };
438
+ };
439
+ const snapJson = (s) => {
440
+ const out = {};
441
+ const j = (x) => (typeof x === 'number' ? String(x) : x);
442
+ for (const [k, v] of Object.entries(s.leaves))
443
+ out[k] = j(v);
444
+ for (const [k, cells] of Object.entries(s.maps))
445
+ out[k] = Object.fromEntries(Object.entries(cells).map(([key, c]) => [key, Object.fromEntries(Object.entries(c).map(([f, x]) => [f, j(x)]))]));
446
+ for (const [k, xs] of Object.entries(s.lists ?? {}))
447
+ out[k] = xs.map(j);
448
+ return out;
449
+ };
450
+ const ctorArgs = (params) => (read.ctor ? { a: read.ctor.map(pa => argJson(pa.arg, params)) } : {});
451
+ const argJson = (a, inputs) => (a.k === 'input' ? (typeof inputs[a.name] === 'number' ? String(inputs[a.name]) : inputs[a.name]) : a.k === 'rec' ? Object.fromEntries(a.fields.map(([f, x]) => [f, argJson(x, inputs)])) : null);
452
+ // A drawn number within its variable's type (a value of the type is all the code can hold); a quarter of them at
453
+ // the type's own edges (where Go wraps).
454
+ const ranges = rangesOf(m, read, pkg), consts = constantsOf(m), strs = ['a', 'b', 'c', ''];
455
+ // (a natural, by its type or as the caller states, drawn at 0 or above)
456
+ const fit = (x, name, rand) => { const y = fit0(x, name, rand); return typeof y === 'number' && y < 0 && sorts.get(name) === 'nat' ? Math.min(-y, ranges.get(name)?.[1] ?? -y) : y; };
457
+ const fit0 = (x, name, rand) => {
458
+ if (typeof x !== 'number')
459
+ return x;
460
+ const rg = ranges.get(name);
461
+ if (!rg)
462
+ return x;
463
+ if (rand(4) === 0 && rg[1] < Number.MAX_SAFE_INTEGER) {
464
+ const e = [rg[0], rg[0] + 1, rg[1] - 1, rg[1]];
465
+ return e[rand(4)];
466
+ }
467
+ const [lo, hi] = rg;
468
+ if (x >= lo && x <= hi)
469
+ return x;
470
+ if (Number.isFinite(hi) && Number.isFinite(lo))
471
+ return lo + (((x - lo) % (hi - lo + 1)) + (hi - lo + 1)) % (hi - lo + 1);
472
+ return x < lo ? lo : x;
473
+ };
474
+ // A nil *big.Int holds 0 (the rule's encoding of it).
475
+ // (and a fixed array, C's, holds its length's items: a state made without them holds zeros)
476
+ const normalize = (s) => {
477
+ for (const l of read.leaves)
478
+ if (l.kind === 'big' && s.leaves[`${l.name}_nil`] === true)
479
+ s.leaves[l.name] = 0;
480
+ for (const d of m.lists ?? [])
481
+ if (d.len !== undefined) {
482
+ const xs = s.lists?.[d.name] ?? [];
483
+ s.lists = { ...s.lists, [d.name]: Array.from({ length: d.len }, (_, i) => xs[i] ?? (d.fields[0].sort.k === 'bool' ? false : 0)) };
484
+ }
485
+ return s;
486
+ };
487
+ let coverage;
488
+ const r0 = performance.now();
489
+ const side = {
490
+ // (a constructor's arguments, C++'s: the rule's parameters)
491
+ make: params => { const res = ask({ op: 'new', ...ctorArgs(params) }); return res.bad ? { ok: false, error: `the code can't be made with it (${res.bad})` } : { ok: true, value: res.id }; },
492
+ at: (s, params) => { const res = ask({ op: 'at', state: snapJson(s), ...ctorArgs(params) }); return res.bad ? undefined : res.id; },
493
+ snapOf: self => toSnap(ask({ op: 'get', id: self }).state),
494
+ call: (self, e, args) => {
495
+ // (the answers' values: the event's last argument, each one within its type or the request is outside)
496
+ let answers;
497
+ if (read.answers?.length) {
498
+ const v = args.pop();
499
+ 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]))
500
+ 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 }]; }));
501
+ }
502
+ const res = ask({ op: 'call', id: self, m: e.call, a: args, ...(answers ? { answers } : {}) });
503
+ if (res.frame)
504
+ throw new Error(`the code changes ${res.frame}, a field the rule leaves out`);
505
+ if (res.bad)
506
+ return { ok: false, error: `the code can't be given it (${res.bad})` };
507
+ if (res.err !== undefined || res.panic !== undefined)
508
+ return { ok: false, error: res.err !== undefined ? `error: ${res.err}` : `panic: ${res.panic}` };
509
+ 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 };
510
+ },
511
+ args: (inputs, e) => e.args.map(a => argJson(a, inputs)),
512
+ setNow: () => { },
513
+ coverage: () => (coverage ??= closeAndCount()),
514
+ 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; },
515
+ drawSnap: rand => {
516
+ const leaves = {}, maps = {}, lists = {};
517
+ for (const v of m.state) {
518
+ if (m.outputs.includes(v.name))
519
+ continue;
520
+ let x = draw(v.sort, sorts, v.name, rand, consts, bound, strs);
521
+ if (typeof x === 'number' && sorts.get(v.name) === 'nat' && x < 0)
522
+ x = -x;
523
+ if (typeof x === 'number' && Math.abs(x) > Number.MAX_SAFE_INTEGER / 4)
524
+ x = rand(bound);
525
+ leaves[v.name] = fit(x, v.name, rand);
526
+ }
527
+ normalize({ leaves, maps });
528
+ for (const d of m.maps) {
529
+ const cells = {};
530
+ if (leaves[`${d.name}_nil`] !== true)
531
+ for (let i = rand(4); i > 0; i--) {
532
+ const key = d.key === 'str' ? strs[rand(3)] : String(rand(4));
533
+ cells[key] = Object.fromEntries(d.fields.map(f => { let x = draw(f.sort, sorts, `${d.name}.${f.name}`, rand, consts, bound, strs); if (typeof x === 'number' && sorts.get(`${d.name}.${f.name}`) === 'nat')
534
+ x = Math.abs(x); return [f.name, fit(x, `${d.name}.${f.name}`, rand)]; }));
535
+ }
536
+ maps[d.name] = cells;
537
+ }
538
+ for (const d of m.lists ?? []) {
539
+ const f = d.fields[0];
540
+ lists[d.name] = Array.from({ length: d.len ?? rand(4) }, () => { let x = draw(f.sort, sorts, `${d.name}.$item`, rand, consts, bound, strs); if (typeof x === 'number' && sorts.get(`${d.name}.$item`) === 'nat')
541
+ x = Math.abs(x); return fit(x, `${d.name}.$item`, rand); });
542
+ }
543
+ return { leaves, maps, ...(m.lists?.length ? { lists } : {}) };
544
+ },
545
+ normalize,
546
+ edge: (s, raw) => read.edges.some(c => evalB(c, s, raw)),
547
+ };
548
+ // The harness told to stop: its counters written as it exits.
549
+ function closeAndCount() {
550
+ fs.closeSync(wi);
551
+ wi = -1;
552
+ while (line() !== undefined) { /* to its end */ }
553
+ fs.closeSync(ro);
554
+ ro = -1;
555
+ return count();
556
+ }
557
+ const ev = drive(m, r, sorts, side, opts);
558
+ return { ...ev, runMs: Math.round(performance.now() - r0) };
559
+ }
560
+ finally {
561
+ if (wi >= 0)
562
+ try {
563
+ fs.closeSync(wi);
564
+ }
565
+ catch { /* closed */ }
566
+ if (ro >= 0)
567
+ try {
568
+ fs.closeSync(ro);
569
+ }
570
+ catch { /* closed */ }
571
+ try {
572
+ child?.kill();
573
+ }
574
+ catch { /* gone */ }
575
+ }
576
+ }
577
+ // Each fixed-width number's range, by the rule's name (inputs, state, map fields, list items).
578
+ function rangesOf(m, read, pkg) {
579
+ const out = new Map();
580
+ const rg = (t) => {
581
+ const x = pkg.ttab[t];
582
+ if (x?.k !== 'int')
583
+ return undefined;
584
+ const bits = x.bits ?? 64;
585
+ if (bits >= 64)
586
+ return x.signed === false ? [0, Number.MAX_SAFE_INTEGER] : [-Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER];
587
+ return x.signed === false ? [0, 2 ** bits - 1] : [-(2 ** (bits - 1)), 2 ** (bits - 1) - 1];
588
+ };
589
+ for (const l of read.leaves) {
590
+ const r = l.kind === 'int' ? rg(l.t) : undefined;
591
+ if (r)
592
+ out.set(l.name, r);
593
+ }
594
+ for (const pa of read.ctor ?? []) {
595
+ const r = rg(pa.t);
596
+ if (r && pa.arg.k === 'input')
597
+ out.set(pa.arg.name, r);
598
+ }
599
+ for (const meth of read.methods)
600
+ for (const pa of meth.params) {
601
+ if (pa.arg.k === 'input') {
602
+ const r = rg(pa.t);
603
+ if (r)
604
+ out.set(pa.arg.name, r);
605
+ }
606
+ if (pa.arg.k === 'rec') {
607
+ const pt = pkg.ttab[pa.t], st = pt.k === 'ptr' ? pkg.ttab[pt.elem] : pt;
608
+ for (const [f, a] of pa.arg.fields) {
609
+ const ft = (st.fields ?? st.xfields)?.find(g => g.name === f)?.t;
610
+ const r = ft !== undefined ? rg(ft) : undefined;
611
+ if (r && a.k === 'input')
612
+ out.set(a.name, r);
613
+ }
614
+ }
615
+ }
616
+ for (const d of m.maps) {
617
+ const l = read.leaves.find(x => x.name === d.name && x.kind === 'map');
618
+ if (!l)
619
+ continue;
620
+ const mt = pkg.ttab[l.t], vt = pkg.ttab[mt.elem];
621
+ for (const f of d.fields) {
622
+ const r = rg(vt.k === 'struct' ? vt.fields.find(g => g.name === f.name).t : mt.elem);
623
+ if (r)
624
+ out.set(`${d.name}.${f.name}`, r);
625
+ }
626
+ }
627
+ for (const d of m.lists ?? []) {
628
+ const l = read.leaves.find(x => x.name === d.name && x.kind === 'list');
629
+ const r = l ? rg(pkg.ttab[l.t].elem) : undefined;
630
+ if (r)
631
+ out.set(`${d.name}.$item`, r);
632
+ }
633
+ return out;
634
+ }
635
+ // A condition at a state and a request: core/extract-check.ts's evaluator, the snapshot's cells and items beside it.
636
+ const evalB = (c, s, inputs) => {
637
+ const env = { ...s.leaves, ...Object.fromEntries(Object.entries(s.lists ?? {}).map(([k, xs]) => [`${k}_len`, xs.length])), ...inputs };
638
+ return evalTerm(c, env, (map, key, field) => (field === '$item' ? s.lists?.[map]?.[Number(key)] ?? 0 : field === 'has' ? !!s.maps[map]?.[String(key)] : s.maps[map]?.[String(key)]?.[field] ?? 0)) === true;
639
+ };