eutaxy 0.4.0 → 0.5.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.
@@ -0,0 +1,1546 @@
1
+ import { i as canonicalJson } from "./src-s6uYyC0B.mjs";
2
+ // packages/spec/src/ir.ts
3
+ const domains = [
4
+ "int",
5
+ "nat",
6
+ "number",
7
+ "boolean",
8
+ "string",
9
+ "bigint"
10
+ ];
11
+ // packages/spec/src/tokens.ts
12
+ const glyphs = {
13
+ "∧": "and",
14
+ "∨": "or",
15
+ "¬": "not",
16
+ "→": "implies",
17
+ "↔": "iff",
18
+ "≡": "equiv",
19
+ "≢": "nequiv",
20
+ "≠": "neq",
21
+ "∀": "forall",
22
+ "∃": "exists",
23
+ "∈": "member",
24
+ "∞": "infinity"
25
+ };
26
+ /** ASCII spellings of Lemma connectives, longest first. */
27
+ const asciiOps = [
28
+ ["<->", "iff"],
29
+ ["==>", "implies"],
30
+ ["->", "implies"],
31
+ ["\\/", "or"]
32
+ ];
33
+ const punctuators = [
34
+ ">>>=",
35
+ "...",
36
+ "===",
37
+ "!==",
38
+ "**=",
39
+ "<<=",
40
+ ">>=",
41
+ ">>>",
42
+ "&&=",
43
+ "||=",
44
+ "??=",
45
+ "=>",
46
+ "==",
47
+ "!=",
48
+ "<=",
49
+ ">=",
50
+ "&&",
51
+ "||",
52
+ "??",
53
+ "?.",
54
+ "++",
55
+ "--",
56
+ "+=",
57
+ "-=",
58
+ "*=",
59
+ "/=",
60
+ "%=",
61
+ "&=",
62
+ "|=",
63
+ "^=",
64
+ "**",
65
+ "<<",
66
+ ">>"
67
+ ];
68
+ /** Keywords after which a `/` starts a regular expression rather than a division. */
69
+ const regexAfter = /* @__PURE__ */ new Set([
70
+ "in",
71
+ "of",
72
+ "typeof",
73
+ "instanceof",
74
+ "return",
75
+ "new",
76
+ "delete",
77
+ "void",
78
+ "case",
79
+ "do",
80
+ "else",
81
+ "yield",
82
+ "await"
83
+ ]);
84
+ const identStart = /[\p{ID_Start}$_]/u;
85
+ const identPart = /[\p{ID_Continue}$‌‍]/u;
86
+ const numberAt = /^(?:0[xXoObB][0-9a-fA-F_]+n?|(?:\d[\d_]*(?:\.[\d_]*)?|\.\d[\d_]*)(?:[eE][+-]?\d[\d_]*)?n?)/;
87
+ var TokenizeError = class extends Error {};
88
+ /** Keywords whose parenthesized condition is followed by a statement, not an operator. */
89
+ const controlKeywords = /* @__PURE__ */ new Set([
90
+ "if",
91
+ "while",
92
+ "for",
93
+ "with"
94
+ ]);
95
+ /**
96
+ * Whether the code tokens up to `k` end an operand, so a `/` after them
97
+ * divides. `conditions` holds the `)` that close a control statement's
98
+ * condition (`if (x) /re/.test(s)`), after which a statement starts.
99
+ */
100
+ function endsOperand$1(tokens, k, conditions, blocks) {
101
+ while (k >= 0 && tokens[k]?.kind === "comment") k--;
102
+ const t = tokens[k];
103
+ if (!t) return false;
104
+ switch (t.kind) {
105
+ case "ident": {
106
+ const before = tokens.slice(0, k).findLast((u) => u.kind !== "comment");
107
+ if (before?.kind === "punct" && (before.text === "." || before.text === "?.")) return true;
108
+ return !regexAfter.has(t.text);
109
+ }
110
+ case "punct":
111
+ if (t.text === "!" || t.text === "++" || t.text === "--") return endsOperand$1(tokens, k - 1, conditions, blocks);
112
+ if (t.text === ")") return !conditions.has(k);
113
+ if (t.text === "}") return !blocks.has(k);
114
+ return t.text === "]";
115
+ case "op": return false;
116
+ default: return true;
117
+ }
118
+ }
119
+ /** The end of a quoted string starting at `i`. */
120
+ function endOfString(text, i) {
121
+ const quote = text[i];
122
+ for (let j = i + 1; j < text.length; j++) {
123
+ const c = text[j];
124
+ if (c === "\\") j++;
125
+ else if (c === quote) return j + 1;
126
+ else if (c === "\n") break;
127
+ }
128
+ throw new TokenizeError(`unterminated string at offset ${i}`);
129
+ }
130
+ /** The end of the template literal starting at `i`, substitutions included. */
131
+ function endOfTemplate(text, i) {
132
+ for (let j = i + 1; j < text.length; j++) {
133
+ const c = text[j];
134
+ if (c === "\\") j++;
135
+ else if (c === "`") return j + 1;
136
+ else if (c === "$" && text[j + 1] === "{") j = endOfSubstitution(text, j + 2) - 1;
137
+ }
138
+ throw new TokenizeError(`unterminated template literal at offset ${i}`);
139
+ }
140
+ /** The offset just past the `}` that closes a substitution whose body starts at `i`, scanned as code. */
141
+ function endOfSubstitution(text, i) {
142
+ return scan(text, i, { untilBrace: true }).end;
143
+ }
144
+ /** The source of each `${…}` substitution in a template literal's text, outermost only. */
145
+ function templateSubstitutions(template) {
146
+ const out = [];
147
+ for (let j = 1; j < template.length; j++) {
148
+ const c = template[j];
149
+ if (c === "\\") j++;
150
+ else if (c === "$" && template[j + 1] === "{") {
151
+ const end = endOfSubstitution(template, j + 2);
152
+ out.push(template.slice(j + 2, end - 1));
153
+ j = end - 1;
154
+ }
155
+ }
156
+ return out;
157
+ }
158
+ /** The end of the regex literal starting at `i`, flags included. */
159
+ function endOfRegex(text, i) {
160
+ let inClass = false;
161
+ for (let j = i + 1; j < text.length; j++) {
162
+ const c = text[j];
163
+ if (c === "\\") j++;
164
+ else if (c === "\n") break;
165
+ else if (inClass) {
166
+ if (c === "]") inClass = false;
167
+ } else if (c === "[") inClass = true;
168
+ else if (c === "/") {
169
+ let k = j + 1;
170
+ while (k < text.length && identPart.test(text[k])) k++;
171
+ return k;
172
+ }
173
+ }
174
+ throw new TokenizeError(`unterminated regular expression at offset ${i}`);
175
+ }
176
+ /** Tokens of `text`; comments are dropped unless `comments` is set (then they are "comment" tokens). */
177
+ function tokenize(text, options = {}) {
178
+ return scan(text, 0, options).tokens;
179
+ }
180
+ /**
181
+ * Scan from `start`. With `untilBrace`, stop after the `}` that closes an
182
+ * enclosing substitution (one not opened in the scanned code) and return
183
+ * the offset after it.
184
+ */
185
+ function scan(text, start, options) {
186
+ const tokens = [];
187
+ const push = (kind, start, end, op) => {
188
+ tokens.push({
189
+ kind,
190
+ text: text.slice(start, end),
191
+ start,
192
+ end,
193
+ ...op ? { op } : {}
194
+ });
195
+ };
196
+ let braces = 0;
197
+ const parens = [];
198
+ const conditions = /* @__PURE__ */ new Set();
199
+ const curlies = [];
200
+ const blocks = /* @__PURE__ */ new Set();
201
+ let i = start;
202
+ while (i < text.length) {
203
+ const c = text[i];
204
+ if (/\s/u.test(c)) {
205
+ i++;
206
+ continue;
207
+ }
208
+ if (c === "/" && text[i + 1] === "/") {
209
+ const from = i;
210
+ while (i < text.length && text[i] !== "\n") i++;
211
+ push("comment", from, i);
212
+ continue;
213
+ }
214
+ if (c === "/" && text[i + 1] === "*") {
215
+ const close = text.indexOf("*/", i + 2);
216
+ if (close < 0) throw new TokenizeError(`unterminated comment at offset ${i}`);
217
+ push("comment", i, close + 2);
218
+ i = close + 2;
219
+ continue;
220
+ }
221
+ const glyph = glyphs[c];
222
+ if (glyph) {
223
+ push("op", i, i + 1, glyph);
224
+ i++;
225
+ continue;
226
+ }
227
+ const ascii = asciiOps.find(([s]) => text.startsWith(s, i));
228
+ if (ascii) {
229
+ push("op", i, i + ascii[0].length, ascii[1]);
230
+ i += ascii[0].length;
231
+ continue;
232
+ }
233
+ if (c === "/") {
234
+ if (!endsOperand$1(tokens, tokens.length - 1, conditions, blocks)) {
235
+ const end = endOfRegex(text, i);
236
+ push("regex", i, end);
237
+ i = end;
238
+ continue;
239
+ }
240
+ if (text[i + 1] === "\\") {
241
+ push("op", i, i + 2, "and");
242
+ i += 2;
243
+ continue;
244
+ }
245
+ }
246
+ if (c === "\"" || c === "'") {
247
+ const end = endOfString(text, i);
248
+ push("string", i, end);
249
+ i = end;
250
+ continue;
251
+ }
252
+ if (c === "`") {
253
+ const end = endOfTemplate(text, i);
254
+ push("template", i, end);
255
+ i = end;
256
+ continue;
257
+ }
258
+ const num = numberAt.exec(text.slice(i));
259
+ if (num && (/\d/.test(c) || c === "." && /\d/.test(text[i + 1] ?? ""))) {
260
+ push("number", i, i + num[0].length);
261
+ i += num[0].length;
262
+ continue;
263
+ }
264
+ if (identStart.test(c)) {
265
+ let j = i + 1;
266
+ while (j < text.length && identPart.test(text[j])) j++;
267
+ push("ident", i, j);
268
+ i = j;
269
+ continue;
270
+ }
271
+ const p = punctuators.find((s) => text.startsWith(s, i)) ?? c;
272
+ if (p === "(") {
273
+ const before = tokens.findLast((t) => t.kind !== "comment");
274
+ parens.push(before?.kind === "ident" && controlKeywords.has(before.text));
275
+ } else if (p === ")" && parens.pop()) conditions.add(tokens.length);
276
+ if (p === "{") {
277
+ const before = tokens.findLast((t) => t.kind !== "comment");
278
+ curlies.push(before === void 0 || before.kind === "punct" && [
279
+ ")",
280
+ "{",
281
+ "}",
282
+ ";",
283
+ "=>"
284
+ ].includes(before.text) || before.kind === "ident" && [
285
+ "else",
286
+ "do",
287
+ "try",
288
+ "finally"
289
+ ].includes(before.text));
290
+ } else if (p === "}" && curlies.pop()) blocks.add(tokens.length);
291
+ if (p === "{") braces++;
292
+ if (p === "}" && braces-- === 0 && options.untilBrace) return {
293
+ tokens: keep(tokens, options),
294
+ end: i + 1
295
+ };
296
+ push("punct", i, i + p.length);
297
+ i += p.length;
298
+ }
299
+ if (options.untilBrace) throw new TokenizeError(`unterminated template substitution at offset ${start}`);
300
+ return {
301
+ tokens: keep(tokens, options),
302
+ end: i
303
+ };
304
+ }
305
+ function keep(tokens, options) {
306
+ return options.comments ? tokens : tokens.filter((t) => t.kind !== "comment");
307
+ }
308
+ // packages/spec/src/parse.ts
309
+ /**
310
+ * The Lemma `@ensures` property parser: grammar.ebnf of lemma-lang, with
311
+ * the side conditions it states on atoms. A property is a quantifier
312
+ * prefix and a braced formula body; the body's structure (connectives,
313
+ * equations, grouping) is Lemma, and its leaves are TypeScript expressions
314
+ * kept verbatim. Validation that needs the enclosing module (free
315
+ * identifiers exported) is left to whoever evaluates the leaves.
316
+ */
317
+ /** A property that is not Lemma. `stage` says which part rejected it. */
318
+ var LemmaSyntaxError = class extends Error {
319
+ stage;
320
+ constructor(stage, message) {
321
+ super(message);
322
+ this.stage = stage;
323
+ }
324
+ };
325
+ const numeric = /* @__PURE__ */ new Set([
326
+ "int",
327
+ "nat",
328
+ "number",
329
+ "bigint"
330
+ ]);
331
+ const literalSyntax = {
332
+ int: /^[+-]?\d[\d_]*$/,
333
+ nat: /^[+-]?\d[\d_]*$/,
334
+ bigint: /^[+-]?\d[\d_]*n?$/,
335
+ number: /^[+-]?(?:\d[\d_]*(?:\.[\d_]*)?|\.\d[\d_]*)(?:[eE][+-]?\d+)?$/
336
+ };
337
+ const assignments = /* @__PURE__ */ new Set([
338
+ "=",
339
+ "+=",
340
+ "-=",
341
+ "*=",
342
+ "/=",
343
+ "%=",
344
+ "**=",
345
+ "<<=",
346
+ ">>=",
347
+ ">>>=",
348
+ "&=",
349
+ "|=",
350
+ "^=",
351
+ "&&=",
352
+ "||=",
353
+ "??="
354
+ ]);
355
+ /** Parse the text after `@ensures{name}`. Throws LemmaSyntaxError. */
356
+ function parseProperty(text) {
357
+ let tokens;
358
+ try {
359
+ tokens = tokenize(text);
360
+ } catch (err) {
361
+ if (err instanceof TokenizeError) throw new LemmaSyntaxError("formula", err.message);
362
+ throw err;
363
+ }
364
+ const prefix = new Prefix(tokens);
365
+ return {
366
+ binders: prefix.parse(),
367
+ ...new Body(text, tokens, prefix.at).parse()
368
+ };
369
+ }
370
+ const isOp = (t, op) => t?.kind === "op" && t.op === op;
371
+ const isPunct$1 = (t, p) => t?.kind === "punct" && t.text === p;
372
+ var Prefix = class {
373
+ tokens;
374
+ at = 0;
375
+ constructor(tokens) {
376
+ this.tokens = tokens;
377
+ }
378
+ fail(message) {
379
+ throw new LemmaSyntaxError("prefix", message);
380
+ }
381
+ peek() {
382
+ return this.tokens[this.at];
383
+ }
384
+ next(what) {
385
+ const t = this.tokens[this.at++];
386
+ if (!t) this.fail(`expected ${what}, found the end of the annotation`);
387
+ return t;
388
+ }
389
+ parse() {
390
+ const first = this.next("forall");
391
+ if (isOp(first, "exists") || first.kind === "ident" && first.text === "exists") this.fail("existential quantifiers are not Lemma: sampling cannot confirm that something exists, so state the property with forall");
392
+ if (!(isOp(first, "forall") || first.kind === "ident" && first.text === "forall")) this.fail(`a property starts with forall, not ${JSON.stringify(first.text)}`);
393
+ const binders = [];
394
+ while (isPunct$1(this.peek(), "(")) binders.push(...this.group());
395
+ if (binders.length === 0) this.fail("forall needs at least one binder group, as in (x: int)");
396
+ const seen = /* @__PURE__ */ new Set();
397
+ for (const b of binders) {
398
+ if (seen.has(b.name)) this.fail(`${b.name} is bound twice`);
399
+ seen.add(b.name);
400
+ }
401
+ if (!isPunct$1(this.peek(), "{")) this.fail("expected { to open the property body after the binders");
402
+ return binders;
403
+ }
404
+ group() {
405
+ this.next("(");
406
+ const names = [];
407
+ while (this.peek()?.kind === "ident") names.push(this.next("a name").text);
408
+ const colon = this.next(":");
409
+ if (!isPunct$1(colon, ":")) this.fail(names.length === 0 ? "a binder group needs at least one name before the colon, as in (x: int)" : `expected : before the domain, found ${JSON.stringify(colon.text)}`);
410
+ if (names.length === 0) this.fail("a binder group needs at least one name before the colon, as in (x: int)");
411
+ for (const n of names) if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(n)) this.fail(`${JSON.stringify(n)} is not a binder name`);
412
+ const d = this.next("a domain");
413
+ if (d.kind !== "ident" || !domains.includes(d.text)) this.fail(`${JSON.stringify(d.text)} is not a Lemma domain (one of ${domains.join(", ")})`);
414
+ const domain = d.text;
415
+ let guard;
416
+ const member = this.peek();
417
+ if (isOp(member, "member") || member?.kind === "ident" && member.text === "in") {
418
+ this.at++;
419
+ guard = this.guard(domain);
420
+ }
421
+ const close = this.next(")");
422
+ if (!isPunct$1(close, ")")) this.fail(`expected ) to close the binder group, found ${JSON.stringify(close.text)}`);
423
+ return names.map((name) => ({
424
+ name,
425
+ domain,
426
+ ...guard ? { guard } : {}
427
+ }));
428
+ }
429
+ guard(domain) {
430
+ const t = this.peek();
431
+ if (t?.kind === "regex") {
432
+ this.at++;
433
+ if (domain !== "string") this.fail(`a regex guard applies to string, not ${domain}`);
434
+ const slash = t.text.lastIndexOf("/");
435
+ const pattern = t.text.slice(1, slash);
436
+ const flags = t.text.slice(slash + 1);
437
+ if (!/^[su]*$/.test(flags) || new Set(flags).size !== flags.length) this.fail(`a regex guard takes only the s and u flags, not ${JSON.stringify(flags)}`);
438
+ try {
439
+ new RegExp(`^(?:${pattern})$`, flags);
440
+ } catch (err) {
441
+ this.fail(`the regex guard does not compile: ${String(err)}`);
442
+ }
443
+ return {
444
+ kind: "regex",
445
+ pattern,
446
+ flags
447
+ };
448
+ }
449
+ if (!numeric.has(domain)) this.fail(`an interval guard applies to numeric domains only, not ${domain}`);
450
+ const open = this.next("[ or (");
451
+ if (!(isPunct$1(open, "[") || isPunct$1(open, "("))) this.fail(`expected an interval or a regex after ∈, found ${JSON.stringify(open.text)}`);
452
+ const lower = this.endpoint(domain, isPunct$1(open, "["));
453
+ const comma = this.next(",");
454
+ if (!isPunct$1(comma, ",")) this.fail(`expected , between the interval's endpoints, found ${JSON.stringify(comma.text)}`);
455
+ const upperValue = this.endpointValue(domain);
456
+ const close = this.next("] or )");
457
+ if (isPunct$1(close, ",")) this.fail("an interval has exactly two endpoints");
458
+ if (!(isPunct$1(close, "]") || isPunct$1(close, ")"))) this.fail(`expected ] or ) to close the interval, found ${JSON.stringify(close.text)}`);
459
+ const upper = {
460
+ value: upperValue,
461
+ inclusive: isPunct$1(close, "]")
462
+ };
463
+ this.checkInterval(domain, lower, upper);
464
+ return {
465
+ kind: "interval",
466
+ lower,
467
+ upper
468
+ };
469
+ }
470
+ endpoint(domain, inclusive) {
471
+ return {
472
+ value: this.endpointValue(domain),
473
+ inclusive
474
+ };
475
+ }
476
+ endpointValue(domain) {
477
+ let sign = "";
478
+ const s = this.peek();
479
+ if (isPunct$1(s, "-") || isPunct$1(s, "+")) {
480
+ this.at++;
481
+ sign = s?.text === "-" ? "-" : "";
482
+ }
483
+ const t = this.next("an endpoint");
484
+ if (isOp(t, "infinity") || t.kind === "ident" && t.text === "Infinity") return `${sign}∞`;
485
+ if (t.kind !== "number") this.fail(`${JSON.stringify(t.text)} is not an interval endpoint`);
486
+ const value = `${sign}${t.text}`;
487
+ const syntax = literalSyntax[domain];
488
+ if (syntax && !syntax.test(value)) this.fail(`${value} is not a ${domain} literal`);
489
+ return value;
490
+ }
491
+ checkInterval(domain, lower, upper) {
492
+ const integral = domain !== "number";
493
+ for (const e of [lower, upper]) if (e.value.endsWith("∞") && e.inclusive && integral) this.fail(`an ∞ endpoint must be exclusive for ${domain}`);
494
+ if (lower.value === "∞") this.fail("the lower endpoint cannot be +∞");
495
+ if (upper.value === "-∞") this.fail("the upper endpoint cannot be -∞");
496
+ const exact = (v) => integral && !v.endsWith("∞") ? BigInt(v.replace(/_/g, "").replace(/n$/, "")) : endpointNumber(v);
497
+ const lo = exact(lower.value);
498
+ const hi = exact(upper.value);
499
+ if (lo > hi || lo === hi && !(lower.inclusive && upper.inclusive)) this.fail(`the interval from ${lower.value} to ${upper.value} is empty`);
500
+ }
501
+ };
502
+ /** An endpoint's value for ordering: exact for integer literals, as a double otherwise. */
503
+ function endpointNumber(value) {
504
+ if (value === "∞") return Number.POSITIVE_INFINITY;
505
+ if (value === "-∞") return Number.NEGATIVE_INFINITY;
506
+ return Number(value.replace(/_/g, "").replace(/n$/, ""));
507
+ }
508
+ const connectives = /* @__PURE__ */ new Set([
509
+ "and",
510
+ "or",
511
+ "not",
512
+ "implies",
513
+ "iff"
514
+ ]);
515
+ var Body = class {
516
+ text;
517
+ tokens;
518
+ open;
519
+ /** Per token of the body: how many brackets enclose it inside the body braces. */
520
+ depth = /* @__PURE__ */ new Map();
521
+ /** Bracket matches, both ways. */
522
+ match = /* @__PURE__ */ new Map();
523
+ /** Per token: the innermost enclosing opening bracket, or -1. */
524
+ enclosing = /* @__PURE__ */ new Map();
525
+ constructor(text, tokens, open) {
526
+ this.text = text;
527
+ this.tokens = tokens;
528
+ this.open = open;
529
+ }
530
+ fail(message) {
531
+ throw new LemmaSyntaxError("formula", message);
532
+ }
533
+ parse() {
534
+ const pairs = {
535
+ ")": "(",
536
+ "]": "[",
537
+ "}": "{"
538
+ };
539
+ const stack = [];
540
+ let close = -1;
541
+ for (let i = this.open; i < this.tokens.length; i++) {
542
+ const t = this.tokens[i];
543
+ this.depth.set(i, stack.length - 1);
544
+ this.enclosing.set(i, stack[stack.length - 1] ?? -1);
545
+ if (t.kind !== "punct") continue;
546
+ if (t.text === "(" || t.text === "[" || t.text === "{") stack.push(i);
547
+ else if (pairs[t.text]) {
548
+ const o = stack.pop();
549
+ if (o === void 0 || this.tokens[o]?.text !== pairs[t.text]) this.fail(`unbalanced ${t.text} in the property body`);
550
+ this.match.set(o, i);
551
+ this.match.set(i, o);
552
+ if (stack.length === 0) {
553
+ close = i;
554
+ break;
555
+ }
556
+ }
557
+ }
558
+ if (close < 0) this.fail("the property body is not closed with }");
559
+ if (close !== this.tokens.length - 1) this.fail("the } closing the property body must be the annotation's last token");
560
+ const s = this.open + 1;
561
+ const e = close;
562
+ if (s >= e) this.fail("the property body is empty");
563
+ const grouped = isPunct$1(this.tokens[s], "(") && this.match.get(s) === e - 1;
564
+ const f = this.formula(s, e, 0);
565
+ if (!grouped && f.kind === "implies") return {
566
+ requires: [...f.antecedents],
567
+ claim: f.consequent
568
+ };
569
+ return {
570
+ requires: [],
571
+ claim: f
572
+ };
573
+ }
574
+ at(i, base) {
575
+ return this.depth.get(i) === base;
576
+ }
577
+ /** Base-level positions of tokens satisfying `pred` in [s, e). */
578
+ split(s, e, base, pred) {
579
+ const out = [];
580
+ for (let i = s; i < e; i++) if (this.at(i, base) && pred(this.tokens[i], i)) out.push(i);
581
+ return out;
582
+ }
583
+ segments(s, e, cuts) {
584
+ const out = [];
585
+ let from = s;
586
+ for (const c of cuts) {
587
+ out.push([from, c]);
588
+ from = c + 1;
589
+ }
590
+ out.push([from, e]);
591
+ return out;
592
+ }
593
+ formula(s, e, base) {
594
+ if (s >= e) this.fail("a connective is missing an operand");
595
+ const iff = this.split(s, e, base, (t, i) => {
596
+ if (t.op === "iff") return true;
597
+ const prev = this.tokens[i - 1];
598
+ return t.kind === "ident" && t.text === "iff" && !isPunct$1(prev, ".") && !isPunct$1(prev, "?.");
599
+ });
600
+ if (iff.length > 1) this.fail("↔ is non-associative: parenthesize a ↔ b ↔ c");
601
+ if (iff.length === 1) {
602
+ const k = iff[0];
603
+ return {
604
+ kind: "iff",
605
+ left: this.formula(s, k, base),
606
+ right: this.formula(k + 1, e, base)
607
+ };
608
+ }
609
+ const implies = this.split(s, e, base, (t) => t.op === "implies");
610
+ if (implies.length > 0) {
611
+ const parts = this.segments(s, e, implies).map(([a, b]) => this.formula(a, b, base));
612
+ return {
613
+ kind: "implies",
614
+ antecedents: parts.slice(0, -1),
615
+ consequent: parts[parts.length - 1]
616
+ };
617
+ }
618
+ for (const kind of ["or", "and"]) {
619
+ const cuts = this.split(s, e, base, (t) => t.op === kind);
620
+ if (cuts.length > 0) return {
621
+ kind,
622
+ operands: this.segments(s, e, cuts).map(([a, b]) => this.formula(a, b, base))
623
+ };
624
+ }
625
+ if (isOp(this.tokens[s], "not")) return {
626
+ kind: "not",
627
+ operand: this.formula(s + 1, e, base)
628
+ };
629
+ if (isPunct$1(this.tokens[s], "(") && this.match.get(s) === e - 1) return this.formula(s + 1, e - 1, base + 1);
630
+ return this.atom(s, e, base);
631
+ }
632
+ slice(s, e) {
633
+ return this.text.slice(this.tokens[s].start, this.tokens[e - 1].end).trim();
634
+ }
635
+ atom(s, e, base) {
636
+ const equations = [];
637
+ for (let i = s; i < e; i++) {
638
+ const t = this.tokens[i];
639
+ const prev = i > s ? this.tokens[i - 1] : void 0;
640
+ if (t.kind === "op") {
641
+ if (t.op === "equiv" || t.op === "nequiv") {
642
+ if (!this.at(i, base)) this.fail(`${t.text} only joins an atom's two sides; in nested positions call Object.is`);
643
+ equations.push(i);
644
+ } else if (t.op === "neq") this.fail("≠ is not Lemma: write ≢ (not the same value) or !==");
645
+ else if (t.op === "forall" || t.op === "exists") this.fail("quantifiers nest only in the prefix");
646
+ else if (connectives.has(t.op)) this.fail(`${t.text} inside a JavaScript expression: use && || ! there, or parenthesize the whole formula`);
647
+ else this.fail(`${t.text} belongs in a binder group, not the property body`);
648
+ }
649
+ if (t.kind === "ident" && (t.text === "forall" || t.text === "exists") && !isPunct$1(prev, ".") && !isPunct$1(prev, "?.")) this.fail("quantifiers nest only in the prefix");
650
+ if (t.kind === "template") for (const sub of templateSubstitutions(t.text)) this.nested(sub);
651
+ if (t.kind !== "punct") continue;
652
+ if (t.text === "==" || t.text === "!=") this.fail(`loose ${t.text} is not allowed: use ≡ / ≢ or === / !==`);
653
+ if (assignments.has(t.text) && !this.inParameterList(i)) this.fail(`assignments are not allowed in a property (${t.text})`);
654
+ if (!this.at(i, base)) continue;
655
+ if (t.text === "&&" || t.text === "||") this.fail(`${t.text} at an atom's top level: use ${t.text === "&&" ? "∧" : "∨"}`);
656
+ if (t.text === "!" && !endsOperand(prev)) this.fail("prefix ! at an atom's top level: use ¬");
657
+ }
658
+ if (equations.length > 1) this.fail("≡ is non-associative: write a ≡ b ∧ b ≡ c");
659
+ if (equations.length === 0) return {
660
+ kind: "atom",
661
+ text: this.slice(s, e)
662
+ };
663
+ const k = equations[0];
664
+ for (let i = s; i < e; i++) {
665
+ const t = this.tokens[i];
666
+ if (this.at(i, base) && t.kind === "punct" && [
667
+ "??",
668
+ "?",
669
+ "===",
670
+ "!==",
671
+ ",",
672
+ "=>"
673
+ ].includes(t.text)) this.fail(`${t.text} beside an equation is ambiguous: parenthesize the side it belongs to`);
674
+ }
675
+ if (k === s || k === e - 1) this.fail(`${this.tokens[k]?.text} needs an expression on both sides`);
676
+ return {
677
+ kind: "equation",
678
+ left: this.slice(s, k),
679
+ right: this.slice(k + 1, e),
680
+ negated: this.tokens[k]?.op === "nequiv"
681
+ };
682
+ }
683
+ /** Check an expression nested in an atom (a template substitution): what no position allows. */
684
+ nested(text) {
685
+ let tokens;
686
+ try {
687
+ tokens = tokenize(text);
688
+ } catch (err) {
689
+ if (err instanceof TokenizeError) this.fail(err.message);
690
+ throw err;
691
+ }
692
+ const stack = [];
693
+ const enclosing = [];
694
+ const match = /* @__PURE__ */ new Map();
695
+ tokens.forEach((t, i) => {
696
+ enclosing.push(stack[stack.length - 1] ?? -1);
697
+ if (t.kind !== "punct") return;
698
+ if (t.text === "(" || t.text === "[" || t.text === "{") stack.push(i);
699
+ else if (t.text === ")" || t.text === "]" || t.text === "}") {
700
+ const o = stack.pop();
701
+ if (o !== void 0) match.set(o, i);
702
+ }
703
+ });
704
+ tokens.forEach((t, i) => {
705
+ const prev = tokens[i - 1];
706
+ if (t.kind === "op") {
707
+ if (t.op === "equiv" || t.op === "nequiv") this.fail(`${t.text} only joins an atom's two sides; in nested positions call Object.is`);
708
+ if (t.op === "neq") this.fail("≠ is not Lemma: write ≢ (not the same value) or !==");
709
+ if (t.op === "forall" || t.op === "exists") this.fail("quantifiers nest only in the prefix");
710
+ this.fail(`${t.text} inside a JavaScript expression: use && || ! there, or parenthesize the whole formula`);
711
+ }
712
+ if (t.kind === "ident" && (t.text === "forall" || t.text === "exists") && !isPunct$1(prev, ".") && !isPunct$1(prev, "?.")) this.fail("quantifiers nest only in the prefix");
713
+ if (t.kind === "template") for (const sub of templateSubstitutions(t.text)) this.nested(sub);
714
+ if (t.kind !== "punct") return;
715
+ if (t.text === "==" || t.text === "!=") this.fail(`loose ${t.text} is not allowed: use ≡ / ≢ or === / !==`);
716
+ if (assignments.has(t.text)) {
717
+ const open = enclosing[i] ?? -1;
718
+ const close = open >= 0 ? match.get(open) : void 0;
719
+ if (!(t.text === "=" && isPunct$1(tokens[open], "(") && close !== void 0 && isPunct$1(tokens[close + 1], "=>"))) this.fail(`assignments are not allowed in a property (${t.text})`);
720
+ }
721
+ });
722
+ }
723
+ /** A default initializer: `=` directly inside the parentheses of an arrow function's parameters. */
724
+ inParameterList(i) {
725
+ if (this.tokens[i]?.text !== "=") return false;
726
+ const open = this.enclosing.get(i) ?? -1;
727
+ if (open < 0 || !isPunct$1(this.tokens[open], "(")) return false;
728
+ const close = this.match.get(open);
729
+ return close !== void 0 && isPunct$1(this.tokens[close + 1], "=>");
730
+ }
731
+ };
732
+ /** Whether a token ends an operand, so a `!` after it is postfix (non-null assertion). */
733
+ function endsOperand(t) {
734
+ if (!t) return false;
735
+ if (t.kind === "punct") return t.text === ")" || t.text === "]" || t.text === "}";
736
+ return t.kind !== "op";
737
+ }
738
+ // packages/spec/src/extract.ts
739
+ const tagLine = /^@(\w+)(?:\{([^}]*)\})?/;
740
+ /** The JSDoc's tags, each with its text up to the next tag. */
741
+ function tags(comment, lineOf) {
742
+ const body = comment.text.slice(3, -2);
743
+ const first = lineOf(comment.start);
744
+ const out = [];
745
+ body.split("\n").forEach((raw, i) => {
746
+ const line = raw.replace(/^\s*\*?\s?/, "");
747
+ const m = tagLine.exec(line.trimStart());
748
+ if (m) out.push({
749
+ name: m[1],
750
+ label: m[2],
751
+ lines: [line.trimStart().slice(m[0].length)],
752
+ line: first + i
753
+ });
754
+ else out[out.length - 1]?.lines.push(line);
755
+ });
756
+ return out.map((t) => ({
757
+ name: t.name,
758
+ label: t.label,
759
+ text: t.lines.join("\n").trim(),
760
+ line: t.line
761
+ }));
762
+ }
763
+ const isWord = (t, w) => t?.kind === "ident" && t.text === w;
764
+ const isPunct = (t, p) => t?.kind === "punct" && t.text === p;
765
+ /** `export [async] function [*] name(` at `i`: the name and the index of `(`. */
766
+ function functionAt(tokens, i) {
767
+ if (!isWord(tokens[i], "export")) return null;
768
+ let j = i + 1;
769
+ if (isWord(tokens[j], "async")) j++;
770
+ if (!isWord(tokens[j], "function")) return null;
771
+ j++;
772
+ if (isPunct(tokens[j], "*")) j++;
773
+ const name = tokens[j];
774
+ if (name?.kind !== "ident") return null;
775
+ j++;
776
+ if (isPunct(tokens[j], "<")) j = skipAngles(tokens, j);
777
+ return isPunct(tokens[j], "(") ? {
778
+ name: name.text,
779
+ open: j
780
+ } : null;
781
+ }
782
+ /** The index after the `>` closing the type parameters opened at `i`. */
783
+ function skipAngles(tokens, i) {
784
+ let depth = 0;
785
+ for (let j = i; j < tokens.length; j++) {
786
+ const t = tokens[j];
787
+ if (t.kind !== "punct") continue;
788
+ if (t.text === "<") depth++;
789
+ else if (t.text === ">" || t.text === ">>" || t.text === ">>>") {
790
+ depth -= t.text.length;
791
+ if (depth <= 0) return j + 1;
792
+ }
793
+ }
794
+ return tokens.length;
795
+ }
796
+ /**
797
+ * Parameter names of the list opened at `open`; null for destructured and
798
+ * rest parameters. `ambiguous` when a default value has a top-level `<` or
799
+ * `>`: a comparison or a generic call's type arguments (`pair<A, B>()`),
800
+ * which a token scan cannot tell apart, and guessing wrong would bind a
801
+ * binder to another parameter's argument.
802
+ */
803
+ function params(tokens, open) {
804
+ const firsts = [];
805
+ let depth = 0;
806
+ let start = true;
807
+ let inType = false;
808
+ let inDefault = false;
809
+ let ambiguous = false;
810
+ for (let j = open + 1; j < tokens.length; j++) {
811
+ const t = tokens[j];
812
+ if (depth === 0 && isPunct(t, ")")) break;
813
+ if (start) firsts.push(t);
814
+ start = false;
815
+ if (t.kind !== "punct") continue;
816
+ if (inDefault && depth === 0 && /^(<|>)/.test(t.text) && t.text !== ">=" && t.text !== "<=") ambiguous = true;
817
+ if ([
818
+ "(",
819
+ "[",
820
+ "{"
821
+ ].includes(t.text) || inType && t.text === "<") depth++;
822
+ else if ([
823
+ ")",
824
+ "]",
825
+ "}"
826
+ ].includes(t.text)) depth--;
827
+ else if (inType && /^>+$/.test(t.text)) depth -= t.text.length;
828
+ else if (depth === 0 && t.text === ":") inType = true;
829
+ else if (depth === 0 && t.text === "=") {
830
+ inType = false;
831
+ inDefault = true;
832
+ } else if (t.text === "," && depth === 0) {
833
+ start = true;
834
+ inType = false;
835
+ inDefault = false;
836
+ }
837
+ }
838
+ return {
839
+ names: firsts.filter((t) => !isWord(t, "this")).map((t) => t.kind === "ident" ? t.text : null),
840
+ ambiguous
841
+ };
842
+ }
843
+ /** Names the module exports as values (not types). */
844
+ function exportedNames(tokens) {
845
+ const names = /* @__PURE__ */ new Set();
846
+ for (let i = 0; i < tokens.length; i++) {
847
+ if (!isWord(tokens[i], "export")) continue;
848
+ let j = i + 1;
849
+ if (isWord(tokens[j], "declare")) j++;
850
+ if (isWord(tokens[j], "default")) continue;
851
+ if (isWord(tokens[j], "async")) j++;
852
+ if (isWord(tokens[j], "abstract")) j++;
853
+ const kw = tokens[j];
854
+ if ([
855
+ "function",
856
+ "class",
857
+ "enum"
858
+ ].some((w) => isWord(kw, w))) {
859
+ let k = j + 1;
860
+ if (isPunct(tokens[k], "*")) k++;
861
+ if (tokens[k]?.kind === "ident") names.add(tokens[k].text);
862
+ } else if ([
863
+ "const",
864
+ "let",
865
+ "var"
866
+ ].some((w) => isWord(kw, w))) {
867
+ let depth = 0;
868
+ let expectName = true;
869
+ for (let k = j + 1; k < tokens.length; k++) {
870
+ const t = tokens[k];
871
+ if (expectName && depth === 0 && t.kind === "ident") names.add(t.text);
872
+ expectName = false;
873
+ if (t.kind !== "punct") continue;
874
+ if ([
875
+ "(",
876
+ "[",
877
+ "{"
878
+ ].includes(t.text)) depth++;
879
+ else if ([
880
+ ")",
881
+ "]",
882
+ "}"
883
+ ].includes(t.text)) depth--;
884
+ else if (t.text === "," && depth === 0) expectName = true;
885
+ else if (t.text === ";" && depth === 0) break;
886
+ if (depth < 0) break;
887
+ }
888
+ } else if (isPunct(kw, "{")) {
889
+ const close = tokens.findIndex((t, k) => k > j && isPunct(t, "}"));
890
+ if (close < 0 || isWord(tokens[close + 1], "from")) continue;
891
+ for (let k = j + 1; k < close; k++) {
892
+ const t = tokens[k];
893
+ if (t.kind !== "ident" || isWord(tokens[k - 1], "type")) continue;
894
+ if (isWord(tokens[k + 1], "as")) continue;
895
+ if (isWord(t, "as") || isWord(t, "type")) continue;
896
+ names.add(t.text);
897
+ }
898
+ }
899
+ }
900
+ return [...names];
901
+ }
902
+ function extractSpecs(source) {
903
+ const starts = [0];
904
+ for (let i = 0; i < source.length; i++) if (source[i] === "\n") starts.push(i + 1);
905
+ const lineOf = (offset) => {
906
+ let lo = 0;
907
+ let hi = starts.length - 1;
908
+ while (lo < hi) {
909
+ const mid = lo + hi + 1 >> 1;
910
+ if (starts[mid] <= offset) lo = mid;
911
+ else hi = mid - 1;
912
+ }
913
+ return lo + 1;
914
+ };
915
+ let all;
916
+ try {
917
+ all = tokenize(source, { comments: true });
918
+ } catch (err) {
919
+ if (err instanceof TokenizeError) return {
920
+ functions: [],
921
+ exports: [],
922
+ errors: [{
923
+ line: 1,
924
+ message: err.message
925
+ }]
926
+ };
927
+ throw err;
928
+ }
929
+ const code = all.filter((t) => t.kind !== "comment");
930
+ const indexOf = new Map(code.map((t, i) => [t, i]));
931
+ const errors = [];
932
+ const functions = [];
933
+ all.forEach((comment, i) => {
934
+ if (comment.kind !== "comment" || !comment.text.startsWith("/**")) return;
935
+ const found = tags(comment, lineOf).filter((t) => [
936
+ "ensures",
937
+ "total",
938
+ "throws"
939
+ ].includes(t.name));
940
+ if (found.length === 0) return;
941
+ const next = all.slice(i + 1).find((t) => t.kind !== "comment");
942
+ const decl = next ? functionAt(code, indexOf.get(next) ?? -1) : null;
943
+ if (!decl) {
944
+ errors.push({
945
+ line: found[0]?.line ?? lineOf(comment.start),
946
+ message: "Lemma annotations attach to an exported function declaration"
947
+ });
948
+ return;
949
+ }
950
+ const ensures = [];
951
+ for (const t of found) {
952
+ if (t.name !== "ensures") continue;
953
+ const name = t.label?.trim();
954
+ if (!name) {
955
+ errors.push({
956
+ line: t.line,
957
+ message: "@ensures needs a name, as in @ensures{non-negative}"
958
+ });
959
+ continue;
960
+ }
961
+ if (ensures.some((e) => e.name === name)) {
962
+ errors.push({
963
+ line: t.line,
964
+ message: `${decl.name} has two properties named ${name}`
965
+ });
966
+ continue;
967
+ }
968
+ try {
969
+ ensures.push({
970
+ name,
971
+ property: parseProperty(t.text),
972
+ text: t.text
973
+ });
974
+ } catch (err) {
975
+ if (!(err instanceof LemmaSyntaxError)) throw err;
976
+ errors.push({
977
+ line: t.line,
978
+ message: `@ensures{${name}} on ${decl.name}: ${err.message}`
979
+ });
980
+ }
981
+ }
982
+ if (functions.some((f) => f.name === decl.name)) {
983
+ errors.push({
984
+ line: lineOf(code[decl.open].start),
985
+ message: `${decl.name} is annotated on more than one declaration (overloads): put its annotations on one`
986
+ });
987
+ return;
988
+ }
989
+ const signature = params(code, decl.open);
990
+ if (signature.ambiguous) errors.push({
991
+ line: lineOf(code[decl.open].start),
992
+ message: `cannot tell the parameters of ${decl.name} apart: a default value has a top-level < or >; parenthesize it`
993
+ });
994
+ functions.push({
995
+ name: decl.name,
996
+ params: signature.names,
997
+ ensures,
998
+ total: found.some((t) => t.name === "total"),
999
+ throws: found.some((t) => t.name === "throws"),
1000
+ line: lineOf(code[decl.open].start)
1001
+ });
1002
+ });
1003
+ return {
1004
+ functions,
1005
+ exports: exportedNames(code),
1006
+ errors
1007
+ };
1008
+ }
1009
+ // packages/spec/src/predicate.ts
1010
+ const tsType = {
1011
+ int: "number",
1012
+ nat: "number",
1013
+ number: "number",
1014
+ boolean: "boolean",
1015
+ string: "string",
1016
+ bigint: "bigint"
1017
+ };
1018
+ /** Words that cannot name a binding. */
1019
+ const reserved = new Set("await break case catch class const continue debugger default delete do else enum export extends false finally for function if implements import in instanceof interface let new null package private protected public return static super switch this throw true try typeof var void while with yield arguments eval".split(" "));
1020
+ function islands(f) {
1021
+ switch (f.kind) {
1022
+ case "atom": return [f.text];
1023
+ case "equation": return [f.left, f.right];
1024
+ case "not": return islands(f.operand);
1025
+ case "and":
1026
+ case "or": return f.operands.flatMap(islands);
1027
+ case "implies": return [...f.antecedents, f.consequent].flatMap(islands);
1028
+ case "iff": return [...islands(f.left), ...islands(f.right)];
1029
+ }
1030
+ }
1031
+ /**
1032
+ * Indices of the tokens that are TypeScript type positions or binding
1033
+ * names, not references, and the scopes arrow functions bind names in.
1034
+ */
1035
+ function notReferences(tokens) {
1036
+ const skip = /* @__PURE__ */ new Set();
1037
+ const scopes = [];
1038
+ const match = /* @__PURE__ */ new Map();
1039
+ const stack = [];
1040
+ /** Per token, the innermost open bracket around it, or -1. */
1041
+ const enclosing = [];
1042
+ tokens.forEach((t, i) => {
1043
+ enclosing.push(stack[stack.length - 1] ?? -1);
1044
+ if (t.kind !== "punct") return;
1045
+ if (t.text === "(" || t.text === "[" || t.text === "{") stack.push(i);
1046
+ else if (t.text === ")" || t.text === "]" || t.text === "}") {
1047
+ const o = stack.pop();
1048
+ if (o !== void 0) match.set(o, i);
1049
+ }
1050
+ });
1051
+ const is = (k, text) => tokens[k]?.kind === "punct" && tokens[k]?.text === text;
1052
+ /** The last token of an arrow body starting at `k`: a block, or an expression up to a top-level `,` or close. */
1053
+ const bodyEnd = (k) => {
1054
+ if (is(k, "{")) return match.get(k) ?? tokens.length - 1;
1055
+ let depth = 0;
1056
+ for (let m = k; m < tokens.length; m++) {
1057
+ const u = tokens[m];
1058
+ if (u.kind !== "punct") continue;
1059
+ if (u.text === "(" || u.text === "[" || u.text === "{") depth++;
1060
+ else if (u.text === ")" || u.text === "]" || u.text === "}") {
1061
+ if (depth === 0) return m - 1;
1062
+ depth--;
1063
+ } else if (u.text === "," && depth === 0) return m - 1;
1064
+ }
1065
+ return tokens.length - 1;
1066
+ };
1067
+ /**
1068
+ * The index just after a type starting at `k`: names, dots, brackets,
1069
+ * unions and intersections, and type arguments, but a `<` only when its
1070
+ * `>` closes before anything that cannot be in a type (else it compares).
1071
+ */
1072
+ const typeEnd = (k) => {
1073
+ const typeish = (u, angles) => u !== void 0 && (u.kind === "ident" || u.kind === "string" || u.kind === "number" || u.kind === "punct" && [
1074
+ ".",
1075
+ "[",
1076
+ "]",
1077
+ "|",
1078
+ "&"
1079
+ ].includes(u.text) || angles > 0 && u.kind === "punct" && [
1080
+ ",",
1081
+ "(",
1082
+ ")",
1083
+ "=>",
1084
+ ":",
1085
+ "{",
1086
+ "}",
1087
+ ";"
1088
+ ].includes(u.text));
1089
+ let m = k;
1090
+ while (m < tokens.length) {
1091
+ const u = tokens[m];
1092
+ if (u.kind === "punct" && u.text === "<") {
1093
+ let angles = 0;
1094
+ let n = m;
1095
+ for (; n < tokens.length; n++) {
1096
+ const w = tokens[n];
1097
+ if (w.kind === "punct" && w.text === "<") angles++;
1098
+ else if (w.kind === "punct" && /^>+$/.test(w.text)) {
1099
+ angles -= w.text.length;
1100
+ if (angles <= 0) break;
1101
+ } else if (!typeish(w, angles)) break;
1102
+ }
1103
+ if (angles > 0 || n >= tokens.length || !/^>+$/.test(tokens[n].text)) return m;
1104
+ m = n + 1;
1105
+ continue;
1106
+ }
1107
+ if (!typeish(u, 0)) return m;
1108
+ m++;
1109
+ }
1110
+ return m;
1111
+ };
1112
+ /** After the `)` of a parameter list at `close`: an optional `: ReturnType`, then the index of what follows. */
1113
+ const afterReturnType = (close) => {
1114
+ if (!is(close + 1, ":")) return close + 1;
1115
+ const end = typeEnd(close + 2);
1116
+ for (let m = close + 2; m < end; m++) skip.add(m);
1117
+ return end;
1118
+ };
1119
+ /**
1120
+ * The names a parameter list from `open` to `close` binds, skipping them and
1121
+ * their type annotations. A `:` directly in the list starts a type; inside a
1122
+ * destructuring pattern it renames (`{ a: b }` binds b).
1123
+ */
1124
+ const parameters = (open, close) => {
1125
+ const names = /* @__PURE__ */ new Set();
1126
+ const nesting = [];
1127
+ let inType = false;
1128
+ let inDefault = false;
1129
+ let defaultDepth = 0;
1130
+ for (let k = open + 1; k < close; k++) {
1131
+ const u = tokens[k];
1132
+ if (inDefault) {
1133
+ if (u.kind !== "punct") continue;
1134
+ if (u.text === "(" || u.text === "[" || u.text === "{") {
1135
+ defaultDepth++;
1136
+ continue;
1137
+ }
1138
+ if ((u.text === ")" || u.text === "]" || u.text === "}") && defaultDepth > 0) {
1139
+ defaultDepth--;
1140
+ continue;
1141
+ }
1142
+ if (defaultDepth > 0 || !(u.text === "," || u.text === ")" || u.text === "]" || u.text === "}")) continue;
1143
+ inDefault = false;
1144
+ }
1145
+ if (u.kind === "punct") {
1146
+ if (!inType && u.text === "=") {
1147
+ inDefault = true;
1148
+ defaultDepth = 0;
1149
+ continue;
1150
+ }
1151
+ if (inType) {
1152
+ if (u.text === "(" || u.text === "[" || u.text === "{" || u.text === "<") nesting.push(u.text);
1153
+ else if (nesting.length > 0 && [
1154
+ ")",
1155
+ "]",
1156
+ "}"
1157
+ ].includes(u.text)) nesting.pop();
1158
+ else if (nesting.length > 0 && /^>+$/.test(u.text)) nesting.splice(-u.text.length);
1159
+ else if (nesting.length === 0 && u.text === ",") inType = false;
1160
+ else if (nesting.length === 0 && u.text === "=") {
1161
+ inType = false;
1162
+ inDefault = true;
1163
+ defaultDepth = 0;
1164
+ }
1165
+ continue;
1166
+ }
1167
+ if (u.text === "{" || u.text === "[") nesting.push(u.text);
1168
+ else if (u.text === "}" || u.text === "]") nesting.pop();
1169
+ else if (u.text === ":" && nesting.length === 0) inType = true;
1170
+ continue;
1171
+ }
1172
+ if (inType) {
1173
+ skip.add(k);
1174
+ continue;
1175
+ }
1176
+ if (u.kind !== "ident") continue;
1177
+ const prev = tokens[k - 1];
1178
+ const next = tokens[k + 1];
1179
+ if (nesting.length > 0 && next?.kind === "punct" && next.text === ":") {
1180
+ skip.add(k);
1181
+ continue;
1182
+ }
1183
+ if (prev?.kind === "punct" && [
1184
+ "(",
1185
+ ",",
1186
+ "...",
1187
+ "{",
1188
+ "[",
1189
+ ":"
1190
+ ].includes(prev.text)) {
1191
+ names.add(u.text);
1192
+ skip.add(k);
1193
+ }
1194
+ }
1195
+ return names;
1196
+ };
1197
+ tokens.forEach((t, i) => {
1198
+ if (t.kind === "ident" && is(i + 1, "=>")) {
1199
+ skip.add(i);
1200
+ scopes.push({
1201
+ names: /* @__PURE__ */ new Set([t.text]),
1202
+ from: i,
1203
+ to: bodyEnd(i + 2)
1204
+ });
1205
+ }
1206
+ const close = is(i, "(") ? match.get(i) : void 0;
1207
+ const arrow = close === void 0 ? -1 : afterReturnType(close);
1208
+ if (close !== void 0 && is(arrow, "=>")) scopes.push({
1209
+ names: parameters(i, close),
1210
+ from: i,
1211
+ to: bodyEnd(arrow + 1)
1212
+ });
1213
+ if (t.kind === "ident" && is(i + 1, "(") && (is(i - 1, "{") || is(i - 1, ","))) {
1214
+ const end = match.get(i + 1);
1215
+ const body = end === void 0 ? -1 : afterReturnType(end);
1216
+ if (end !== void 0 && is(body, "{")) {
1217
+ skip.add(i);
1218
+ scopes.push({
1219
+ names: parameters(i + 1, end),
1220
+ from: i + 1,
1221
+ to: match.get(body) ?? tokens.length - 1
1222
+ });
1223
+ }
1224
+ }
1225
+ if (t.kind === "ident" && t.text === "for" && is(i + 1, "(")) {
1226
+ const end = match.get(i + 1);
1227
+ const decl = tokens[i + 2];
1228
+ if (end !== void 0 && decl?.kind === "ident" && [
1229
+ "const",
1230
+ "let",
1231
+ "var"
1232
+ ].includes(decl.text)) {
1233
+ const names = /* @__PURE__ */ new Set();
1234
+ for (let k = i + 3; k < end; k++) {
1235
+ const u = tokens[k];
1236
+ if (u.kind === "ident" && (u.text === "of" || u.text === "in")) {
1237
+ skip.add(k);
1238
+ break;
1239
+ }
1240
+ if (u.kind === "ident" && !is(k + 1, ":")) {
1241
+ names.add(u.text);
1242
+ skip.add(k);
1243
+ }
1244
+ }
1245
+ const body = end + 1;
1246
+ const to = is(body, "{") ? match.get(body) ?? tokens.length - 1 : bodyEnd(body);
1247
+ scopes.push({
1248
+ names,
1249
+ from: i,
1250
+ to
1251
+ });
1252
+ }
1253
+ }
1254
+ if (t.kind === "ident" && t.text === "catch" && is(i + 1, "(")) {
1255
+ const end = match.get(i + 1);
1256
+ if (end !== void 0 && is(end + 1, "{")) scopes.push({
1257
+ names: parameters(i + 1, end),
1258
+ from: i + 1,
1259
+ to: match.get(end + 1) ?? tokens.length - 1
1260
+ });
1261
+ }
1262
+ if (t.kind === "ident" && t.text === "function") {
1263
+ const named = tokens[i + 1]?.kind === "ident";
1264
+ const statement = i === 0 || [
1265
+ "{",
1266
+ "}",
1267
+ ";"
1268
+ ].some((p) => is(i - 1, p));
1269
+ if (named && statement) {
1270
+ const open = enclosing[i] ?? -1;
1271
+ skip.add(i + 1);
1272
+ scopes.push({
1273
+ names: /* @__PURE__ */ new Set([tokens[i + 1].text]),
1274
+ from: open,
1275
+ to: open >= 0 ? match.get(open) ?? tokens.length - 1 : tokens.length - 1
1276
+ });
1277
+ }
1278
+ const open = named ? i + 2 : i + 1;
1279
+ const end = is(open, "(") ? match.get(open) : void 0;
1280
+ const body = end === void 0 ? -1 : afterReturnType(end);
1281
+ if (end !== void 0 && is(body, "{")) {
1282
+ const names = parameters(open, end);
1283
+ if (named) {
1284
+ names.add(tokens[i + 1].text);
1285
+ skip.add(i + 1);
1286
+ }
1287
+ scopes.push({
1288
+ names,
1289
+ from: i,
1290
+ to: match.get(body) ?? tokens.length - 1
1291
+ });
1292
+ }
1293
+ }
1294
+ if (t.kind === "ident" && is(i + 1, ":") && (is(i - 1, "{") || is(i - 1, ","))) skip.add(i);
1295
+ if (t.kind === "ident" && (t.text === "as" || t.text === "satisfies")) {
1296
+ skip.add(i);
1297
+ for (let k = i + 1; k < typeEnd(i + 1); k++) skip.add(k);
1298
+ }
1299
+ if (t.kind === "ident" && is(i + 1, "<")) {
1300
+ const end = typeEnd(i + 1);
1301
+ if (end > i + 1 && is(end, "(")) for (let m = i + 2; m < end; m++) skip.add(m);
1302
+ }
1303
+ });
1304
+ return {
1305
+ skip,
1306
+ scopes
1307
+ };
1308
+ }
1309
+ /**
1310
+ * Identifiers the islands refer to from outside: not after a `.`, not a
1311
+ * binder, not an object key, an arrow function's parameter or a type. What
1312
+ * is left may still over-approximate (a `function` expression's parameter),
1313
+ * which only costs a binding the inner name shadows.
1314
+ */
1315
+ function freeNames(p) {
1316
+ const bound = new Set(p.binders.map((b) => b.name));
1317
+ const names = /* @__PURE__ */ new Set();
1318
+ const scan = (text, outer) => {
1319
+ const tokens = tokenize(text);
1320
+ const { skip, scopes } = notReferences(tokens);
1321
+ const local = (n, i) => scopes.some((sc) => sc.names.has(n) && sc.from <= i && i <= sc.to);
1322
+ tokens.forEach((t, i) => {
1323
+ if (t.kind === "template") {
1324
+ const inScope = new Set(outer);
1325
+ for (const sc of scopes) if (sc.from <= i && i <= sc.to) for (const n of sc.names) inScope.add(n);
1326
+ for (const sub of templateSubstitutions(t.text)) scan(sub, inScope);
1327
+ }
1328
+ const prev = tokens[i - 1];
1329
+ if (t.kind !== "ident" || skip.has(i) || bound.has(t.text) || reserved.has(t.text) || outer.has(t.text) || local(t.text, i)) return;
1330
+ if (prev?.kind === "punct" && (prev.text === "." || prev.text === "?.")) return;
1331
+ names.add(t.text);
1332
+ });
1333
+ };
1334
+ for (const text of [...p.requires, p.claim].flatMap(islands)) scan(text, /* @__PURE__ */ new Set());
1335
+ return [...names];
1336
+ }
1337
+ function expression(f, h) {
1338
+ switch (f.kind) {
1339
+ case "atom": return `${h.bool}((${f.text}))`;
1340
+ case "equation": return `${f.negated ? "!" : ""}${h.same}((${f.left}), (${f.right}))`;
1341
+ case "not": return `!${expression(f.operand, h)}`;
1342
+ case "and":
1343
+ case "or": return `(${f.operands.map((o) => expression(o, h)).join(f.kind === "and" ? " && " : " || ")})`;
1344
+ case "implies": return `(!(${f.antecedents.map((a) => expression(a, h)).join(" && ")}) || ${expression(f.consequent, h)})`;
1345
+ case "iff": return `(${expression(f.left, h)} === ${expression(f.right, h)})`;
1346
+ }
1347
+ }
1348
+ /**
1349
+ * The predicate's source: an expression evaluating to the arrow function.
1350
+ * It takes the helpers as parameters under names fresh for this property,
1351
+ * so no binder or identifier in it can shadow them, and binds each free
1352
+ * name from the module's namespace when it has it, else from the globals,
1353
+ * which is the scope Lemma gives a property (re-exports included).
1354
+ */
1355
+ function predicateSource(p, helpers) {
1356
+ const free = freeNames(p).filter((n) => ![
1357
+ "globalThis",
1358
+ "undefined",
1359
+ "NaN",
1360
+ "Infinity"
1361
+ ].includes(n));
1362
+ const taken = /* @__PURE__ */ new Set([
1363
+ ...p.binders.map((b) => b.name),
1364
+ ...free,
1365
+ "globalThis"
1366
+ ]);
1367
+ const fresh = (base) => {
1368
+ let name = base;
1369
+ while (taken.has(name)) name = `${name}$`;
1370
+ taken.add(name);
1371
+ return name;
1372
+ };
1373
+ const local = {
1374
+ bool: fresh("__bool"),
1375
+ same: fresh("__same"),
1376
+ scope: fresh("__scope"),
1377
+ unresolved: fresh("__unresolved"),
1378
+ missing: fresh("__missing")
1379
+ };
1380
+ const params = p.binders.map((b) => `${b.name}: ${tsType[b.domain]}`).join(", ");
1381
+ return [
1382
+ `((${local.bool}: (v: unknown) => boolean, ${local.same}: (a: unknown, b: unknown) => boolean, ${local.scope}: any, ${local.unresolved}: (names: string[]) => never) => {`,
1383
+ ` const ${local.missing}: string[] = [];`,
1384
+ ...free.map((n) => {
1385
+ const k = JSON.stringify(n);
1386
+ return ` const ${n} = ${k} in ${local.scope} ? ${local.scope}[${k}] : ${k} in globalThis ? (globalThis as any)[${k}] : (${local.missing}.push(${k}), undefined);`;
1387
+ }),
1388
+ ` return (${params}): "held" | "discarded" | "refuted" => {`,
1389
+ ` if (${local.missing}.length > 0) ${local.unresolved}(${local.missing});`,
1390
+ ...p.requires.map((r) => ` if (!${expression(r, local)}) return "discarded";`),
1391
+ ` return ${expression(p.claim, local)} ? "held" : "refuted";`,
1392
+ " };",
1393
+ `})(${helpers.bool}, ${helpers.same}, ${helpers.scope}, ${helpers.unresolved})`
1394
+ ].join("\n");
1395
+ }
1396
+ // packages/report/src/regression.ts
1397
+ /**
1398
+ * The Vitest regression emitter. Given a violation, produce a test file that
1399
+ * replays its shrunk schedule on the restricted scenario. By default the
1400
+ * test expects the invariants to hold, so it fails while the bug exists and
1401
+ * passes once it is fixed. With `expect: "violates"` it asserts the recorded
1402
+ * violation instead, which is how Eutaxy's own corpus exercises the emitter.
1403
+ *
1404
+ * The emitter knows nothing about any platform: the caller supplies the
1405
+ * import lines and the expression that builds the platform.
1406
+ */
1407
+ function emitRegressionTest(verdict, options) {
1408
+ const engineModule = options.engineModule ?? "eutaxy";
1409
+ const mode = options.expect ?? "holds";
1410
+ const schedule = canonicalJson(verdict.schedule);
1411
+ const kept = canonicalJson([...verdict.keptEvents]);
1412
+ const keys = canonicalJson([...verdict.violation.keys]);
1413
+ const title = mode === "holds" ? `${verdict.scenario}: ${verdict.violation.invariant} holds on the recorded schedule` : `${verdict.scenario}: ${verdict.violation.invariant} is still violated on the recorded schedule`;
1414
+ const assertion = mode === "holds" ? ` expect(violations.map((v) => \`\${v.invariant}: \${v.message}\`)).toEqual([]);` : ` expect(violations.map((v) => [v.invariant, v.keys])).toContainEqual([${JSON.stringify(verdict.violation.invariant)}, ${keys}]);`;
1415
+ const observe = options.observe ?? [];
1416
+ const replayLines = observe.length === 0 ? [" const log = await replay(spec, platform, schedule);"] : [
1417
+ ` const observers = [${observe.map((o) => `observeCore(${o.namespace}, ${JSON.stringify(o.functions)})`).join(", ")}];`,
1418
+ " const log = await replay(spec, platform, schedule).finally(() => {",
1419
+ " for (const o of observers) o.restore();",
1420
+ " });"
1421
+ ];
1422
+ return [
1423
+ "// Generated by Eutaxy. Replays a recorded violation; regenerate rather than edit.",
1424
+ `// Scenario ${verdict.scenario}, seed ${String(verdict.seed)}: ${verdict.violation.message}`,
1425
+ `import { checkInvariants, ${observe.length > 0 ? "observeCore, " : ""}replay, restrictSpec } from ${JSON.stringify(engineModule)};`,
1426
+ ...options.imports,
1427
+ "import { expect, test } from \"vitest\";",
1428
+ "",
1429
+ `const schedule = ${schedule} as const;`,
1430
+ `const keptEvents = ${kept} as const;`,
1431
+ "",
1432
+ `test(${JSON.stringify(title)}, async () => {`,
1433
+ ` const platform = ${options.platform};`,
1434
+ ` const spec = restrictSpec(platform, ${options.scenario}, keptEvents);`,
1435
+ ...replayLines,
1436
+ " const violations = checkInvariants(log, spec.invariants);",
1437
+ assertion,
1438
+ "});",
1439
+ ""
1440
+ ].join("\n");
1441
+ }
1442
+ /**
1443
+ * The JSON report: one object, canonical, with a schema version at the top.
1444
+ * Spec verdicts, when there are any, sit beside the scenario's, never in it.
1445
+ */
1446
+ function renderJson(verdict, specs = []) {
1447
+ return canonicalJson({
1448
+ schemaVersion: 1,
1449
+ generator: "eutaxy",
1450
+ verdict,
1451
+ ...specs.length > 0 ? { specs } : {}
1452
+ });
1453
+ }
1454
+ /** Spec verdicts as text: one line each, a counterexample under a refutation. */
1455
+ function renderSpecs(specs) {
1456
+ if (specs.length === 0) return "";
1457
+ const out = ["Specs (CHECKED means held on the inputs the simulator passed; it is not a proof)"];
1458
+ for (const v of specs) {
1459
+ const what = `${v.function} ${v.property}`;
1460
+ switch (v.kind) {
1461
+ case "CHECKED":
1462
+ out.push(` CHECKED ${what}: held on ${v.inputs} input(s)${v.discarded > 0 ? `, ${v.discarded} outside the claim` : ""}`);
1463
+ break;
1464
+ case "REFUTED": {
1465
+ const c = v.counterexample;
1466
+ out.push(` REFUTED ${what}: false at ${c.call}${c.error ? `, which threw ${c.error}` : ""}`);
1467
+ out.push(` ${c.binders.map((b) => `${b.name} = ${b.value}`).join(", ")}`);
1468
+ out.push(` ${v.text.replace(/\s+/g, " ")}`);
1469
+ break;
1470
+ }
1471
+ case "UNKNOWN": out.push(` UNKNOWN ${what}: ${v.cause}: ${v.reason}`);
1472
+ }
1473
+ }
1474
+ return out.join("\n");
1475
+ }
1476
+ function clip(s, max) {
1477
+ return s.length <= max ? s : `${s.slice(0, max - 1)}…`;
1478
+ }
1479
+ function pad(s, width) {
1480
+ return s.length >= width ? s : s + " ".repeat(width - s.length);
1481
+ }
1482
+ /** The trace as a fixed-width table; evidence rows are marked with `*`. */
1483
+ function renderTrace(log, evidence = []) {
1484
+ const rows = log.entries.map((e) => [
1485
+ evidence.includes(e.seq) ? "*" : " ",
1486
+ String(e.seq),
1487
+ e.invocation,
1488
+ e.kind,
1489
+ e.target,
1490
+ e.op,
1491
+ clip(canonicalJson(e.payload), 72)
1492
+ ]);
1493
+ const header = [
1494
+ " ",
1495
+ "seq",
1496
+ "invocation",
1497
+ "kind",
1498
+ "target",
1499
+ "op",
1500
+ "payload"
1501
+ ];
1502
+ const widths = header.map((h, i) => Math.max(h.length, ...rows.map((r) => r[i].length)));
1503
+ const line = (cells) => cells.map((c, i) => i === cells.length - 1 ? c : pad(c, widths[i])).join(" ").trimEnd();
1504
+ return [line(header), ...rows.map(line)].join("\n");
1505
+ }
1506
+ /** A readable report: verdict, what it rests on, and for a violation the schedule and trace. */
1507
+ function renderText(verdict) {
1508
+ const out = [];
1509
+ const r = verdict.reached;
1510
+ out.push(`${verdict.kind} ${verdict.scenario} (seed ${String(verdict.seed)})`);
1511
+ switch (verdict.kind) {
1512
+ case "VIOLATED":
1513
+ out.push("");
1514
+ out.push(`Invariant ${verdict.violation.invariant} is violated: ${verdict.violation.message}`);
1515
+ out.push(`Keys: ${verdict.violation.keys.join(", ")}`);
1516
+ out.push("");
1517
+ out.push(`Schedule (run seed ${verdict.schedule.seed}), events kept: ${verdict.keptEvents.join(", ")}`);
1518
+ if (verdict.schedule.faults.length === 0) out.push(" no injected faults");
1519
+ for (const f of verdict.schedule.faults) out.push(` ${f.fault} at ${f.invocation} effect #${f.ordinal} (${f.target} ${f.op})`);
1520
+ out.push(`Shrunk: ${verdict.shrunk.eventsRemoved} event(s) and ${verdict.shrunk.faultsRemoved} fault(s) removed in ${verdict.shrunk.runs} run(s)`);
1521
+ out.push("");
1522
+ out.push("Trace:");
1523
+ out.push(renderTrace(verdict.trace, verdict.violation.evidence));
1524
+ break;
1525
+ case "BOUNDED": {
1526
+ const b = verdict.bounds;
1527
+ out.push("");
1528
+ out.push("No violation found within the stated bounds. This is not a proof.");
1529
+ out.push(`Bounds: faults per run ≤ ${b.maxFaultsPerRun}, redeliveries ≤ ${b.maxRedeliveries}, concurrent invocations ≤ ${b.maxConcurrentInvocations}, budget ${b.budgetMs} ms`);
1530
+ const e = r.exhaustive;
1531
+ if (e) out.push(`Exhaustive: ${e.complete ? "every schedule within the bounds ran" : "stopped at the budget before every schedule ran"} (${e.schedules} schedules${e.reduction ? ", partial-order reduction" : ""})`);
1532
+ break;
1533
+ }
1534
+ case "UNSUPPORTED":
1535
+ out.push("");
1536
+ out.push(`Eutaxy could not decide this scenario (${verdict.cause}): ${verdict.reason}`);
1537
+ }
1538
+ out.push("");
1539
+ out.push(`Explored: ${r.runs} run(s), ${r.effectPoints} effect point(s), ${r.faultsInjected} fault(s) injected, ${r.elapsedMs} ms`);
1540
+ out.push("Assumptions:");
1541
+ for (const a of verdict.assumptions) out.push(` - ${a}`);
1542
+ return out.join("\n");
1543
+ }
1544
+ export { emitRegressionTest as a, LemmaSyntaxError as c, renderTrace as i, endpointNumber as l, renderSpecs as n, predicateSource as o, renderText as r, extractSpecs as s, renderJson as t, parseProperty as u };
1545
+
1546
+ //# sourceMappingURL=src-CgfGiH25.mjs.map