eutaxy 0.18.0 → 0.19.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.
Files changed (75) hide show
  1. package/README.md +15 -12
  2. package/dist/aws.d.mts +3 -3
  3. package/dist/aws.d.mts.map +1 -1
  4. package/dist/aws.mjs +13 -4
  5. package/dist/aws.mjs.map +1 -1
  6. package/dist/bin.mjs +1 -1
  7. package/dist/check-zkHLdWyf.mjs +1281 -0
  8. package/dist/check-zkHLdWyf.mjs.map +1 -0
  9. package/dist/cli-Bxjvq4p9.mjs +297 -0
  10. package/dist/cli-Bxjvq4p9.mjs.map +1 -0
  11. package/dist/cli.d.mts.map +1 -1
  12. package/dist/cli.mjs +1 -1
  13. package/dist/cloudflare.d.mts +38 -6
  14. package/dist/cloudflare.d.mts.map +1 -1
  15. package/dist/cloudflare.mjs +6466 -3
  16. package/dist/cloudflare.mjs.map +1 -0
  17. package/dist/{delivery-invariants-D-_GPOqE.d.mts → delivery-invariants-C3GXJIbg.d.mts} +2 -2
  18. package/dist/{delivery-invariants-D-_GPOqE.d.mts.map → delivery-invariants-C3GXJIbg.d.mts.map} +1 -1
  19. package/dist/{delivery-invariants-BRwfZJrs.mjs → delivery-invariants-DsBHpT1n.mjs} +2 -2
  20. package/dist/{delivery-invariants-BRwfZJrs.mjs.map → delivery-invariants-DsBHpT1n.mjs.map} +1 -1
  21. package/dist/draft-DEUDffHa.mjs +467 -0
  22. package/dist/draft-DEUDffHa.mjs.map +1 -0
  23. package/dist/{src-H1Q8ytEx.mjs → generate-TBJM3-2P.mjs} +3 -618
  24. package/dist/generate-TBJM3-2P.mjs.map +1 -0
  25. package/dist/index.d.mts +36 -36
  26. package/dist/index.d.mts.map +1 -1
  27. package/dist/index.mjs +6 -3
  28. package/dist/index.mjs.map +1 -1
  29. package/dist/install-DkzpGA5D.mjs +611 -0
  30. package/dist/install-DkzpGA5D.mjs.map +1 -0
  31. package/dist/{explore-D33RP9hF.d.mts → ir-KpC2epGn.d.mts} +70 -70
  32. package/dist/ir-KpC2epGn.d.mts.map +1 -0
  33. package/dist/keys-xtanNmuR.mjs +111 -0
  34. package/dist/keys-xtanNmuR.mjs.map +1 -0
  35. package/dist/mcp-DEn3HnLz.mjs +539 -0
  36. package/dist/mcp-DEn3HnLz.mjs.map +1 -0
  37. package/dist/{platform-CawKCUru.d.mts → platform-Cs9V9t2k.d.mts} +25 -11
  38. package/dist/platform-Cs9V9t2k.d.mts.map +1 -0
  39. package/dist/pool-CXN4CwGY.mjs +61 -0
  40. package/dist/pool-CXN4CwGY.mjs.map +1 -0
  41. package/dist/{provers-DS44OeEm.mjs → provers-D8VaY_OM.mjs} +18 -2
  42. package/dist/provers-D8VaY_OM.mjs.map +1 -0
  43. package/dist/reader-B9FSoEYW.mjs +1 -0
  44. package/dist/reader-Cz6_bLf6.mjs +3774 -0
  45. package/dist/reader-Cz6_bLf6.mjs.map +1 -0
  46. package/dist/report-_Vzavqg0.mjs +310 -0
  47. package/dist/report-_Vzavqg0.mjs.map +1 -0
  48. package/dist/src-B2DpVbMN.mjs +2 -0
  49. package/dist/src-BFGTvuA_.mjs +1235 -0
  50. package/dist/src-BFGTvuA_.mjs.map +1 -0
  51. package/dist/src-BtLZPRyG.mjs +120 -0
  52. package/dist/src-BtLZPRyG.mjs.map +1 -0
  53. package/dist/src-CB8DcvsK.mjs +1 -0
  54. package/dist/src-COuquJvI.mjs +269 -0
  55. package/dist/src-COuquJvI.mjs.map +1 -0
  56. package/dist/src-Chn-m_r1.mjs +1082 -0
  57. package/dist/src-Chn-m_r1.mjs.map +1 -0
  58. package/dist/{src-Whn0RMSh.mjs → src-D-MeEFn3.mjs} +589 -517
  59. package/dist/src-D-MeEFn3.mjs.map +1 -0
  60. package/dist/src-DwYD3QQJ.mjs +346 -0
  61. package/dist/src-DwYD3QQJ.mjs.map +1 -0
  62. package/dist/toolchain-DWfymxAJ.mjs +80 -0
  63. package/dist/toolchain-DWfymxAJ.mjs.map +1 -0
  64. package/dist/verdict-evEM5Gxx.mjs +12 -0
  65. package/dist/verdict-evEM5Gxx.mjs.map +1 -0
  66. package/package.json +4 -1
  67. package/dist/cli-DyA7uTBg.mjs +0 -9447
  68. package/dist/cli-DyA7uTBg.mjs.map +0 -1
  69. package/dist/explore-D33RP9hF.d.mts.map +0 -1
  70. package/dist/platform-CawKCUru.d.mts.map +0 -1
  71. package/dist/provers-DS44OeEm.mjs.map +0 -1
  72. package/dist/src-H1Q8ytEx.mjs.map +0 -1
  73. package/dist/src-Whn0RMSh.mjs.map +0 -1
  74. package/dist/workerd-tI8INa6v.mjs +0 -6334
  75. package/dist/workerd-tI8INa6v.mjs.map +0 -1
