leanfran 0.0.0-stage → 0.6.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,2931 @@
1
+ import { a as blockInputs, c as canonicalJson, i as blockFnv, r as blockContent, s as modelSchema } from "./embed-BlX4FUDH.js";
2
+ import { S as resolve$1 } from "./marshal-DhKsxhRw.js";
3
+ import { t as blockRegistry } from "./block-CU7YIXdj.js";
4
+ import { basename, dirname, join, relative, resolve, sep } from "node:path";
5
+ import { fileURLToPath, pathToFileURL } from "node:url";
6
+ import { spawnSync } from "node:child_process";
7
+ import { createHash } from "node:crypto";
8
+ import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, rmdirSync, writeFileSync } from "node:fs";
9
+ import { Visitor, parseSync } from "oxc-parser";
10
+ // src/scan.ts
11
+ var SyncError = class extends Error {
12
+ code;
13
+ constructor(message, code) {
14
+ super(message);
15
+ this.name = "SyncError";
16
+ this.code = code;
17
+ }
18
+ };
19
+ function lineStarts$1(text) {
20
+ const starts = [0];
21
+ for (let i = 0; i < text.length; i++) if (text[i] === "\n") starts.push(i + 1);
22
+ return starts;
23
+ }
24
+ function position(starts, offset) {
25
+ let lo = 0;
26
+ let hi = starts.length - 1;
27
+ while (lo < hi) {
28
+ const mid = lo + hi + 1 >> 1;
29
+ if ((starts[mid] ?? 0) <= offset) lo = mid;
30
+ else hi = mid - 1;
31
+ }
32
+ return {
33
+ line: lo + 1,
34
+ col: offset - (starts[lo] ?? 0) + 1
35
+ };
36
+ }
37
+ function normalizeNewlines(s) {
38
+ return s.replaceAll("\r\n", "\n").replaceAll("\r", "\n");
39
+ }
40
+ function tsFiles(dir) {
41
+ const out = [];
42
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
43
+ const p = join(dir, e.name);
44
+ if (e.isDirectory()) {
45
+ if (e.name !== "_lean" && e.name !== "node_modules") out.push(...tsFiles(p));
46
+ } else if (e.name.endsWith(".ts") && !e.name.endsWith(".d.ts")) out.push(p);
47
+ }
48
+ return out.toSorted();
49
+ }
50
+ function posixRelative(root, file) {
51
+ return relative(root, file).split(sep).join("/");
52
+ }
53
+ function keyName(k, computed) {
54
+ if (computed) return void 0;
55
+ if (k.type === "Identifier") return k.name;
56
+ if (k.type === "Literal" && typeof k.value === "string") return k.value;
57
+ }
58
+ function templateText(t, raw) {
59
+ const q = t.quasis[0];
60
+ if (t.expressions.length !== 0 || q === void 0) return void 0;
61
+ const text = raw ? q.value.raw : q.value.cooked;
62
+ return text === null ? void 0 : normalizeNewlines(text);
63
+ }
64
+ function isStringRaw(e) {
65
+ return e.type === "MemberExpression" && !e.computed && e.object.type === "Identifier" && e.object.name === "String" && e.property.type === "Identifier" && e.property.name === "raw";
66
+ }
67
+ function staticString(e) {
68
+ if (e === null) return void 0;
69
+ if (e.type === "Literal" && typeof e.value === "string") return e.value;
70
+ if (e.type === "TemplateLiteral") return templateText(e, false);
71
+ }
72
+ function scanFile(root, file) {
73
+ const text = readFileSync(file, "utf8");
74
+ const starts = lineStarts$1(text);
75
+ const module = posixRelative(root, file);
76
+ const fail = (offset, msg) => {
77
+ const p = position(starts, offset);
78
+ throw new SyncError(`${file}:${p.line}:${p.col}: ${msg}`, 252);
79
+ };
80
+ const parsed = parseSync(file, text, {
81
+ lang: "ts",
82
+ sourceType: "module"
83
+ });
84
+ const firstError = parsed.errors[0];
85
+ if (firstError !== void 0) {
86
+ const label = firstError.labels[0];
87
+ fail(label?.start ?? 0, `cannot parse: ${firstError.message}`);
88
+ }
89
+ const direct = /* @__PURE__ */ new Set();
90
+ const namespaces = /* @__PURE__ */ new Set();
91
+ const bindings = /* @__PURE__ */ new Map();
92
+ const exported = /* @__PURE__ */ new Set();
93
+ const fromSpec = (spec) => spec.startsWith(".") ? resolve(dirname(file), spec) : spec;
94
+ for (const s of parsed.program.body) if (s.type === "ImportDeclaration") {
95
+ for (const sp of s.specifiers) if (sp.type === "ImportNamespaceSpecifier") bindings.set(sp.local.name, {
96
+ from: fromSpec(s.source.value),
97
+ exportName: null
98
+ });
99
+ else if (sp.type === "ImportSpecifier") bindings.set(sp.local.name, {
100
+ from: fromSpec(s.source.value),
101
+ exportName: sp.imported.type === "Literal" ? sp.imported.value : sp.imported.name
102
+ });
103
+ } else if (s.type === "ExportNamedDeclaration") {
104
+ const d = s.declaration;
105
+ if (d?.type === "VariableDeclaration") {
106
+ for (const x of d.declarations) if (x.id.type === "Identifier") exported.add(x.id.name);
107
+ }
108
+ if ((d?.type === "FunctionDeclaration" || d?.type === "ClassDeclaration") && d.id !== null) exported.add(d.id.name);
109
+ if (s.source === null) {
110
+ for (const sp of s.specifiers) if (sp.local.type === "Identifier" && sp.exported.type === "Identifier" && sp.local.name === sp.exported.name) exported.add(sp.local.name);
111
+ }
112
+ }
113
+ const binding = (name, e) => {
114
+ if (e.type === "Identifier") {
115
+ const i = bindings.get(e.name);
116
+ if (i !== void 0 && i.exportName !== null) return {
117
+ name,
118
+ from: i.from,
119
+ exportName: i.exportName
120
+ };
121
+ if (exported.has(e.name)) return {
122
+ name,
123
+ from: file,
124
+ exportName: e.name
125
+ };
126
+ } else if (e.type === "MemberExpression" && !e.computed && e.object.type === "Identifier" && e.property.type === "Identifier") {
127
+ const i = bindings.get(e.object.name);
128
+ if (i !== void 0 && i.exportName === null) return {
129
+ name,
130
+ from: i.from,
131
+ exportName: e.property.name
132
+ };
133
+ }
134
+ return fail(e.start, `the model ${name} must be an exported variable of the module, a named import or a property of a namespace import`);
135
+ };
136
+ for (const s of parsed.program.body) {
137
+ if (s.type !== "ImportDeclaration" || s.source.value !== "leanfran" || s.importKind === "type") continue;
138
+ for (const sp of s.specifiers) if (sp.type === "ImportNamespaceSpecifier") namespaces.add(sp.local.name);
139
+ else if (sp.type === "ImportSpecifier" && sp.importKind !== "type") {
140
+ if ((sp.imported.type === "Literal" ? sp.imported.value : sp.imported.name) === "lean") direct.add(sp.local.name);
141
+ }
142
+ }
143
+ if (direct.size === 0 && namespaces.size === 0) return [];
144
+ const isLean = (c) => {
145
+ const f = c.callee;
146
+ if (f.type === "Identifier") return direct.has(f.name);
147
+ return f.type === "MemberExpression" && !f.computed && f.object.type === "Identifier" && namespaces.has(f.object.name) && f.property.type === "Identifier" && f.property.name === "lean";
148
+ };
149
+ const blocks = [];
150
+ const stringArray = (e, what) => {
151
+ if (e.type !== "ArrayExpression") return fail(e.start, `${what} must be an array literal of strings`);
152
+ return e.elements.map((x) => staticString(x) ?? fail(x?.start ?? e.start, `${what} must hold string literals`));
153
+ };
154
+ const objectEntries = (e, what) => e.properties.map((p) => {
155
+ if (p.type !== "Property" || p.kind !== "init" || p.method) return fail(p.start, `${what} must be an object literal of plain properties`);
156
+ return [
157
+ keyName(p.key, p.computed) ?? fail(p.start, `${what} must have literal keys`),
158
+ p.value,
159
+ p.start
160
+ ];
161
+ });
162
+ const readBlock = (c) => {
163
+ const [nameArg, sourceArg, optionsArg, ...rest] = c.arguments;
164
+ if (rest.length !== 0) fail(c.start, "lean(...) takes at most 3 arguments");
165
+ const name = (nameArg?.type === "Literal" && typeof nameArg.value === "string" ? nameArg.value : void 0) ?? fail(nameArg?.start ?? c.start, "the block name of lean(...) must be a string literal");
166
+ let source;
167
+ let sourceStart = 0;
168
+ if (sourceArg?.type === "TemplateLiteral") {
169
+ source = templateText(sourceArg, false);
170
+ sourceStart = sourceArg.start + 1;
171
+ } else if (sourceArg?.type === "TaggedTemplateExpression" && isStringRaw(sourceArg.tag)) {
172
+ source = templateText(sourceArg.quasi, true);
173
+ sourceStart = sourceArg.quasi.start + 1;
174
+ }
175
+ if (source === void 0) return fail(sourceArg?.start ?? c.start, "the Lean source of lean(...) must be a template literal or String.raw`...` without ${}");
176
+ let imports = [];
177
+ let uses = [];
178
+ const output = {};
179
+ const modelNames = [];
180
+ const models = [];
181
+ if (optionsArg !== void 0) {
182
+ if (optionsArg.type !== "ObjectExpression") return fail(optionsArg.start, "the options of lean(...) must be an object literal");
183
+ for (const [k, v, at] of objectEntries(optionsArg, "the options of lean(...)")) if (k === "imports") imports = stringArray(v, "imports");
184
+ else if (k === "uses") uses = stringArray(v, "uses");
185
+ else if (k === "models") {
186
+ if (v.type !== "ObjectExpression") return fail(v.start, "models must be an object literal");
187
+ for (const [m, mv] of objectEntries(v, "models")) {
188
+ modelNames.push(m);
189
+ models.push(binding(m, mv));
190
+ }
191
+ } else if (k === "output") {
192
+ if (v.type !== "ObjectExpression") return fail(v.start, "output must be an object literal");
193
+ for (const [o, ov, oat] of objectEntries(v, "output")) {
194
+ if (o !== "tagKey" && o !== "option") return fail(oat, `unknown output setting ${o}`);
195
+ output[o] = staticString(ov) ?? fail(ov.start, `output.${o} must be a string literal`);
196
+ }
197
+ } else return fail(at, `unknown option ${k} of lean(...)`);
198
+ }
199
+ return {
200
+ file,
201
+ module,
202
+ name,
203
+ source,
204
+ imports,
205
+ uses,
206
+ output,
207
+ modelNames,
208
+ models,
209
+ at: position(starts, c.start),
210
+ sourceAt: position(starts, sourceStart)
211
+ };
212
+ };
213
+ new Visitor({ CallExpression(c) {
214
+ if (isLean(c)) blocks.push(readBlock(c));
215
+ } }).visit(parsed.program);
216
+ return blocks;
217
+ }
218
+ // src/models.ts
219
+ const LEAN_KEYWORDS$1 = /* @__PURE__ */ new Set([
220
+ "at",
221
+ "by",
222
+ "do",
223
+ "else",
224
+ "end",
225
+ "fun",
226
+ "have",
227
+ "if",
228
+ "in",
229
+ "let",
230
+ "match",
231
+ "mut",
232
+ "namespace",
233
+ "open",
234
+ "section",
235
+ "then",
236
+ "theorem",
237
+ "def",
238
+ "structure",
239
+ "inductive",
240
+ "where",
241
+ "with",
242
+ "from",
243
+ "import",
244
+ "instance",
245
+ "class",
246
+ "variable",
247
+ "universe",
248
+ "deriving",
249
+ "show",
250
+ "calc",
251
+ "for",
252
+ "return",
253
+ "try",
254
+ "catch",
255
+ "finally",
256
+ "unless",
257
+ "break",
258
+ "continue",
259
+ "macro",
260
+ "syntax",
261
+ "local",
262
+ "private",
263
+ "protected",
264
+ "partial",
265
+ "unsafe",
266
+ "noncomputable",
267
+ "abbrev",
268
+ "example",
269
+ "axiom",
270
+ "opaque",
271
+ "extends",
272
+ "notation",
273
+ "Type",
274
+ "Sort",
275
+ "Prop"
276
+ ]);
277
+ const IDENT = /^[A-Za-z_][A-Za-z0-9_']*$/u;
278
+ const ANNOTATIONS = /* @__PURE__ */ new Set([
279
+ "$schema",
280
+ "$id",
281
+ "$comment",
282
+ "$defs",
283
+ "definitions",
284
+ "id",
285
+ "title",
286
+ "description",
287
+ "default",
288
+ "examples",
289
+ "readOnly",
290
+ "writeOnly",
291
+ "deprecated"
292
+ ]);
293
+ const UNMAPPED = /* @__PURE__ */ new Set([
294
+ "multipleOf",
295
+ "pattern",
296
+ "format",
297
+ "uniqueItems",
298
+ "contentEncoding",
299
+ "contentMediaType"
300
+ ]);
301
+ function leanIdent$1(s) {
302
+ return IDENT.test(s) && !LEAN_KEYWORDS$1.has(s) ? s : `«${s}»`;
303
+ }
304
+ function leanIdentWithSuffix(s, suffix) {
305
+ return IDENT.test(s) && !LEAN_KEYWORDS$1.has(s) ? `${s}${suffix}` : `«${s}${suffix}»`;
306
+ }
307
+ function isSchema(v) {
308
+ return typeof v === "object" && v !== null && !Array.isArray(v);
309
+ }
310
+ function fail(cx, path, msg) {
311
+ throw new SyncError(`${cx.module}: the model ${cx.model}${path === "" ? "" : `.${path}`}: ${msg}`, 254);
312
+ }
313
+ function numberLit(v, nat, kind) {
314
+ if (kind === "number") return `(${Number.isInteger(v) ? `${v}.0` : String(v)} : Float)`;
315
+ if (nat) return String(v);
316
+ return `(${v} : Int)`;
317
+ }
318
+ function checkKeys(cx, path, s, allowed) {
319
+ for (const k of Object.keys(s)) {
320
+ if (allowed.includes(k) || ANNOTATIONS.has(k)) continue;
321
+ if (UNMAPPED.has(k)) {
322
+ cx.unmapped.push(`${path} ${k} ${canonicalJson(s[k])}`);
323
+ continue;
324
+ }
325
+ fail(cx, path, `the JSON Schema keyword ${k} cannot be mapped to Lean`);
326
+ }
327
+ }
328
+ function withoutSchemaUri(s) {
329
+ const { $schema: _, ...rest } = s;
330
+ return canonicalJson(rest);
331
+ }
332
+ function equalModel(cx, s) {
333
+ const c = withoutSchemaUri(s);
334
+ for (const [name, m] of cx.models) if (withoutSchemaUri(m) === c) return name;
335
+ }
336
+ function resolveRef(cx, path, ref) {
337
+ if (ref === "#") return {
338
+ schema: cx.root,
339
+ name: cx.model
340
+ };
341
+ const key = /^#\/(?:\$defs|definitions)\/([^/]+)$/u.exec(ref)?.[1];
342
+ if (key === void 0) return fail(cx, path, `the $ref ${ref} is not a local definition`);
343
+ const defs = cx.root["$defs"] ?? cx.root["definitions"];
344
+ const def = isSchema(defs) ? defs[key] : void 0;
345
+ if (!isSchema(def)) return fail(cx, path, `the $ref ${ref} has no definition`);
346
+ return {
347
+ schema: def,
348
+ name: key
349
+ };
350
+ }
351
+ function nullable(s) {
352
+ const any = s["anyOf"];
353
+ if (Array.isArray(any) && any.length === 2) {
354
+ const items = any.filter(isSchema);
355
+ const nulls = items.filter((x) => x["type"] === "null");
356
+ const others = items.filter((x) => x["type"] !== "null");
357
+ const other = others[0];
358
+ if (nulls.length === 1 && other !== void 0 && others.length === 1) {
359
+ const { anyOf: _, ...rest } = s;
360
+ return {
361
+ ...rest,
362
+ ...other
363
+ };
364
+ }
365
+ }
366
+ const t = s["type"];
367
+ if (Array.isArray(t) && t.length === 2 && t.includes("null")) {
368
+ const other = t.find((x) => x !== "null");
369
+ if (typeof other === "string") return {
370
+ ...s,
371
+ type: other
372
+ };
373
+ }
374
+ }
375
+ function enumType(cx, path, name, values) {
376
+ const strings = values.filter((v) => typeof v === "string");
377
+ if (strings.length !== values.length || strings.length === 0) return fail(cx, path, "an enum must list strings");
378
+ const prev = cx.enums.get(name);
379
+ if (prev !== void 0 && canonicalJson(prev) !== canonicalJson(strings)) return fail(cx, path, `the enum ${name} is defined twice`);
380
+ cx.enums.set(name, strings);
381
+ return `${cx.enumsNs}.${leanIdent$1(name)}`;
382
+ }
383
+ function structRef(cx, name) {
384
+ cx.deps.add(name);
385
+ return leanIdent$1(name);
386
+ }
387
+ function fieldType(cx, path, s, hint) {
388
+ const ref = s["$ref"];
389
+ if (typeof ref === "string") {
390
+ const r = resolveRef(cx, path, ref);
391
+ if (r.name === cx.model && r.schema === cx.root) return {
392
+ lean: structRef(cx, cx.model),
393
+ nat: false,
394
+ kind: "other"
395
+ };
396
+ const other = equalModel(cx, r.schema);
397
+ if (other !== void 0) return {
398
+ lean: structRef(cx, other),
399
+ nat: false,
400
+ kind: "other"
401
+ };
402
+ return {
403
+ lean: nestedStruct(cx, path, `${cx.model}_${r.name}`, r.schema),
404
+ nat: false,
405
+ kind: "other"
406
+ };
407
+ }
408
+ const e = s["enum"];
409
+ if (Array.isArray(e)) {
410
+ checkKeys(cx, path, s, ["enum", "type"]);
411
+ return {
412
+ lean: enumType(cx, path, `${cx.model}_${hint}`, e),
413
+ nat: false,
414
+ kind: "other"
415
+ };
416
+ }
417
+ const c = s["const"];
418
+ if (typeof c === "string") {
419
+ checkKeys(cx, path, s, ["const", "type"]);
420
+ return {
421
+ lean: enumType(cx, path, `${cx.model}_${hint}`, [c]),
422
+ nat: false,
423
+ kind: "other"
424
+ };
425
+ }
426
+ switch (s["type"]) {
427
+ case "integer": {
428
+ const lo = lowerBound(s);
429
+ const nat = lo !== void 0 && lo >= 0;
430
+ return {
431
+ lean: nat ? "Nat" : "Int",
432
+ nat,
433
+ kind: "integer"
434
+ };
435
+ }
436
+ case "number": return {
437
+ lean: "Float",
438
+ nat: false,
439
+ kind: "number"
440
+ };
441
+ case "string": return {
442
+ lean: "String",
443
+ nat: false,
444
+ kind: "string"
445
+ };
446
+ case "boolean":
447
+ checkKeys(cx, path, s, ["type", "const"]);
448
+ return {
449
+ lean: "Bool",
450
+ nat: false,
451
+ kind: "other"
452
+ };
453
+ case "array": {
454
+ const items = s["items"];
455
+ if (!isSchema(items)) return fail(cx, path, "an array needs an items schema");
456
+ const inner = fieldType(cx, `${path}[]`, items, hint);
457
+ return {
458
+ lean: `List ${paren(inner.lean)}`,
459
+ nat: false,
460
+ kind: "array",
461
+ item: {
462
+ schema: items,
463
+ type: inner
464
+ }
465
+ };
466
+ }
467
+ case "object": {
468
+ const other = equalModel(cx, s);
469
+ if (other !== void 0) return {
470
+ lean: structRef(cx, other),
471
+ nat: false,
472
+ kind: "other"
473
+ };
474
+ return {
475
+ lean: nestedStruct(cx, path, `${cx.model}_${hint}`, s),
476
+ nat: false,
477
+ kind: "other"
478
+ };
479
+ }
480
+ default: return fail(cx, path, `the schema ${canonicalJson(s)} cannot be mapped to Lean`);
481
+ }
482
+ }
483
+ function paren(t) {
484
+ return t.includes(" ") ? `(${t})` : t;
485
+ }
486
+ function lowerBound(s) {
487
+ const min = s["minimum"];
488
+ const ex = s["exclusiveMinimum"];
489
+ if (typeof min === "number") return min;
490
+ if (typeof ex === "number") return Math.floor(ex) + 1;
491
+ }
492
+ function proofsOf(cx, path, s, t) {
493
+ const out = [];
494
+ const lit = (v) => numberLit(v, t.nat, t.kind);
495
+ if (t.kind === "integer" || t.kind === "number") {
496
+ checkKeys(cx, path, s, [
497
+ "type",
498
+ "minimum",
499
+ "maximum",
500
+ "exclusiveMinimum",
501
+ "exclusiveMaximum",
502
+ "const"
503
+ ]);
504
+ const num = (k) => {
505
+ const v = s[k];
506
+ return typeof v === "number" ? v : void 0;
507
+ };
508
+ const min = num("minimum");
509
+ const max = num("maximum");
510
+ const exMin = num("exclusiveMinimum");
511
+ const exMax = num("exclusiveMaximum");
512
+ if (min !== void 0 && !(t.nat && min === 0)) out.push({
513
+ suffix: "ge",
514
+ prop: (v) => `${lit(min)} ≤ ${v}`
515
+ });
516
+ if (exMin !== void 0) out.push({
517
+ suffix: "gt",
518
+ prop: (v) => `${lit(exMin)} < ${v}`
519
+ });
520
+ if (max !== void 0) out.push({
521
+ suffix: "le",
522
+ prop: (v) => `${v} ≤ ${lit(max)}`
523
+ });
524
+ if (exMax !== void 0) out.push({
525
+ suffix: "lt",
526
+ prop: (v) => `${v} < ${lit(exMax)}`
527
+ });
528
+ const c = s["const"];
529
+ if (typeof c === "number") out.push({
530
+ suffix: "eq",
531
+ prop: (v) => `${v} = ${lit(c)}`
532
+ });
533
+ } else if (t.kind === "string" || t.kind === "array") {
534
+ const lenKeys = t.kind === "string" ? ["minLength", "maxLength"] : ["minItems", "maxItems"];
535
+ checkKeys(cx, path, s, [
536
+ "type",
537
+ "items",
538
+ ...lenKeys
539
+ ]);
540
+ const [minK, maxK] = lenKeys;
541
+ const minV = minK === void 0 ? void 0 : s[minK];
542
+ const maxV = maxK === void 0 ? void 0 : s[maxK];
543
+ if (typeof minV === "number" && minV > 0) out.push({
544
+ suffix: t.kind === "string" ? "min_length" : "min_items",
545
+ prop: (v) => `${minV} ≤ ${v}.length`
546
+ });
547
+ if (typeof maxV === "number") out.push({
548
+ suffix: t.kind === "string" ? "max_length" : "max_items",
549
+ prop: (v) => `${v}.length ≤ ${maxV}`
550
+ });
551
+ if (t.item !== void 0) for (const p of proofsOf(cx, `${path}[]`, t.item.schema, t.item.type)) out.push({
552
+ suffix: `items_${p.suffix}`,
553
+ prop: (v) => `(${v}.all fun v => decide (${p.prop("v")})) = true`
554
+ });
555
+ }
556
+ return out;
557
+ }
558
+ function nestedStruct(cx, path, name, s) {
559
+ if (cx.structs.get(name) === void 0) {
560
+ const sub = {
561
+ ...cx,
562
+ model: name,
563
+ deps: /* @__PURE__ */ new Set(),
564
+ unmapped: []
565
+ };
566
+ cx.structs.set(name, {
567
+ name,
568
+ doc: "",
569
+ fields: [],
570
+ deps: /* @__PURE__ */ new Set()
571
+ });
572
+ cx.structs.set(name, structSource(sub, s, `A part of the model ${cx.model} of ${cx.module}.`));
573
+ }
574
+ return structRef(cx, name);
575
+ }
576
+ function structSource(cx, s, doc) {
577
+ checkKeys(cx, "", s, [
578
+ "type",
579
+ "properties",
580
+ "required",
581
+ "additionalProperties"
582
+ ]);
583
+ if (s["type"] !== "object") fail(cx, "", "the schema of a model must be an object");
584
+ const additional = s["additionalProperties"];
585
+ if (additional !== void 0 && additional !== false && !(isSchema(additional) && Object.keys(additional).length === 0)) fail(cx, "", "additionalProperties with a schema cannot be mapped to Lean");
586
+ const props = s["properties"];
587
+ const properties = isSchema(props) ? props : {};
588
+ const req = s["required"];
589
+ const required = new Set(Array.isArray(req) ? req.filter((x) => typeof x === "string") : []);
590
+ const fields = [];
591
+ for (const [key, raw] of Object.entries(properties)) {
592
+ if (!isSchema(raw)) fail(cx, key, "the property schema is not an object");
593
+ const inner = nullable(raw);
594
+ const option = inner !== void 0 || !required.has(key);
595
+ const target = inner ?? raw;
596
+ const t = fieldType(cx, key, target, key);
597
+ const proofs = proofsOf(cx, key, target, t);
598
+ const name = required.has(key) ? leanIdent$1(key) : leanIdentWithSuffix(key, "?");
599
+ fields.push(` ${name} : ${option ? `Option ${paren(t.lean)}` : t.lean}`);
600
+ for (const p of proofs) {
601
+ const prop = option ? `(${name}.all fun v => decide (${p.prop("v")})) = true` : p.prop(name);
602
+ fields.push(` ${leanIdentWithSuffix(key, `_${p.suffix}`)} : ${prop}`);
603
+ }
604
+ }
605
+ const unmapped = cx.unmapped.length === 0 ? "" : ` Not assumed in Lean: ${cx.unmapped.join(", ")}.`;
606
+ return {
607
+ name: cx.model,
608
+ doc: `${doc}${unmapped}`,
609
+ fields,
610
+ deps: new Set(cx.deps)
611
+ };
612
+ }
613
+ function order(structs, module) {
614
+ const out = [];
615
+ const state = /* @__PURE__ */ new Map();
616
+ const visit = (name) => {
617
+ const st = state.get(name);
618
+ if (st === "done") return;
619
+ if (st === "visiting") throw new SyncError(`${module}: the models refer to each other in a cycle through ${name}`, 254);
620
+ const s = structs.get(name);
621
+ if (s === void 0) return;
622
+ state.set(name, "visiting");
623
+ for (const d of s.deps) if (d !== name) visit(d);
624
+ state.set(name, "done");
625
+ out.push(s);
626
+ };
627
+ for (const name of structs.keys()) visit(name);
628
+ return out;
629
+ }
630
+ function modelsLean(module, namespace, models) {
631
+ const schemas = /* @__PURE__ */ new Map();
632
+ for (const [name, schema] of models) {
633
+ if (!isSchema(schema)) throw new SyncError(`${module}: the model ${name} is not an object schema`, 254);
634
+ schemas.set(name, schema);
635
+ }
636
+ const ns = namespace.map((p) => `«${p}»`).join(".");
637
+ const enumsNs = `LeanTsEnums.${ns}`;
638
+ const modelsNs = `LeanTsModels.${ns}`;
639
+ const enums = /* @__PURE__ */ new Map();
640
+ const structs = /* @__PURE__ */ new Map();
641
+ for (const [name, root] of schemas) {
642
+ const cx = {
643
+ module,
644
+ model: name,
645
+ root,
646
+ models: schemas,
647
+ enumsNs,
648
+ modelsNs,
649
+ enums,
650
+ structs,
651
+ unmapped: [],
652
+ deps: /* @__PURE__ */ new Set()
653
+ };
654
+ structs.set(name, {
655
+ name,
656
+ doc: "",
657
+ fields: [],
658
+ deps: /* @__PURE__ */ new Set()
659
+ });
660
+ structs.set(name, structSource(cx, root, `The model ${name} of ${module}.`));
661
+ }
662
+ const enumSrc = [...enums].map(([name, values]) => `inductive ${leanIdent$1(name)} where\n${values.map((v) => ` | ${leanIdent$1(v)}`).join("\n")}\n deriving DecidableEq, Repr\n`).join("\n");
663
+ const structSrc = order(structs, module).map((s) => `/-- ${s.doc.replaceAll("-/", "- /")} -/\nstructure ${leanIdent$1(s.name)} where\n${s.fields.join("\n")}\n`).join("\n");
664
+ return {
665
+ lean: (enums.size === 0 ? "" : `namespace ${enumsNs}\n\n${enumSrc}\nend ${enumsNs}\n\n`) + `namespace ${modelsNs}\n\n${structSrc}\nend ${modelsNs}\n`,
666
+ names: [...schemas.keys()]
667
+ };
668
+ }
669
+ // src/sync.ts
670
+ const LAKEFILE = `name = "leanfran-workspace"
671
+ defaultTargets = ["LeanTsModels", "LeanTsEmbed", "LeanTsCsimp"]
672
+
673
+ [[lean_lib]]
674
+ name = "LeanTsModels"
675
+
676
+ [[lean_lib]]
677
+ name = "LeanTsEmbed"
678
+
679
+ [[lean_lib]]
680
+ name = "LeanTsCsimp"
681
+ `;
682
+ const DEFAULT_SETTINGS = {
683
+ tagKey: "ctor",
684
+ option: "null"
685
+ };
686
+ const TAG_KEY = /^[A-Za-z_$][A-Za-z0-9_$]*$/u;
687
+ const BLOCK_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/u;
688
+ const LAKE_MESSAGE = /^(error|warning): (?:\.\/)*(LeanTs(?:Embed|Models)\/[^:]+\.lean):(\d+):(\d+): (.*)$/u;
689
+ function readJson(file) {
690
+ return JSON.parse(readFileSync(file, "utf8"));
691
+ }
692
+ function isRecord(v) {
693
+ return typeof v === "object" && v !== null && !Array.isArray(v);
694
+ }
695
+ function checkSettings(settings, where) {
696
+ const out = {};
697
+ for (const [k, v] of Object.entries(settings)) if (k === "tagKey") {
698
+ if (typeof v !== "string" || !TAG_KEY.test(v)) throw new SyncError(`${where}: tagKey must be a JavaScript identifier (got ${JSON.stringify(v)})`, 254);
699
+ out[k] = v;
700
+ } else if (k === "option") {
701
+ if (v !== "null" && v !== "undefined") throw new SyncError(`${where}: option must be "null" or "undefined" (got ${JSON.stringify(v)})`, 254);
702
+ out[k] = v;
703
+ } else throw new SyncError(`${where}: unknown setting ${k}`, 254);
704
+ return out;
705
+ }
706
+ function packageRoot(dir) {
707
+ const root = resolve(dir);
708
+ if (!existsSync(join(root, "package.json"))) throw new SyncError(`no package.json in ${root}`, 252);
709
+ if (!existsSync(join(root, "src"))) throw new SyncError(`no src directory in ${root}`, 252);
710
+ return root;
711
+ }
712
+ function packageConfig(root) {
713
+ const pkg = readJson(join(root, "package.json"));
714
+ const field = isRecord(pkg) ? pkg["leanfran"] : void 0;
715
+ if (field === void 0) return {};
716
+ const where = `${join(root, "package.json")} ("leanfran")`;
717
+ if (!isRecord(field)) throw new SyncError(`${where}: must be an object`, 254);
718
+ return checkSettings(field, where);
719
+ }
720
+ function leanIdent(s) {
721
+ const t = s.replaceAll(/[^A-Za-z0-9_]/gu, "_");
722
+ return /^[0-9]/u.test(t) ? `_${t}` : t;
723
+ }
724
+ function leanName(parts) {
725
+ return parts.map((p, i) => i === 0 ? p : `«${p}»`).join(".");
726
+ }
727
+ function moduleParts(module) {
728
+ const parts = module.replace(/\.ts$/u, "").split("/");
729
+ return (parts[0] === "src" ? parts.slice(1) : parts).map(leanIdent);
730
+ }
731
+ function locate(b) {
732
+ return `${b.file}:${b.at.line}:${b.at.col}`;
733
+ }
734
+ function placeholder(module) {
735
+ return `// Placeholder written by leanfran sync for ${module}. Do not edit.\nexport {}\n`;
736
+ }
737
+ function aliasFile(b) {
738
+ return join(dirname(b.file), "_lean", `${basename(b.file, ".ts")}.ts`);
739
+ }
740
+ function outputsOf(blocks) {
741
+ const out = /* @__PURE__ */ new Map();
742
+ const perModule = /* @__PURE__ */ new Map();
743
+ for (const b of blocks) perModule.set(b.module, [...perModule.get(b.module) ?? [], b]);
744
+ for (const b of blocks) out.set(b.outFile, "");
745
+ for (const [module, bs] of perModule) {
746
+ const only = bs[0];
747
+ if (bs.length !== 1 || only === void 0) continue;
748
+ const alias = aliasFile(only);
749
+ if (out.has(alias)) throw new SyncError(`${only.file}:${only.at.line}:${only.at.col}: the generated module ${alias} of ${module} is also the module of another block`, 252);
750
+ out.set(alias, `// Generated by leanfran sync from ${module}. Do not edit.\nexport * from "./${basename(only.outFile)}"\n`);
751
+ }
752
+ return out;
753
+ }
754
+ let recordRound = 0;
755
+ async function recordModels(files) {
756
+ recordRound++;
757
+ const registry = blockRegistry();
758
+ registry.recording = [];
759
+ try {
760
+ for (const f of files) try {
761
+ await import(`${pathToFileURL(f).href}?leanfran-record=${recordRound}`);
762
+ } catch (e) {
763
+ throw new SyncError(`importing ${f} to read its models: ${e instanceof Error ? e.message : String(e)}`, 254);
764
+ }
765
+ return registry.recording;
766
+ } finally {
767
+ registry.recording = null;
768
+ }
769
+ }
770
+ function recordedModels(b, recorded) {
771
+ const r = recorded.find((x) => x.name === b.name && x.source === b.source);
772
+ if (r === void 0) throw new SyncError(`${locate(b)}: importing ${b.file} did not run lean(${JSON.stringify(b.name)}, ...)`, 254);
773
+ const models = isRecord(r.options) ? r.options["models"] : void 0;
774
+ if (!isRecord(models)) throw new SyncError(`${locate(b)}: the models of the block are not an object`, 254);
775
+ const out = {};
776
+ for (const k of b.modelNames) try {
777
+ out[k] = modelSchema(k, models[k]);
778
+ } catch (e) {
779
+ throw new SyncError(`${locate(b)}: ${e instanceof Error ? e.message : String(e)}`, 254);
780
+ }
781
+ return out;
782
+ }
783
+ async function readPackage(dir, writePlaceholders) {
784
+ const root = packageRoot(dir);
785
+ const config = packageConfig(root);
786
+ const scanned = tsFiles(join(root, "src")).flatMap((f) => scanFile(root, f));
787
+ const seen = /* @__PURE__ */ new Map();
788
+ const leanModules = /* @__PURE__ */ new Map();
789
+ const pre = [];
790
+ for (const b of scanned) {
791
+ if (!BLOCK_NAME.test(b.name)) throw new SyncError(`${locate(b)}: the block name ${JSON.stringify(b.name)} must be an identifier`, 252);
792
+ const q = `${b.module}:${b.name}`;
793
+ const prev = seen.get(q);
794
+ if (prev !== void 0) throw new SyncError(`${locate(b)}: the Lean block ${b.name} is also defined at ${locate(prev)}`, 252);
795
+ seen.set(q, b);
796
+ const leanModule = [
797
+ "LeanTsEmbed",
798
+ ...moduleParts(b.module),
799
+ b.name
800
+ ];
801
+ const ln = leanModule.join(".");
802
+ const clash = leanModules.get(ln);
803
+ if (clash !== void 0) throw new SyncError(`${locate(b)}: the Lean module ${ln} is also the module of ${locate(clash)}`, 252);
804
+ leanModules.set(ln, b);
805
+ const settings = {
806
+ ...DEFAULT_SETTINGS,
807
+ ...config,
808
+ ...checkSettings(b.output, `${locate(b)} (output)`)
809
+ };
810
+ pre.push({
811
+ b,
812
+ leanModule,
813
+ outFile: join(dirname(b.file), "_lean", `${basename(b.file, ".ts")}__${b.name}.ts`),
814
+ settings
815
+ });
816
+ }
817
+ const withModels = [...new Set(pre.filter((p) => p.b.modelNames.length !== 0).map((p) => p.b.file))];
818
+ if (writePlaceholders && withModels.length !== 0) for (const f of outputsOf(pre.map((p) => ({
819
+ ...p.b,
820
+ outFile: p.outFile
821
+ }))).keys()) {
822
+ if (existsSync(f)) continue;
823
+ mkdirSync(dirname(f), { recursive: true });
824
+ writeFileSync(f, placeholder(posixRelative(root, f)));
825
+ }
826
+ const recorded = withModels.length === 0 ? [] : await recordModels(withModels);
827
+ return {
828
+ root,
829
+ config,
830
+ blocks: pre.map(({ b, leanModule, outFile, settings }) => {
831
+ const models = b.modelNames.length === 0 ? {} : recordedModels(b, recorded);
832
+ const inputs = {
833
+ ...blockInputs(b.name, b.source, {
834
+ imports: b.imports,
835
+ uses: b.uses,
836
+ output: b.output
837
+ }),
838
+ models
839
+ };
840
+ const key = createHash("sha256").update(canonicalJson({
841
+ module: b.module,
842
+ package: config,
843
+ block: blockContent(inputs)
844
+ })).digest("hex");
845
+ return {
846
+ ...b,
847
+ leanModule,
848
+ outFile,
849
+ settings,
850
+ inputs,
851
+ fnv: blockFnv(inputs),
852
+ key
853
+ };
854
+ })
855
+ };
856
+ }
857
+ function resolveUse(pkg, b, use) {
858
+ const i = use.lastIndexOf(":");
859
+ const module = i < 0 ? b.module : posixRelative(pkg.root, resolve(dirname(b.file), use.slice(0, i)));
860
+ const name = i < 0 ? use : use.slice(i + 1);
861
+ const found = pkg.blocks.find((x) => x.module === module && x.name === name);
862
+ if (found === void 0) throw new SyncError(`${locate(b)}: the Lean block ${b.name} uses ${JSON.stringify(use)}, which is not a block of the package`, 252);
863
+ if (canonicalJson(found.settings) !== canonicalJson(b.settings)) throw new SyncError(`${locate(b)}: the Lean block ${b.name} (settings ${canonicalJson(b.settings)}) uses ${found.name} of ${found.module} (settings ${canonicalJson(found.settings)}); the settings must be the same`, 254);
864
+ return found;
865
+ }
866
+ function modelsModule(b) {
867
+ return ["LeanTsModels", ...moduleParts(b.module)];
868
+ }
869
+ function blockLean(pkg, b) {
870
+ const used = b.uses.map((u) => resolveUse(pkg, b, u));
871
+ const models = b.modelNames.length === 0 ? [] : [leanName(modelsModule(b))];
872
+ const imports = [.../* @__PURE__ */ new Set([
873
+ ...b.imports,
874
+ ...models,
875
+ ...used.map((u) => leanName(u.leanModule))
876
+ ])];
877
+ const ns = leanName(b.leanModule);
878
+ const head = imports.map((i) => `import ${i}\n`).join("") + `\nnamespace ${ns}\n` + [...models, ...used.map((u) => leanName(u.leanModule))].map((o) => `open ${o}\n`).join("") + "\n";
879
+ return {
880
+ head,
881
+ text: `${head}${b.source}\n\nend ${ns}\n`
882
+ };
883
+ }
884
+ function leanMessages(output, offsets) {
885
+ const lines = output.split("\n");
886
+ const out = [];
887
+ for (let i = 0; i < lines.length; i++) {
888
+ const m = LAKE_MESSAGE.exec((lines[i] ?? "").trim());
889
+ if (m === null) continue;
890
+ const [, sev, path, ln, col, msg] = m;
891
+ const info = offsets.get(path ?? "");
892
+ const k = Number(ln) - (info?.headLines ?? 0);
893
+ const c = Number(col);
894
+ let text;
895
+ if (info === void 0) text = `${path}:${ln}:${col}: ${sev}: ${msg}`;
896
+ else if (k < 1) text = `${locate(info.b)}: ${sev}: (lean block ${info.b.name}, Lean ${ln}:${col}) ${msg}`;
897
+ else {
898
+ const line = info.b.sourceAt.line + k - 1;
899
+ const tsCol = k === 1 ? info.b.sourceAt.col + c : c + 1;
900
+ text = `${info.b.file}:${line}:${tsCol}: ${sev}: (lean block ${info.b.name}, Lean ${k}:${c}) ${msg}`;
901
+ }
902
+ while (i + 1 < lines.length && (lines[i + 1] ?? "").trim() !== "" && LAKE_MESSAGE.exec((lines[i + 1] ?? "").trim()) === null && !/^(✖|✔|⣿|trace:|info:|error:|warning:|Some required|- )/u.test(lines[i + 1] ?? "")) {
903
+ text += `\n${lines[i + 1]}`;
904
+ i++;
905
+ }
906
+ out.push(text);
907
+ }
908
+ return out;
909
+ }
910
+ function run(cmd, args, cwd) {
911
+ const r = spawnSync(cmd, args, {
912
+ cwd,
913
+ encoding: "utf8",
914
+ maxBuffer: 1 << 28
915
+ });
916
+ if (r.error !== void 0) throw new SyncError(`cannot run ${cmd}: ${r.error.message}`, 255);
917
+ return {
918
+ status: r.status ?? 255,
919
+ stdout: r.stdout,
920
+ stderr: r.stderr
921
+ };
922
+ }
923
+ function leanTypescriptCli(given) {
924
+ return given ?? process.env["LEANFRAN_TYPESCRIPT"] ?? "leanfran-typescript";
925
+ }
926
+ function specifier(from, to) {
927
+ const r = relative(dirname(from), to).split(sep).join("/");
928
+ return r.startsWith(".") ? r : `./${r}`;
929
+ }
930
+ function removeStale(dir, keep) {
931
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
932
+ const p = join(dir, e.name);
933
+ if (e.isDirectory()) {
934
+ if (e.name === "node_modules") continue;
935
+ if (e.name === "_lean") {
936
+ for (const f of readdirSync(p)) if (!keep.has(join(p, f))) rmSync(join(p, f), { recursive: true });
937
+ if (readdirSync(p).length === 0) rmdirSync(p);
938
+ } else removeStale(p, keep);
939
+ }
940
+ }
941
+ }
942
+ function packageModels(pkg) {
943
+ const perModule = /* @__PURE__ */ new Map();
944
+ for (const b of pkg.blocks) {
945
+ if (b.modelNames.length === 0) continue;
946
+ const entry = perModule.get(b.module) ?? {
947
+ parts: modelsModule(b),
948
+ models: /* @__PURE__ */ new Map(),
949
+ b
950
+ };
951
+ perModule.set(b.module, entry);
952
+ for (const [name, schema] of Object.entries(b.inputs.models)) {
953
+ const prev = entry.models.get(name);
954
+ if (prev !== void 0 && canonicalJson(prev) !== canonicalJson(schema)) throw new SyncError(`${locate(b)}: the model ${name} has another JSON Schema in the block ${entry.b.name} of the same module`, 252);
955
+ entry.models.set(name, schema);
956
+ }
957
+ }
958
+ const out = /* @__PURE__ */ new Map();
959
+ for (const [module, e] of perModule) out.set(e.parts, modelsLean(module, e.parts.slice(1), e.models).lean);
960
+ return out;
961
+ }
962
+ function blocksFile(root) {
963
+ return join(root, ".leanfran", "blocks.json");
964
+ }
965
+ function named(v) {
966
+ if (!Array.isArray(v)) return [];
967
+ return v.flatMap((x) => isRecord(x) && typeof x["lean"] === "string" && typeof x["typescript"] === "string" ? [{
968
+ lean: x["lean"],
969
+ typescript: x["typescript"]
970
+ }] : []);
971
+ }
972
+ async function syncPackage(dir, cliPath, log, csimp = () => /* @__PURE__ */ new Map()) {
973
+ const cli = leanTypescriptCli(cliPath);
974
+ const gv = run(cli, ["--generator-version"]);
975
+ if (gv.status !== 0) throw new SyncError(`${cli} --generator-version failed: ${gv.stderr}`, 255);
976
+ if (gv.stdout.trim() !== "10") throw new SyncError(`${cli} generates version ${gv.stdout.trim()}, this leanfran expects 10`, 255);
977
+ const pkg = await readPackage(dir, true);
978
+ const ws = join(pkg.root, ".leanfran", "workspace");
979
+ rmSync(join(ws, "LeanTsEmbed"), {
980
+ recursive: true,
981
+ force: true
982
+ });
983
+ rmSync(join(ws, "LeanTsModels"), {
984
+ recursive: true,
985
+ force: true
986
+ });
987
+ rmSync(join(ws, "LeanTsCsimp"), {
988
+ recursive: true,
989
+ force: true
990
+ });
991
+ mkdirSync(ws, { recursive: true });
992
+ writeFileSync(join(ws, "lakefile.toml"), LAKEFILE);
993
+ const models = packageModels(pkg);
994
+ for (const [module, m] of models) {
995
+ const rel = `${module.join("/")}.lean`;
996
+ mkdirSync(dirname(join(ws, rel)), { recursive: true });
997
+ writeFileSync(join(ws, rel), m);
998
+ }
999
+ writeFileSync(join(ws, "LeanTsModels.lean"), [...models.keys()].map((m) => `import ${leanName(m)}\n`).join("") || "\n");
1000
+ writeFileSync(join(ws, "LeanTsEmbed.lean"), pkg.blocks.map((b) => `import ${leanName(b.leanModule)}\n`).join("") || "\n");
1001
+ const csimps = csimp(pkg);
1002
+ for (const [rel, text] of csimps) {
1003
+ mkdirSync(dirname(join(ws, rel)), { recursive: true });
1004
+ writeFileSync(join(ws, rel), text);
1005
+ }
1006
+ writeFileSync(join(ws, "LeanTsCsimp.lean"), [...csimps.keys()].map((rel) => `import ${leanName(rel.replace(/\.lean$/u, "").split("/"))}\n`).join("") || "\n");
1007
+ const offsets = /* @__PURE__ */ new Map();
1008
+ for (const b of pkg.blocks) {
1009
+ const { head, text } = blockLean(pkg, b);
1010
+ const rel = `${b.leanModule.join("/")}.lean`;
1011
+ mkdirSync(dirname(join(ws, rel)), { recursive: true });
1012
+ writeFileSync(join(ws, rel), text);
1013
+ offsets.set(rel, {
1014
+ b,
1015
+ headLines: head.split("\n").length - 1
1016
+ });
1017
+ }
1018
+ const lake = run(process.env["LAKE"] ?? "lake", ["build"], ws);
1019
+ const messages = leanMessages(lake.stdout + lake.stderr, offsets);
1020
+ for (const m of messages) if (lake.status !== 0 || m.split("\n")[0]?.includes(": warning:") === true) log(`leanfran: ${m}`);
1021
+ if (lake.status !== 0) {
1022
+ if (messages.length === 0) log(lake.stdout + lake.stderr);
1023
+ throw new SyncError("lake build failed", 254);
1024
+ }
1025
+ const jobs = pkg.blocks.map((b) => ({
1026
+ module: b.leanModule.join("."),
1027
+ namespace: b.leanModule.join("."),
1028
+ output_file: b.outFile,
1029
+ type_modules: b.uses.map((u) => {
1030
+ const used = resolveUse(pkg, b, u);
1031
+ return {
1032
+ namespace: used.leanModule.join("."),
1033
+ module: specifier(b.outFile, used.outFile)
1034
+ };
1035
+ }),
1036
+ model_modules: b.models.map((m) => ({
1037
+ namespace: [...modelsModule(b), m.name].join("."),
1038
+ key: `${b.fnv}:${m.name}`,
1039
+ module: m.from.startsWith("/") ? specifier(b.outFile, m.from) : m.from,
1040
+ export: m.exportName
1041
+ })),
1042
+ tag_key: b.settings["tagKey"],
1043
+ option: b.settings["option"],
1044
+ block: {
1045
+ name: b.name,
1046
+ module: b.module,
1047
+ fnv: b.fnv
1048
+ },
1049
+ ts_root: `${posixRelative(dirname(b.outFile), pkg.root)}/`
1050
+ }));
1051
+ writeFileSync(join(ws, "batch.json"), JSON.stringify(jobs, null, 2) + "\n");
1052
+ const outputs = outputsOf(pkg.blocks);
1053
+ const companions = pkg.blocks.map((b) => b.outFile.replace(/\.ts$/u, ".block.ts"));
1054
+ for (const c of companions) rmSync(c, { force: true });
1055
+ const summaries = /* @__PURE__ */ new Map();
1056
+ if (pkg.blocks.length !== 0) {
1057
+ const gen = run(cli, [
1058
+ "module",
1059
+ "generate",
1060
+ "--batch",
1061
+ join(ws, "batch.json"),
1062
+ "--import",
1063
+ "LeanTsCsimp",
1064
+ "--search-path",
1065
+ join(ws, ".lake", "build", "lib", "lean"),
1066
+ "--output",
1067
+ "json"
1068
+ ]);
1069
+ if (gen.status !== 0) {
1070
+ log(gen.stderr + gen.stdout);
1071
+ throw new SyncError("leanfran-typescript module generate failed", gen.status);
1072
+ }
1073
+ const parsed = JSON.parse(gen.stdout);
1074
+ if (Array.isArray(parsed)) parsed.forEach((s, i) => {
1075
+ const b = pkg.blocks[i];
1076
+ if (b !== void 0 && isRecord(s)) summaries.set(b.outFile, {
1077
+ public: named(s["public"]),
1078
+ types: named(s["types"])
1079
+ });
1080
+ const skipped = isRecord(s) ? s["skipped"] : void 0;
1081
+ if (Array.isArray(skipped)) {
1082
+ for (const k of skipped) if (isRecord(k)) log(`leanfran: skipped ${String(k["name"])}: ${String(k["reason"])}`);
1083
+ }
1084
+ });
1085
+ }
1086
+ for (const [f, text] of outputs) if (text !== "") writeFileSync(f, text);
1087
+ removeStale(join(pkg.root, "src"), /* @__PURE__ */ new Set([...outputs.keys(), ...companions.filter((c) => existsSync(c))]));
1088
+ const registry = {};
1089
+ for (const b of pkg.blocks) registry[`${b.module}:${b.name}`] = {
1090
+ sha256: b.key,
1091
+ fnv: b.fnv,
1092
+ output: posixRelative(pkg.root, b.outFile)
1093
+ };
1094
+ writeFileSync(blocksFile(pkg.root), JSON.stringify(JSON.parse(canonicalJson(registry)), null, 2) + "\n");
1095
+ log(`leanfran: ${pkg.blocks.length} blocks of ${pkg.root} checked and generated`);
1096
+ return {
1097
+ pkg,
1098
+ summaries
1099
+ };
1100
+ }
1101
+ function statusPackage(pkg) {
1102
+ const file = blocksFile(pkg.root);
1103
+ const recorded = existsSync(file) ? readJson(file) : {};
1104
+ const known = isRecord(recorded) ? recorded : {};
1105
+ const rows = [];
1106
+ const current = /* @__PURE__ */ new Set();
1107
+ for (const b of pkg.blocks) {
1108
+ const q = `${b.module}:${b.name}`;
1109
+ current.add(q);
1110
+ const entry = known[q];
1111
+ const fresh = isRecord(entry) && entry["sha256"] === b.key && existsSync(b.outFile);
1112
+ rows.push({
1113
+ block: q,
1114
+ state: fresh ? "fresh" : "stale"
1115
+ });
1116
+ }
1117
+ for (const q of Object.keys(known)) if (!current.has(q)) rows.push({
1118
+ block: q,
1119
+ state: "removed"
1120
+ });
1121
+ return rows.toSorted((a, b) => a.block.localeCompare(b.block));
1122
+ }
1123
+ // src/verify/translate.ts
1124
+ const NUM = { k: "num" };
1125
+ const BIG = { k: "big" };
1126
+ const BOOL = { k: "bool" };
1127
+ const STR = { k: "str" };
1128
+ var TranslateError = class extends SyncError {
1129
+ constructor(message) {
1130
+ super(message, 254);
1131
+ this.name = "TranslateError";
1132
+ }
1133
+ };
1134
+ var Fn = class {
1135
+ name;
1136
+ node;
1137
+ params;
1138
+ ret;
1139
+ retNat;
1140
+ src;
1141
+ fails = false;
1142
+ constructor(name, node, src, types) {
1143
+ this.name = name;
1144
+ this.node = node;
1145
+ this.src = src;
1146
+ const params = [];
1147
+ for (const p of node.params) params.push(paramOf(p, src, types, name));
1148
+ this.params = params;
1149
+ const r = node.returnType?.typeAnnotation;
1150
+ if (r === void 0 || r === null) throw new TranslateError(`${src.where(node.start)}: ${name} has no return type annotation`);
1151
+ this.ret = tsType(r, src, types);
1152
+ this.retNat = isNat(r, types);
1153
+ }
1154
+ };
1155
+ function paramOf(p, src, types, fn) {
1156
+ if (p.type !== "Identifier") throw new TranslateError(`${src.where(p.start)}: the parameters of ${fn} must be plain names`);
1157
+ const ann = p.typeAnnotation?.typeAnnotation;
1158
+ if (ann === void 0 || ann === null) throw new TranslateError(`${src.where(p.start)}: the parameter ${p.name} of ${fn} has no type annotation`);
1159
+ return {
1160
+ name: p.name,
1161
+ type: tsType(ann, src, types),
1162
+ nat: isNat(ann, types)
1163
+ };
1164
+ }
1165
+ function isNat(t, types) {
1166
+ return t.type === "TSTypeReference" && t.typeName.type === "Identifier" && t.typeName.name === "Nat" && types.reference("Nat", void 0, t.start)?.k === "big";
1167
+ }
1168
+ function tsType(t, src, types) {
1169
+ const bad = () => {
1170
+ throw new TranslateError(`${src.where(t.start)}: the type is outside the subset leanfran translates`);
1171
+ };
1172
+ switch (t.type) {
1173
+ case "TSNumberKeyword": return NUM;
1174
+ case "TSBigIntKeyword": return BIG;
1175
+ case "TSBooleanKeyword": return BOOL;
1176
+ case "TSStringKeyword": return STR;
1177
+ case "TSParenthesizedType": return tsType(t.typeAnnotation, src, types);
1178
+ case "TSArrayType": return {
1179
+ k: "list",
1180
+ item: tsType(t.elementType, src, types)
1181
+ };
1182
+ case "TSTypeOperator": return t.operator === "readonly" ? tsType(t.typeAnnotation, src, types) : bad();
1183
+ case "TSTupleType": return {
1184
+ k: "tuple",
1185
+ items: t.elementTypes.map((e) => e.type === "TSOptionalType" || e.type === "TSRestType" ? bad() : tsType(e, src, types))
1186
+ };
1187
+ case "TSUnionType": {
1188
+ const rest = t.types.filter((x) => x.type !== "TSNullKeyword" && x.type !== "TSUndefinedKeyword");
1189
+ const only = rest[0];
1190
+ if (rest.length !== 1 || t.types.length !== 2 || only === void 0) return bad();
1191
+ return {
1192
+ k: "opt",
1193
+ item: tsType(only, src, types),
1194
+ absent: t.types.some((x) => x.type === "TSNullKeyword") ? "null" : "undefined"
1195
+ };
1196
+ }
1197
+ case "TSTypeReference": {
1198
+ const n = t.typeName;
1199
+ const args = t.typeArguments?.params ?? [];
1200
+ const query = args[0];
1201
+ if (args.length === 1 && query?.type === "TSTypeQuery" && query.exprName.type === "Identifier") return types.model(query.exprName.name, t.start) ?? bad();
1202
+ if (n.type === "Identifier") {
1203
+ const arg = args[0];
1204
+ if ((n.name === "Array" || n.name === "ReadonlyArray") && args.length === 1 && arg !== void 0) return {
1205
+ k: "list",
1206
+ item: tsType(arg, src, types)
1207
+ };
1208
+ if (args.length !== 0) return bad();
1209
+ return types.reference(n.name, void 0, t.start) ?? bad();
1210
+ }
1211
+ if (n.type === "TSQualifiedName" && n.left.type === "Identifier" && args.length === 0) return types.reference(n.right.name, n.left.name, t.start) ?? bad();
1212
+ return bad();
1213
+ }
1214
+ default: return bad();
1215
+ }
1216
+ }
1217
+ function leanType(t) {
1218
+ if (t.k === "num" || t.k === "big") return "Int";
1219
+ if (t.k === "bool") return "Bool";
1220
+ if (t.k === "str") return "String";
1221
+ if (t.k === "list") return `(List ${leanType(t.item)})`;
1222
+ if (t.k === "tuple") return `(${t.items.map(leanType).join(" × ")})`;
1223
+ if (t.k === "opt") return `(Option ${leanType(t.item)})`;
1224
+ return `_root_.${t.lean}`;
1225
+ }
1226
+ const LEAN_KEYWORDS = /* @__PURE__ */ new Set([
1227
+ "at",
1228
+ "by",
1229
+ "do",
1230
+ "end",
1231
+ "else",
1232
+ "fun",
1233
+ "have",
1234
+ "if",
1235
+ "in",
1236
+ "let",
1237
+ "match",
1238
+ "mut",
1239
+ "then",
1240
+ "with",
1241
+ "return",
1242
+ "for",
1243
+ "from",
1244
+ "show",
1245
+ "where",
1246
+ "open",
1247
+ "namespace",
1248
+ "section",
1249
+ "def",
1250
+ "theorem",
1251
+ "structure",
1252
+ "inductive",
1253
+ "instance",
1254
+ "class",
1255
+ "abbrev",
1256
+ "import",
1257
+ "deriving",
1258
+ "unless",
1259
+ "break",
1260
+ "continue",
1261
+ "try",
1262
+ "catch",
1263
+ "finally",
1264
+ "local",
1265
+ "private",
1266
+ "protected",
1267
+ "partial",
1268
+ "variable",
1269
+ "universe",
1270
+ "macro",
1271
+ "syntax",
1272
+ "Type",
1273
+ "Prop",
1274
+ "Sort",
1275
+ "none",
1276
+ "some",
1277
+ "true",
1278
+ "false"
1279
+ ]);
1280
+ function ident(name) {
1281
+ return LEAN_KEYWORDS.has(name) || !/^[A-Za-z_][A-Za-z0-9_]*$/u.test(name) ? `«${name}»` : name;
1282
+ }
1283
+ function stringLit(s) {
1284
+ let out = "\"";
1285
+ for (const ch of s) {
1286
+ const c = ch.codePointAt(0) ?? 0;
1287
+ if (ch === "\"") out += "\\\"";
1288
+ else if (ch === "\\") out += "\\\\";
1289
+ else if (ch === "\n") out += "\\n";
1290
+ else if (ch === " ") out += "\\t";
1291
+ else if (ch === "\r") out += "\\r";
1292
+ else if (c < 32) out += `\\x${c.toString(16).padStart(2, "0")}`;
1293
+ else out += ch;
1294
+ }
1295
+ return out + "\"";
1296
+ }
1297
+ function same(a, b) {
1298
+ const key = (t) => JSON.stringify(t, (k, v) => k === "absent" ? void 0 : v);
1299
+ return key(a) === key(b);
1300
+ }
1301
+ function isInt(t) {
1302
+ return t.k === "num" || t.k === "big";
1303
+ }
1304
+ const ERRORS = /* @__PURE__ */ new Set([
1305
+ "Error",
1306
+ "RangeError",
1307
+ "TypeError"
1308
+ ]);
1309
+ function tupleProj(base, i, n) {
1310
+ let s = base;
1311
+ for (let k = 0; k < i; k++) s = `${s}.2`;
1312
+ return i < n - 1 ? `${s}.1` : s;
1313
+ }
1314
+ function terminates(stmts) {
1315
+ const last = stmts[stmts.length - 1];
1316
+ if (last === void 0) return false;
1317
+ if (last.type === "ReturnStatement" || last.type === "ThrowStatement") return true;
1318
+ if (last.type === "BlockStatement") return terminates(last.body);
1319
+ if (last.type === "IfStatement") return last.alternate !== null && terminates([last.consequent]) && terminates([last.alternate]);
1320
+ return false;
1321
+ }
1322
+ function isNil(x) {
1323
+ return x.type === "Literal" && x.value === null && x.raw === "null" || x.type === "Identifier" && x.name === "undefined";
1324
+ }
1325
+ function nullCheck(e) {
1326
+ if (e.type !== "BinaryExpression" || e.operator !== "===" && e.operator !== "!==") return void 0;
1327
+ const name = e.left.type === "Identifier" && isNil(e.right) ? e.left.name : e.right.type === "Identifier" && isNil(e.left) ? e.right.name : void 0;
1328
+ return name === void 0 ? void 0 : {
1329
+ name,
1330
+ isNull: e.operator === "==="
1331
+ };
1332
+ }
1333
+ var Translator = class {
1334
+ fns;
1335
+ types;
1336
+ constructor(fns, types) {
1337
+ this.fns = new Map(fns.map((f) => [f.name, f]));
1338
+ this.types = types;
1339
+ }
1340
+ definitions() {
1341
+ let out = /* @__PURE__ */ new Map();
1342
+ for (let round = 0; round <= this.fns.size + 1; round++) {
1343
+ const before = [...this.fns.values()].map((f) => f.fails).join();
1344
+ out = new Map([...this.fns.values()].map((f) => [f.name, this.definition(f)]));
1345
+ if ([...this.fns.values()].map((f) => f.fails).join() === before) return out;
1346
+ }
1347
+ return out;
1348
+ }
1349
+ fail(fn, at, msg) {
1350
+ throw new TranslateError(`${fn.src.where(at)}: ${fn.name}: ${msg}`);
1351
+ }
1352
+ definition(fn) {
1353
+ const scope = /* @__PURE__ */ new Map();
1354
+ const binders = [];
1355
+ const prelude = [];
1356
+ for (const p of fn.params) {
1357
+ scope.set(p.name, {
1358
+ t: p.type,
1359
+ mutable: false,
1360
+ local: false
1361
+ });
1362
+ if (p.nat) {
1363
+ binders.push(`(${ident(p.name)} : Nat)`);
1364
+ prelude.push(` let ${ident(p.name)} : Int := ${ident(p.name)}`);
1365
+ } else binders.push(`(${ident(p.name)} : ${leanType(p.type)})`);
1366
+ }
1367
+ const body = fn.node.body;
1368
+ if (body === null) this.fail(fn, fn.node.start, "has no body");
1369
+ const lines = body.type === "BlockStatement" ? this.block(fn, body.body, scope, 1) : [` return ${this.expr(fn, body, scope, fn.ret).c}`];
1370
+ const ret = leanType(fn.ret);
1371
+ const head = fn.fails ? `Ts.M ${ret} := do` : `${ret} := Id.run do`;
1372
+ return [
1373
+ `def ${ident(fn.name)} ${binders.join(" ")} : ${head}`,
1374
+ ...prelude,
1375
+ ...lines
1376
+ ].join("\n");
1377
+ }
1378
+ block(fn, stmts, scope, indent) {
1379
+ const out = [];
1380
+ const pad = " ".repeat(indent);
1381
+ for (let i = 0; i < stmts.length; i++) {
1382
+ const s = stmts[i];
1383
+ if (s === void 0) continue;
1384
+ if (s.type === "IfStatement") {
1385
+ const nc = nullCheck(s.test);
1386
+ const v = nc === void 0 ? void 0 : scope.get(nc.name);
1387
+ if (nc !== void 0 && v !== void 0 && v.t.k === "opt") {
1388
+ const inner = new Map(scope);
1389
+ inner.set(nc.name, {
1390
+ t: v.t.item,
1391
+ mutable: false,
1392
+ local: false
1393
+ });
1394
+ const someBranch = nc.isNull ? s.alternate : s.consequent;
1395
+ const noneBranch = nc.isNull ? s.consequent : s.alternate;
1396
+ const rest = stmts.slice(i + 1);
1397
+ const takeRest = nc.isNull && s.alternate === null && terminates([s.consequent]);
1398
+ const someStmts = takeRest ? rest : someBranch === null ? [] : [someBranch];
1399
+ out.push(`${pad}match ${ident(nc.name)} with`);
1400
+ out.push(`${pad}| some ${ident(nc.name)} =>`);
1401
+ out.push(...this.nonEmpty(this.block(fn, someStmts, inner, indent + 1), indent + 1));
1402
+ out.push(`${pad}| none =>`);
1403
+ out.push(...this.nonEmpty(noneBranch === null ? [] : this.block(fn, [noneBranch], new Map(scope), indent + 1), indent + 1));
1404
+ if (takeRest) return out;
1405
+ continue;
1406
+ }
1407
+ }
1408
+ out.push(...this.stmt(fn, s, scope, indent));
1409
+ }
1410
+ return out;
1411
+ }
1412
+ nonEmpty(lines, indent) {
1413
+ return lines.length === 0 ? [`${" ".repeat(indent)}pure ()`] : lines;
1414
+ }
1415
+ stmt(fn, s, scope, indent) {
1416
+ const pad = " ".repeat(indent);
1417
+ switch (s.type) {
1418
+ case "ReturnStatement":
1419
+ if (s.argument === null) return this.fail(fn, s.start, "a function must return a value");
1420
+ return [`${pad}return ${this.expr(fn, s.argument, scope, fn.ret).c}`];
1421
+ case "BlockStatement": return this.nonEmpty(this.block(fn, s.body, new Map(scope), indent), indent);
1422
+ case "EmptyStatement": return [];
1423
+ case "VariableDeclaration":
1424
+ if (s.kind !== "const" && s.kind !== "let") return this.fail(fn, s.start, `${s.kind} declarations are outside the subset`);
1425
+ return s.declarations.flatMap((d) => {
1426
+ if (d.init === null) return this.fail(fn, d.start, "a variable needs an initial value");
1427
+ return this.declareVar(fn, d.id, d.init, scope, pad);
1428
+ });
1429
+ case "IfStatement": {
1430
+ const out = [`${pad}if ${this.cond(fn, s.test, scope)} then`];
1431
+ out.push(...this.nonEmpty(this.block(fn, [s.consequent], new Map(scope), indent + 1), indent + 1));
1432
+ if (s.alternate !== null) {
1433
+ out.push(`${pad}else`);
1434
+ out.push(...this.nonEmpty(this.block(fn, [s.alternate], new Map(scope), indent + 1), indent + 1));
1435
+ }
1436
+ return out;
1437
+ }
1438
+ case "ForOfStatement": {
1439
+ if (s.await) return this.fail(fn, s.start, "for await is outside the subset");
1440
+ const l = s.left;
1441
+ if (l.type !== "VariableDeclaration" || l.declarations.length !== 1) return this.fail(fn, s.start, "only `for (const x of xs)` is in the subset");
1442
+ const id = l.declarations[0]?.id;
1443
+ if (id === void 0 || id.type !== "Identifier") return this.fail(fn, s.start, "only `for (const x of xs)` is in the subset");
1444
+ const xs = this.expr(fn, s.right, scope);
1445
+ if (xs.t.k !== "list") return this.fail(fn, s.right.start, "for ... of iterates over an array");
1446
+ const inner = new Map(scope);
1447
+ inner.set(id.name, {
1448
+ t: xs.t.item,
1449
+ mutable: false,
1450
+ local: false
1451
+ });
1452
+ return [`${pad}for ${ident(id.name)} in ${xs.c} do`, ...this.nonEmpty(this.block(fn, [s.body], inner, indent + 1), indent + 1)];
1453
+ }
1454
+ case "ForStatement": return this.forRange(fn, s, scope, indent);
1455
+ case "WhileStatement": return [`${pad}while ${this.cond(fn, s.test, scope)} do`, ...this.nonEmpty(this.block(fn, [s.body], new Map(scope), indent + 1), indent + 1)];
1456
+ case "BreakStatement":
1457
+ if (s.label !== null) return this.fail(fn, s.start, "labelled break is outside the subset");
1458
+ return [`${pad}break`];
1459
+ case "ContinueStatement":
1460
+ if (s.label !== null) return this.fail(fn, s.start, "labelled continue is outside the subset");
1461
+ return [`${pad}continue`];
1462
+ case "ThrowStatement": {
1463
+ const a = s.argument;
1464
+ if (a.type !== "NewExpression" || a.callee.type !== "Identifier" || !ERRORS.has(a.callee.name)) return this.fail(fn, s.start, "only `throw new Error(...)` (or a built-in Error) is in the subset");
1465
+ const m = a.arguments[0];
1466
+ const msg = m === void 0 ? "\"\"" : m.type === "SpreadElement" ? this.fail(fn, m.start, "spread arguments are outside the subset") : this.expr(fn, m, scope, STR).c;
1467
+ fn.fails = true;
1468
+ return [`${pad}throw (Ts.Exc.error ${stringLit(a.callee.name)} ${msg})`];
1469
+ }
1470
+ case "SwitchStatement": return this.switchStmt(fn, s, scope, indent);
1471
+ case "ExpressionStatement": return this.exprStmt(fn, s.expression, scope, pad);
1472
+ default: return this.fail(fn, s.start, `${s.type} is outside the subset`);
1473
+ }
1474
+ }
1475
+ switchStmt(fn, s, scope, indent) {
1476
+ const pad = " ".repeat(indent);
1477
+ const d = s.discriminant;
1478
+ let subject;
1479
+ let tagged;
1480
+ if (d.type === "MemberExpression" && !d.computed && d.object.type === "Identifier" && scope.get(d.object.name)?.t.k === "ind") {
1481
+ const t = scope.get(d.object.name)?.t;
1482
+ if (t?.k !== "ind" || d.property.name !== t.tagKey) return this.fail(fn, d.start, "switch on an inductive value reads its tag key");
1483
+ tagged = {
1484
+ name: d.object.name,
1485
+ t
1486
+ };
1487
+ subject = {
1488
+ c: ident(d.object.name),
1489
+ t
1490
+ };
1491
+ } else subject = this.expr(fn, d, scope);
1492
+ const out = [`${pad}match ${subject.c} with`];
1493
+ let hasDefault = false;
1494
+ const seen = /* @__PURE__ */ new Set();
1495
+ for (const c of s.cases) {
1496
+ const body = c.consequent.filter((x) => !(x.type === "BreakStatement" && x.label === null));
1497
+ const last = c.consequent[c.consequent.length - 1];
1498
+ if (c.consequent.length !== 0 && !terminates(c.consequent) && !(last?.type === "BreakStatement" && last.label === null)) return this.fail(fn, c.start, "each case must end with return, throw or break");
1499
+ if (c.consequent.length === 0) return this.fail(fn, c.start, "fall-through cases are outside the subset");
1500
+ if (body.some((x) => x.type === "BreakStatement")) return this.fail(fn, c.start, "break inside a case is only allowed at its end");
1501
+ const inner = new Map(scope);
1502
+ let pat;
1503
+ const rest = tagged?.t.variants.filter((v) => !seen.has(v.name)) ?? [];
1504
+ const only = rest[0];
1505
+ if (c.test === null && tagged !== void 0 && rest.length === 1 && only !== void 0) {
1506
+ hasDefault = true;
1507
+ const names = only.fields.map((f) => `${tagged.name}_${f.key}`);
1508
+ pat = `.${ident(only.name)}${names.map((n) => ` ${ident(n)}`).join("")}`;
1509
+ inner.set(tagged.name, {
1510
+ t: {
1511
+ ...tagged.t,
1512
+ variants: [only]
1513
+ },
1514
+ mutable: false,
1515
+ local: false
1516
+ });
1517
+ } else if (c.test === null) {
1518
+ hasDefault = true;
1519
+ pat = "_";
1520
+ } else if (c.test.type !== "Literal" || typeof c.test.value !== "string") return this.fail(fn, c.test.start, "case labels must be string literals");
1521
+ else {
1522
+ const label = c.test.value;
1523
+ seen.add(label);
1524
+ if (tagged !== void 0) {
1525
+ const v = tagged.t.variants.find((x) => x.name === label);
1526
+ if (v === void 0) return this.fail(fn, c.test.start, `${tagged.t.ts} has no constructor ${label}`);
1527
+ const names = v.fields.map((f) => `${tagged.name}_${f.key}`);
1528
+ pat = `.${ident(label)}${names.map((n) => ` ${ident(n)}`).join("")}`;
1529
+ inner.set(tagged.name, {
1530
+ t: {
1531
+ ...tagged.t,
1532
+ variants: [v]
1533
+ },
1534
+ mutable: false,
1535
+ local: false
1536
+ });
1537
+ } else if (subject.t.k === "enum") {
1538
+ if (!subject.t.ctors.includes(label)) return this.fail(fn, c.test.start, `${subject.t.ts} has no constructor ${label}`);
1539
+ pat = `.${ident(label)}`;
1540
+ } else if (subject.t.k === "str") pat = stringLit(label);
1541
+ else return this.fail(fn, d.start, "switch is on a string, an enum or the tag of an inductive value");
1542
+ }
1543
+ out.push(`${pad}| ${pat} =>`);
1544
+ out.push(...this.nonEmpty(this.block(fn, body, inner, indent + 1), indent + 1));
1545
+ }
1546
+ const total = tagged !== void 0 ? tagged.t.variants.every((v) => seen.has(v.name)) : subject.t.k === "enum" && subject.t.ctors.every((x) => seen.has(x));
1547
+ if (!hasDefault && !total) out.push(`${pad}| _ => pure ()`);
1548
+ return out;
1549
+ }
1550
+ forRange(fn, s, scope, indent) {
1551
+ const pad = " ".repeat(indent);
1552
+ const bad = () => this.fail(fn, s.start, "only `for (let i = a; i < b; i++)` (or `i <= b`) is in the subset");
1553
+ const init = s.init;
1554
+ if (init === null || init.type !== "VariableDeclaration" || init.declarations.length !== 1) return bad();
1555
+ const d = init.declarations[0];
1556
+ if (d === void 0 || d.id.type !== "Identifier" || d.init === null) return bad();
1557
+ const i = d.id.name;
1558
+ const t = s.test;
1559
+ if (t === null || t.type !== "BinaryExpression" || t.operator !== "<" && t.operator !== "<=" || t.left.type !== "Identifier" || t.left.name !== i) return bad();
1560
+ const u = s.update;
1561
+ if (!(u !== null && (u.type === "UpdateExpression" && u.operator === "++" && u.argument.type === "Identifier" && u.argument.name === i || u.type === "AssignmentExpression" && u.operator === "+=" && u.left.type === "Identifier" && u.left.name === i && u.right.type === "Literal" && (u.right.value === 1 || u.right.value === 1n)))) return bad();
1562
+ const a = this.expr(fn, d.init, scope);
1563
+ if (!isInt(a.t)) return bad();
1564
+ const b = this.expr(fn, t.right, scope, a.t);
1565
+ const assigned = assignedNames(s.body);
1566
+ if (assigned.has(i)) return this.fail(fn, s.body.start, `the loop variable ${i} is assigned in the body`);
1567
+ for (const n of identifiers(t.right)) if (assigned.has(n)) return this.fail(fn, t.right.start, `the bound reads ${n}, which the body assigns`);
1568
+ const hi = t.operator === "<=" ? `(${b.c} + 1)` : b.c;
1569
+ const inner = new Map(scope);
1570
+ inner.set(i, {
1571
+ t: a.t,
1572
+ mutable: false,
1573
+ local: false
1574
+ });
1575
+ return [`${pad}for ${ident(i)} in Ts.range ${a.c} ${hi} do`, ...this.nonEmpty(this.block(fn, [s.body], inner, indent + 1), indent + 1)];
1576
+ }
1577
+ declareVar(fn, id, init, scope, pad) {
1578
+ if (id.type === "Identifier") {
1579
+ const ann = id.typeAnnotation?.typeAnnotation;
1580
+ const t = ann === void 0 || ann === null ? void 0 : tsType(ann, fn.src, this.types);
1581
+ const v = this.expr(fn, init, scope, t);
1582
+ const ty = t ?? v.t;
1583
+ scope.set(id.name, {
1584
+ t: ty,
1585
+ mutable: true,
1586
+ local: true
1587
+ });
1588
+ return [`${pad}let mut ${ident(id.name)} : ${leanType(ty)} := ${v.c}`];
1589
+ }
1590
+ if (id.type === "ArrayPattern") {
1591
+ const v = this.expr(fn, init, scope);
1592
+ if (v.t.k !== "tuple") return this.fail(fn, id.start, "array destructuring is for tuples");
1593
+ const items = v.t.items;
1594
+ const tmp = `__t${id.start}`;
1595
+ const out = [`${pad}let ${tmp} := ${v.c}`];
1596
+ id.elements.forEach((e, k) => {
1597
+ if (e === null) return;
1598
+ if (e.type !== "Identifier") this.fail(fn, e.start, "only names are allowed in destructuring");
1599
+ const it = items[k];
1600
+ if (it === void 0) this.fail(fn, e.start, "the tuple has no such element");
1601
+ scope.set(e.name, {
1602
+ t: it,
1603
+ mutable: true,
1604
+ local: true
1605
+ });
1606
+ out.push(`${pad}let mut ${ident(e.name)} : ${leanType(it)} := ${tupleProj(tmp, k, items.length)}`);
1607
+ });
1608
+ return out;
1609
+ }
1610
+ if (id.type === "ObjectPattern") {
1611
+ const v = this.expr(fn, init, scope);
1612
+ if (v.t.k !== "struct") return this.fail(fn, id.start, "object destructuring is for structures");
1613
+ const st = v.t;
1614
+ const tmp = `__t${id.start}`;
1615
+ const out = [`${pad}let ${tmp} := ${v.c}`];
1616
+ for (const p of id.properties) {
1617
+ if (p.type !== "Property" || p.computed || p.key.type !== "Identifier" || p.value.type !== "Identifier") return this.fail(fn, p.start, "only `{ a, b: c }` is allowed in destructuring");
1618
+ const keyName = p.key.name;
1619
+ const f = st.fields.find((x) => x.key === keyName);
1620
+ if (f === void 0) return this.fail(fn, p.start, `${st.ts} has no field ${keyName}`);
1621
+ scope.set(p.value.name, {
1622
+ t: f.type,
1623
+ mutable: true,
1624
+ local: true
1625
+ });
1626
+ const read = `${tmp}.${ident(f.lean)}`;
1627
+ out.push(`${pad}let mut ${ident(p.value.name)} : ${leanType(f.type)} := ${f.nat ? `(${read} : Int)` : read}`);
1628
+ }
1629
+ return out;
1630
+ }
1631
+ return this.fail(fn, id.start, "this declaration is outside the subset");
1632
+ }
1633
+ exprStmt(fn, e, scope, pad) {
1634
+ if (e.type === "AssignmentExpression") {
1635
+ if (e.left.type !== "Identifier") return this.fail(fn, e.start, "only assignments to local variables are in the subset");
1636
+ const name = e.left.name;
1637
+ const v = scope.get(name);
1638
+ if (v === void 0 || !v.local) return this.fail(fn, e.start, `${name} is not a local variable`);
1639
+ const x = ident(name);
1640
+ if (e.operator === "=") return [`${pad}${x} := ${this.expr(fn, e.right, scope, v.t).c}`];
1641
+ const op = e.operator.slice(0, -1);
1642
+ return [`${pad}${x} := ${this.binary(fn, op, {
1643
+ c: x,
1644
+ t: v.t
1645
+ }, e.right, scope, e.start).c}`];
1646
+ }
1647
+ if (e.type === "UpdateExpression") {
1648
+ if (e.argument.type !== "Identifier") return this.fail(fn, e.start, "++ and -- apply to local variables");
1649
+ const name = e.argument.name;
1650
+ const v = scope.get(name);
1651
+ if (v === void 0 || !v.local || !isInt(v.t)) return this.fail(fn, e.start, `${name} is not a local number`);
1652
+ return [`${pad}${ident(name)} := ${ident(name)} ${e.operator === "++" ? "+" : "-"} 1`];
1653
+ }
1654
+ if (e.type === "CallExpression" && e.callee.type === "MemberExpression" && !e.callee.computed && e.callee.property.type === "Identifier" && e.callee.property.name === "push") {
1655
+ const target = e.callee.object;
1656
+ const v = target.type === "Identifier" ? scope.get(target.name) : void 0;
1657
+ if (target.type !== "Identifier" || v === void 0 || !v.local || v.t.k !== "list") return this.fail(fn, e.start, "push only to an array created in the function");
1658
+ const items = e.arguments.map((a) => a.type === "SpreadElement" ? this.fail(fn, a.start, "spread arguments are outside the subset") : this.expr(fn, a, scope, v.t.k === "list" ? v.t.item : void 0).c);
1659
+ return [`${pad}${ident(target.name)} := ${ident(target.name)} ++ [${items.join(", ")}]`];
1660
+ }
1661
+ return this.fail(fn, e.start, "this expression statement is outside the subset");
1662
+ }
1663
+ cond(fn, e, scope) {
1664
+ const c = this.expr(fn, e, scope, BOOL);
1665
+ if (c.t.k !== "bool") return this.fail(fn, e.start, "a condition must be a boolean");
1666
+ return c.c;
1667
+ }
1668
+ lifted(fn, call) {
1669
+ fn.fails = true;
1670
+ return `(← ${call})`;
1671
+ }
1672
+ binary(fn, op, a, rightNode, scope, at) {
1673
+ const b = this.expr(fn, rightNode, scope, isInt(a.t) ? a.t : void 0);
1674
+ if (op === "+") {
1675
+ if (a.t.k === "str" && b.t.k === "str") return {
1676
+ c: `(${a.c} ++ ${b.c})`,
1677
+ t: STR
1678
+ };
1679
+ if (a.t.k === "str" || b.t.k === "str") {
1680
+ const s = (x) => x.t.k === "str" ? x.c : `(Ts.str ${x.c})`;
1681
+ return {
1682
+ c: `(${s(a)} ++ ${s(b)})`,
1683
+ t: STR
1684
+ };
1685
+ }
1686
+ }
1687
+ if (op === "+" || op === "-" || op === "*") {
1688
+ if (!isInt(a.t) || !isInt(b.t)) return this.fail(fn, at, `${op} needs numbers`);
1689
+ if (a.t.k !== b.t.k) return this.fail(fn, at, "number and bigint do not mix");
1690
+ return {
1691
+ c: `(${a.c} ${op} ${b.c})`,
1692
+ t: a.t
1693
+ };
1694
+ }
1695
+ if (op === "%") {
1696
+ if (!isInt(a.t) || a.t.k !== b.t.k) return this.fail(fn, at, "% needs two numbers or two bigints");
1697
+ return {
1698
+ c: this.lifted(fn, `Ts.rem ${a.c} ${b.c}`),
1699
+ t: a.t
1700
+ };
1701
+ }
1702
+ if (op === "/") {
1703
+ if (a.t.k === "big" && b.t.k === "big") return {
1704
+ c: this.lifted(fn, `Ts.truncDiv ${a.c} ${b.c}`),
1705
+ t: BIG
1706
+ };
1707
+ return this.fail(fn, at, "number division is only in Math.floor(a / b) or Math.trunc(a / b)");
1708
+ }
1709
+ if (op === "<" || op === "<=" || op === ">" || op === ">=") {
1710
+ if (!(isInt(a.t) && a.t.k === b.t.k || a.t.k === "str" && b.t.k === "str")) return this.fail(fn, at, `${op} compares two numbers, two bigints or two strings`);
1711
+ const sym = op === "<=" ? "≤" : op === ">=" ? "≥" : op;
1712
+ return {
1713
+ c: `(decide (${a.c} ${sym} ${b.c}))`,
1714
+ t: BOOL
1715
+ };
1716
+ }
1717
+ if (op === "===" || op === "!==") {
1718
+ if (!same(a.t, b.t)) return this.fail(fn, at, `${op} compares values of the same type`);
1719
+ return {
1720
+ c: `(${a.c} ${op === "===" ? "==" : "!="} ${b.c})`,
1721
+ t: BOOL
1722
+ };
1723
+ }
1724
+ return this.fail(fn, at, `the operator ${op} is outside the subset`);
1725
+ }
1726
+ expr(fn, e, scope, want) {
1727
+ switch (e.type) {
1728
+ case "ParenthesizedExpression": return this.expr(fn, e.expression, scope, want);
1729
+ case "Literal": {
1730
+ const v = e.value;
1731
+ if (typeof v === "boolean") return {
1732
+ c: v ? "true" : "false",
1733
+ t: BOOL
1734
+ };
1735
+ if (typeof v === "bigint") return {
1736
+ c: `(${v} : Int)`,
1737
+ t: BIG
1738
+ };
1739
+ if (typeof v === "number") {
1740
+ if (!Number.isSafeInteger(v)) return this.fail(fn, e.start, "only safe integers are in the subset");
1741
+ return {
1742
+ c: `(${v} : Int)`,
1743
+ t: want?.k === "big" ? BIG : NUM
1744
+ };
1745
+ }
1746
+ if (typeof v === "string") return {
1747
+ c: stringLit(v),
1748
+ t: STR
1749
+ };
1750
+ if (v === null && want?.k === "opt") return {
1751
+ c: "none",
1752
+ t: want
1753
+ };
1754
+ return this.fail(fn, e.start, "this literal is outside the subset");
1755
+ }
1756
+ case "Identifier": {
1757
+ if (e.name === "undefined" && want?.k === "opt") return {
1758
+ c: "none",
1759
+ t: want
1760
+ };
1761
+ const v = scope.get(e.name);
1762
+ if (v === void 0) return this.fail(fn, e.start, `unknown name ${e.name}`);
1763
+ return {
1764
+ c: ident(e.name),
1765
+ t: v.t
1766
+ };
1767
+ }
1768
+ case "TemplateLiteral": {
1769
+ const parts = [];
1770
+ e.quasis.forEach((q, i) => {
1771
+ const text = q.value.cooked ?? this.fail(fn, q.start, "invalid escape in the template");
1772
+ if (text !== "") parts.push(stringLit(text));
1773
+ const x = e.expressions[i];
1774
+ if (x !== void 0) {
1775
+ const o = this.expr(fn, x, scope);
1776
+ if (o.t.k !== "str" && !isInt(o.t) && o.t.k !== "bool") this.fail(fn, x.start, "${} takes a string, a number, a bigint or a boolean");
1777
+ parts.push(o.t.k === "str" ? o.c : `(Ts.str ${o.c})`);
1778
+ }
1779
+ });
1780
+ return {
1781
+ c: parts.length === 0 ? "\"\"" : `(${parts.join(" ++ ")})`,
1782
+ t: STR
1783
+ };
1784
+ }
1785
+ case "UnaryExpression": {
1786
+ const a = this.expr(fn, e.argument, scope, want);
1787
+ if (e.operator === "-" && isInt(a.t)) return {
1788
+ c: `(-${a.c})`,
1789
+ t: a.t
1790
+ };
1791
+ if (e.operator === "!" && a.t.k === "bool") return {
1792
+ c: `(!${a.c})`,
1793
+ t: BOOL
1794
+ };
1795
+ return this.fail(fn, e.start, `the operator ${e.operator} is outside the subset`);
1796
+ }
1797
+ case "BinaryExpression": {
1798
+ if (e.left.type === "PrivateIdentifier") return this.fail(fn, e.start, "outside the subset");
1799
+ if (e.operator === "==" || e.operator === "!=") return this.fail(fn, e.start, `${e.operator} is outside the subset; use ${e.operator}=`);
1800
+ const nc = nullCheck(e);
1801
+ if (nc !== void 0) {
1802
+ const v = scope.get(nc.name);
1803
+ if (v === void 0 || v.t.k !== "opt") return this.fail(fn, e.start, `${nc.name} is not optional`);
1804
+ return {
1805
+ c: `${ident(nc.name)}.${nc.isNull ? "isNone" : "isSome"}`,
1806
+ t: BOOL
1807
+ };
1808
+ }
1809
+ if ((e.operator === "===" || e.operator === "!==") && (isNil(e.left) || isNil(e.right))) {
1810
+ const o = this.expr(fn, isNil(e.right) ? e.left : e.right, scope);
1811
+ if (o.t.k !== "opt") return this.fail(fn, e.start, "only optional values are compared with null or undefined");
1812
+ return {
1813
+ c: `${o.c}.${e.operator === "===" ? "isNone" : "isSome"}`,
1814
+ t: BOOL
1815
+ };
1816
+ }
1817
+ const a = this.expr(fn, e.left, scope, want !== void 0 && isInt(want) ? want : void 0);
1818
+ return this.binary(fn, e.operator, a, e.right, scope, e.start);
1819
+ }
1820
+ case "LogicalExpression": {
1821
+ if (e.operator === "??") {
1822
+ const a = this.expr(fn, e.left, scope);
1823
+ if (a.t.k !== "opt") return this.fail(fn, e.start, "?? needs an optional value on its left");
1824
+ const b = this.expr(fn, e.right, scope, a.t.item);
1825
+ return {
1826
+ c: `(${a.c}.getD ${b.c})`,
1827
+ t: a.t.item
1828
+ };
1829
+ }
1830
+ const a = this.expr(fn, e.left, scope, BOOL);
1831
+ const b = this.expr(fn, e.right, scope, BOOL);
1832
+ if (a.t.k !== "bool" || b.t.k !== "bool") return this.fail(fn, e.start, `${e.operator} needs booleans`);
1833
+ return {
1834
+ c: `(${a.c} ${e.operator} ${b.c})`,
1835
+ t: BOOL
1836
+ };
1837
+ }
1838
+ case "ConditionalExpression": {
1839
+ const c = this.cond(fn, e.test, scope);
1840
+ const a = this.expr(fn, e.consequent, scope, want);
1841
+ const b = this.expr(fn, e.alternate, scope, want ?? a.t);
1842
+ return {
1843
+ c: `(if ${c} then ${a.c} else ${b.c})`,
1844
+ t: a.t
1845
+ };
1846
+ }
1847
+ case "TSNonNullExpression": {
1848
+ const x = e.expression;
1849
+ if (x.type === "MemberExpression" && x.computed) {
1850
+ const xs = this.expr(fn, x.object, scope);
1851
+ if (xs.t.k === "list") {
1852
+ const i = this.expr(fn, x.property, scope);
1853
+ return {
1854
+ c: this.lifted(fn, `Ts.get ${xs.c} ${i.c}`),
1855
+ t: xs.t.item
1856
+ };
1857
+ }
1858
+ }
1859
+ const o = this.expr(fn, x, scope);
1860
+ if (o.t.k !== "opt") return this.fail(fn, e.start, "! applies to an optional value or xs[i]");
1861
+ return {
1862
+ c: this.lifted(fn, `Ts.unwrap ${o.c}`),
1863
+ t: o.t.item
1864
+ };
1865
+ }
1866
+ case "MemberExpression": return this.member(fn, e, scope);
1867
+ case "ArrayExpression": {
1868
+ const item = want?.k === "list" ? want.item : void 0;
1869
+ const parts = e.elements.map((x) => x === null || x.type === "SpreadElement" ? this.fail(fn, e.start, "holes and spreads are outside the subset") : this.expr(fn, x, scope, item));
1870
+ if (want?.k === "tuple") return {
1871
+ c: `(${e.elements.map((x, k) => x === null || x.type === "SpreadElement" ? this.fail(fn, e.start, "holes and spreads are outside the subset") : this.expr(fn, x, scope, want.items[k])).map((p) => p.c).join(", ")})`,
1872
+ t: want
1873
+ };
1874
+ const t = item ?? parts[0]?.t;
1875
+ if (t === void 0) return this.fail(fn, e.start, "annotate the type of an empty array");
1876
+ return {
1877
+ c: `[${parts.map((p) => p.c).join(", ")}]`,
1878
+ t: {
1879
+ k: "list",
1880
+ item: t
1881
+ }
1882
+ };
1883
+ }
1884
+ case "ObjectExpression": return this.object(fn, e, scope, want);
1885
+ case "CallExpression": return this.call(fn, e, scope, want);
1886
+ default: return this.fail(fn, e.start, `${e.type} is outside the subset`);
1887
+ }
1888
+ }
1889
+ object(fn, e, scope, want) {
1890
+ const entries = /* @__PURE__ */ new Map();
1891
+ for (const p of e.properties) {
1892
+ if (p.type !== "Property" || p.kind !== "init" || p.method || p.computed) return this.fail(fn, p.start, "only plain properties are in the subset");
1893
+ const k = p.key.type === "Identifier" ? p.key.name : p.key.type === "Literal" && typeof p.key.value === "string" ? p.key.value : this.fail(fn, p.start, "property keys must be names");
1894
+ entries.set(k, p.value);
1895
+ }
1896
+ const fieldsOf = (fields) => fields.map((f) => {
1897
+ const v = entries.get(f.key);
1898
+ if (v === void 0) return this.fail(fn, e.start, `the field ${f.key} is missing`);
1899
+ const x = this.expr(fn, v, scope, f.type).c;
1900
+ return `${ident(f.lean)} := ${f.nat ? `(${x}).toNat` : x}`;
1901
+ }).join(", ");
1902
+ if (want?.k === "struct") {
1903
+ for (const k of entries.keys()) if (!want.fields.some((f) => f.key === k)) this.fail(fn, e.start, `${want.ts} has no field ${k}`);
1904
+ return {
1905
+ c: `({ ${fieldsOf(want.fields)} } : ${leanType(want)})`,
1906
+ t: want
1907
+ };
1908
+ }
1909
+ if (want?.k === "ind") {
1910
+ const tag = entries.get(want.tagKey);
1911
+ if (tag === void 0 || tag.type !== "Literal" || typeof tag.value !== "string") return this.fail(fn, e.start, `the ${want.tagKey} of an inductive value must be a string literal`);
1912
+ const name = tag.value;
1913
+ const v = want.variants.find((x) => x.name === name);
1914
+ if (v === void 0) return this.fail(fn, e.start, `${want.ts} has no constructor ${name}`);
1915
+ const args = v.fields.map((f) => {
1916
+ const x = entries.get(f.key);
1917
+ if (x === void 0) return this.fail(fn, e.start, `the field ${f.key} is missing`);
1918
+ const c = this.expr(fn, x, scope, f.type).c;
1919
+ return f.nat ? `(${c}).toNat` : c;
1920
+ });
1921
+ return {
1922
+ c: `(${leanType(want)}.${ident(name)}${args.map((a) => ` ${a}`).join("")})`,
1923
+ t: want
1924
+ };
1925
+ }
1926
+ return this.fail(fn, e.start, "an object literal needs a structure or inductive type from its context");
1927
+ }
1928
+ member(fn, e, scope) {
1929
+ if (e.optional) return this.fail(fn, e.start, "?. is outside the subset");
1930
+ const o = this.expr(fn, e.object, scope);
1931
+ if (e.computed) {
1932
+ if (o.t.k === "tuple") {
1933
+ const p = e.property;
1934
+ if (p.type !== "Literal" || typeof p.value !== "number") return this.fail(fn, e.start, "a tuple is indexed by a number literal");
1935
+ const t = o.t.items[p.value];
1936
+ if (t === void 0) return this.fail(fn, e.start, "the tuple has no such element");
1937
+ return {
1938
+ c: tupleProj(o.c, p.value, o.t.items.length),
1939
+ t
1940
+ };
1941
+ }
1942
+ if (o.t.k === "list") {
1943
+ const i = this.expr(fn, e.property, scope);
1944
+ if (!isInt(i.t)) return this.fail(fn, e.start, "an array index is a number");
1945
+ return {
1946
+ c: `(Ts.index ${o.c} ${i.c})`,
1947
+ t: {
1948
+ k: "opt",
1949
+ item: o.t.item,
1950
+ absent: "undefined"
1951
+ }
1952
+ };
1953
+ }
1954
+ return this.fail(fn, e.start, "only arrays and tuples are indexed");
1955
+ }
1956
+ if (e.property.type !== "Identifier") return this.fail(fn, e.start, "outside the subset");
1957
+ const name = e.property.name;
1958
+ if (name === "length") {
1959
+ if (o.t.k === "list") return {
1960
+ c: `(Ts.length ${o.c})`,
1961
+ t: NUM
1962
+ };
1963
+ if (o.t.k === "str") return {
1964
+ c: `(Ts.strLength ${o.c})`,
1965
+ t: NUM
1966
+ };
1967
+ }
1968
+ if (o.t.k === "struct") {
1969
+ const f = o.t.fields.find((x) => x.key === name);
1970
+ if (f === void 0) return this.fail(fn, e.start, `${o.t.ts} has no field ${name}`);
1971
+ const read = `${o.c}.${ident(f.lean)}`;
1972
+ return {
1973
+ c: f.nat ? `(${read} : Int)` : read,
1974
+ t: f.type
1975
+ };
1976
+ }
1977
+ if (o.t.k === "ind" && o.t.variants.length === 1) {
1978
+ const f = o.t.variants[0]?.fields.find((x) => x.key === name);
1979
+ if (f !== void 0 && e.object.type === "Identifier") {
1980
+ const read = ident(`${e.object.name}_${f.key}`);
1981
+ return {
1982
+ c: f.nat ? `(${read} : Int)` : read,
1983
+ t: f.type
1984
+ };
1985
+ }
1986
+ }
1987
+ return this.fail(fn, e.start, `the property ${name} is outside the subset`);
1988
+ }
1989
+ arrow(fn, a, scope, params) {
1990
+ if (a === void 0 || a.type !== "ArrowFunctionExpression" || a.async) return this.fail(fn, a?.start ?? 0, "the argument must be an arrow function");
1991
+ if (a.params.length !== params.length) return this.fail(fn, a.start, `the arrow function takes ${params.length} parameters`);
1992
+ const inner = new Map(scope);
1993
+ const names = a.params.map((p, k) => {
1994
+ if (p.type !== "Identifier") return this.fail(fn, p.start, "arrow parameters must be names");
1995
+ const t = params[k];
1996
+ if (t === void 0) return this.fail(fn, p.start, "outside the subset");
1997
+ inner.set(p.name, {
1998
+ t,
1999
+ mutable: false,
2000
+ local: false
2001
+ });
2002
+ return ident(p.name);
2003
+ });
2004
+ let body;
2005
+ if (a.body.type === "BlockStatement") {
2006
+ const only = a.body.body[0];
2007
+ if (a.body.body.length !== 1 || only?.type !== "ReturnStatement" || only.argument === null) return this.fail(fn, a.start, "the arrow function body must be one expression or one return");
2008
+ body = only.argument;
2009
+ } else body = a.body;
2010
+ const out = this.expr(fn, body, inner);
2011
+ if (out.c.includes("←")) return this.fail(fn, a.start, "an arrow function must not fail");
2012
+ return {
2013
+ ...out,
2014
+ ps: names.join(" ")
2015
+ };
2016
+ }
2017
+ args(fn, c) {
2018
+ return c.arguments.map((a) => a.type === "SpreadElement" ? this.fail(fn, a.start, "spread arguments are outside the subset") : a);
2019
+ }
2020
+ call(fn, c, scope, want) {
2021
+ if (c.optional) return this.fail(fn, c.start, "?. is outside the subset");
2022
+ const f = c.callee;
2023
+ const args = this.args(fn, c);
2024
+ if (f.type === "Identifier") {
2025
+ if (f.name === "BigInt" || f.name === "Number") {
2026
+ const x = args[0];
2027
+ if (args.length !== 1 || x === void 0) return this.fail(fn, c.start, `${f.name} takes one argument`);
2028
+ const o = this.expr(fn, x, scope);
2029
+ if (!isInt(o.t)) return this.fail(fn, c.start, `${f.name} converts a number or a bigint`);
2030
+ return {
2031
+ c: o.c,
2032
+ t: f.name === "BigInt" ? BIG : NUM
2033
+ };
2034
+ }
2035
+ if (f.name === "String") {
2036
+ const x = args[0];
2037
+ if (args.length !== 1 || x === void 0) return this.fail(fn, c.start, "String takes one argument");
2038
+ const o = this.expr(fn, x, scope);
2039
+ return {
2040
+ c: o.t.k === "str" ? o.c : `(Ts.str ${o.c})`,
2041
+ t: STR
2042
+ };
2043
+ }
2044
+ const target = this.fns.get(f.name);
2045
+ if (target === void 0) return this.fail(fn, c.start, `${f.name} is not a model function of this module`);
2046
+ if (args.length !== target.params.length) return this.fail(fn, c.start, `${f.name} takes ${target.params.length} arguments`);
2047
+ const parts = args.map((a, k) => {
2048
+ const p = target.params[k];
2049
+ if (p === void 0) return this.fail(fn, c.start, "outside the subset");
2050
+ const x = this.expr(fn, a, scope, p.type).c;
2051
+ return p.nat ? `(${x}).toNat` : x;
2052
+ });
2053
+ const call = `${ident(target.name)}${parts.map((p) => ` ${p}`).join("")}`;
2054
+ return {
2055
+ c: target.fails ? this.lifted(fn, call) : `(${call})`,
2056
+ t: target.ret
2057
+ };
2058
+ }
2059
+ if (f.type !== "MemberExpression" || f.computed || f.property.type !== "Identifier") return this.fail(fn, c.start, "this call is outside the subset");
2060
+ const m = f.property.name;
2061
+ if (f.object.type === "Identifier" && f.object.name === "Math" && !scope.has("Math")) {
2062
+ if ((m === "floor" || m === "trunc") && args.length === 1) {
2063
+ const d = args[0];
2064
+ if (d?.type === "BinaryExpression" && d.operator === "/") {
2065
+ const a = this.expr(fn, d.left, scope, NUM);
2066
+ const b = this.expr(fn, d.right, scope, NUM);
2067
+ if (a.t.k !== "num" || b.t.k !== "num") return this.fail(fn, c.start, `Math.${m}(a / b) divides numbers`);
2068
+ return {
2069
+ c: this.lifted(fn, `Ts.${m === "floor" ? "floorDiv" : "truncDiv"} ${a.c} ${b.c}`),
2070
+ t: NUM
2071
+ };
2072
+ }
2073
+ return this.fail(fn, c.start, `Math.${m} is only in the form Math.${m}(a / b)`);
2074
+ }
2075
+ if ((m === "max" || m === "min") && args.length === 2) {
2076
+ const [x, y] = args;
2077
+ if (x === void 0 || y === void 0) return this.fail(fn, c.start, "outside the subset");
2078
+ const a = this.expr(fn, x, scope, want);
2079
+ const b = this.expr(fn, y, scope, a.t);
2080
+ if (a.t.k !== "num" || b.t.k !== "num") return this.fail(fn, c.start, `Math.${m} takes numbers`);
2081
+ return {
2082
+ c: `(${m} ${a.c} ${b.c})`,
2083
+ t: NUM
2084
+ };
2085
+ }
2086
+ if (m === "abs" && args.length === 1 && args[0] !== void 0) {
2087
+ const a = this.expr(fn, args[0], scope, NUM);
2088
+ if (a.t.k !== "num") return this.fail(fn, c.start, "Math.abs takes a number");
2089
+ return {
2090
+ c: `(Ts.abs ${a.c})`,
2091
+ t: NUM
2092
+ };
2093
+ }
2094
+ return this.fail(fn, c.start, `Math.${m} is outside the subset`);
2095
+ }
2096
+ const o = this.expr(fn, f.object, scope);
2097
+ if (o.t.k === "str" && (m === "startsWith" || m === "endsWith" || m === "includes") && args.length === 1) {
2098
+ const x = args[0];
2099
+ if (x === void 0) return this.fail(fn, c.start, "outside the subset");
2100
+ const a = this.expr(fn, x, scope, STR);
2101
+ if (a.t.k !== "str") return this.fail(fn, c.start, `${m} takes a string`);
2102
+ return {
2103
+ c: `(Ts.${m} ${o.c} ${a.c})`,
2104
+ t: BOOL
2105
+ };
2106
+ }
2107
+ if (o.t.k !== "list") return this.fail(fn, c.start, `the method ${m} is outside the subset`);
2108
+ const item = o.t.item;
2109
+ if (m === "includes" && args.length === 1 && args[0] !== void 0) {
2110
+ const a = this.expr(fn, args[0], scope, item);
2111
+ return {
2112
+ c: `(${o.c}.contains ${a.c})`,
2113
+ t: BOOL
2114
+ };
2115
+ }
2116
+ if (m === "map" && args.length === 1) {
2117
+ const a = this.arrow(fn, args[0], scope, [item]);
2118
+ return {
2119
+ c: `(${o.c}.map fun ${a.ps} => ${a.c})`,
2120
+ t: {
2121
+ k: "list",
2122
+ item: a.t
2123
+ }
2124
+ };
2125
+ }
2126
+ if ((m === "filter" || m === "some" || m === "every") && args.length === 1) {
2127
+ const a = this.arrow(fn, args[0], scope, [item]);
2128
+ if (a.t.k !== "bool") return this.fail(fn, c.start, `the arrow function of ${m} returns a boolean`);
2129
+ const lean = m === "filter" ? "filter" : m === "some" ? "any" : "all";
2130
+ return {
2131
+ c: `(${o.c}.${lean} fun ${a.ps} => ${a.c})`,
2132
+ t: m === "filter" ? o.t : BOOL
2133
+ };
2134
+ }
2135
+ if (m === "reduce" && args.length === 2 && args[1] !== void 0) {
2136
+ const init = this.expr(fn, args[1], scope, want);
2137
+ const a = this.arrow(fn, args[0], scope, [init.t, item]);
2138
+ return {
2139
+ c: `(${o.c}.foldl (fun ${a.ps} => ${a.c}) ${init.c})`,
2140
+ t: init.t
2141
+ };
2142
+ }
2143
+ return this.fail(fn, c.start, `the method ${m} is outside the subset`);
2144
+ }
2145
+ };
2146
+ function isAnyNode(x) {
2147
+ return typeof x === "object" && x !== null && typeof Reflect.get(x, "type") === "string";
2148
+ }
2149
+ function walk(node, visit) {
2150
+ if (Array.isArray(node)) {
2151
+ for (const x of node) walk(x, visit);
2152
+ return;
2153
+ }
2154
+ if (typeof node !== "object" || node === null) return;
2155
+ if (isAnyNode(node)) visit(node);
2156
+ for (const [k, v] of Object.entries(node)) if (k !== "parent") walk(v, visit);
2157
+ }
2158
+ function assignedNames(node) {
2159
+ const out = /* @__PURE__ */ new Set();
2160
+ walk(node, (n) => {
2161
+ const target = n.type === "AssignmentExpression" ? n["left"] : n.type === "UpdateExpression" ? n["argument"] : null;
2162
+ if (typeof target === "object" && target !== null && Reflect.get(target, "type") === "Identifier") {
2163
+ const name = Reflect.get(target, "name");
2164
+ if (typeof name === "string") out.add(name);
2165
+ }
2166
+ });
2167
+ return out;
2168
+ }
2169
+ function identifiers(node) {
2170
+ const out = /* @__PURE__ */ new Set();
2171
+ walk(node, (n) => {
2172
+ if (n.type === "Identifier" && typeof n["name"] === "string") out.add(n["name"]);
2173
+ });
2174
+ return out;
2175
+ }
2176
+ function astHash(node) {
2177
+ return JSON.stringify(node, (k, v) => k === "start" || k === "end" || k === "parent" || k === "range" || k === "loc" ? void 0 : typeof v === "bigint" ? `${v}n` : v);
2178
+ }
2179
+ // src/verify/check.ts
2180
+ const STATUSES = [
2181
+ "proved",
2182
+ "sorry",
2183
+ "axioms",
2184
+ "failed",
2185
+ "missing",
2186
+ "mismatch",
2187
+ "unextracted",
2188
+ "stale"
2189
+ ];
2190
+ function isStatus(s) {
2191
+ return typeof s === "string" && STATUSES.includes(s);
2192
+ }
2193
+ function isDesc(x) {
2194
+ return isRecord(x) && typeof x["kind"] === "string";
2195
+ }
2196
+ const LAKEFILE_EXTRA = `
2197
+ [[lean_lib]]
2198
+ name = "LeanTsLib"
2199
+
2200
+ [[lean_lib]]
2201
+ name = "LeanTsModel"
2202
+
2203
+ [[lean_lib]]
2204
+ name = "Proofs"
2205
+ globs = ["Proofs.+"]
2206
+ `;
2207
+ function lineStarts(text) {
2208
+ const starts = [0];
2209
+ for (let i = 0; i < text.length; i++) if (text[i] === "\n") starts.push(i + 1);
2210
+ return starts;
2211
+ }
2212
+ function locator(file, text) {
2213
+ const starts = lineStarts(text);
2214
+ return (offset) => {
2215
+ let lo = 0;
2216
+ let hi = starts.length - 1;
2217
+ while (lo < hi) {
2218
+ const mid = lo + hi + 1 >> 1;
2219
+ if ((starts[mid] ?? 0) <= offset) lo = mid;
2220
+ else hi = mid - 1;
2221
+ }
2222
+ return `${file}:${lo + 1}:${offset - (starts[lo] ?? 0) + 1}`;
2223
+ };
2224
+ }
2225
+ function tsSpecifierFile(file, spec) {
2226
+ return resolve(dirname(file), spec);
2227
+ }
2228
+ function readSource(root, file) {
2229
+ const text = readFileSync(file, "utf8");
2230
+ const where = locator(file, text);
2231
+ const parsed = parseSync(file, text, {
2232
+ lang: "ts",
2233
+ sourceType: "module",
2234
+ preserveParens: false
2235
+ });
2236
+ const err = parsed.errors[0];
2237
+ if (err !== void 0) throw new SyncError(`${where(err.labels[0]?.start ?? 0)}: cannot parse: ${err.message}`, 252);
2238
+ const imports = /* @__PURE__ */ new Map();
2239
+ const fns = /* @__PURE__ */ new Map();
2240
+ const modelNames = /* @__PURE__ */ new Set();
2241
+ const verifyNamespaces = /* @__PURE__ */ new Set();
2242
+ for (const s of parsed.program.body) {
2243
+ if (s.type === "ImportDeclaration") {
2244
+ const from = s.source.value.startsWith(".") ? tsSpecifierFile(file, s.source.value) : s.source.value;
2245
+ for (const sp of s.specifiers) {
2246
+ if (sp.type === "ImportNamespaceSpecifier") imports.set(sp.local.name, {
2247
+ from,
2248
+ exportName: null
2249
+ });
2250
+ else if (sp.type === "ImportSpecifier") {
2251
+ const name = sp.imported.type === "Literal" ? sp.imported.value : sp.imported.name;
2252
+ imports.set(sp.local.name, {
2253
+ from,
2254
+ exportName: name
2255
+ });
2256
+ if (from === "leanfran/verify" && name === "model") modelNames.add(sp.local.name);
2257
+ }
2258
+ if (sp.type === "ImportNamespaceSpecifier" && from === "leanfran/verify") verifyNamespaces.add(sp.local.name);
2259
+ }
2260
+ continue;
2261
+ }
2262
+ const d = s.type === "ExportNamedDeclaration" ? s.declaration : s;
2263
+ if (d === null) continue;
2264
+ if (d.type === "FunctionDeclaration" && d.id !== null) fns.set(d.id.name, d);
2265
+ if (d.type === "VariableDeclaration" && d.kind === "const") {
2266
+ for (const x of d.declarations) if (x.id.type === "Identifier" && x.init?.type === "ArrowFunctionExpression") fns.set(x.id.name, x.init);
2267
+ }
2268
+ }
2269
+ const module = posixRelative(root, file);
2270
+ const models = [];
2271
+ const specRef = (e, label) => {
2272
+ const bad = () => {
2273
+ throw new SyncError(`${where(e.start)}: the ${label} specification must be a function of a generated module (a named import or a property of a namespace import of _lean/)`, 252);
2274
+ };
2275
+ if (e.type === "Identifier") {
2276
+ const i = imports.get(e.name);
2277
+ if (i === void 0 || i.exportName === null) return bad();
2278
+ return {
2279
+ exportName: i.exportName,
2280
+ outFile: i.from,
2281
+ at: e.start
2282
+ };
2283
+ }
2284
+ if (e.type === "MemberExpression" && !e.computed && e.object.type === "Identifier" && e.property.type === "Identifier") {
2285
+ const i = imports.get(e.object.name);
2286
+ if (i === void 0 || i.exportName !== null) return bad();
2287
+ return {
2288
+ exportName: e.property.name,
2289
+ outFile: i.from,
2290
+ at: e.start
2291
+ };
2292
+ }
2293
+ return bad();
2294
+ };
2295
+ new Visitor({ CallExpression(c) {
2296
+ const f = c.callee;
2297
+ if (!(f.type === "Identifier" && modelNames.has(f.name) || f.type === "MemberExpression" && !f.computed && f.object.type === "Identifier" && verifyNamespaces.has(f.object.name) && f.property.type === "Identifier" && f.property.name === "model")) return;
2298
+ const [target, options, ...rest] = c.arguments;
2299
+ if (target?.type !== "Identifier" || options?.type !== "ObjectExpression" || rest.length !== 0) throw new SyncError(`${where(c.start)}: model takes a function of the module and an object literal`, 252);
2300
+ const fnNode = fns.get(target.name);
2301
+ if (fnNode === void 0) throw new SyncError(`${where(target.start)}: ${target.name} must be a function declaration or a const arrow function of the module`, 252);
2302
+ let refines;
2303
+ let requires;
2304
+ const ensures = [];
2305
+ for (const p of options.properties) {
2306
+ if (p.type !== "Property" || p.computed || p.key.type !== "Identifier") throw new SyncError(`${where(p.start)}: the options of model must be plain properties`, 252);
2307
+ if (p.key.name === "refines") refines = specRef(p.value, "refines");
2308
+ else if (p.key.name === "requires") requires = specRef(p.value, "requires");
2309
+ else if (p.key.name === "ensures") {
2310
+ if (p.value.type !== "ObjectExpression") throw new SyncError(`${where(p.value.start)}: ensures must be an object literal of labelled specifications`, 252);
2311
+ for (const q of p.value.properties) {
2312
+ if (q.type !== "Property" || q.computed || q.key.type !== "Identifier") throw new SyncError(`${where(q.start)}: the labels of ensures must be names`, 252);
2313
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(q.key.name) || q.key.name === "refines" || q.key.name === "returnsNat") throw new SyncError(`${where(q.start)}: ${q.key.name} cannot be a label of ensures`, 252);
2314
+ ensures.push([q.key.name, specRef(q.value, q.key.name)]);
2315
+ }
2316
+ } else throw new SyncError(`${where(p.start)}: unknown option ${p.key.name} of model`, 252);
2317
+ }
2318
+ models.push({
2319
+ file,
2320
+ module,
2321
+ fn: target.name,
2322
+ fnNode,
2323
+ refines,
2324
+ requires,
2325
+ ensures,
2326
+ hash: createHash("sha256").update(astHash({
2327
+ fn: fnNode,
2328
+ options
2329
+ })).digest("hex"),
2330
+ at: c.start
2331
+ });
2332
+ } }).visit(parsed.program);
2333
+ return {
2334
+ file,
2335
+ where,
2336
+ module,
2337
+ program: parsed.program,
2338
+ imports,
2339
+ fns,
2340
+ models
2341
+ };
2342
+ }
2343
+ function readSources(root) {
2344
+ return tsFiles(join(root, "src")).map((f) => readSource(root, f));
2345
+ }
2346
+ function blockOf(pkg, file) {
2347
+ const f = file.endsWith(".ts") ? file : `${file}.ts`;
2348
+ return pkg.blocks.find((b) => b.outFile === f) ?? pkg.blocks.find((b) => aliasFile(b) === f && pkg.blocks.filter((x) => x.module === b.module).length === 1);
2349
+ }
2350
+ function specBlock(pkg, src, ref) {
2351
+ const b = blockOf(pkg, ref.outFile);
2352
+ if (b === void 0) throw new SyncError(`${src.where(ref.at)}: ${ref.outFile} is not a module generated from a lean(...) block`, 252);
2353
+ return b;
2354
+ }
2355
+ function specHash(pkg, src, m) {
2356
+ const refs = [
2357
+ m.refines,
2358
+ m.requires,
2359
+ ...m.ensures.map(([, r]) => r)
2360
+ ].filter((r) => r !== void 0);
2361
+ const keys = [...new Set(refs.map((r) => specBlock(pkg, src, r).key))].toSorted();
2362
+ return createHash("sha256").update(JSON.stringify({
2363
+ fn: m.hash,
2364
+ blocks: keys
2365
+ })).digest("hex");
2366
+ }
2367
+ function modelModule(module) {
2368
+ return ["LeanTsModel", ...moduleParts(module)];
2369
+ }
2370
+ function qualified(m) {
2371
+ return `${m.module}:${m.fn}`;
2372
+ }
2373
+ const DESCS_CHILD = `
2374
+ import { pathToFileURL } from "node:url"
2375
+ const ser = (d0, stack) => {
2376
+ let d = d0
2377
+ while (d.kind === "ref") d = d.get()
2378
+ if ((d.kind === "struct" || d.kind === "inductive") && stack.includes(d.name)) return { kind: "recursive", name: d.name }
2379
+ const st = d.kind === "struct" || d.kind === "inductive" ? [...stack, d.name] : stack
2380
+ const v = (x) => ({ name: x.name, fields: x.fields.map((f) => ({ key: f.key, omitNone: f.omitNone, flat: f.flat, desc: ser(f.desc, st) })) })
2381
+ switch (d.kind) {
2382
+ case "list": case "array": case "option": return { ...d, item: ser(d.item, st) }
2383
+ case "prod": return { kind: "prod", fst: ser(d.fst, st), snd: ser(d.snd, st) }
2384
+ case "except": return { kind: "except", error: ser(d.error, st), value: ser(d.value, st) }
2385
+ case "struct": return { kind: "struct", name: d.name, trivial: d.trivial, variant: v(d.variant) }
2386
+ case "inductive": return { kind: "inductive", name: d.name, tagKey: d.tagKey, variants: d.variants.map(v) }
2387
+ case "subtype": return { kind: "subtype", name: d.name, base: ser(d.base, st) }
2388
+ case "model": return { kind: "model", name: d.name, key: d.key }
2389
+ case "fin": return { kind: "fin", bound: String(d.bound) }
2390
+ default: return { kind: d.kind, ...(d.bits === undefined ? {} : { bits: d.bits }), ...(d.name === undefined ? {} : { name: d.name }), ...(d.ctors === undefined ? {} : { ctors: d.ctors }) }
2391
+ }
2392
+ }
2393
+ const [first, ...files] = JSON.parse(process.argv[1])
2394
+ for (const f of first) await import(pathToFileURL(f).href)
2395
+ const out = {}
2396
+ for (const f of files) {
2397
+ const m = await import(pathToFileURL(f).href)
2398
+ out[f] = {}
2399
+ for (const [k, x] of Object.entries(m)) {
2400
+ const d = (typeof x === "object" && x !== null) || typeof x === "function" ? x.desc : undefined
2401
+ if (typeof d === "object" && d !== null && typeof d.kind === "string") out[f][k] = ser(d, [])
2402
+ }
2403
+ }
2404
+ process.stdout.write(JSON.stringify(out))
2405
+ `;
2406
+ function loadDescs(pkg, sources) {
2407
+ const users = sources.filter((s) => s.models.length !== 0);
2408
+ const files = /* @__PURE__ */ new Set();
2409
+ for (const s of users) for (const i of s.imports.values()) if (blockOf(pkg, i.from) !== void 0) files.add(i.from.endsWith(".ts") ? i.from : `${i.from}.ts`);
2410
+ const out = /* @__PURE__ */ new Map();
2411
+ if (files.size === 0) return out;
2412
+ const r = spawnSync(process.execPath, [
2413
+ "--input-type=module",
2414
+ "-e",
2415
+ DESCS_CHILD,
2416
+ JSON.stringify([users.map((s) => s.file), ...files])
2417
+ ], {
2418
+ encoding: "utf8",
2419
+ maxBuffer: 1 << 28
2420
+ });
2421
+ if (r.status !== 0) throw new SyncError(`reading the types of the generated modules: ${r.stderr}`, 254);
2422
+ const parsed = JSON.parse(r.stdout);
2423
+ if (!isRecord(parsed)) throw new SyncError("reading the types of the generated modules returned no object", 255);
2424
+ for (const [f, ds] of Object.entries(parsed)) {
2425
+ const m = /* @__PURE__ */ new Map();
2426
+ if (isRecord(ds)) {
2427
+ for (const [k, d] of Object.entries(ds)) if (isDesc(d)) m.set(k, d);
2428
+ }
2429
+ out.set(f, m);
2430
+ }
2431
+ return out;
2432
+ }
2433
+ function descType(d, names, seen) {
2434
+ const r = resolve$1(d);
2435
+ const fields = (fs) => fs.flatMap((f) => {
2436
+ if (f.flat) {
2437
+ const inner = descType(f.desc, names, seen);
2438
+ return inner.k === "struct" ? [...inner.fields] : [];
2439
+ }
2440
+ const fr = resolve$1(f.desc);
2441
+ return [{
2442
+ key: f.key,
2443
+ lean: f.omitNone ? `${f.key}?` : f.key,
2444
+ type: descType(f.desc, names, seen),
2445
+ nat: fr.kind === "nat"
2446
+ }];
2447
+ });
2448
+ const leanOf = (name) => {
2449
+ const l = names.get(name);
2450
+ if (l === void 0) throw new TranslateError(`the Lean name of the type ${name} is unknown`);
2451
+ return l;
2452
+ };
2453
+ switch (r.kind) {
2454
+ case "nat":
2455
+ case "int": return BIG;
2456
+ case "bool": return BOOL;
2457
+ case "string": return STR;
2458
+ case "list": return {
2459
+ k: "list",
2460
+ item: descType(r.item, names, seen)
2461
+ };
2462
+ case "option": return {
2463
+ k: "opt",
2464
+ item: descType(r.item, names, seen),
2465
+ absent: r.absent
2466
+ };
2467
+ case "prod": return {
2468
+ k: "tuple",
2469
+ items: [descType(r.fst, names, seen), descType(r.snd, names, seen)]
2470
+ };
2471
+ case "struct":
2472
+ if (seen.has(r.name)) throw new TranslateError(`the recursive type ${r.name} is outside the subset`);
2473
+ return {
2474
+ k: "struct",
2475
+ lean: leanOf(r.name),
2476
+ ts: r.name,
2477
+ fields: fields(r.variant.fields)
2478
+ };
2479
+ case "enum": return {
2480
+ k: "enum",
2481
+ lean: leanOf(r.name),
2482
+ ts: r.name,
2483
+ ctors: r.ctors
2484
+ };
2485
+ case "inductive": {
2486
+ if (seen.has(r.name)) throw new TranslateError(`the recursive type ${r.name} is outside the subset`);
2487
+ const inner = /* @__PURE__ */ new Set([...seen, r.name]);
2488
+ return {
2489
+ k: "ind",
2490
+ lean: leanOf(r.name),
2491
+ ts: r.name,
2492
+ tagKey: r.tagKey,
2493
+ variants: r.variants.map((v) => ({
2494
+ name: v.name,
2495
+ fields: v.fields.map((f) => ({
2496
+ key: f.key,
2497
+ lean: f.key,
2498
+ type: descType(f.desc, names, inner),
2499
+ nat: resolve$1(f.desc).kind === "nat"
2500
+ }))
2501
+ }))
2502
+ };
2503
+ }
2504
+ default: throw new TranslateError(`the Lean type of kind ${r.kind} is outside the subset`);
2505
+ }
2506
+ }
2507
+ function nullableOf(s) {
2508
+ const any = s["anyOf"];
2509
+ if (Array.isArray(any) && any.length === 2) {
2510
+ const other = any.find((x) => !(isRecord(x) && x["type"] === "null"));
2511
+ if (isRecord(other) && any.some((x) => isRecord(x) && x["type"] === "null")) return other;
2512
+ }
2513
+ const t = s["type"];
2514
+ if (Array.isArray(t) && t.length === 2 && t.includes("null")) return {
2515
+ ...s,
2516
+ type: t.find((x) => x !== "null")
2517
+ };
2518
+ }
2519
+ function jsonType(s, where) {
2520
+ if (!isRecord(s)) throw new TranslateError(`${where}: a property schema is not an object`);
2521
+ const min = s["minimum"];
2522
+ const ex = s["exclusiveMinimum"];
2523
+ const lo = typeof min === "number" ? min : typeof ex === "number" ? Math.floor(ex) + 1 : void 0;
2524
+ switch (s["type"]) {
2525
+ case "integer": return {
2526
+ t: NUM,
2527
+ nat: lo !== void 0 && lo >= 0
2528
+ };
2529
+ case "string": return {
2530
+ t: STR,
2531
+ nat: false
2532
+ };
2533
+ case "boolean": return {
2534
+ t: BOOL,
2535
+ nat: false
2536
+ };
2537
+ case "array": return {
2538
+ t: {
2539
+ k: "list",
2540
+ item: jsonType(s["items"], where).t
2541
+ },
2542
+ nat: false
2543
+ };
2544
+ default: throw new TranslateError(`${where}: the model property ${JSON.stringify(s)} is outside the subset leanfran translates`);
2545
+ }
2546
+ }
2547
+ function modelStruct(json, lean, ts, where) {
2548
+ if (!isRecord(json) || !isRecord(json["properties"])) throw new TranslateError(`${where}: the model ${ts} is not an object schema`);
2549
+ const req = json["required"];
2550
+ const required = new Set(Array.isArray(req) ? req.filter((x) => typeof x === "string") : []);
2551
+ return {
2552
+ k: "struct",
2553
+ lean,
2554
+ ts,
2555
+ fields: Object.entries(json["properties"]).map(([key, raw]) => {
2556
+ if (!isRecord(raw)) throw new TranslateError(`${where}: the property ${key} of ${ts} is not an object`);
2557
+ const inner = nullableOf(raw);
2558
+ const { t, nat } = jsonType(inner ?? raw, where);
2559
+ if (!required.has(key)) return {
2560
+ key,
2561
+ lean: `${key}?`,
2562
+ type: {
2563
+ k: "opt",
2564
+ item: t,
2565
+ absent: "undefined"
2566
+ },
2567
+ nat: false
2568
+ };
2569
+ if (inner !== void 0) return {
2570
+ key,
2571
+ lean: key,
2572
+ type: {
2573
+ k: "opt",
2574
+ item: t,
2575
+ absent: "null"
2576
+ },
2577
+ nat: false
2578
+ };
2579
+ return {
2580
+ key,
2581
+ lean: key,
2582
+ type: t,
2583
+ nat
2584
+ };
2585
+ })
2586
+ };
2587
+ }
2588
+ function typeResolver(pkg, src, summaries, descs) {
2589
+ return {
2590
+ reference(name, qualifier, at) {
2591
+ const local = qualifier ?? name;
2592
+ const i = src.imports.get(local);
2593
+ if (i === void 0) return void 0;
2594
+ const exportName = qualifier === void 0 ? i.exportName : i.exportName === null ? name : void 0;
2595
+ if (exportName === void 0 || exportName === null) return void 0;
2596
+ if (i.from === "leanfran/schema" && (exportName === "Nat" || exportName === "Int")) return BIG;
2597
+ const b = blockOf(pkg, i.from);
2598
+ if (b === void 0) return void 0;
2599
+ if (summaries === void 0 || descs === void 0) return {
2600
+ k: "struct",
2601
+ lean: exportName,
2602
+ ts: exportName,
2603
+ fields: []
2604
+ };
2605
+ const summary = summaries.get(b.outFile);
2606
+ const d = descs.get(i.from.endsWith(".ts") ? i.from : `${i.from}.ts`)?.get(exportName);
2607
+ if (summary === void 0 || d === void 0) throw new TranslateError(`${src.where(at)}: ${exportName} is not a type generated from ${b.name}`);
2608
+ return descType(d, new Map(summary.types.map((t) => [t.typescript, t.lean])), /* @__PURE__ */ new Set());
2609
+ },
2610
+ model(name, at) {
2611
+ const i = src.imports.get(name);
2612
+ const from = i === void 0 ? src.file : i.from;
2613
+ const exportName = i === void 0 ? name : i.exportName;
2614
+ for (const b of pkg.blocks) for (const m of b.models) if (m.from === from && m.exportName === exportName) {
2615
+ const json = b.inputs.models[m.name];
2616
+ if (json === void 0) throw new TranslateError(`${src.where(at)}: no JSON Schema of the model ${m.name}`);
2617
+ return modelStruct(json, `${leanName(["LeanTsModels", ...moduleParts(b.module)])}.${leanIdent$1(m.name)}`, m.name, src.where(at));
2618
+ }
2619
+ }
2620
+ };
2621
+ }
2622
+ function specName(pkg, src, ref, summaries) {
2623
+ const b = specBlock(pkg, src, ref);
2624
+ const p = summaries.get(b.outFile)?.public.find((x) => x.typescript === ref.exportName);
2625
+ if (p === void 0) throw new SyncError(`${src.where(ref.at)}: ${ref.exportName} is not a public function of the block ${b.name}`, 252);
2626
+ return {
2627
+ lean: p.lean,
2628
+ module: leanName(b.leanModule)
2629
+ };
2630
+ }
2631
+ function obligations(m, fn, pkg, src, summaries) {
2632
+ const binders = fn.params.map((p) => `(${ident(p.name)} : ${p.nat ? "Nat" : leanType(p.type)})`);
2633
+ const args = fn.params.map((p) => ident(p.name)).join(" ");
2634
+ const a = args === "" ? "" : ` ${args}`;
2635
+ const call = `(${ident(fn.name)}${a})`;
2636
+ const imports = /* @__PURE__ */ new Set();
2637
+ const spec = (r) => {
2638
+ const n = specName(pkg, src, r, summaries);
2639
+ imports.add(n.module);
2640
+ return `_root_.${n.lean}`;
2641
+ };
2642
+ const pre = m.requires === void 0 ? "" : `${spec(m.requires)}${a} = true → `;
2643
+ const wrap = (body) => binders.length === 0 ? `${pre}${body}` : `∀ ${binders.join(" ")}, ${pre}${body}`;
2644
+ const ret = leanType(fn.ret);
2645
+ const props = /* @__PURE__ */ new Map();
2646
+ if (m.refines !== void 0) {
2647
+ const expected = `(${spec(m.refines)}${a} : ${ret})`;
2648
+ props.set("refines", wrap(fn.fails ? `${call} = Except.ok ${expected}` : `${call} = ${expected}`));
2649
+ }
2650
+ for (const [label, r] of m.ensures) {
2651
+ const e = spec(r);
2652
+ props.set(label, wrap(fn.fails ? `∀ r, ${call} = Except.ok r → ${e}${a} r = true` : `${e}${a} ${call} = true`));
2653
+ }
2654
+ if (fn.retNat) props.set("returnsNat", wrap(fn.fails ? `∀ r, ${call} = Except.ok r → 0 ≤ r` : `0 ≤ ${call}`));
2655
+ return {
2656
+ props,
2657
+ imports
2658
+ };
2659
+ }
2660
+ function libDir() {
2661
+ const here = dirname(fileURLToPath(import.meta.url));
2662
+ const dev = join(here, "..", "lean");
2663
+ return existsSync(join(dev, "LeanTsLib")) ? dev : join(here, "..", "src", "lean");
2664
+ }
2665
+ function leanFiles(dir) {
2666
+ if (!existsSync(dir)) return [];
2667
+ const out = [];
2668
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
2669
+ const p = join(dir, e.name);
2670
+ if (e.isDirectory()) out.push(...leanFiles(p));
2671
+ else if (e.name.endsWith(".lean")) out.push(p);
2672
+ }
2673
+ return out.toSorted();
2674
+ }
2675
+ function lockFile(root) {
2676
+ return join(root, "leanfran.lock");
2677
+ }
2678
+ function readLock(root) {
2679
+ const f = lockFile(root);
2680
+ if (!existsSync(f)) return {};
2681
+ const j = JSON.parse(readFileSync(f, "utf8"));
2682
+ if (!isRecord(j)) throw new SyncError(`${f}: not a JSON object`, 254);
2683
+ const out = {};
2684
+ for (const [k, v] of Object.entries(j)) {
2685
+ if (!isRecord(v) || typeof v["spec_hash"] !== "string" || typeof v["lean"] !== "string" || !isRecord(v["obligations"])) throw new SyncError(`${f}: the entry ${k} is malformed`, 254);
2686
+ const obls = {};
2687
+ for (const [l, s] of Object.entries(v["obligations"])) {
2688
+ if (!isStatus(s)) throw new SyncError(`${f}: the entry ${k} has an unknown status for ${l}`, 254);
2689
+ obls[l] = s;
2690
+ }
2691
+ const c = v["csimp"];
2692
+ const csimp = isRecord(c) && typeof c["spec"] === "string" && typeof c["module"] === "string" && Array.isArray(c["modes"]) && c["modes"].every((x) => typeof x === "string") ? {
2693
+ spec: c["spec"],
2694
+ module: c["module"],
2695
+ modes: c["modes"].map(String)
2696
+ } : void 0;
2697
+ if (c !== void 0 && csimp === void 0) throw new SyncError(`${f}: the csimp of ${k} is malformed`, 254);
2698
+ out[k] = {
2699
+ spec_hash: v["spec_hash"],
2700
+ lean: v["lean"],
2701
+ obligations: obls,
2702
+ ...csimp === void 0 ? {} : { csimp }
2703
+ };
2704
+ }
2705
+ return out;
2706
+ }
2707
+ function moduleFileOf(ws, parts) {
2708
+ return join(ws, `${parts.join("/")}.lean`);
2709
+ }
2710
+ async function checkPackage(dir, cliPath, log) {
2711
+ const cli = leanTypescriptCli(cliPath);
2712
+ const { pkg, summaries } = await syncPackage(dir, cliPath, log, csimpFiles);
2713
+ const before = canonicalJson(Object.fromEntries(csimpFiles(pkg)));
2714
+ const ws = join(pkg.root, ".leanfran", "workspace");
2715
+ const sources = readSources(pkg.root).filter((s) => s.models.length !== 0);
2716
+ const descs = loadDescs(pkg, sources);
2717
+ rmSync(join(ws, "LeanTsLib"), {
2718
+ recursive: true,
2719
+ force: true
2720
+ });
2721
+ cpSync(join(libDir(), "LeanTsLib"), join(ws, "LeanTsLib"), { recursive: true });
2722
+ writeFileSync(join(ws, "LeanTsLib.lean"), "import LeanTsLib.Ts\n");
2723
+ rmSync(join(ws, "LeanTsModel"), {
2724
+ recursive: true,
2725
+ force: true
2726
+ });
2727
+ rmSync(join(ws, "Proofs"), {
2728
+ recursive: true,
2729
+ force: true
2730
+ });
2731
+ const proofsSrc = join(pkg.root, "lean", "Proofs");
2732
+ if (existsSync(proofsSrc)) cpSync(proofsSrc, join(ws, "Proofs"), { recursive: true });
2733
+ else mkdirSync(join(ws, "Proofs"), { recursive: true });
2734
+ writeFileSync(join(ws, "Proofs", "Empty.lean"), "");
2735
+ writeFileSync(join(ws, "lakefile.toml"), readFileSync(join(ws, "lakefile.toml"), "utf8") + LAKEFILE_EXTRA);
2736
+ const refs = [];
2737
+ const modelModules = [];
2738
+ const hashes = /* @__PURE__ */ new Map();
2739
+ const candidates = /* @__PURE__ */ new Map();
2740
+ for (const src of sources) {
2741
+ const types = typeResolver(pkg, src, summaries, descs);
2742
+ const fns = src.models.map((m) => new Fn(m.fn, m.fnNode, src, types));
2743
+ const seen = /* @__PURE__ */ new Set();
2744
+ for (const m of src.models) {
2745
+ if (seen.has(m.fn)) throw new SyncError(`${src.where(m.at)}: ${m.fn} has two model(...) calls`, 252);
2746
+ seen.add(m.fn);
2747
+ }
2748
+ const defs = new Translator(fns, types).definitions();
2749
+ const parts = modelModule(src.module);
2750
+ const ns = leanName(parts);
2751
+ const imports = /* @__PURE__ */ new Set(["LeanTsLib"]);
2752
+ for (const i of src.imports.values()) {
2753
+ const b = blockOf(pkg, i.from);
2754
+ if (b !== void 0) imports.add(leanName(b.leanModule));
2755
+ }
2756
+ const body = [];
2757
+ src.models.forEach((m, k) => {
2758
+ const fn = fns[k];
2759
+ if (fn === void 0) return;
2760
+ const modes = fn.params.map((p) => modeOf(p.type));
2761
+ const target = `ts:${m.module}#${m.fn}(${modes.map((x) => x === "mixed" ? "_" : x).join(",")})`;
2762
+ body.push(`/-- \`${m.module}\` ${m.fn}, translated from TypeScript. -/\n@[extern ${JSON.stringify(target)}]\n${defs.get(m.fn) ?? ""}`);
2763
+ if (m.refines !== void 0 && m.requires === void 0 && !modes.includes("mixed")) {
2764
+ const n = specName(pkg, src, m.refines, summaries);
2765
+ candidates.set(qualified(m), {
2766
+ spec: n.lean,
2767
+ module: n.module,
2768
+ modes
2769
+ });
2770
+ }
2771
+ const o = obligations(m, fn, pkg, src, summaries);
2772
+ for (const i of o.imports) imports.add(i);
2773
+ for (const [label, prop] of o.props) {
2774
+ body.push(`abbrev ${ident(m.fn)}.obligation.${label} : Prop :=\n ${prop}`);
2775
+ refs.push({
2776
+ m,
2777
+ label,
2778
+ lean: `${parts.join(".")}.${m.fn}`
2779
+ });
2780
+ }
2781
+ hashes.set(qualified(m), specHash(pkg, src, m));
2782
+ });
2783
+ const text = [...imports].toSorted().map((i) => `import ${i}\n`).join("") + `\nnamespace ${ns}\n\n${body.join("\n\n")}\n\nend ${ns}\n`;
2784
+ const file = moduleFileOf(ws, parts);
2785
+ mkdirSync(dirname(file), { recursive: true });
2786
+ writeFileSync(file, text);
2787
+ modelModules.push(ns);
2788
+ }
2789
+ writeFileSync(join(ws, "LeanTsModel.lean"), modelModules.map((m) => `import ${m}\n`).join("") || "\n");
2790
+ const proofModules = leanFiles(join(ws, "Proofs")).map((p) => relative(ws, p).replace(/\.lean$/u, "").split(sep).map((c) => /^[A-Za-z_][A-Za-z0-9_]*$/u.test(c) ? c : `«${c}»`).join("."));
2791
+ writeFileSync(join(ws, "Proofs.lean"), proofModules.map((m) => `import ${m}\n`).join(""));
2792
+ const lake = process.env["LAKE"] ?? "lake";
2793
+ const built = run(lake, [
2794
+ "build",
2795
+ "LeanTsLib",
2796
+ "LeanTsModel"
2797
+ ], ws);
2798
+ if (built.status !== 0) {
2799
+ log(built.stdout + built.stderr);
2800
+ throw new SyncError("lake build of the translated functions failed", 254);
2801
+ }
2802
+ const failedText = [];
2803
+ const okProofs = [];
2804
+ for (const m of proofModules) {
2805
+ const r = run(lake, ["build", m], ws);
2806
+ if (r.status === 0) {
2807
+ okProofs.push(m);
2808
+ continue;
2809
+ }
2810
+ failedText.push(readFileSync(join(ws, `${m.replaceAll(/[«»]/gu, "").split(".").join("/")}.lean`), "utf8"));
2811
+ for (const line of (r.stdout + r.stderr).split("\n")) if (/^(error:| |⊢|case )/u.test(line) || line.includes(": error")) log(`leanfran: ${line}`);
2812
+ }
2813
+ const oblFile = join(ws, "obligations.json");
2814
+ writeFileSync(oblFile, JSON.stringify(refs.map((r) => ({
2815
+ model: r.lean,
2816
+ label: r.label
2817
+ }))));
2818
+ let results = [];
2819
+ if (refs.length !== 0) {
2820
+ const r = run(cli, [
2821
+ "obligations",
2822
+ "check",
2823
+ "--search-path",
2824
+ join(ws, ".lake", "build", "lib", "lean"),
2825
+ "--obligations",
2826
+ oblFile,
2827
+ "--modules",
2828
+ ...modelModules.map((m) => m.replaceAll(/[«»]/gu, "")),
2829
+ ...okProofs.map((m) => m.replaceAll(/[«»]/gu, ""))
2830
+ ]);
2831
+ if (r.status !== 0) {
2832
+ log(r.stderr);
2833
+ throw new SyncError("leanfran-typescript obligations check failed", r.status);
2834
+ }
2835
+ const parsed = JSON.parse(r.stdout);
2836
+ if (!Array.isArray(parsed) || parsed.length !== refs.length) throw new SyncError("leanfran-typescript obligations check returned an unexpected result", 255);
2837
+ results = parsed;
2838
+ }
2839
+ const lock = {};
2840
+ const rows = [];
2841
+ refs.forEach((ref, k) => {
2842
+ const res = results[k];
2843
+ const raw = isRecord(res) ? res["status"] : void 0;
2844
+ if (!isStatus(raw)) throw new SyncError(`leanfran-typescript obligations check returned no status for ${ref.lean} ${ref.label}`, 255);
2845
+ let status = raw;
2846
+ if (status === "missing" && failedText.some((t) => t.includes(`${ref.m.fn}.proof.${ref.label}`))) status = "failed";
2847
+ if (isRecord(res) && typeof res["detail"] === "string" && status === "mismatch") log(`leanfran: ${res["detail"]}`);
2848
+ const q = qualified(ref.m);
2849
+ const entry = lock[q] ?? {
2850
+ spec_hash: hashes.get(q) ?? "",
2851
+ lean: ref.lean,
2852
+ obligations: {}
2853
+ };
2854
+ entry.obligations[ref.label] = status;
2855
+ const cand = candidates.get(q);
2856
+ if (ref.label === "refines" && status === "proved" && cand !== void 0) entry.csimp = cand;
2857
+ lock[q] = entry;
2858
+ rows.push({
2859
+ fn: q,
2860
+ label: ref.label,
2861
+ status
2862
+ });
2863
+ });
2864
+ const sorted = Object.fromEntries(Object.entries(lock).toSorted(([a], [b]) => a.localeCompare(b)));
2865
+ writeFileSync(lockFile(pkg.root), JSON.stringify(sorted, null, 2) + "\n");
2866
+ if (canonicalJson(Object.fromEntries(csimpFiles(pkg))) !== before) await syncPackage(dir, cliPath, log, csimpFiles);
2867
+ return {
2868
+ rows,
2869
+ lock: sorted
2870
+ };
2871
+ }
2872
+ function modeOf(t) {
2873
+ const kinds = /* @__PURE__ */ new Set();
2874
+ const walk = (x) => {
2875
+ if (x.k === "num" || x.k === "big") kinds.add(x.k);
2876
+ else if (x.k === "list" || x.k === "opt") walk(x.item);
2877
+ else if (x.k === "tuple") x.items.forEach(walk);
2878
+ else if (x.k === "struct") x.fields.forEach((f) => walk(f.type));
2879
+ else if (x.k === "ind") x.variants.forEach((v) => v.fields.forEach((f) => walk(f.type)));
2880
+ };
2881
+ walk(t);
2882
+ if (kinds.has("num") && kinds.has("big")) return "mixed";
2883
+ return kinds.has("num") ? "n" : "_";
2884
+ }
2885
+ function csimpFiles(pkg) {
2886
+ const lock = readLock(pkg.root);
2887
+ const out = /* @__PURE__ */ new Map();
2888
+ for (const src of readSources(pkg.root)) {
2889
+ const parts = ["LeanTsCsimp", ...moduleParts(src.module)];
2890
+ const ns = leanName(parts);
2891
+ const imports = /* @__PURE__ */ new Set();
2892
+ const defs = [];
2893
+ for (const m of src.models) {
2894
+ const e = lock[qualified(m)];
2895
+ if (e?.csimp === void 0 || e.obligations["refines"] !== "proved") continue;
2896
+ if (e.spec_hash !== specHash(pkg, src, m)) continue;
2897
+ imports.add(e.csimp.module);
2898
+ const target = `ts:${m.module}#${m.fn}(${e.csimp.modes.join(",")})`;
2899
+ defs.push(`@[extern ${JSON.stringify(target)}]\ndef ${ident(m.fn)} := @_root_.${e.csimp.spec}\n\n@[csimp] theorem ${ident(m.fn)}.csimp : @_root_.${e.csimp.spec} = @${ident(m.fn)} := rfl`);
2900
+ }
2901
+ if (defs.length === 0) continue;
2902
+ out.set(`${parts.join("/")}.lean`, [...imports].toSorted().map((i) => `import ${i}\n`).join("") + `\nnamespace ${ns}\n\n${defs.join("\n\n")}\n\nend ${ns}\n`);
2903
+ }
2904
+ return out;
2905
+ }
2906
+ function statusModels(pkg) {
2907
+ const lock = readLock(pkg.root);
2908
+ const rows = [];
2909
+ for (const src of readSources(pkg.root)) for (const m of src.models) {
2910
+ const q = qualified(m);
2911
+ const entry = lock[q];
2912
+ const types = typeResolver(pkg, src, void 0, void 0);
2913
+ const fn = new Fn(m.fn, m.fnNode, src, types);
2914
+ const labels = [
2915
+ ...m.refines === void 0 ? [] : ["refines"],
2916
+ ...m.ensures.map(([l]) => l),
2917
+ ...fn.retNat ? ["returnsNat"] : []
2918
+ ];
2919
+ const stale = entry === void 0 || entry.spec_hash !== specHash(pkg, src, m);
2920
+ for (const label of labels) {
2921
+ const st = entry?.obligations[label];
2922
+ rows.push({
2923
+ fn: q,
2924
+ label,
2925
+ status: stale || st === void 0 ? "stale" : st
2926
+ });
2927
+ }
2928
+ }
2929
+ return rows;
2930
+ }
2931
+ export { statusModels as a, astHash as c, statusPackage as d, syncPackage as f, readSource as i, leanTypescriptCli as l, csimpFiles as n, BIG as o, SyncError as p, modelStruct as r, Fn as s, checkPackage as t, readPackage as u };