lemmascript 0.6.5 → 0.6.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/package.json +1 -1
- package/tools/dist/condition-facts.js +54 -31
- package/tools/dist/config.js +31 -18
- package/tools/dist/dafny-emit.js +42 -6
- package/tools/dist/extract.js +353 -90
- package/tools/dist/ir.js +19 -0
- package/tools/dist/lean-emit.js +6 -3
- package/tools/dist/lsc.js +9 -14
- package/tools/dist/narrow.js +36 -34
- package/tools/dist/resolve.js +68 -14
- package/tools/dist/run-log.js +1 -1
- package/tools/dist/source-projects.js +31 -0
- package/tools/dist/transform.js +42 -3
- package/tools/dist/types.js +17 -1
package/tools/dist/ir.js
CHANGED
|
@@ -19,6 +19,25 @@ export function patternBinds(p, name) {
|
|
|
19
19
|
return patternBinders(p).includes(name);
|
|
20
20
|
}
|
|
21
21
|
// ── Literal queries ──────────────────────────────────────────
|
|
22
|
+
/** Expand JavaScript's shortest decimal spelling without exponent syntax. */
|
|
23
|
+
export function decimalNumberLiteral(value) {
|
|
24
|
+
if (!Number.isFinite(value))
|
|
25
|
+
throw new Error(`Cannot emit non-finite numeric literal: ${value}`);
|
|
26
|
+
const text = String(value);
|
|
27
|
+
const [mantissa, exponent] = text.split("e");
|
|
28
|
+
if (exponent === undefined)
|
|
29
|
+
return text;
|
|
30
|
+
const negative = mantissa.startsWith("-");
|
|
31
|
+
const [whole, fraction = ""] = (negative ? mantissa.slice(1) : mantissa).split(".");
|
|
32
|
+
const digits = whole + fraction;
|
|
33
|
+
const point = whole.length + Number(exponent);
|
|
34
|
+
const expanded = point <= 0
|
|
35
|
+
? `0.${"0".repeat(-point)}${digits}`
|
|
36
|
+
: point >= digits.length
|
|
37
|
+
? digits + "0".repeat(point - digits.length)
|
|
38
|
+
: `${digits.slice(0, point)}.${digits.slice(point)}`;
|
|
39
|
+
return negative ? `-${expanded}` : expanded;
|
|
40
|
+
}
|
|
22
41
|
/** The exact value of an integer-literal operand (possibly negated), or null
|
|
23
42
|
* when `e` isn't one. Answers in compiler-side `bigint` so a backend folding a
|
|
24
43
|
* literal into arithmetic stays exact: JS bitwise operators truncate to 32 bits
|
package/tools/dist/lean-emit.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* opaque-tainted types, discriminator/destructor lowering, method dispatch,
|
|
5
5
|
* and support-import selection.
|
|
6
6
|
*/
|
|
7
|
-
import { anyExpr, usesNameInDecl, patternBinders } from "./ir.js";
|
|
7
|
+
import { anyExpr, decimalNumberLiteral, usesNameInDecl, patternBinders } from "./ir.js";
|
|
8
8
|
import { freshName, freshNameWhere } from "./names.js";
|
|
9
9
|
// ── Ty → Lean type string ──────────────────────────────────
|
|
10
10
|
function tyToLean(ty) {
|
|
@@ -278,8 +278,11 @@ function emitMethodCall(tyKind, method, monadic, obj, args) {
|
|
|
278
278
|
// String methods
|
|
279
279
|
if (tyKind === "string") {
|
|
280
280
|
_needsJSString = true;
|
|
281
|
-
if (method === "indexOf")
|
|
281
|
+
if (method === "indexOf") {
|
|
282
|
+
if (args.length !== 1)
|
|
283
|
+
throw new Error("Lean string.indexOf does not support a position argument");
|
|
282
284
|
return `JSString.indexOf ${obj} ${args[0]}`;
|
|
285
|
+
}
|
|
283
286
|
if (method === "slice")
|
|
284
287
|
return `JSString.slice ${obj} ${args[0]} ${args[1]}`;
|
|
285
288
|
}
|
|
@@ -324,7 +327,7 @@ function emitExpr(e, parentPrec) {
|
|
|
324
327
|
switch (e.kind) {
|
|
325
328
|
// `undefined` is the IR's spelling of the absent optional (mirrors dafny-emit's None)
|
|
326
329
|
case "var": return e.name === "undefined" ? "none" : escapeName(e.name);
|
|
327
|
-
case "num": return
|
|
330
|
+
case "num": return decimalNumberLiteral(e.value);
|
|
328
331
|
// Already canonical decimal; Lean's `Int` is mathematical, so no `n` suffix.
|
|
329
332
|
case "bigint": return e.value;
|
|
330
333
|
case "bool": return e.value ? "true" : "false";
|
package/tools/dist/lsc.js
CHANGED
|
@@ -4,7 +4,6 @@
|
|
|
4
4
|
*
|
|
5
5
|
* Pipeline: extract → resolve → narrow → transform → peephole → emit
|
|
6
6
|
*/
|
|
7
|
-
import { Project, ScriptTarget } from "ts-morph";
|
|
8
7
|
import { existsSync, mkdirSync, readFileSync } from "fs";
|
|
9
8
|
import { execFileSync } from "child_process";
|
|
10
9
|
import { createRequire } from "module";
|
|
@@ -20,9 +19,10 @@ import { emitDafnyFile, emittedNameMap } from "./dafny-emit.js";
|
|
|
20
19
|
import { dafnyGen, dafnyCheckDiff, dafnyVerify, dafnyRegen } from "./dafny-commands.js";
|
|
21
20
|
import { leanGen, leanCheck } from "./lean-commands.js";
|
|
22
21
|
import { runInfo, runTypedInfo } from "./info-command.js";
|
|
23
|
-
import { RunLog, resolveLogDir, runLogEnabled } from "./run-log.js";
|
|
22
|
+
import { RunLog, resolveLogDir, runLogEnabled, safely } from "./run-log.js";
|
|
24
23
|
import { runRuns } from "./runs-command.js";
|
|
25
|
-
import {
|
|
24
|
+
import { SourceProjects } from "./source-projects.js";
|
|
25
|
+
import { loadConfigOptions, parseFileOptions, resolveDafnyArtifactDir, resolveOptions, } from "./config.js";
|
|
26
26
|
/** Version of the lemmascript package — the root package.json sits two levels
|
|
27
27
|
* above this module from both tools/src/ (tsx) and tools/dist/ (installed). */
|
|
28
28
|
function lscVersion() {
|
|
@@ -255,15 +255,16 @@ function runBatch(cmd, backend, slow, timeLimit, extraFlags, configPath) {
|
|
|
255
255
|
process.exit(1);
|
|
256
256
|
}
|
|
257
257
|
const verifySlow = slow || timeLimit !== undefined;
|
|
258
|
+
const projects = new SourceProjects();
|
|
258
259
|
for (const e of readEntries()) {
|
|
259
260
|
const timeout = timeLimit ?? e.timeout;
|
|
260
261
|
const flags = extraFlags ?? e.flags;
|
|
261
262
|
if (cmd === "check" && backend === "dafny" && !verifySlow && timeout !== undefined && timeout > 60) {
|
|
262
263
|
console.log(`=== ${path.basename(e.file)} (timeout ${timeout}s > 60s, gen-check only) ===`);
|
|
263
|
-
runFile("gen-check", e.file, backend, undefined, undefined, false, false, configPath);
|
|
264
|
+
runFile("gen-check", e.file, backend, undefined, undefined, false, false, configPath, projects);
|
|
264
265
|
}
|
|
265
266
|
else {
|
|
266
|
-
runFile(cmd, e.file, backend, timeout, flags, false, false, configPath);
|
|
267
|
+
runFile(cmd, e.file, backend, timeout, flags, false, false, configPath, projects);
|
|
267
268
|
}
|
|
268
269
|
}
|
|
269
270
|
}
|
|
@@ -281,19 +282,13 @@ function guardRelocatedDafnyProof(sourceDir, artifactDir, base, targetDfyPath) {
|
|
|
281
282
|
legacyPaths.map(p => ` ${p}`).join("\n") +
|
|
282
283
|
`\nMove the hand-written .dfy to ${targetDfyPath}, inspect or remove stale .dfy.base/.dfy.merged files, then rerun. The .dfy.gen file is regeneratable.`);
|
|
283
284
|
}
|
|
284
|
-
function runFile(cmd, filePath, backend, timeLimit, extraFlags, noVerify = false, typedInfo = false, configPath) {
|
|
285
|
+
function runFile(cmd, filePath, backend, timeLimit, extraFlags, noVerify = false, typedInfo = false, configPath, projects = new SourceProjects()) {
|
|
285
286
|
const absPath = path.resolve(filePath);
|
|
286
287
|
if (!existsSync(absPath)) {
|
|
287
288
|
console.error(`File not found: ${absPath}`);
|
|
288
289
|
process.exit(1);
|
|
289
290
|
}
|
|
290
|
-
|
|
291
|
-
const tsConfigFilePath = findUp("tsconfig.json", absPath) ?? undefined;
|
|
292
|
-
const project = tsConfigFilePath
|
|
293
|
-
? new Project({ tsConfigFilePath })
|
|
294
|
-
: new Project({ compilerOptions: { strict: true, target: ScriptTarget.ESNext, lib: ["lib.esnext.d.ts"] } });
|
|
295
|
-
const sourceFile = project.addSourceFileAtPath(absPath);
|
|
296
|
-
project.resolveSourceFileDependencies();
|
|
291
|
+
const sourceFile = projects.load(absPath);
|
|
297
292
|
const fullText = sourceFile.getFullText();
|
|
298
293
|
const { options, configFile } = effectiveOptions(absPath, fullText, configPath);
|
|
299
294
|
// Checked here, for every command, so a bad LSC_RUN_LOG fails like a bad config value.
|
|
@@ -376,7 +371,7 @@ function runFile(cmd, filePath, backend, timeLimit, extraFlags, noVerify = false
|
|
|
376
371
|
// so an aborted run leaves no snapshot; each helper records the stage it detects.
|
|
377
372
|
const logCmd = cmd === "check" || cmd === "regen" ? cmd : null;
|
|
378
373
|
const log = logCmd && runLogOn
|
|
379
|
-
? new RunLog({ logDir: resolveLogDir(absPath, configFile), cmd: logCmd, sourcePath: absPath, extraFlags, lscVersion: lscVersion
|
|
374
|
+
? new RunLog({ logDir: resolveLogDir(absPath, configFile), cmd: logCmd, sourcePath: absPath, extraFlags, lscVersion: safely(lscVersion) })
|
|
380
375
|
: undefined;
|
|
381
376
|
if (cmd === "gen") {
|
|
382
377
|
dafnyGen(genPath, dfyPath, text);
|
package/tools/dist/narrow.js
CHANGED
|
@@ -34,13 +34,12 @@
|
|
|
34
34
|
* binder counter) threads through the walk; no module-level state.
|
|
35
35
|
*/
|
|
36
36
|
import { isTerminatorKind } from "./typedir.js";
|
|
37
|
-
import { freshName } from "./names.js";
|
|
38
37
|
import { builtinSpec } from "./builtins.js";
|
|
39
|
-
import { presentFact, leadingPresent, leadingIsArray, flattenOr, noneDetector,
|
|
38
|
+
import { presentFact, leadingPresent, leadingIsArray, flattenOr, noneDetector, bindPresentFact, freshPathBinder, binderHintForMapAccess, freshOcBinder, applyChain, restoreDiscriminantFlag, arrayBoundsCond, exprEqual, isArrayFact, typeofStringFact, variantFact, negVariantFact, presentMatchStmts, presentMatchExpr, } from "./condition-facts.js";
|
|
40
39
|
// ── Walkers ──────────────────────────────────────────────────
|
|
41
40
|
function walkExpr(e, ctx) {
|
|
42
41
|
const r = recurseExpr(e, ctx);
|
|
43
|
-
return ruleNullish(r, ctx) ?? ruleNullishIndex(r) ?? ruleOptChainIndex(r) ?? ruleOptChain(r, ctx) ?? ruleImplOptional(r, ctx) ?? ruleImplArrayIsArray(r, ctx) ?? ruleConditionalArrayIsArray(r, ctx) ?? ruleConditionalAndArrayIsArray(r, ctx) ?? ruleConditionalAndOptional(r, ctx) ?? ruleConditionalOptionalSimple(r) ?? ruleConditionalInMap(r, ctx) ?? ruleConditionalOptionalTruthy(r) ?? r;
|
|
42
|
+
return ruleNullish(r, ctx) ?? ruleNullishIndex(r) ?? ruleOptChainIndex(r) ?? ruleOptChain(r, ctx) ?? ruleImplOptional(r, ctx) ?? ruleImplArrayIsArray(r, ctx) ?? ruleConditionalArrayIsArray(r, ctx) ?? ruleConditionalAndArrayIsArray(r, ctx) ?? ruleConditionalAndOptional(r, ctx) ?? ruleConditionalOptionalSimple(r, ctx) ?? ruleConditionalInMap(r, ctx) ?? ruleConditionalOptionalTruthy(r, ctx) ?? r;
|
|
44
43
|
}
|
|
45
44
|
function recurseExpr(e, ctx) {
|
|
46
45
|
const re = (x) => walkExpr(x, ctx);
|
|
@@ -85,7 +84,7 @@ function walkStmt(s, ctx) {
|
|
|
85
84
|
// array rule fires; independent narrows commute, so the order is harmless.)
|
|
86
85
|
// && rules fire before the simple rule because they produce nested ifs whose
|
|
87
86
|
// inner shape doesn't match the simple rule directly.
|
|
88
|
-
return ruleIfAndOptional(r, ctx) ?? ruleIfAndArrayIsArray(r, ctx) ?? ruleIfOptionalSimple(r) ?? ruleExprStmtAndOptional(r, ctx) ?? ruleOptionalIndexBinding(r) ?? r;
|
|
87
|
+
return ruleIfAndOptional(r, ctx) ?? ruleIfAndArrayIsArray(r, ctx) ?? ruleIfOptionalSimple(r, ctx) ?? ruleExprStmtAndOptional(r, ctx) ?? ruleOptionalIndexBinding(r) ?? r;
|
|
89
88
|
}
|
|
90
89
|
function walkStmts(stmts, ctx) {
|
|
91
90
|
const result = [];
|
|
@@ -99,7 +98,7 @@ function walkStmts(stmts, ctx) {
|
|
|
99
98
|
i += tagged.consumed - 1;
|
|
100
99
|
continue;
|
|
101
100
|
}
|
|
102
|
-
const consumed = ruleEarlyReturnOrChain(s, rest, ctx) ?? ruleEarlyReturnConsume(s, rest) ?? ruleEarlyReturnOptChainCompare(s, rest, ctx);
|
|
101
|
+
const consumed = ruleEarlyReturnOrChain(s, rest, ctx) ?? ruleEarlyReturnConsume(s, rest, ctx) ?? ruleEarlyReturnOptChainCompare(s, rest, ctx);
|
|
103
102
|
if (consumed) {
|
|
104
103
|
result.push(walkStmt(consumed, ctx));
|
|
105
104
|
return result;
|
|
@@ -107,7 +106,7 @@ function walkStmts(stmts, ctx) {
|
|
|
107
106
|
// walkStmt first — narrow's expression rules may rewrite the let init from
|
|
108
107
|
// `conditional` to `someMatch`, in which case the let-cond desugar shouldn't fire.
|
|
109
108
|
const walked = walkStmt(s, ctx);
|
|
110
|
-
const expanded = ruleLetCondAndOptional(walked);
|
|
109
|
+
const expanded = ruleLetCondAndOptional(walked, ctx);
|
|
111
110
|
if (expanded) {
|
|
112
111
|
for (const x of expanded)
|
|
113
112
|
result.push(walkStmt(x, ctx));
|
|
@@ -159,7 +158,7 @@ function isTerminating(stmts) {
|
|
|
159
158
|
/** Driver: `if (e !== undefined) then else` — presence fact in if position.
|
|
160
159
|
* → `someMatch e { Some(_e_val) => then, None => else }`. Requires a
|
|
161
160
|
* non-empty Some branch. */
|
|
162
|
-
function ruleIfOptionalSimple(s) {
|
|
161
|
+
function ruleIfOptionalSimple(s, ctx) {
|
|
163
162
|
if (s.kind !== "if")
|
|
164
163
|
return null;
|
|
165
164
|
const check = presentFact(s.cond);
|
|
@@ -169,12 +168,12 @@ function ruleIfOptionalSimple(s) {
|
|
|
169
168
|
const noneBody = check.negated ? s.then : s.else;
|
|
170
169
|
if (someBody.length === 0)
|
|
171
170
|
return null;
|
|
172
|
-
return presentMatchStmts(check, someBody, noneBody);
|
|
171
|
+
return presentMatchStmts(check, someBody, noneBody, ctx);
|
|
173
172
|
}
|
|
174
173
|
/** Driver: `if (e === undefined) terminate; rest` — presence fact in
|
|
175
174
|
* early-return position, consuming the rest of the block into the
|
|
176
175
|
* narrowed scope. Fires when the Some branch is empty. */
|
|
177
|
-
function ruleEarlyReturnConsume(s, rest) {
|
|
176
|
+
function ruleEarlyReturnConsume(s, rest, ctx) {
|
|
178
177
|
if (s.kind !== "if")
|
|
179
178
|
return null;
|
|
180
179
|
if (rest.length === 0)
|
|
@@ -188,7 +187,7 @@ function ruleEarlyReturnConsume(s, rest) {
|
|
|
188
187
|
return null;
|
|
189
188
|
if (!isTerminating(noneBranch))
|
|
190
189
|
return null;
|
|
191
|
-
return presentMatchStmts(check, rest, noneBranch);
|
|
190
|
+
return presentMatchStmts(check, rest, noneBranch, ctx);
|
|
192
191
|
}
|
|
193
192
|
/** Driver: `if (D1 || … || Dn) terminate; rest` — De-Morgan position. Each `Di`
|
|
194
193
|
* that detects some optional `x` is None (`!x`, `x === undefined`,
|
|
@@ -217,7 +216,7 @@ function ruleEarlyReturnOrChain(s, rest, ctx) {
|
|
|
217
216
|
residualLeaves.push(leaf);
|
|
218
217
|
continue;
|
|
219
218
|
}
|
|
220
|
-
const key =
|
|
219
|
+
const key = d.binder; // memoized by full path, not by the ambiguous hint
|
|
221
220
|
if (seen.has(key))
|
|
222
221
|
return null; // two detectors on one optional: rare; leave to other rules
|
|
223
222
|
seen.add(key);
|
|
@@ -259,10 +258,9 @@ function ruleEarlyReturnOptChainCompare(s, rest, ctx) {
|
|
|
259
258
|
return null;
|
|
260
259
|
const lit = c.left === oc ? c.right : c.left;
|
|
261
260
|
const innerTy = oc.obj.ty.inner;
|
|
262
|
-
const
|
|
263
|
-
if (
|
|
261
|
+
const binder = freshPathBinder(oc.obj, ctx);
|
|
262
|
+
if (binder === null)
|
|
264
263
|
return null;
|
|
265
|
-
const binder = freshName(hint);
|
|
266
264
|
const binderVar = { kind: "var", name: binder, ty: innerTy };
|
|
267
265
|
const unwrapped = applyChain(binderVar, oc.chain);
|
|
268
266
|
restoreDiscriminantFlag(unwrapped, ctx.decls);
|
|
@@ -276,7 +274,7 @@ function ruleEarlyReturnOptChainCompare(s, rest, ctx) {
|
|
|
276
274
|
}
|
|
277
275
|
/** Driver (expression): `e !== undefined ? a : b` — presence fact in
|
|
278
276
|
* ternary position. */
|
|
279
|
-
function ruleConditionalOptionalSimple(e) {
|
|
277
|
+
function ruleConditionalOptionalSimple(e, ctx) {
|
|
280
278
|
if (e.kind !== "conditional")
|
|
281
279
|
return null;
|
|
282
280
|
const check = presentFact(e.cond);
|
|
@@ -284,7 +282,7 @@ function ruleConditionalOptionalSimple(e) {
|
|
|
284
282
|
return null;
|
|
285
283
|
const someBody = check.negated ? e.else : e.then;
|
|
286
284
|
const noneBody = check.negated ? e.then : e.else;
|
|
287
|
-
return presentMatchExpr(check, someBody, noneBody, e.ty);
|
|
285
|
+
return presentMatchExpr(check, someBody, noneBody, e.ty, ctx);
|
|
288
286
|
}
|
|
289
287
|
/** Driver (expression): `(path !== undefined [&& rest]) ==> B` — presence
|
|
290
288
|
* fact in implication position (spec premises). The premise's optional
|
|
@@ -312,6 +310,7 @@ function ruleImplOptional(e, ctx) {
|
|
|
312
310
|
const innerBody = restCond
|
|
313
311
|
? { kind: "binop", op: "==>", left: restCond, right: e.right, ty: { kind: "bool" } }
|
|
314
312
|
: e.right;
|
|
313
|
+
check = bindPresentFact(check, ctx);
|
|
315
314
|
return {
|
|
316
315
|
kind: "someMatch",
|
|
317
316
|
scrutinee: check.scrutinee, binderTy: check.innerTy,
|
|
@@ -457,15 +456,14 @@ function ruleConditionalInMap(e, ctx) {
|
|
|
457
456
|
/** Driver (expression): `opt ? a : b` (truthiness — cond itself is optional).
|
|
458
457
|
* Only fires for simple var or simple `obj.field` cond. Historical shape:
|
|
459
458
|
* no falsy gate on the bound value (unlike the other truthiness positions). */
|
|
460
|
-
function ruleConditionalOptionalTruthy(e) {
|
|
459
|
+
function ruleConditionalOptionalTruthy(e, ctx) {
|
|
461
460
|
if (e.kind !== "conditional")
|
|
462
461
|
return null;
|
|
463
462
|
if (e.cond.ty.kind !== "optional")
|
|
464
463
|
return null;
|
|
465
|
-
const
|
|
466
|
-
if (
|
|
464
|
+
const binder = freshPathBinder(e.cond, ctx);
|
|
465
|
+
if (binder === null)
|
|
467
466
|
return null;
|
|
468
|
-
const binder = freshName(hint);
|
|
469
467
|
return {
|
|
470
468
|
kind: "someMatch",
|
|
471
469
|
scrutinee: e.cond, binderTy: e.cond.ty.inner,
|
|
@@ -488,7 +486,7 @@ function ruleIfAndOptional(s, ctx) {
|
|
|
488
486
|
return null;
|
|
489
487
|
const { check, restCond } = extracted;
|
|
490
488
|
const innerIf = { kind: "if", cond: restCond, then: s.then, else: [] };
|
|
491
|
-
return presentMatchStmts(check, [walkStmt(innerIf, ctx)], []);
|
|
489
|
+
return presentMatchStmts(check, [walkStmt(innerIf, ctx)], [], ctx);
|
|
492
490
|
}
|
|
493
491
|
/** Driver: a bare expression statement `x !== undefined && rest` (the
|
|
494
492
|
* `if`-less guard idiom, TS-equivalent to `if (x !== undefined) rest;`).
|
|
@@ -507,14 +505,14 @@ function ruleExprStmtAndOptional(s, ctx) {
|
|
|
507
505
|
return null;
|
|
508
506
|
const { check, restCond } = extracted;
|
|
509
507
|
const innerStmt = { kind: "expr", expr: restCond };
|
|
510
|
-
return presentMatchStmts(check, [walkStmt(innerStmt, ctx)], []);
|
|
508
|
+
return presentMatchStmts(check, [walkStmt(innerStmt, ctx)], [], ctx);
|
|
511
509
|
}
|
|
512
510
|
/** Driver (statement): `let x = (e_opt && rest) ? a : b` — presence fact in
|
|
513
511
|
* conditional-initializer position, where rest may contain method calls.
|
|
514
512
|
* → `var x: T := b; someMatch e_opt { Some(_v) => { if rest { x := a } } }`.
|
|
515
513
|
* Statement-level form is needed because Dafny doesn't allow method calls
|
|
516
514
|
* inside match expression arms. */
|
|
517
|
-
function ruleLetCondAndOptional(s) {
|
|
515
|
+
function ruleLetCondAndOptional(s, ctx) {
|
|
518
516
|
if (s.kind !== "let" || s.mutable)
|
|
519
517
|
return null;
|
|
520
518
|
if (s.init.kind !== "conditional")
|
|
@@ -527,7 +525,7 @@ function ruleLetCondAndOptional(s) {
|
|
|
527
525
|
then: [{ kind: "assign", target: s.name, value: s.init.then }], else: [] };
|
|
528
526
|
return [
|
|
529
527
|
{ kind: "let", name: s.name, ty: s.ty, mutable: true, init: s.init.else },
|
|
530
|
-
presentMatchStmts(check, [assignIf], []),
|
|
528
|
+
presentMatchStmts(check, [assignIf], [], ctx),
|
|
531
529
|
];
|
|
532
530
|
}
|
|
533
531
|
/** Does this expression contain a method call that would be lifted to a
|
|
@@ -593,7 +591,7 @@ function ruleConditionalAndOptional(e, ctx) {
|
|
|
593
591
|
kind: "conditional",
|
|
594
592
|
cond: restCond, then: e.then, else: e.else, ty: e.ty,
|
|
595
593
|
};
|
|
596
|
-
return presentMatchExpr(check, walkExpr(innerCond, ctx), e.else, e.ty);
|
|
594
|
+
return presentMatchExpr(check, walkExpr(innerCond, ctx), e.else, e.ty, ctx);
|
|
597
595
|
}
|
|
598
596
|
// ── Variant drivers (discriminants and synth array-unions) ──
|
|
599
597
|
/** Driver (expression): `Array.isArray(x) ==> B` or `!Array.isArray(x) ==> B` —
|
|
@@ -637,15 +635,14 @@ function ruleConditionalArrayIsArray(e, ctx) {
|
|
|
637
635
|
const matched = pos ?? tof ?? (neg ? { scrutinee: neg.scrutinee, typeName: neg.typeName, variant: "NonArrayBranch" } : null);
|
|
638
636
|
if (!matched)
|
|
639
637
|
return null;
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
const elseBody = positive ? e.else : e.then;
|
|
638
|
+
// The selected variant already accounts for negation. Its arm always runs
|
|
639
|
+
// the source then-branch; swapping branches here would negate the test twice.
|
|
643
640
|
return {
|
|
644
641
|
kind: "tagMatch",
|
|
645
642
|
scrutinee: matched.scrutinee,
|
|
646
643
|
typeName: matched.typeName,
|
|
647
|
-
cases: [{ variant: matched.variant, body: walkExpr(
|
|
648
|
-
fallthrough: walkExpr(
|
|
644
|
+
cases: [{ variant: matched.variant, body: walkExpr(e.then, ctx) }],
|
|
645
|
+
fallthrough: walkExpr(e.else, ctx),
|
|
649
646
|
ty: e.ty,
|
|
650
647
|
};
|
|
651
648
|
}
|
|
@@ -766,12 +763,17 @@ function ruleDiscriminantNegEarlyReturn(stmts, ctx) {
|
|
|
766
763
|
}
|
|
767
764
|
// ── Function / module entry ──────────────────────────────────
|
|
768
765
|
function narrowFunction(fn, ctx) {
|
|
766
|
+
// Contracts and the body bind their payloads in separate generated scopes.
|
|
767
|
+
// Do not reserve a body's names because of a contract's \result (or another
|
|
768
|
+
// function's paths). Keep the shared counter's traversal order unchanged.
|
|
769
|
+
const specCtx = { decls: ctx.decls, oc: ctx.oc };
|
|
770
|
+
const bodyCtx = { decls: ctx.decls, oc: ctx.oc };
|
|
769
771
|
return {
|
|
770
772
|
...fn,
|
|
771
|
-
requires: fn.requires.map(e => walkExpr(e,
|
|
772
|
-
ensures: fn.ensures.map(e => walkExpr(e,
|
|
773
|
-
decreases: fn.decreases ? walkExpr(fn.decreases,
|
|
774
|
-
body: walkStmts(fn.body,
|
|
773
|
+
requires: fn.requires.map(e => walkExpr(e, specCtx)),
|
|
774
|
+
ensures: fn.ensures.map(e => walkExpr(e, specCtx)),
|
|
775
|
+
decreases: fn.decreases ? walkExpr(fn.decreases, specCtx) : null,
|
|
776
|
+
body: walkStmts(fn.body, bodyCtx),
|
|
775
777
|
};
|
|
776
778
|
}
|
|
777
779
|
export function narrowModule(mod) {
|
package/tools/dist/resolve.js
CHANGED
|
@@ -58,6 +58,10 @@ function resolveTsType(tsType, overrides, varName) {
|
|
|
58
58
|
/** Infer a conditional's result type after its branches have been resolved or
|
|
59
59
|
* contextually coerced. A void branch is the source-level null/undefined arm. */
|
|
60
60
|
function conditionalResultTy(thenTy, elseTy) {
|
|
61
|
+
if ((thenTy.kind === "int" || thenTy.kind === "nat") &&
|
|
62
|
+
(elseTy.kind === "int" || elseTy.kind === "nat")) {
|
|
63
|
+
return { ...thenTy, kind: thenTy.kind === "int" || elseTy.kind === "int" ? "int" : "nat" };
|
|
64
|
+
}
|
|
61
65
|
let ty = thenTy.kind !== "unknown" ? thenTy : elseTy;
|
|
62
66
|
if (thenTy.kind === "void" && elseTy.kind !== "void" && elseTy.kind !== "unknown") {
|
|
63
67
|
ty = { kind: "optional", inner: elseTy };
|
|
@@ -272,8 +276,15 @@ function expandAlias(ty, typeDecls, seen = new Set()) {
|
|
|
272
276
|
if (ty.kind === "user") {
|
|
273
277
|
if (seen.has(ty.name))
|
|
274
278
|
return ty;
|
|
279
|
+
const dot = ty.name.lastIndexOf(".");
|
|
280
|
+
const enumDecl = typeDecls.find(d => d.name === ty.name.slice(0, dot));
|
|
281
|
+
if (dot > 0 && enumDecl?.constEnumMembers?.some(m => m.name === ty.name.slice(dot + 1)))
|
|
282
|
+
return { kind: "int" };
|
|
275
283
|
const decl = declOfDotted(typeDecls, ty.name);
|
|
276
284
|
if (decl?.kind === "alias" && decl.aliasOfTy) {
|
|
285
|
+
// Numeric enums must behave as numbers (not truthy user objects).
|
|
286
|
+
if (decl.constEnumMembers)
|
|
287
|
+
return { kind: "int" };
|
|
277
288
|
const target = decl.aliasOfTy;
|
|
278
289
|
if (target.kind === "array" || target.kind === "map" || target.kind === "set" || target.kind === "optional" || target.kind === "user") {
|
|
279
290
|
return expandAlias(target, typeDecls, new Set([...seen, ty.name]));
|
|
@@ -293,6 +304,22 @@ function expandAlias(ty, typeDecls, seen = new Set()) {
|
|
|
293
304
|
return { kind: "map", key: expandAlias(ty.key, typeDecls, seen), value: expandAlias(ty.value, typeDecls, seen) };
|
|
294
305
|
return ty;
|
|
295
306
|
}
|
|
307
|
+
/** Numeric aliases keep their names in declarations but use their underlying
|
|
308
|
+
* types in expressions. Optional payloads need the same treatment for zero's
|
|
309
|
+
* falsiness; collection elements are resolved when read. */
|
|
310
|
+
function numericValueType(ty, typeDecls, seen = new Set()) {
|
|
311
|
+
if (ty.kind === "optional")
|
|
312
|
+
return { ...ty, inner: numericValueType(ty.inner, typeDecls, seen) };
|
|
313
|
+
if (ty.kind !== "user" || seen.has(ty.name))
|
|
314
|
+
return ty;
|
|
315
|
+
const decl = declOfDotted(typeDecls, ty.name);
|
|
316
|
+
if (decl?.kind === "alias" && decl.aliasOfTy) {
|
|
317
|
+
const target = numericValueType(decl.aliasOfTy, typeDecls, new Set([...seen, ty.name]));
|
|
318
|
+
if (target.kind === "int" || target.kind === "nat" || target.kind === "real")
|
|
319
|
+
return target;
|
|
320
|
+
}
|
|
321
|
+
return ty;
|
|
322
|
+
}
|
|
296
323
|
function getDiscriminant(ctx, typeName) {
|
|
297
324
|
return findDecl(ctx, typeName)?.discriminant;
|
|
298
325
|
}
|
|
@@ -657,8 +684,9 @@ function lookupFieldTy(objTy, field, ctx) {
|
|
|
657
684
|
let mergeBinder = 0;
|
|
658
685
|
/** Expand `{ ...base, ...override }` into a faithful field-wise merge. Driven by
|
|
659
686
|
* the result record type's fields: an override field wins when present, else the
|
|
660
|
-
* base's field shows through.
|
|
661
|
-
* (`
|
|
687
|
+
* base's field shows through. `f?:` fields decide presence at runtime (`Some?`);
|
|
688
|
+
* required fields (including `T | null`) are always copied from the override.
|
|
689
|
+
* An `Option`-typed override is the whole merge guarded by its tag. */
|
|
662
690
|
function resolveRecordMerge(base, override, ctx) {
|
|
663
691
|
const tbase = resolveExpr(base, ctx);
|
|
664
692
|
const tover = resolveExpr(override, ctx);
|
|
@@ -683,9 +711,10 @@ function resolveRecordMerge(base, override, ctx) {
|
|
|
683
711
|
fields: fields.map(f => {
|
|
684
712
|
const ft = f.type;
|
|
685
713
|
const ovf = { kind: "field", obj: ov, field: f.name, ty: ft };
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
714
|
+
// A required key is always copied, even when its value is null/undefined.
|
|
715
|
+
if (ft.kind !== "optional" || !f.optionalKey)
|
|
716
|
+
return { name: f.name, value: ovf };
|
|
717
|
+
// `f?:` key: override field wins iff present, else base's field
|
|
689
718
|
const bvf = { kind: "field", obj: bv, field: f.name, ty: ft };
|
|
690
719
|
const binder = freshName(`_m${mergeBinder++}`);
|
|
691
720
|
// someBody is the unwrapped present value; transform re-wraps each arm in
|
|
@@ -753,7 +782,22 @@ function tryRecordIndexByEnum(obj, idx, ctx) {
|
|
|
753
782
|
}
|
|
754
783
|
return expr;
|
|
755
784
|
}
|
|
785
|
+
function resolveConstEnumMember(obj, name, ctx) {
|
|
786
|
+
if (obj.kind !== "var" || lookup(ctx.env, obj.name))
|
|
787
|
+
return undefined;
|
|
788
|
+
const decl = ctx.typeDecls.find(d => d.name === obj.name);
|
|
789
|
+
if (!decl?.constEnumMembers)
|
|
790
|
+
return undefined;
|
|
791
|
+
const member = decl.constEnumMembers.find(m => m.name === name);
|
|
792
|
+
if (!member)
|
|
793
|
+
throw new Error(`Unknown const enum member ${obj.name}.${name}`);
|
|
794
|
+
return resolveExpr({ kind: "num", value: member.value }, ctx);
|
|
795
|
+
}
|
|
756
796
|
function resolveExpr(e, ctx) {
|
|
797
|
+
const expr = resolveExprInner(e, ctx);
|
|
798
|
+
return { ...expr, ty: numericValueType(expr.ty, ctx.typeDecls) };
|
|
799
|
+
}
|
|
800
|
+
function resolveExprInner(e, ctx) {
|
|
757
801
|
switch (e.kind) {
|
|
758
802
|
case "var":
|
|
759
803
|
if (e.name === "undefined")
|
|
@@ -827,7 +871,8 @@ function resolveExpr(e, ctx) {
|
|
|
827
871
|
}
|
|
828
872
|
case "unop": {
|
|
829
873
|
const expr = resolveExpr(e.expr, ctx);
|
|
830
|
-
const ty = e.op === "!" ? { kind: "bool" } : e.op === "typeof" ? { kind: "string" }
|
|
874
|
+
const ty = e.op === "!" ? { kind: "bool" } : e.op === "typeof" ? { kind: "string" }
|
|
875
|
+
: e.op === "-" && expr.ty.kind === "nat" ? { ...expr.ty, kind: "int" } : expr.ty;
|
|
831
876
|
return { kind: "unop", op: e.op, expr, ty };
|
|
832
877
|
}
|
|
833
878
|
case "call": {
|
|
@@ -840,8 +885,7 @@ function resolveExpr(e, ctx) {
|
|
|
840
885
|
throw new Error("perm(a, b) may only be used in //@ specifications");
|
|
841
886
|
const a = resolveExpr(e.args[0], ctx);
|
|
842
887
|
const b = resolveExpr(e.args[1], ctx);
|
|
843
|
-
|
|
844
|
-
throw new Error(`perm(a, b) requires two array arguments (got ${a.ty.kind} and ${b.ty.kind})`);
|
|
888
|
+
// Let the backend check argument types, including calls to proof helpers.
|
|
845
889
|
const fn = { kind: "var", name: "Perm", ty: { kind: "unknown" } };
|
|
846
890
|
return { kind: "call", fn, args: [a, b], ty: { kind: "bool" }, callKind: "pure" };
|
|
847
891
|
}
|
|
@@ -929,6 +973,11 @@ function resolveExpr(e, ctx) {
|
|
|
929
973
|
...(paramTypes ? { paramTys: paramTypes } : {}) };
|
|
930
974
|
}
|
|
931
975
|
case "index": {
|
|
976
|
+
if (e.idx.kind === "str") {
|
|
977
|
+
const member = resolveConstEnumMember(e.obj, e.idx.value, ctx);
|
|
978
|
+
if (member)
|
|
979
|
+
return member;
|
|
980
|
+
}
|
|
932
981
|
const obj = resolveExpr(e.obj, ctx);
|
|
933
982
|
const idx = resolveExpr(e.idx, ctx);
|
|
934
983
|
// Map bracket access: default to Option<V>. But if the enclosing scope has a
|
|
@@ -964,6 +1013,9 @@ function resolveExpr(e, ctx) {
|
|
|
964
1013
|
return { kind: "index", obj, idx, ty: idxTy };
|
|
965
1014
|
}
|
|
966
1015
|
case "field": {
|
|
1016
|
+
const member = resolveConstEnumMember(e.obj, e.field, ctx);
|
|
1017
|
+
if (member)
|
|
1018
|
+
return member;
|
|
967
1019
|
const obj = resolveExpr(e.obj, ctx);
|
|
968
1020
|
let isDiscriminant = false;
|
|
969
1021
|
let ty = { kind: "unknown" };
|
|
@@ -1762,10 +1814,10 @@ function resolveFunction(fn, typeDecls, pureFns, fnParams = new Map(), fnReturns
|
|
|
1762
1814
|
};
|
|
1763
1815
|
}
|
|
1764
1816
|
function resolveClass(cls, typeDecls, pureFns, fnParams = new Map(), fnReturns = new Map(), externs = new Map(), moduleConstants = new Map()) {
|
|
1765
|
-
const fields = cls.fields.map(f => ({ name: f.name, ty: parseTsType(f.tsType) }));
|
|
1817
|
+
const fields = cls.fields.map(f => ({ name: f.name, ty: expandAlias(parseTsType(f.tsType), typeDecls) }));
|
|
1766
1818
|
// Create a synthetic record type for 'this' so field access resolves
|
|
1767
1819
|
const thisType = { kind: "user", name: cls.name };
|
|
1768
|
-
const thisDecl = { name: cls.name, kind: "record", fields: cls.fields.map(f => ({ name: f.name, tsType: f.tsType, type:
|
|
1820
|
+
const thisDecl = { name: cls.name, kind: "record", fields: cls.fields.map((f, i) => ({ name: f.name, tsType: f.tsType, type: fields[i].ty })) };
|
|
1769
1821
|
const allTypeDecls = [...typeDecls, thisDecl];
|
|
1770
1822
|
const methods = cls.methods.map(fn => resolveFunction(fn, allTypeDecls, pureFns, fnParams, fnReturns, externs, moduleConstants, {
|
|
1771
1823
|
thisBinding: { name: "this", ty: thisType },
|
|
@@ -1870,13 +1922,15 @@ export function resolveModule(raw) {
|
|
|
1870
1922
|
});
|
|
1871
1923
|
const emptyCtx = { env: null, typeDecls: raw.typeDecls, overrides: new Map(), allowResult: false, returnTy: { kind: "int" }, pureFns, fnParams, fnReturns, externs, inSpec: false, inLambda: false, narrowedPaths: [], narrowedIndices: [] };
|
|
1872
1924
|
const constants = (raw.constants ?? []).map(c => {
|
|
1873
|
-
const
|
|
1925
|
+
const declaredTy = expandAlias(parseTsType(c.tsType), raw.typeDecls);
|
|
1874
1926
|
// Propagate the declared type into the value's resolution context so that
|
|
1875
1927
|
// record literals on map-typed constants (e.g. `Record<string, number>`)
|
|
1876
1928
|
// get their `ty` set to `map<...>` rather than `user("...")`.
|
|
1877
|
-
const valueCtx = { ...emptyCtx, returnTy:
|
|
1878
|
-
const value =
|
|
1879
|
-
|
|
1929
|
+
const valueCtx = { ...emptyCtx, returnTy: declaredTy };
|
|
1930
|
+
const value = resolveExpr(c.value, valueCtx);
|
|
1931
|
+
// TypeScript's number defaults to int, but fractional initializers need real.
|
|
1932
|
+
const ty = declaredTy.kind === "int" && value.ty.kind === "real" ? value.ty : declaredTy;
|
|
1933
|
+
return { name: c.name, ty, value: coerceToTargetTy(value, ty, raw.typeDecls) };
|
|
1880
1934
|
});
|
|
1881
1935
|
const moduleConstants = new Map(constants.map(c => [c.name, c.ty]));
|
|
1882
1936
|
return {
|
package/tools/dist/run-log.js
CHANGED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { Project, ScriptTarget } from "ts-morph";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { findUp } from "./config.js";
|
|
4
|
+
/** Full TypeScript projects shared for the duration of one CLI batch. */
|
|
5
|
+
export class SourceProjects {
|
|
6
|
+
projects = new Map();
|
|
7
|
+
load(filePath) {
|
|
8
|
+
const absPath = path.resolve(filePath);
|
|
9
|
+
const tsConfigFilePath = findUp("tsconfig.json", absPath) ?? undefined;
|
|
10
|
+
const cached = tsConfigFilePath ? this.projects.get(tsConfigFilePath) : undefined;
|
|
11
|
+
const existing = cached?.project.getSourceFile(absPath);
|
|
12
|
+
if (existing && cached?.sources.has(existing))
|
|
13
|
+
return existing;
|
|
14
|
+
// Keep every configured file and its dependencies: otherwise ambient
|
|
15
|
+
// declarations and module augmentations can silently change the model.
|
|
16
|
+
const project = tsConfigFilePath
|
|
17
|
+
? new Project({ tsConfigFilePath })
|
|
18
|
+
: new Project({ compilerOptions: { strict: true, target: ScriptTarget.ESNext, lib: ["lib.esnext.d.ts"] } });
|
|
19
|
+
const included = project.getSourceFile(absPath);
|
|
20
|
+
if (tsConfigFilePath && included) {
|
|
21
|
+
this.projects.set(tsConfigFilePath, { project, sources: new Set(project.getSourceFiles()) });
|
|
22
|
+
return included;
|
|
23
|
+
}
|
|
24
|
+
// An explicitly requested file outside the configured graph may introduce
|
|
25
|
+
// globals or augmentations. Give it a fresh project so it cannot affect
|
|
26
|
+
// later entries. Files without a tsconfig likewise remain independent.
|
|
27
|
+
const sourceFile = project.addSourceFileAtPath(absPath);
|
|
28
|
+
project.resolveSourceFileDependencies();
|
|
29
|
+
return sourceFile;
|
|
30
|
+
}
|
|
31
|
+
}
|