@@ -0,0 +1,1082 @@
1
+ import { n as isSpec } from "./combinators-CLfsPfhT.mjs";
2
+ import { d as render, n as conforms } from "./generate-TBJM3-2P.mjs";
3
+ import { i as shrinkRefutation, o as evaluate } from "./src-DwYD3QQJ.mjs";
4
+ import { t as inPool } from "./pool-CXN4CwGY.mjs";
5
+ import { n as proofsOf, r as unknownOutcome } from "./provers-D8VaY_OM.mjs";
6
+ import { i as installed, r as host } from "./toolchain-DWfymxAJ.mjs";
7
+ import { C as isListExpr, a as readForEngine, h as builtinsAssumption, i as outsideProofs, l as renameVars, m as typeOf, o as readArrowBody, r as engineGap, v as readBinderType, w as listKinds, y as OutsideSubset } from "./reader-Cz6_bLf6.mjs";
8
+ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
9
+ import { availableParallelism, tmpdir } from "node:os";
10
+ import { dirname, join } from "node:path";
11
+ import { spawn } from "node:child_process";
12
+ import { pathToFileURL } from "node:url";
13
+ // packages/prover-smt/src/emit.ts
14
+ /**
15
+ * SMT-LIB 2 for a module in the subset and the properties on it, as Z3
16
+ * reads it. `number` is the IEEE double (the floating-point theory, so
17
+ * NaN, the infinities and -0 are in every binder's domain and `===` is
18
+ * `fp.eq`, as in JavaScript), `string` a sequence of 16-bit code units,
19
+ * `boolean` Bool, a record a datatype with one constructor, a tagged
20
+ * union a datatype with one constructor per member holding that member's
21
+ * record (so a record may be a member of several unions: a member is
22
+ * wrapped where one of its unions is expected, and unwrapped where a test
23
+ * of the tag narrows the union to it), a nullable type an
24
+ * option datatype (`none`, `some`), with a name narrowed by a null check
25
+ * bound to its value in the branch the check guards. Each property is one
26
+ * script: the definitions, the binders as constants with what their
27
+ * TypeScript types say beyond their sorts, the precondition asserted, the
28
+ * claim's negation asserted, `check-sat`; an `unsat` is a proof, a model
29
+ * is a candidate counterexample. Values in Z3's models are decoded back to
30
+ * JavaScript values by this module too.
31
+ */
32
+ const F64 = "(_ FloatingPoint 11 53)";
33
+ const STR = "(Seq (_ BitVec 16))";
34
+ /** A name as an SMT-LIB symbol: simple when it can be, quoted with | otherwise. */
35
+ function symbol(name) {
36
+ const escaped = name.replace(/%/g, "%25").replace(/\\/g, "%5c").replace(/\|/g, "%7c");
37
+ return /^[A-Za-z~!@$%^&*_+=<>.?/-][A-Za-z0-9~!@$%^&*_+=<>.?/-]*$/.test(escaped) ? escaped : `|${escaped}|`;
38
+ }
39
+ /** TypeScript names as SMT symbols that cannot clash with each other or with the theories' names. */
40
+ const ident = {
41
+ fn: (name) => symbol(`f_${name}`),
42
+ /** The datatype of a record, or of a union. */
43
+ record: (name) => symbol(`R_${name}`),
44
+ constructor: (name) => symbol(`mk_${name}`),
45
+ /** A union's constructor for one member, holding the member's record, and its selector. */
46
+ inject: (union, member) => symbol(`in.${union}.${member}`),
47
+ project: (union, member) => symbol(`out.${union}.${member}`),
48
+ field: (record, field) => symbol(`fld.${record}.${field}`),
49
+ variable: (name) => symbol(`v_${name}`),
50
+ /** The option datatype over a sort, and its constructors and selector. */
51
+ option: (base) => symbol(`Opt.${base}`),
52
+ none: (base) => symbol(`none.${base}`),
53
+ some: (base) => symbol(`some.${base}`),
54
+ val: (base) => symbol(`val.${base}`)
55
+ };
56
+ /** The short name a sort has inside option names: `Opt.F64`, `Opt.R_X`. */
57
+ function sortName(t, module) {
58
+ if (t.kind === "list" || t.kind === "nothing") return fail(listsOutside);
59
+ switch (t.kind) {
60
+ case "int": return "F64";
61
+ case "bool": return "Bool";
62
+ case "string": return "Str";
63
+ case "record":
64
+ case "union": return ident.record(t.name);
65
+ case "nullable": return ident.option(sortName(t.inner, module));
66
+ case "null": return fail("null has no sort of its own");
67
+ }
68
+ }
69
+ function sort(t, module) {
70
+ if (t.kind === "list" || t.kind === "nothing") return fail(listsOutside);
71
+ switch (t.kind) {
72
+ case "int": return F64;
73
+ case "bool": return "Bool";
74
+ case "string": return STR;
75
+ case "record":
76
+ case "union":
77
+ case "nullable": return sortName(t, module);
78
+ case "null": return fail("null has no sort of its own");
79
+ }
80
+ }
81
+ /** A constructor applied: a bare symbol when there are no arguments. */
82
+ function construct(name, values) {
83
+ return values.length === 0 ? ident.constructor(name) : `(${ident.constructor(name)} ${values.join(" ")})`;
84
+ }
85
+ /** A double as a floating-point literal. */
86
+ function numberTerm(n) {
87
+ if (Number.isNaN(n)) return "(_ NaN 11 53)";
88
+ if (n === Number.POSITIVE_INFINITY) return "(_ +oo 11 53)";
89
+ if (n === Number.NEGATIVE_INFINITY) return "(_ -oo 11 53)";
90
+ if (Object.is(n, -0)) return "(_ -zero 11 53)";
91
+ if (n === 0) return "(_ +zero 11 53)";
92
+ const view = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(8));
93
+ view.setFloat64(0, n);
94
+ const bits = view.getBigUint64(0);
95
+ const sign = bits >> 63n & 1n;
96
+ const exponent = bits >> 52n & 2047n;
97
+ const significand = bits & (1n << 52n) - 1n;
98
+ return `(fp #b${sign} #b${exponent.toString(2).padStart(11, "0")} #b${significand.toString(2).padStart(52, "0")})`;
99
+ }
100
+ /** A JavaScript string as a sequence of its UTF-16 code units. */
101
+ function stringTerm(s) {
102
+ if (s.length === 0) return `(as seq.empty ${STR})`;
103
+ const units = [];
104
+ for (let i = 0; i < s.length; i++) units.push(`(seq.unit #x${s.charCodeAt(i).toString(16).padStart(4, "0")})`);
105
+ return units.length === 1 ? units[0] : `(seq.++ ${units.join(" ")})`;
106
+ }
107
+ function env(module) {
108
+ return {
109
+ module,
110
+ types: /* @__PURE__ */ new WeakMap(),
111
+ ctx: {
112
+ records: new Map(module.records.map((r) => [r.name, r])),
113
+ unions: module.unions,
114
+ signatures: new Map(module.functions.map((f) => [f.name, {
115
+ params: f.params,
116
+ returns: f.returns
117
+ }]))
118
+ }
119
+ };
120
+ }
121
+ /** Why a list, or an operation on one, is refused here. */
122
+ const listsOutside = "arrays are not in this engine's subset (the Lean engine takes them)";
123
+ const fail = (message) => {
124
+ throw new OutsideSubset(message, 0);
125
+ };
126
+ /** `Number.isInteger(x)`: finite and equal to its truncation. */
127
+ function isIntegerTerm(x) {
128
+ return `(and (not (fp.isNaN ${x})) (not (fp.isInfinite ${x})) (fp.eq ${x} (fp.roundToIntegral RTZ ${x})))`;
129
+ }
130
+ /** The members of a union, as records, in declaration order. */
131
+ function membersOf(union, env) {
132
+ return (env.module.unions.find((x) => x.name === union) ?? fail(`no union ${union}`)).members.map((m) => env.ctx.records.get(m.record) ?? fail(`no record ${m.record}`));
133
+ }
134
+ const tester = (constructorSymbol) => constructorSymbol.startsWith("|") ? `|is-${constructorSymbol.slice(1)}` : `is-${constructorSymbol}`;
135
+ /** `===` of two terms of a type, as JavaScript has it. */
136
+ function sameAs(a, b, t, env) {
137
+ if (t.kind === "list" || t.kind === "nothing") return fail(listsOutside);
138
+ switch (t.kind) {
139
+ case "int": return `(fp.eq ${a} ${b})`;
140
+ case "bool":
141
+ case "string": return `(= ${a} ${b})`;
142
+ case "nullable": {
143
+ const base = sortName(t.inner, env.module);
144
+ return `(ite (and (${tester(ident.some(base))} ${a}) (${tester(ident.some(base))} ${b})) ${sameAs(`(${ident.val(base)} ${a})`, `(${ident.val(base)} ${b})`, t.inner, env)} (and (${tester(ident.none(base))} ${a}) (${tester(ident.none(base))} ${b})))`;
145
+ }
146
+ case "record":
147
+ case "union":
148
+ case "null": return fail("=== on records compares references in JavaScript; compare their fields instead");
149
+ }
150
+ }
151
+ /**
152
+ * A term of type `actual` as a value of type `want`: a member record
153
+ * wrapped in the union's constructor for it, a value wrapped in `some`
154
+ * where a nullable is wanted, a nullable member mapped into the nullable
155
+ * union. Anything else is already of the sort wanted.
156
+ */
157
+ function lift(inner, actual, want, module) {
158
+ if (want.kind === "union" && actual.kind === "record") return `(${ident.inject(want.name, actual.name)} ${inner})`;
159
+ if (want.kind !== "nullable") return inner;
160
+ if (actual.kind === "null") return inner;
161
+ if (actual.kind === "nullable") {
162
+ if (want.inner.kind !== "union" || actual.inner.kind !== "record") return inner;
163
+ const from = sortName(actual.inner, module);
164
+ const to = sortName(want.inner, module);
165
+ return `(ite (${tester(ident.none(from))} ${inner}) ${ident.none(to)} (${ident.some(to)} ${lift(`(${ident.val(from)} ${inner})`, actual.inner, want.inner, module)}))`;
166
+ }
167
+ return `(${ident.some(sortName(want.inner, module))} ${lift(inner, actual, want.inner, module)})`;
168
+ }
169
+ /**
170
+ * A term of the expression's type, or of `expected` where one is given:
171
+ * `null` and a non-null value become the option's constructors where a
172
+ * nullable is expected, and a member record its union's where the union is.
173
+ */
174
+ function term(e, scope, env, expected) {
175
+ const t = (x, want) => term(x, scope, env, want);
176
+ if (isListExpr(e)) return fail(listsOutside);
177
+ const typed = (x) => {
178
+ const key = JSON.stringify([...scope]);
179
+ let byScope = env.types.get(x);
180
+ if (!byScope) {
181
+ byScope = /* @__PURE__ */ new Map();
182
+ env.types.set(x, byScope);
183
+ }
184
+ let found = byScope.get(key);
185
+ if (!found) {
186
+ found = typeOf(x, scope, env.ctx, fail);
187
+ byScope.set(key, found);
188
+ }
189
+ return found;
190
+ };
191
+ const coerceIn = (x, want, sc) => {
192
+ if (x.kind === "cond" || x.kind === "let" || x.kind === "narrow" || x.kind === "narrowTag" || x.kind === "null") return term(x, sc, env, want);
193
+ const actual = sc === scope ? typed(x) : typeOf(x, sc, env.ctx, fail);
194
+ return lift(term(x, sc, env, want), actual, want, env.module);
195
+ };
196
+ const coerce = (x, want) => coerceIn(x, want, scope);
197
+ const narrowed = (body, inner) => expected ? coerceIn(body, expected, inner) : term(body, inner, env);
198
+ switch (e.kind) {
199
+ case "int": return numberTerm(Number(e.value));
200
+ case "bool": return e.value ? "true" : "false";
201
+ case "string": return stringTerm(e.value);
202
+ case "null":
203
+ if (expected?.kind !== "nullable") fail("null where no nullable type is expected");
204
+ return ident.none(sortName(expected.inner, env.module));
205
+ case "var": return ident.variable(e.name);
206
+ case "narrow": {
207
+ const nt = scope.get(e.name);
208
+ if (nt?.kind !== "nullable") fail(`${e.name} is narrowed but is not a nullable`);
209
+ const base = sortName(nt.inner, env.module);
210
+ const inner = new Map(scope);
211
+ inner.set(e.name, nt.inner);
212
+ return `(let ((${ident.variable(e.name)} (${ident.val(base)} ${ident.variable(e.name)}))) ${narrowed(e.body, inner)})`;
213
+ }
214
+ case "narrowTag": {
215
+ const nt = scope.get(e.name);
216
+ if (nt?.kind !== "union") fail(`${e.name} is narrowed by a tag but is not a union`);
217
+ const inner = new Map(scope);
218
+ inner.set(e.name, {
219
+ kind: "record",
220
+ name: e.member
221
+ });
222
+ const v = ident.variable(e.name);
223
+ return `(let ((${v} (${ident.project(nt.name, e.member)} ${v}))) ${narrowed(e.body, inner)})`;
224
+ }
225
+ case "neg": return `(fp.neg ${t(e.operand)})`;
226
+ case "not": return `(not ${t(e.operand)})`;
227
+ case "isInteger": return isIntegerTerm(t(e.operand));
228
+ case "floor": return `(fp.roundToIntegral RTN ${t(e.operand)})`;
229
+ case "binary": {
230
+ const lt = typed(e.left);
231
+ const rt = typed(e.right);
232
+ switch (e.op) {
233
+ case "+": return lt.kind === "string" ? `(seq.++ ${t(e.left)} ${t(e.right)})` : `(fp.add RNE ${t(e.left)} ${t(e.right)})`;
234
+ case "-": return `(fp.sub RNE ${t(e.left)} ${t(e.right)})`;
235
+ case "*": return `(fp.mul RNE ${t(e.left)} ${t(e.right)})`;
236
+ case "/": return `(fp.div RNE ${t(e.left)} ${t(e.right)})`;
237
+ case "<": return `(fp.lt ${t(e.left)} ${t(e.right)})`;
238
+ case "<=": return `(fp.leq ${t(e.left)} ${t(e.right)})`;
239
+ case ">": return `(fp.gt ${t(e.left)} ${t(e.right)})`;
240
+ case ">=": return `(fp.geq ${t(e.left)} ${t(e.right)})`;
241
+ case "===":
242
+ case "!==": {
243
+ let eq;
244
+ if (lt.kind === "null" || rt.kind === "null") {
245
+ const side = lt.kind === "null" ? e.right : e.left;
246
+ const st = lt.kind === "null" ? rt : lt;
247
+ if (st.kind !== "nullable") fail("a comparison with null of something that is not nullable");
248
+ eq = `(${tester(ident.none(sortName(st.inner, env.module)))} ${t(side)})`;
249
+ } else if (lt.kind === "nullable" && rt.kind !== "nullable") {
250
+ const base = sortName(lt.inner, env.module);
251
+ eq = `(and (${tester(ident.some(base))} ${t(e.left)}) ${sameAs(`(${ident.val(base)} ${t(e.left)})`, t(e.right), lt.inner, env)})`;
252
+ } else if (rt.kind === "nullable" && lt.kind !== "nullable") {
253
+ const base = sortName(rt.inner, env.module);
254
+ eq = `(and (${tester(ident.some(base))} ${t(e.right)}) ${sameAs(t(e.left), `(${ident.val(base)} ${t(e.right)})`, rt.inner, env)})`;
255
+ } else eq = sameAs(t(e.left), t(e.right), lt, env);
256
+ return e.op === "===" ? eq : `(not ${eq})`;
257
+ }
258
+ case "&&": return `(and ${t(e.left)} ${t(e.right)})`;
259
+ case "||": return `(or ${t(e.left)} ${t(e.right)})`;
260
+ }
261
+ break;
262
+ }
263
+ case "cond": {
264
+ const want = expected ?? typed(e);
265
+ return `(ite ${t(e.test)} ${coerce(e.ifTrue, want)} ${coerce(e.ifFalse, want)})`;
266
+ }
267
+ case "call": {
268
+ const sig = env.ctx.signatures.get(e.callee) ?? fail(`no signature for ${e.callee}`);
269
+ const args = e.args.map((a, i) => coerce(a, sig.params[i].type));
270
+ return args.length === 0 ? ident.fn(e.callee) : `(${ident.fn(e.callee)} ${args.join(" ")})`;
271
+ }
272
+ case "field": {
273
+ const o = typed(e.object);
274
+ const obj = t(e.object);
275
+ if (o.kind === "union") return membersOf(o.name, env).reduceRight((rest, m) => {
276
+ const read = `(${ident.field(m.name, e.field)} (${ident.project(o.name, m.name)} ${obj}))`;
277
+ return rest === void 0 ? read : `(ite (${tester(ident.inject(o.name, m.name))} ${obj}) ${read} ${rest})`;
278
+ }, void 0);
279
+ if (o.kind !== "record") fail(`field ${e.field} read from a ${o.kind}`);
280
+ return `(${ident.field(o.name, e.field)} ${obj})`;
281
+ }
282
+ case "record": {
283
+ const type = typed(e);
284
+ if (type.kind !== "record") fail("a record literal of no record type");
285
+ const values = (env.ctx.records.get(type.name) ?? fail(`no record ${type.name}`)).fields.map((f) => {
286
+ const given = e.fields.find((x) => x.name === f.name) ?? fail(`${type.name} literal without ${f.name}`);
287
+ return coerce(given.value, f.type);
288
+ });
289
+ return construct(type.name, values);
290
+ }
291
+ case "let": {
292
+ const inner = new Map(scope);
293
+ const bound = e.type ?? typed(e.value);
294
+ inner.set(e.name, bound);
295
+ const value = e.type ? coerce(e.value, e.type) : t(e.value);
296
+ return `(let ((${ident.variable(e.name)} ${value})) ${narrowed(e.body, inner)})`;
297
+ }
298
+ }
299
+ }
300
+ function emitFunction(f, module) {
301
+ const e = env(module);
302
+ const scope = new Map(f.params.map((p) => [p.name, p.type]));
303
+ const params = f.params.map((p) => `(${ident.variable(p.name)} ${sort(p.type, module)})`).join(" ");
304
+ const body = (() => {
305
+ const b = f.body;
306
+ if (b.kind === "cond" || b.kind === "let" || b.kind === "narrow" || b.kind === "narrowTag" || b.kind === "null") return term(b, scope, e, f.returns);
307
+ return lift(term(b, scope, e, f.returns), typeOf(b, scope, e.ctx, fail), f.returns, module);
308
+ })();
309
+ return `(define-fun ${ident.fn(f.name)} (${params}) ${sort(f.returns, module)}\n ${body})`;
310
+ }
311
+ /**
312
+ * An option sort over every sort the module could mention: the primitives,
313
+ * every record, every union. A body may join a
314
+ * value with `null` in a `const` that no signature shows, so nothing is
315
+ * left to discovery.
316
+ */
317
+ function optionSorts(module) {
318
+ const out = /* @__PURE__ */ new Map();
319
+ const bases = [
320
+ { kind: "int" },
321
+ { kind: "bool" },
322
+ { kind: "string" },
323
+ ...module.records.map((r) => ({
324
+ kind: "record",
325
+ name: r.name
326
+ })),
327
+ ...module.unions.map((u) => ({
328
+ kind: "union",
329
+ name: u.name
330
+ }))
331
+ ];
332
+ for (const b of bases) out.set(sortName(b, module), b);
333
+ return out;
334
+ }
335
+ /**
336
+ * Every datatype in one declaration, so records, unions and options may
337
+ * refer to one another in any order: a record is one constructor, a union
338
+ * one per member holding its record, an option `none` and `some` over its
339
+ * base sort.
340
+ */
341
+ function emitDatatypes(module) {
342
+ const plain = module.records;
343
+ const unions = module.unions;
344
+ const options = optionSorts(module);
345
+ const names = [
346
+ ...plain.map((r) => ident.record(r.name)),
347
+ ...unions.map((u) => ident.record(u.name)),
348
+ ...[...options.keys()].map((base) => ident.option(base))
349
+ ];
350
+ if (names.length === 0) return "";
351
+ const constructorOf = (r) => `(${ident.constructor(r.name)}${r.fields.map((f) => ` (${ident.field(r.name, f.name)} ${sort(f.type, module)})`).join("")})`;
352
+ const bodies = [
353
+ ...plain.map((r) => `(${constructorOf(r)})`),
354
+ ...unions.map((u) => `(${u.members.map((m) => `(${ident.inject(u.name, m.record)} (${ident.project(u.name, m.record)} ${ident.record(m.record)}))`).join(" ")})`),
355
+ ...[...options].map(([base, inner]) => `((${ident.none(base)}) (${ident.some(base)} (${ident.val(base)} ${sort(inner, module)})))`)
356
+ ];
357
+ return `(declare-datatypes (${names.map((n) => `(${n} 0)`).join(" ")}) (${bodies.join(" ")}))`;
358
+ }
359
+ /** What this engine does not take of binder types: arrays, which the Lean engine takes. */
360
+ const binderRule = { array: "arrays are not in the engine's subset yet" };
361
+ /**
362
+ * The subset type a binder ranges over, or `OutsideSubset`: `number` is
363
+ * the double, a union of string literals is a string (constrained to the
364
+ * literals in the script), a record is the module's datatype of that
365
+ * name, `T | null` the option over `T`, a union of records the declared
366
+ * union whose members match. Bigint and what the reader could not read
367
+ * are outside. Read by the reader's `readBinderType` under `binderRule`.
368
+ */
369
+ function binderType(name, t, module) {
370
+ return readBinderType(name, t, module, binderRule);
371
+ }
372
+ /**
373
+ * What a binder's subset type says that its sort does not: a union's
374
+ * members carry their tags, and so on
375
+ * into fields and under an option. Undefined when the sort says it all.
376
+ */
377
+ function wellFormed(target, t, module) {
378
+ switch (t.kind) {
379
+ case "int":
380
+ case "bool":
381
+ case "string":
382
+ case "null": return;
383
+ case "nullable": {
384
+ const base = sortName(t.inner, module);
385
+ const inner = wellFormed(`(${ident.val(base)} ${target})`, t.inner, module);
386
+ return inner === void 0 ? void 0 : `(or (${tester(ident.none(base))} ${target}) ${inner})`;
387
+ }
388
+ case "record": {
389
+ const rec = module.records.find((r) => r.name === t.name);
390
+ if (!rec) return void 0;
391
+ const parts = [];
392
+ for (const f of rec.fields) {
393
+ const read = `(${ident.field(rec.name, f.name)} ${target})`;
394
+ if (f.literal !== void 0) parts.push(typeof f.literal === "string" ? `(= ${read} ${stringTerm(f.literal)})` : `(= ${read} ${f.literal ? "true" : "false"})`);
395
+ const inner = wellFormed(read, f.type, module);
396
+ if (inner !== void 0) parts.push(inner);
397
+ }
398
+ return parts.length === 0 ? void 0 : parts.length === 1 ? parts[0] : `(and ${parts.join(" ")})`;
399
+ }
400
+ case "union": {
401
+ const u = module.unions.find((x) => x.name === t.name);
402
+ if (!u) return void 0;
403
+ return `(or ${u.members.map((m) => {
404
+ const is = `(${tester(ident.inject(u.name, m.record))} ${target})`;
405
+ const inner = wellFormed(`(${ident.project(u.name, m.record)} ${target})`, {
406
+ kind: "record",
407
+ name: m.record
408
+ }, module);
409
+ return inner === void 0 ? is : `(and ${is} ${inner})`;
410
+ }).join(" ")})`;
411
+ }
412
+ }
413
+ }
414
+ /**
415
+ * What a binder's TypeScript type says beyond its sort: a literal, or a
416
+ * union of literals (with or without null), admits only those values,
417
+ * which the solver must be told, since the sort alone would let it pick
418
+ * any string or number.
419
+ */
420
+ function domainConstraint(symbolName, t, subset, module) {
421
+ const literal = (target, v) => typeof v === "string" ? `(= ${target} ${stringTerm(v)})` : typeof v === "number" ? `(fp.eq ${target} ${numberTerm(v)})` : `(= ${target} ${v ? "true" : "false"})`;
422
+ const literals = [];
423
+ let withNull = false;
424
+ if (t.kind === "literal") literals.push(t.value);
425
+ else if (t.kind === "union") for (const m of t.members) if (m.kind === "literal") literals.push(m.value);
426
+ else if (m.kind === "null") withNull = true;
427
+ else return void 0;
428
+ else return void 0;
429
+ if (literals.length === 0) return void 0;
430
+ const over = (target) => {
431
+ const alternatives = literals.map((v) => literal(target, v));
432
+ return alternatives.length === 1 ? alternatives[0] : `(or ${alternatives.join(" ")})`;
433
+ };
434
+ if (subset.kind === "nullable") {
435
+ const base = sortName(subset.inner, module);
436
+ const some = `(and (${tester(ident.some(base))} ${symbolName}) ${over(`(${ident.val(base)} ${symbolName})`)})`;
437
+ return withNull ? `(or (${tester(ident.none(base))} ${symbolName}) ${some})` : some;
438
+ }
439
+ return over(symbolName);
440
+ }
441
+ /** An arrow of the spec file as a Bool term over the binders, its own parameter names renamed to theirs. */
442
+ function arrowTerm(arrow, what, property, types, e) {
443
+ try {
444
+ const binders = property.binders;
445
+ const scope = /* @__PURE__ */ new Map();
446
+ const names = /* @__PURE__ */ new Map();
447
+ arrow.params.forEach((p, i) => {
448
+ const binder = binders[i];
449
+ const type = types[i];
450
+ if (p === null) fail(`a destructured parameter in ${what}`);
451
+ if (!binder || !type) fail(`${what} takes more parameters than the function has`);
452
+ scope.set(p, type);
453
+ names.set(p, binder.name);
454
+ });
455
+ const aliases = new Map(property.imports.map((i) => [i.local, i.fn]));
456
+ const read = readArrowBody(arrow, scope, e.module, aliases);
457
+ const t = typeOf(read, scope, e.ctx, fail);
458
+ if (t.kind !== "bool") fail(`${what} is not boolean (a ${t.kind === "record" ? t.name : t.kind})`);
459
+ return term(renameVars(read, names), new Map(binders.map((b, i) => [b.name, types[i]])), e);
460
+ } catch (err) {
461
+ if (!(err instanceof OutsideSubset)) throw err;
462
+ throw new OutsideSubset(`${what} (spec file line ${arrow.line}): ${err.message}`, arrow.line);
463
+ }
464
+ }
465
+ /** The definitions every script of the module starts with: datatypes, then functions, callees first. */
466
+ function prelude(module) {
467
+ const datatypes = emitDatatypes(module);
468
+ return [
469
+ ";; Generated by Eutaxy's first-party SMT engine from the module and its spec file.",
470
+ "(set-option :produce-models true)",
471
+ ...datatypes === "" ? [] : [datatypes],
472
+ ...module.functions.map((f) => emitFunction(f, module))
473
+ ].join("\n");
474
+ }
475
+ /**
476
+ * One property's script: the binders as constants, what their types say
477
+ * beyond their sorts, the precondition asserted, the claim's negation
478
+ * asserted. `unsat` proves the claim; `sat` comes with the binders' values.
479
+ * `definitions` is the module's `prelude`, when the caller already has it.
480
+ */
481
+ function propertyScript(property, module, definitions = prelude(module)) {
482
+ if (property.kind !== "forall" || !property.ensures) fail("not a forall property");
483
+ const e = env(module);
484
+ const types = property.binders.map((b) => binderType(b.name, b.type, module));
485
+ const binders = property.binders.map((b, i) => ({
486
+ name: b.name,
487
+ symbol: ident.variable(b.name),
488
+ type: types[i]
489
+ }));
490
+ return {
491
+ script: `${[
492
+ definitions,
493
+ ...binders.map((b) => `(declare-const ${b.symbol} ${sort(b.type, module)})`),
494
+ ...binders.flatMap((b) => {
495
+ const c = wellFormed(b.symbol, b.type, module);
496
+ return c === void 0 ? [] : [`(assert ${c})`];
497
+ }),
498
+ ...property.binders.flatMap((b, i) => {
499
+ const c = domainConstraint(binders[i].symbol, b.type, types[i], module);
500
+ return c === void 0 ? [] : [`(assert ${c})`];
501
+ }),
502
+ ...property.when ? [`(assert ${arrowTerm(property.when, "when", property, types, e)})`] : [],
503
+ `(assert (not ${arrowTerm(property.ensures, "ensures", property, types, e)}))`,
504
+ "(check-sat)",
505
+ ...binders.length > 0 ? [`(get-value (${binders.map((b) => b.symbol).join(" ")}))`] : [],
506
+ "(get-info :reason-unknown)"
507
+ ].join("\n")}\n`,
508
+ binders
509
+ };
510
+ }
511
+ /** Z3's output as S-expressions and atoms, in order. */
512
+ function parseSExprs(text) {
513
+ const out = [];
514
+ const stack = [];
515
+ let i = 0;
516
+ const push = (x) => {
517
+ const top = stack[stack.length - 1];
518
+ if (top) top.push(x);
519
+ else out.push(x);
520
+ };
521
+ while (i < text.length) {
522
+ const c = text[i];
523
+ if (/\s/.test(c)) {
524
+ i++;
525
+ continue;
526
+ }
527
+ if (c === ";") {
528
+ while (i < text.length && text[i] !== "\n") i++;
529
+ continue;
530
+ }
531
+ if (c === "(") {
532
+ stack.push([]);
533
+ i++;
534
+ continue;
535
+ }
536
+ if (c === ")") {
537
+ const done = stack.pop();
538
+ if (done) push(done);
539
+ i++;
540
+ continue;
541
+ }
542
+ if (c === "\"") {
543
+ let j = i + 1;
544
+ let s = "";
545
+ while (j < text.length) if (text[j] === "\"" && text[j + 1] === "\"") {
546
+ s += "\"";
547
+ j += 2;
548
+ } else if (text[j] === "\"") break;
549
+ else s += text[j++];
550
+ push(`"${s}"`);
551
+ i = j + 1;
552
+ continue;
553
+ }
554
+ if (c === "|") {
555
+ const j = text.indexOf("|", i + 1);
556
+ push(text.slice(i, j < 0 ? text.length : j + 1));
557
+ i = j < 0 ? text.length : j + 1;
558
+ continue;
559
+ }
560
+ let j = i;
561
+ while (j < text.length && !/[\s()]/.test(text[j])) j++;
562
+ push(text.slice(i, j));
563
+ i = j;
564
+ }
565
+ while (stack.length > 0) {
566
+ const done = stack.pop();
567
+ if (done) push(done);
568
+ }
569
+ return out;
570
+ }
571
+ /** Thrown when a model value is not of the shape the type calls for. */
572
+ var UnreadableModel = class extends Error {};
573
+ const bitsOf = (atom) => atom.startsWith("#b") ? BigInt(`0b${atom.slice(2)}`) : BigInt(`0x${atom.slice(2)}`);
574
+ /** A model value of the type as a JavaScript value. */
575
+ function decode(x, t, module) {
576
+ switch (t.kind) {
577
+ case "bool":
578
+ if (x === "true") return true;
579
+ if (x === "false") return false;
580
+ throw new UnreadableModel(`not a boolean: ${show(x)}`);
581
+ case "int":
582
+ if (Array.isArray(x) && x[0] === "_") {
583
+ const special = x[1];
584
+ if (special === "NaN") return NaN;
585
+ if (special === "+oo") return Number.POSITIVE_INFINITY;
586
+ if (special === "-oo") return Number.NEGATIVE_INFINITY;
587
+ if (special === "+zero") return 0;
588
+ if (special === "-zero") return -0;
589
+ }
590
+ if (Array.isArray(x) && x[0] === "fp" && x.length === 4) {
591
+ const sign = bitsOf(x[1]);
592
+ const exponent = bitsOf(x[2]);
593
+ const significand = bitsOf(x[3]);
594
+ const view = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(8));
595
+ view.setBigUint64(0, sign << 63n | exponent << 52n | significand);
596
+ return view.getFloat64(0);
597
+ }
598
+ throw new UnreadableModel(`not a double: ${show(x)}`);
599
+ case "string": return decodeString(x);
600
+ case "nullable": {
601
+ const base = sortName(t.inner, module);
602
+ if (x === ident.none(base)) return null;
603
+ if (Array.isArray(x) && x[0] === ident.some(base) && x.length === 2) return decode(x[1], t.inner, module);
604
+ throw new UnreadableModel(`not a ${describeSubset(t)}: ${show(x)}`);
605
+ }
606
+ case "union": {
607
+ const u = module.unions.find((y) => y.name === t.name);
608
+ if (!u) throw new UnreadableModel(`no union ${t.name}`);
609
+ const head = Array.isArray(x) ? x[0] : x;
610
+ const member = u.members.find((m) => ident.inject(u.name, m.record) === head);
611
+ if (!member || !Array.isArray(x) || x.length !== 2) throw new UnreadableModel(`not a ${t.name}: ${show(x)}`);
612
+ return decode(x[1], {
613
+ kind: "record",
614
+ name: member.record
615
+ }, module);
616
+ }
617
+ case "record": {
618
+ const rec = module.records.find((r) => r.name === t.name);
619
+ if (!rec) throw new UnreadableModel(`no record ${t.name}`);
620
+ if (rec.fields.length === 0 && x === ident.constructor(t.name)) return {};
621
+ if (!Array.isArray(x) || x[0] !== ident.constructor(t.name) || x.length !== rec.fields.length + 1) throw new UnreadableModel(`not a ${t.name}: ${show(x)}`);
622
+ const out = {};
623
+ rec.fields.forEach((f, i) => {
624
+ out[f.name] = decode(x[i + 1], f.type, module);
625
+ });
626
+ return out;
627
+ }
628
+ case "null": throw new UnreadableModel("a value of type null");
629
+ }
630
+ }
631
+ function describeSubset(t) {
632
+ return t.kind === "nullable" ? `${describeSubset(t.inner)} | null` : t.kind === "record" || t.kind === "union" ? t.name : t.kind;
633
+ }
634
+ function decodeString(x) {
635
+ if (Array.isArray(x)) {
636
+ if (x[0] === "seq.unit" && typeof x[1] === "string") return String.fromCharCode(Number(bitsOf(x[1])));
637
+ if (x[0] === "seq.++") return x.slice(1).map(decodeString).join("");
638
+ if (x[0] === "as" && x[1] === "seq.empty") return "";
639
+ if (x[0] === "_" && x[1] === "seq.empty") return "";
640
+ }
641
+ throw new UnreadableModel(`not a string: ${show(x)}`);
642
+ }
643
+ function show(x) {
644
+ return typeof x === "string" ? x : `(${x.map(show).join(" ")})`;
645
+ }
646
+ /** What a property's script came back with. */
647
+ function readAnswer(output) {
648
+ const parts = parseSExprs(output);
649
+ const first = parts.find((p) => p === "sat" || p === "unsat" || p === "unknown");
650
+ const errors = parts.filter((p) => Array.isArray(p) && p[0] === "error").map((e) => show(e)).filter((e) => !/model is not available/.test(e));
651
+ const values = /* @__PURE__ */ new Map();
652
+ let reason = "";
653
+ for (const p of parts) {
654
+ if (!Array.isArray(p)) continue;
655
+ if (p[0] === ":reason-unknown" && typeof p[1] === "string") reason = p[1].replace(/^"|"$/g, "");
656
+ if (p.every((x) => Array.isArray(x) && x.length === 2 && typeof x[0] === "string")) for (const pair of p) values.set(pair[0], pair[1]);
657
+ }
658
+ if (first === void 0) return {
659
+ result: "error",
660
+ values,
661
+ reason: errors.join("; ") || output.trim(),
662
+ errors
663
+ };
664
+ return {
665
+ result: first,
666
+ values,
667
+ reason,
668
+ errors
669
+ };
670
+ }
671
+ // packages/prover-smt/src/z3.ts
672
+ /**
673
+ * Running Z3 over a process boundary. The engine is pinned to one Z3
674
+ * release, looked for in Eutaxy's cache first (where `eutaxy prover install
675
+ * smt` puts the upstream release named in `z3Downloads`), then as a `z3`
676
+ * on the PATH (or in Homebrew's and the usual local prefixes) that must
677
+ * report that version. Nothing is downloaded during a check; a missing
678
+ * solver is `unavailable`, with how to install it. Every
679
+ * run carries a resource limit, Z3's own machine-independent budget, so
680
+ * the same script gives the same outcome on every machine; a wall-clock
681
+ * timeout is only the safety net.
682
+ */
683
+ /** The Z3 release the engine's contract corpus is checked against. */
684
+ const z3Version = "5.3.2";
685
+ /** How to put the pinned solver on this machine. */
686
+ const installHint = `run: eutaxy prover install smt (or put Z3 ${z3Version} on the PATH, from https://github.com/Z3Prover/z3/releases/tag/z3-${z3Version} or Homebrew: brew install z3)`;
687
+ const z3Release = `https://github.com/Z3Prover/z3/releases/download/z3-${z3Version}`;
688
+ /** The files the solver needs on Linux and macOS: the executable, which links only system libraries. */
689
+ const unixFiles = ["bin/z3"];
690
+ /**
691
+ * On Windows the executable also needs the Visual C++ runtime, which a fresh
692
+ * Windows may lack; the release ships it beside `z3.exe`, and Windows loads
693
+ * a DLL from the executable's own directory first.
694
+ */
695
+ const windowsFiles = [
696
+ "bin/z3.exe",
697
+ "bin/msvcp140.dll",
698
+ "bin/vcruntime140.dll",
699
+ "bin/vcruntime140_1.dll"
700
+ ];
701
+ const z3File = (name, sha256, bytes, files) => ({
702
+ file: name,
703
+ url: `${z3Release}/${name}`,
704
+ sha256,
705
+ bytes,
706
+ entries: Object.fromEntries(files.map((f) => [`${name.replace(/\.zip$/, "")}/${f}`, f]))
707
+ });
708
+ /**
709
+ * The upstream release files `eutaxy prover install smt` downloads, one per
710
+ * platform, as published on Z3's GitHub release with the checksums it
711
+ * reports, and the files taken from each (the rest of the zip, bindings for
712
+ * other languages, headers and the shared library, is not unpacked); the
713
+ * file names carry the version, and a test holds them to `z3Version`. The
714
+ * Linux builds need glibc 2.39 (x64) or 2.38 (arm64).
715
+ */
716
+ const z3Downloads = {
717
+ name: "smt",
718
+ version: z3Version,
719
+ executable: "bin/z3",
720
+ files: {
721
+ "linux-x64": z3File("z3-5.3.2-x64-glibc-2.39.zip", "26d463cddad3901cbf86e3868c784914539f4e3f9b4de1a0b8dc2969806d60e2", 69479256, unixFiles),
722
+ "linux-arm64": z3File("z3-5.3.2-arm64-glibc-2.38.zip", "30b6a718a6cfe1b2db056038cc32eda5410f6d02e5937622b5238645347f59d5", 64803341, unixFiles),
723
+ "darwin-x64": z3File("z3-5.3.2-x64-osx-13.3.zip", "b911dc193f7447a14fba001e8e8a0c2866a544274bb003e76a9e864f03b4d557", 54270076, unixFiles),
724
+ "darwin-arm64": z3File("z3-5.3.2-arm64-osx-13.3.zip", "524290057c943a044ec3d1372db65a9c93f333d9817d58191154c4719ff7f8ad", 53576249, unixFiles),
725
+ "win32-x64": z3File("z3-5.3.2-x64-win.zip", "a75aa2b0383a8ee355387a54daad796911d6a965076751eea18d21a27f38e983", 70867398, windowsFiles)
726
+ }
727
+ };
728
+ /** The resource budget a check runs under (Z3's `rlimit`, in its own units), unless configured. */
729
+ const defaultResourceLimit = 5e7;
730
+ function run(command, args, options) {
731
+ return new Promise((resolve) => {
732
+ let child;
733
+ try {
734
+ child = spawn(command, args, {
735
+ cwd: options.cwd,
736
+ stdio: [
737
+ "ignore",
738
+ "pipe",
739
+ "pipe"
740
+ ]
741
+ });
742
+ } catch (err) {
743
+ resolve({
744
+ code: null,
745
+ stdout: "",
746
+ stderr: String(err),
747
+ timedOut: false
748
+ });
749
+ return;
750
+ }
751
+ let stdout = "";
752
+ let stderr = "";
753
+ let timedOut = false;
754
+ const timer = setTimeout(() => {
755
+ timedOut = true;
756
+ child.kill("SIGKILL");
757
+ }, options.timeoutMs);
758
+ child.stdout?.on("data", (d) => {
759
+ stdout += d.toString();
760
+ });
761
+ child.stderr?.on("data", (d) => {
762
+ stderr += d.toString();
763
+ });
764
+ child.on("error", (err) => {
765
+ clearTimeout(timer);
766
+ resolve({
767
+ code: null,
768
+ stdout,
769
+ stderr: `${stderr}${String(err)}`,
770
+ timedOut
771
+ });
772
+ });
773
+ child.on("close", (code) => {
774
+ clearTimeout(timer);
775
+ resolve({
776
+ code,
777
+ stdout,
778
+ stderr,
779
+ timedOut
780
+ });
781
+ });
782
+ });
783
+ }
784
+ /**
785
+ * Candidates for the `z3` executable: the one `eutaxy prover install smt`
786
+ * put in the cache, `EUTAXY_Z3`, the PATH, then the prefixes package
787
+ * managers install into.
788
+ */
789
+ function candidates(h = host()) {
790
+ const fromEnv = h.env["EUTAXY_Z3"];
791
+ const fromCache = installed(z3Downloads, h);
792
+ return [
793
+ ...fromCache ? [fromCache.executable] : [],
794
+ ...fromEnv ? [fromEnv] : [],
795
+ "z3",
796
+ "/opt/homebrew/bin/z3",
797
+ "/usr/local/bin/z3",
798
+ "/usr/bin/z3"
799
+ ];
800
+ }
801
+ /**
802
+ * The pinned solver if it is installed: a `z3` of exactly that version,
803
+ * wherever among the candidates it is; another version is reported only
804
+ * when no candidate is the pinned one.
805
+ */
806
+ async function findZ3(where = candidates()) {
807
+ let other;
808
+ for (const z3 of where) {
809
+ const v = await run(z3, ["--version"], { timeoutMs: 2e4 });
810
+ if (v.code !== 0) continue;
811
+ const m = /Z3 version (\S+)/.exec(v.stdout);
812
+ if (m?.[1] === "5.3.2") return {
813
+ command: z3,
814
+ version: z3Version
815
+ };
816
+ other ??= m?.[1] ?? "of unknown version";
817
+ }
818
+ if (other !== void 0) return { unavailable: `z3 ${other} found, but the engine is pinned to ${z3Version}; ${installHint}` };
819
+ return { unavailable: `no z3 found; ${installHint}` };
820
+ }
821
+ /** Write the script to a scratch file and run Z3 on it under the resource limit. */
822
+ async function solve(solver, script, options = {}) {
823
+ const dir = mkdtempSync(join(tmpdir(), "eutaxy-smt-"));
824
+ try {
825
+ const file = join(dir, "property.smt2");
826
+ writeFileSync(file, script);
827
+ const result = await run(solver.command, [
828
+ `rlimit=${options.resourceLimit ?? 5e7}`,
829
+ "-smt2",
830
+ file
831
+ ], {
832
+ cwd: dir,
833
+ timeoutMs: options.timeoutMs ?? 12e4
834
+ });
835
+ return {
836
+ run: result,
837
+ resourceLimit: /resource limit/i.test(result.stdout)
838
+ };
839
+ } finally {
840
+ if (!options.keep) rmSync(dir, {
841
+ recursive: true,
842
+ force: true
843
+ });
844
+ }
845
+ }
846
+ /** What every PROVEN verdict of this engine rests on. */
847
+ const engineAssumptions = [
848
+ "number is modelled as the IEEE double (the floating-point theory): NaN, the infinities and -0 are in every binder's domain, and === is fp.eq",
849
+ "string is modelled as a sequence of 16-bit code units, as JavaScript holds it",
850
+ "the function and its callees are pure and total: the module's own, or generic or imported ones read at each call from their own files; nothing else is modelled",
851
+ builtinsAssumption,
852
+ `Z3 ${z3Version} found the claim's negation unsatisfiable under a resource limit; no proof object was checked by a kernel`
853
+ ];
854
+ const proven = {
855
+ kind: "PROVEN",
856
+ engine: {
857
+ name: "smt",
858
+ version: z3Version
859
+ },
860
+ assumptions: engineAssumptions
861
+ };
862
+ const unknown = unknownOutcome;
863
+ const key = (fn, property) => `${fn}\u0000${property}`;
864
+ /** Read and emit: every function the subset takes, and a script per property of the ones with specs. */
865
+ function prepare(input) {
866
+ const read = readForEngine(input, [{
867
+ takes: (t) => t.kind !== "list" && t.kind !== "nothing",
868
+ reason: "arrays are not in this engine's subset (the Lean engine takes them)",
869
+ bodies: listKinds
870
+ }]);
871
+ const { module, fns, outside } = read;
872
+ const scripts = /* @__PURE__ */ new Map();
873
+ const skipped = /* @__PURE__ */ new Map();
874
+ let pre = "";
875
+ try {
876
+ pre = prelude(module);
877
+ for (const fn of fns) {
878
+ if (outside.has(fn.name)) continue;
879
+ for (const property of fn.properties) {
880
+ if (property.kind !== "forall") continue;
881
+ try {
882
+ scripts.set(key(fn.name, property.name), propertyScript(property, module, pre));
883
+ } catch (err) {
884
+ if (!(err instanceof OutsideSubset)) throw err;
885
+ skipped.set(key(fn.name, property.name), err.message);
886
+ }
887
+ }
888
+ }
889
+ } catch (err) {
890
+ if (!(err instanceof OutsideSubset)) throw err;
891
+ engineGap(read, err.message);
892
+ scripts.clear();
893
+ }
894
+ return {
895
+ module,
896
+ fns,
897
+ outside,
898
+ scripts,
899
+ skipped,
900
+ prelude: pre
901
+ };
902
+ }
903
+ /**
904
+ * The spec file as a module. A relative import written without `.ts`
905
+ * (`./domain`, `./domain.js`), which the simulator's loader resolves and
906
+ * Node does not, is completed in a sibling copy that is imported and then
907
+ * removed, so the copy's own relative imports still resolve.
908
+ */
909
+ /** Names each sibling copy apart from another made in the same millisecond. */
910
+ let copies = 0;
911
+ async function importSpecFile(specPath) {
912
+ try {
913
+ return await import(pathToFileURL(specPath).href);
914
+ } catch (err) {
915
+ const code = err.code;
916
+ if (code !== "ERR_MODULE_NOT_FOUND" && code !== "ERR_UNSUPPORTED_DIR_IMPORT") throw err;
917
+ const source = readFileSync(specPath, "utf8");
918
+ const dir = dirname(specPath);
919
+ const rewritten = source.replace(/(from\s*["'])(\.{1,2}\/[^"']+?)(\.js)?(["'])/g, (whole, pre, rel, _js, post) => existsSync(join(dir, `${rel}.ts`)) ? `${pre}${rel}.ts${post}` : whole);
920
+ if (rewritten === source) throw err;
921
+ const copy = join(dir, `.eutaxy-replay-${process.pid}-${Date.now()}-${copies++}.props.ts`);
922
+ writeFileSync(copy, rewritten);
923
+ try {
924
+ return await import(pathToFileURL(copy).href);
925
+ } finally {
926
+ rmSync(copy, { force: true });
927
+ }
928
+ }
929
+ }
930
+ function specLoader() {
931
+ const loaded = /* @__PURE__ */ new Map();
932
+ return (specPath) => {
933
+ let ns = loaded.get(specPath);
934
+ if (ns === void 0) {
935
+ ns = importSpecFile(specPath);
936
+ loaded.set(specPath, ns);
937
+ }
938
+ return ns;
939
+ };
940
+ }
941
+ /** The spec file's export for a property, loaded for replay, or why it could not be. */
942
+ async function loadSpec(load, specPath, property, fn) {
943
+ if (specPath === void 0) return "the engine was not given the spec file's path to replay the counterexample";
944
+ let ns;
945
+ try {
946
+ ns = await load(specPath);
947
+ } catch (err) {
948
+ return `the spec file could not be loaded to replay the counterexample: ${String(err)}`;
949
+ }
950
+ const exported = Object.hasOwn(ns, property.name) ? ns[property.name] : void 0;
951
+ if (!isSpec(exported) || exported.kind !== "forall") return `the spec file exports no forall named ${property.name} to replay the counterexample with`;
952
+ if (typeof exported.fn !== "function" || exported.fn.name !== fn) return `the spec file's ${property.name} is not on ${fn}`;
953
+ return exported;
954
+ }
955
+ /** Prove a module's properties with the pinned Z3. */
956
+ async function proveModule(input) {
957
+ const { fns, outside, scripts, skipped, module, prelude: smt } = prepare(input);
958
+ const specErrors = input.specs.errors;
959
+ const inSubset = fns.filter((f) => !outside.has(f.name));
960
+ const results = outsideProofs(fns, outside);
961
+ if (inSubset.length === 0) return {
962
+ results,
963
+ specErrors
964
+ };
965
+ const allWith = (outcome) => ({
966
+ results: [...results, ...proofsOf(inSubset, outcome)],
967
+ smt,
968
+ specErrors
969
+ });
970
+ const solver = await findZ3();
971
+ if ("unavailable" in solver) return allWith(unknown("unavailable", solver.unavailable));
972
+ const options = {
973
+ ...input.timeoutMs === void 0 ? {} : { timeoutMs: input.timeoutMs },
974
+ ...input.resourceLimit === void 0 ? {} : { resourceLimit: input.resourceLimit }
975
+ };
976
+ if (input.extra && input.extra.length > 0) {
977
+ const checked = await solve(solver, [
978
+ smt,
979
+ ...input.extra.flatMap((x) => [
980
+ "(push)",
981
+ `(assert (not ${x}))`,
982
+ "(check-sat)",
983
+ "(pop)"
984
+ ]),
985
+ ""
986
+ ].join("\n"), options);
987
+ const answers = checked.run.stdout.split("\n").map((l) => l.trim()).filter((l) => /^(sat|unsat|unknown)$/.test(l));
988
+ if (checked.run.timedOut) return allWith(unknown("gave_up", "Z3 did not finish the translation checks in time"));
989
+ if (answers.includes("unknown")) return allWith(unknown("gave_up", "Z3 reached its resource limit on a translation check"));
990
+ const failed = answers.findIndex((a) => a !== "unsat");
991
+ const errors = readAnswer(checked.run.stdout).errors;
992
+ if (checked.run.code !== 0 || errors.length > 0 || answers.length !== input.extra.length || failed >= 0) return allWith(unknown("unsupported", `the emitted SMT failed a translation check${failed >= 0 ? ` (${input.extra[failed]})` : ""}: ${errors[0] ?? (checked.run.stderr || checked.run.stdout).trim().split("\n")[0] ?? ""}`));
993
+ }
994
+ const load = specLoader();
995
+ const jobs = inSubset.flatMap((fn) => fn.properties.map((property) => ({
996
+ fn,
997
+ property
998
+ })));
999
+ const proofs = await inPool(jobs, Math.min(8, availableParallelism()), async ({ fn, property }) => {
1000
+ if (property.kind === "total") return {
1001
+ function: fn.name,
1002
+ property: property.name,
1003
+ outcome: unknown("unsupported", "total is not decided by this engine (Lean proves it by acceptance)")
1004
+ };
1005
+ const k = key(fn.name, property.name);
1006
+ const why = skipped.get(k);
1007
+ if (why !== void 0) return {
1008
+ function: fn.name,
1009
+ property: property.name,
1010
+ outcome: unknown("unsupported", why)
1011
+ };
1012
+ const script = scripts.get(k);
1013
+ if (!script) return void 0;
1014
+ const solved = await solve(solver, script.script, options);
1015
+ return {
1016
+ function: fn.name,
1017
+ property: property.name,
1018
+ outcome: await outcomeOf(solved, script, module, property, fn.name, input, load)
1019
+ };
1020
+ });
1021
+ for (const proof of proofs) if (proof) results.push(proof);
1022
+ return {
1023
+ results,
1024
+ smt,
1025
+ specErrors
1026
+ };
1027
+ }
1028
+ async function outcomeOf(solved, script, module, property, fn, input, load) {
1029
+ if (solved.run.timedOut) return unknown("gave_up", `Z3 did not finish within ${input.timeoutMs ?? 12e4} ms`);
1030
+ if (solved.run.code === null) return unknown("unavailable", `Z3 could not be run: ${solved.run.stderr.trim()}`);
1031
+ const answer = readAnswer(solved.run.stdout);
1032
+ if (answer.errors.length > 0) return unknown("unsupported", `the emitted SMT did not run: ${answer.errors[0]}`);
1033
+ if (answer.result === "unsat") return proven;
1034
+ if (answer.result === "unknown") return unknown("gave_up", solved.resourceLimit ? `Z3 reached its resource limit${answer.reason ? ` (${answer.reason})` : ""}` : `Z3 gave up: ${answer.reason || "unknown"}`);
1035
+ if (answer.result === "error") return unknown("unsupported", `the emitted SMT did not run: ${answer.reason}`);
1036
+ let values;
1037
+ try {
1038
+ values = script.binders.map((b) => {
1039
+ const v = answer.values.get(b.symbol);
1040
+ if (v === void 0) throw new UnreadableModel(`no value for ${b.name} in the model`);
1041
+ return decode(v, b.type, module);
1042
+ });
1043
+ } catch (err) {
1044
+ if (!(err instanceof UnreadableModel)) throw err;
1045
+ return unknown("unsupported", `Z3's model could not be read: ${err.message}`);
1046
+ }
1047
+ const rendered = property.binders.map((b, i) => `${b.name} = ${render(values[i])}`).join(", ");
1048
+ if (!property.binders.every((b, i) => conforms(b.type, values[i]))) return unknown("unsupported", `Z3's model lies outside the parameter types (${rendered}): the engine's model of the types is wider than the types`);
1049
+ const spec = await loadSpec(load, input.specPath, property, fn);
1050
+ if (typeof spec === "string") return unknown("unsupported", `${spec} (the model: ${rendered})`);
1051
+ const evaluation = evaluate(spec, values);
1052
+ if ("malformed" in evaluation) return unknown("unsupported", `the property could not be evaluated on the model (${rendered}): ${evaluation.malformed}`);
1053
+ if (evaluation.outcome !== "refuted") return unknown("unsupported", `the claim ${evaluation.outcome === "held" ? "held" : "was outside its precondition"} on the model Z3 gave (${rendered}): the engine's model of the language differs from the runtime here`);
1054
+ const smallest = shrinkRefutation(spec, property.binders, values, evaluation);
1055
+ return {
1056
+ kind: "REFUTED",
1057
+ engine: {
1058
+ name: "smt",
1059
+ version: z3Version
1060
+ },
1061
+ counterexample: {
1062
+ binders: property.binders.map((b, i) => ({
1063
+ name: b.name,
1064
+ value: render(smallest.values[i])
1065
+ })),
1066
+ ...smallest.error === void 0 ? {} : { error: smallest.error }
1067
+ },
1068
+ assumptions: ["found as a model of the claim's negation by Z3, confirmed by running the spec on it, then shrunk"]
1069
+ };
1070
+ }
1071
+ /** The engine as a `Prover`: available when the pinned solver is installed. */
1072
+ const smtProver = {
1073
+ name: "smt",
1074
+ async available() {
1075
+ const solver = await findZ3();
1076
+ return "unavailable" in solver ? solver : { version: solver.version };
1077
+ },
1078
+ prove: (input) => proveModule(input)
1079
+ };
1080
+ export { propertyScript as C, symbol as D, stringTerm as E, term as O, prelude as S, sort as T, emitDatatypes as _, defaultResourceLimit as a, numberTerm as b, solve as c, F64 as d, STR as f, domainConstraint as g, decode as h, smtProver as i, z3Downloads as l, binderType as m, prepare as n, findZ3 as o, UnreadableModel as p, proveModule as r, installHint as s, engineAssumptions as t, z3Version as u, emitFunction as v, readAnswer as w, parseSExprs as x, ident as y };
1081
+
1082
+ //# sourceMappingURL=src-Chn-m_r1.mjs.map