lemmascript 0.6.15 → 0.6.16
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/extract.js +111 -26
- package/tools/dist/lean-emit.js +13 -12
- package/tools/dist/transform.js +95 -45
package/README.md
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
# LemmaScript (Tech Preview)
|
|
2
2
|
|
|
3
|
+
[](https://github.com/midspiral/LemmaScript/actions/workflows/ci.yml)
|
|
4
|
+
|
|
3
5
|
A verification toolchain for TypeScript. Write ordinary TypeScript with `//@ ` specification annotations. The toolchain generates verifiable code from your TypeScript — either in Dafny or Lean 4 (with Velvet 2).
|
|
4
6
|
|
|
5
7
|
See [SPEC.md](SPEC.md), [DESIGN.md](DESIGN.md), and [GETTING_STARTED.md](GETTING_STARTED.md).
|
package/package.json
CHANGED
package/tools/dist/extract.js
CHANGED
|
@@ -62,6 +62,7 @@ let _validateDependency = () => { };
|
|
|
62
62
|
/** Counter for synthetic names used by let-statement array destructuring
|
|
63
63
|
* when the initializer isn't a bare variable (single-eval temp). */
|
|
64
64
|
let _destrCounter = 0;
|
|
65
|
+
let _switchBreakCounter = 0;
|
|
65
66
|
let _lexicalNames = null;
|
|
66
67
|
const sourceName = (node) => _lexicalNames?.name(node) ?? node.getText();
|
|
67
68
|
/** Register the call's callee as a cross-file extern if applicable, then
|
|
@@ -1883,23 +1884,89 @@ function extractScopedStmts(stmts) {
|
|
|
1883
1884
|
const switchExpr = exprAst.kind === "field" ? exprAst.obj : exprAst;
|
|
1884
1885
|
const cases = [];
|
|
1885
1886
|
let defaultBody = [];
|
|
1886
|
-
// Two JS-`switch` faithfulness concerns
|
|
1887
|
-
// (1) Fall-through: stacked `case A: case B: body`
|
|
1888
|
-
//
|
|
1889
|
-
//
|
|
1890
|
-
//
|
|
1891
|
-
//
|
|
1892
|
-
//
|
|
1893
|
-
//
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
const
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
|
|
1887
|
+
// Two JS-`switch` faithfulness concerns Dafny `match` / Lean `if`-chains don't share:
|
|
1888
|
+
// (1) Fall-through: stacked `case A: case B: body` or non-exiting clauses
|
|
1889
|
+
// continue into the following clause's statements.
|
|
1890
|
+
// (2) `break` is the switch exit, not a loop break. A top-level `break`
|
|
1891
|
+
// terminates the clause, and a guarded `if (c) break;` inside a clause
|
|
1892
|
+
// must exit only the switch, never surviving into `match` where it
|
|
1893
|
+
// would escape to an enclosing `while`/`for` loop. Nested loops and
|
|
1894
|
+
// nested switches own their own `break`s and are not descended into.
|
|
1895
|
+
const hasSwitchBreak = (stmts) => stmts.some(st => st.kind === "break" ||
|
|
1896
|
+
(st.kind === "if" && (hasSwitchBreak(st.then) || hasSwitchBreak(st.else))));
|
|
1897
|
+
const canFallThrough = (stmts) => {
|
|
1898
|
+
for (const st of stmts) {
|
|
1899
|
+
if (st.kind === "break" || st.kind === "return" || st.kind === "throw" || st.kind === "continue") {
|
|
1900
|
+
return false;
|
|
1901
|
+
}
|
|
1902
|
+
if (st.kind === "if" && !canFallThrough(st.then) && !canFallThrough(st.else)) {
|
|
1903
|
+
return false;
|
|
1904
|
+
}
|
|
1905
|
+
}
|
|
1906
|
+
return true;
|
|
1907
|
+
};
|
|
1908
|
+
// Single-pass switch-break lowering organized around which branches of each
|
|
1909
|
+
// `if` can reach the following statements (`rest`):
|
|
1910
|
+
// - Neither branch reaches `rest`: omit `rest`.
|
|
1911
|
+
// - Neither branch contains a switch break: keep the ordinary `if` and continue.
|
|
1912
|
+
// - Exactly one branch reaches `rest`: place `rest` directly in that branch
|
|
1913
|
+
// (emitted once, preserving TypeScript narrowing from `head.cond`).
|
|
1914
|
+
// - Both branches can reach `rest` and an inner path can also break: guard
|
|
1915
|
+
// `rest` once after the `if` with a lazily allocated switch-exit flag.
|
|
1916
|
+
const eliminateSwitchBreaks = (stmts, cont, exitFlag, ensureFlag) => {
|
|
1917
|
+
if (stmts.length === 0)
|
|
1918
|
+
return cont;
|
|
1919
|
+
const [head, ...tail] = stmts;
|
|
1920
|
+
if (head.kind === "break") {
|
|
1921
|
+
return exitFlag === null
|
|
1922
|
+
? []
|
|
1923
|
+
: [{ kind: "assign", target: exitFlag, value: { kind: "bool", value: true }, line: head.line }];
|
|
1924
|
+
}
|
|
1925
|
+
if (head.kind === "return" || head.kind === "throw" || head.kind === "continue") {
|
|
1926
|
+
return [head];
|
|
1927
|
+
}
|
|
1928
|
+
if (head.kind === "if") {
|
|
1929
|
+
const thenFalls = canFallThrough(head.then);
|
|
1930
|
+
const elseFalls = canFallThrough(head.else);
|
|
1931
|
+
if (!thenFalls && !elseFalls) {
|
|
1932
|
+
return [{
|
|
1933
|
+
...head,
|
|
1934
|
+
then: eliminateSwitchBreaks(head.then, [], exitFlag, ensureFlag),
|
|
1935
|
+
else: eliminateSwitchBreaks(head.else, [], exitFlag, ensureFlag),
|
|
1936
|
+
}];
|
|
1937
|
+
}
|
|
1938
|
+
if (!hasSwitchBreak(head.then) && !hasSwitchBreak(head.else)) {
|
|
1939
|
+
return [head, ...eliminateSwitchBreaks(tail, cont, exitFlag, ensureFlag)];
|
|
1940
|
+
}
|
|
1941
|
+
const rest = eliminateSwitchBreaks(tail, cont, exitFlag, ensureFlag);
|
|
1942
|
+
if (!thenFalls || !elseFalls) {
|
|
1943
|
+
return [{
|
|
1944
|
+
...head,
|
|
1945
|
+
then: eliminateSwitchBreaks(head.then, thenFalls ? rest : [], exitFlag, ensureFlag),
|
|
1946
|
+
else: eliminateSwitchBreaks(head.else, elseFalls ? rest : [], exitFlag, ensureFlag),
|
|
1947
|
+
}];
|
|
1948
|
+
}
|
|
1949
|
+
const flag = rest.length > 0 ? (exitFlag ?? ensureFlag()) : exitFlag;
|
|
1950
|
+
const ifStmt = {
|
|
1951
|
+
...head,
|
|
1952
|
+
then: eliminateSwitchBreaks(head.then, [], flag, ensureFlag),
|
|
1953
|
+
else: eliminateSwitchBreaks(head.else, [], flag, ensureFlag),
|
|
1954
|
+
};
|
|
1955
|
+
if (rest.length === 0)
|
|
1956
|
+
return [ifStmt];
|
|
1957
|
+
return [
|
|
1958
|
+
ifStmt,
|
|
1959
|
+
{
|
|
1960
|
+
kind: "if",
|
|
1961
|
+
cond: { kind: "unop", op: "!", expr: { kind: "var", name: flag } },
|
|
1962
|
+
then: rest,
|
|
1963
|
+
else: [],
|
|
1964
|
+
line: head.line,
|
|
1965
|
+
},
|
|
1966
|
+
];
|
|
1967
|
+
}
|
|
1968
|
+
return [head, ...eliminateSwitchBreaks(tail, cont, exitFlag, ensureFlag)];
|
|
1969
|
+
};
|
|
1903
1970
|
const clauseInfos = s.getClauses().map(clause => {
|
|
1904
1971
|
const stmts = extractStmts(clause.getStatements());
|
|
1905
1972
|
let label = null;
|
|
@@ -1910,20 +1977,37 @@ function extractScopedStmts(stmts) {
|
|
|
1910
1977
|
}
|
|
1911
1978
|
label = labelExpr.value;
|
|
1912
1979
|
}
|
|
1913
|
-
return {
|
|
1914
|
-
label,
|
|
1915
|
-
stmts,
|
|
1916
|
-
exits: isExit(stmts[stmts.length - 1]),
|
|
1917
|
-
};
|
|
1980
|
+
return { label, stmts };
|
|
1918
1981
|
});
|
|
1919
1982
|
const fallThroughBody = (start) => {
|
|
1920
|
-
|
|
1983
|
+
const stmts = [];
|
|
1921
1984
|
for (let j = start; j < clauseInfos.length; j++) {
|
|
1922
|
-
|
|
1923
|
-
|
|
1985
|
+
const clauseStmts = clauseInfos[j].stmts;
|
|
1986
|
+
stmts.push(...clauseStmts);
|
|
1987
|
+
if (!canFallThrough(clauseStmts))
|
|
1924
1988
|
break;
|
|
1925
1989
|
}
|
|
1926
|
-
|
|
1990
|
+
let flag = null;
|
|
1991
|
+
const ensureFlag = () => {
|
|
1992
|
+
if (flag === null) {
|
|
1993
|
+
const suffix = _switchBreakCounter === 0 ? "" : String(_switchBreakCounter);
|
|
1994
|
+
_switchBreakCounter += 1;
|
|
1995
|
+
flag = freshName(`_switchBroken${suffix}`);
|
|
1996
|
+
}
|
|
1997
|
+
return flag;
|
|
1998
|
+
};
|
|
1999
|
+
const body = eliminateSwitchBreaks(stmts, [], null, ensureFlag);
|
|
2000
|
+
if (flag === null)
|
|
2001
|
+
return body;
|
|
2002
|
+
const decl = {
|
|
2003
|
+
kind: "let",
|
|
2004
|
+
name: flag,
|
|
2005
|
+
mutable: true,
|
|
2006
|
+
tsType: "boolean",
|
|
2007
|
+
init: { kind: "bool", value: false },
|
|
2008
|
+
line,
|
|
2009
|
+
};
|
|
2010
|
+
return [decl, ...body];
|
|
1927
2011
|
};
|
|
1928
2012
|
for (let i = 0; i < clauseInfos.length; i++) {
|
|
1929
2013
|
const c = clauseInfos[i];
|
|
@@ -2180,6 +2264,7 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
|
|
|
2180
2264
|
// tests) must not leak a havoc key, temp-name counter, or function-local maps.
|
|
2181
2265
|
_havocKey = null;
|
|
2182
2266
|
_destrCounter = 0;
|
|
2267
|
+
_switchBreakCounter = 0;
|
|
2183
2268
|
_lexicalNames = null;
|
|
2184
2269
|
_typeParamMap = new Map();
|
|
2185
2270
|
// Seed the fresh-name check (names.ts) before anything mints: every
|
package/tools/dist/lean-emit.js
CHANGED
|
@@ -470,7 +470,7 @@ function emitExpr(e, parentPrec) {
|
|
|
470
470
|
const l = emitExpr(e.left);
|
|
471
471
|
const r = emitExpr(e.right);
|
|
472
472
|
const condProp = isPropValued(e.left) ? l : `(${l}) = true`;
|
|
473
|
-
const h = `_h${_depIfCounter++}
|
|
473
|
+
const h = freshName(`_h${_depIfCounter++}`);
|
|
474
474
|
const tVal = _boolCtx ? "true" : "True";
|
|
475
475
|
const fVal = _boolCtx ? "false" : "False";
|
|
476
476
|
const rExpr = _boolCtx && isPropValued(e.right) ? `decide (${r})` : r;
|
|
@@ -506,7 +506,7 @@ function emitExpr(e, parentPrec) {
|
|
|
506
506
|
if (tailHasCU(i)) {
|
|
507
507
|
const pStr = emitExpr(p);
|
|
508
508
|
const pProp = isPropValued(p) ? pStr : `(${pStr}) = true`;
|
|
509
|
-
const h = `_h${_depIfCounter++}
|
|
509
|
+
const h = freshName(`_h${_depIfCounter++}`);
|
|
510
510
|
acc = `∀ (${h} : ${pProp}), ${acc}`;
|
|
511
511
|
}
|
|
512
512
|
else {
|
|
@@ -519,7 +519,7 @@ function emitExpr(e, parentPrec) {
|
|
|
519
519
|
// A bare negative literal argument (`f -7 2`) parses as subtraction in Lean.
|
|
520
520
|
const args = e.args.map(a => {
|
|
521
521
|
const s = emitExpr(a);
|
|
522
|
-
return (a.kind === "binop" || a.kind === "unop" || a.kind === "implies" || a.kind === "app" || a.kind === "methodCall" || s.startsWith("-")) ? `(${s})` : s;
|
|
522
|
+
return (a.kind === "binop" || a.kind === "unop" || a.kind === "implies" || a.kind === "app" || a.kind === "methodCall" || a.kind === "if" || a.kind === "let" || a.kind === "match" || s.startsWith("-")) ? `(${s})` : s;
|
|
523
523
|
});
|
|
524
524
|
// Datatype constructor (tagged by transform): Lean needs the qualified name
|
|
525
525
|
// `BaseType.variant`; a bare `variant` is an unknown identifier. (Dafny keeps
|
|
@@ -662,7 +662,7 @@ function emitExpr(e, parentPrec) {
|
|
|
662
662
|
if (hasCU) {
|
|
663
663
|
const c = emitExpr(e.cond);
|
|
664
664
|
const condProp = isPropValued(e.cond) ? c : `(${c}) = true`;
|
|
665
|
-
const h = `_h${_depIfCounter++}
|
|
665
|
+
const h = freshName(`_h${_depIfCounter++}`);
|
|
666
666
|
const t = emitExpr(e.then);
|
|
667
667
|
const f = emitExpr(e.else);
|
|
668
668
|
const tExpr = _boolCtx && isPropValued(e.then) ? `decide (${t})` : t;
|
|
@@ -722,7 +722,7 @@ function emitStmts(stmts, indent) {
|
|
|
722
722
|
anyExprInStmts(rest, x => x.kind === "checkedUnwrap")) {
|
|
723
723
|
const c = emitExpr(s.cond);
|
|
724
724
|
const condProp = isPropValued(s.cond) ? c : `(${c}) = true`;
|
|
725
|
-
const h = `_h${_depIfCounter++}
|
|
725
|
+
const h = freshName(`_h${_depIfCounter++}`);
|
|
726
726
|
out.push(`${pad}if ${h} : ${condProp} then\n${emitStmts(s.then, indent + 1)}\n${pad}else\n${emitStmts(rest, indent + 1)}`);
|
|
727
727
|
break;
|
|
728
728
|
}
|
|
@@ -771,25 +771,26 @@ function emitStmt(s, indent) {
|
|
|
771
771
|
case "break": return `${pad}break`;
|
|
772
772
|
case "continue": return `${pad}continue`;
|
|
773
773
|
case "if": {
|
|
774
|
+
const emitBlock = (stmts, ind) => stmts.length === 0 ? `${" ".repeat(ind)}pure ()` : emitStmts(stmts, ind);
|
|
774
775
|
const hasCU = anyExprInStmts(s.then, x => x.kind === "checkedUnwrap") ||
|
|
775
776
|
anyExprInStmts(s.else, x => x.kind === "checkedUnwrap");
|
|
776
777
|
const condText = hasCU
|
|
777
778
|
? (() => {
|
|
778
779
|
const c = emitExpr(s.cond);
|
|
779
780
|
const condProp = isPropValued(s.cond) ? c : `(${c}) = true`;
|
|
780
|
-
return `_h${_depIfCounter++} : ${condProp}`;
|
|
781
|
+
return `${freshName(`_h${_depIfCounter++}`)} : ${condProp}`;
|
|
781
782
|
})()
|
|
782
783
|
: emitExpr(s.cond);
|
|
783
|
-
let out = `${pad}if ${condText} then\n${
|
|
784
|
+
let out = `${pad}if ${condText} then\n${emitBlock(s.then, indent + 1)}`;
|
|
784
785
|
if (s.else.length > 0) {
|
|
785
786
|
if (!hasCU && s.else.length === 1 && s.else[0].kind === "if") {
|
|
786
787
|
const ei = s.else[0];
|
|
787
|
-
out += `\n${pad}else if ${emitExpr(ei.cond)} then\n${
|
|
788
|
+
out += `\n${pad}else if ${emitExpr(ei.cond)} then\n${emitBlock(ei.then, indent + 1)}`;
|
|
788
789
|
if (ei.else.length > 0)
|
|
789
|
-
out += `\n${pad}else\n${
|
|
790
|
+
out += `\n${pad}else\n${emitBlock(ei.else, indent + 1)}`;
|
|
790
791
|
}
|
|
791
792
|
else {
|
|
792
|
-
out += `\n${pad}else\n${
|
|
793
|
+
out += `\n${pad}else\n${emitBlock(s.else, indent + 1)}`;
|
|
793
794
|
}
|
|
794
795
|
}
|
|
795
796
|
return out;
|
|
@@ -802,7 +803,7 @@ function emitStmt(s, indent) {
|
|
|
802
803
|
const noneArm = s.arms.find(a => a.pattern.kind === "ctor" && a.pattern.ctor === "none");
|
|
803
804
|
if (someArm && noneArm) {
|
|
804
805
|
const boundVar = patternBinders(someArm.pattern)[0]; // ".some x" ⇒ "x"
|
|
805
|
-
const hName = `h_${scrut.replace(/[^a-zA-Z0-9_]/g, "_")}
|
|
806
|
+
const hName = freshName(`h_${scrut.replace(/[^a-zA-Z0-9_]/g, "_")}`);
|
|
806
807
|
const lines = [
|
|
807
808
|
`${pad}if ${hName} : (${scrut}).isSome = true then`,
|
|
808
809
|
`${pad} let ${boundVar} := (${scrut}).get ${hName}`,
|
|
@@ -1050,7 +1051,7 @@ function emitPureExpr(e, indent) {
|
|
|
1050
1051
|
if (hasCU) {
|
|
1051
1052
|
const c = emitExpr(e.cond);
|
|
1052
1053
|
const condProp = isPropValued(e.cond) ? c : `(${c}) = true`;
|
|
1053
|
-
const h = `_h${_depIfCounter++}
|
|
1054
|
+
const h = freshName(`_h${_depIfCounter++}`);
|
|
1054
1055
|
return `${pad}if ${h} : ${condProp} then\n${emitPureExpr(e.then, indent + 1)}\n${pad}else\n${emitPureExpr(e.else, indent + 1)}`;
|
|
1055
1056
|
}
|
|
1056
1057
|
return `${pad}if ${emitExpr(e.cond)} then\n${emitPureExpr(e.then, indent + 1)}\n${pad}else\n${emitPureExpr(e.else, indent + 1)}`;
|
package/tools/dist/transform.js
CHANGED
|
@@ -11,7 +11,7 @@ import { freshName, freshNameWhere, isUserName } from "./names.js";
|
|
|
11
11
|
import { builtinSpec } from "./builtins.js";
|
|
12
12
|
import { lowerIndexedCallback } from "./callback-lowering.js";
|
|
13
13
|
import { isFalsyCapableTy } from "./condition-facts.js";
|
|
14
|
-
import { declOf, declOfKind, declOfTy, unionDeclOfTy,
|
|
14
|
+
import { declOf, declOfKind, declOfTy, unionDeclOfTy, tyBaseName, remainingVariant } from "./typedecls.js";
|
|
15
15
|
import { buildNestedFieldExpr, collectAssignedIrTargets, describeReceiver, emitWriteBacksForTarget, findActiveUnwrapFrame, isMutatingCollectionMethod, makeUnwrapFrame, resolveWriteTargetThroughFrames, } from "./place-lowering.js";
|
|
16
16
|
// ── Generic IR walkers ──────────────────────────────────────
|
|
17
17
|
/**
|
|
@@ -1351,18 +1351,28 @@ function lowerExpr(e, binds) {
|
|
|
1351
1351
|
}
|
|
1352
1352
|
// Math.floor(x):
|
|
1353
1353
|
// - a / b on integral operands → integer floor division, kept in
|
|
1354
|
-
// integer arithmetic (JSFloorDiv on Dafny; native
|
|
1355
|
-
//
|
|
1356
|
-
//
|
|
1354
|
+
// integer arithmetic (JSFloorDiv on Dafny; on Lean, native `/` is
|
|
1355
|
+
// Euclidean `Int.ediv` which matches floor division only when the
|
|
1356
|
+
// divisor is non-negative, so signed/negative divisors emit
|
|
1357
|
+
// qualified `Int.fdiv` directly to avoid colliding with a user
|
|
1358
|
+
// function named `JSFloorDiv`). Checked first: after resolve, `a / b`
|
|
1359
|
+
// is typed `real`, so the real branch below would otherwise drag it
|
|
1360
|
+
// into real arithmetic.
|
|
1357
1361
|
// - real arg → FloorReal (Dafny's .Floor)
|
|
1358
1362
|
// - int arg → identity
|
|
1359
1363
|
if (e.fn.kind === "field" && e.fn.field === "floor" && e.fn.obj.kind === "var" && e.fn.obj.name === "Math" && e.args.length === 1) {
|
|
1360
1364
|
const arg = e.args[0];
|
|
1361
1365
|
if (arg.kind === "binop" && arg.op === "/" && isIntegral(arg.left.ty) && isIntegral(arg.right.ty)) {
|
|
1362
1366
|
const l = lowerExpr(arg.left, binds), r = lowerExpr(arg.right, binds);
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1367
|
+
if (_opts.backend === "dafny") {
|
|
1368
|
+
return { kind: "app", fn: "JSFloorDiv", args: [l, r] };
|
|
1369
|
+
}
|
|
1370
|
+
const nonnegDivisor = isNat(arg.right.ty) ||
|
|
1371
|
+
(arg.right.kind === "num" && arg.right.value > 0) ||
|
|
1372
|
+
(arg.right.kind === "bigint" && BigInt(arg.right.value) > 0n);
|
|
1373
|
+
return nonnegDivisor
|
|
1374
|
+
? { kind: "binop", op: "/", left: l, right: r }
|
|
1375
|
+
: { kind: "app", fn: "Int.fdiv", args: [l, r] };
|
|
1366
1376
|
}
|
|
1367
1377
|
if (arg.ty.kind === "real")
|
|
1368
1378
|
return { kind: "app", fn: "FloorReal", args: [lowerExpr(arg, binds)] };
|
|
@@ -2171,12 +2181,14 @@ function lowerArrayPopOrShift(e, usage) {
|
|
|
2171
2181
|
};
|
|
2172
2182
|
}
|
|
2173
2183
|
/**
|
|
2174
|
-
* Velvet (Lean backend) rejects `return` inside a loop. For a
|
|
2175
|
-
*
|
|
2176
|
-
*
|
|
2177
|
-
* `
|
|
2178
|
-
*
|
|
2179
|
-
*
|
|
2184
|
+
* Velvet (Lean backend) rejects `return` inside a loop. For a loop containing
|
|
2185
|
+
* early `return`s, hoist a mutable `Option T` result variable `_loopRet := none`:
|
|
2186
|
+
* each in-loop `return e` becomes `_loopRet := some e; break`. After the loop,
|
|
2187
|
+
* match on `_loopRet` so an early return returns its saved value, while a normal
|
|
2188
|
+
* exit (or regular `break`) runs the remaining statements with the post-loop
|
|
2189
|
+
* state rather than a stale pre-loop snapshot. Using `Option T` avoids needing
|
|
2190
|
+
* an `Inhabited T` default value whenever fallthrough statements follow the loop.
|
|
2191
|
+
* Dafny is untouched — it keeps the native early returns.
|
|
2180
2192
|
*/
|
|
2181
2193
|
function stmtsContainReturn(stmts) {
|
|
2182
2194
|
for (const s of stmts) {
|
|
@@ -2192,19 +2204,25 @@ function stmtsContainReturn(stmts) {
|
|
|
2192
2204
|
}
|
|
2193
2205
|
function replaceReturnsWithBreak(stmts, retVar) {
|
|
2194
2206
|
return stmts.flatMap((s) => {
|
|
2195
|
-
if (s.kind === "return")
|
|
2196
|
-
return [
|
|
2197
|
-
|
|
2207
|
+
if (s.kind === "return") {
|
|
2208
|
+
return [
|
|
2209
|
+
{ kind: "assign", target: retVar, value: { kind: "app", fn: "Some", args: [s.value] } },
|
|
2210
|
+
{ kind: "break" },
|
|
2211
|
+
];
|
|
2212
|
+
}
|
|
2213
|
+
if (s.kind === "if") {
|
|
2198
2214
|
return [{ ...s, then: replaceReturnsWithBreak(s.then, retVar), else: replaceReturnsWithBreak(s.else, retVar) }];
|
|
2199
|
-
|
|
2215
|
+
}
|
|
2216
|
+
if (s.kind === "match") {
|
|
2200
2217
|
return [{ ...s, arms: s.arms.map(a => ({ ...a, body: replaceReturnsWithBreak(a.body, retVar) })) }];
|
|
2218
|
+
}
|
|
2201
2219
|
return [s];
|
|
2202
2220
|
});
|
|
2203
2221
|
}
|
|
2204
|
-
//
|
|
2205
|
-
//
|
|
2206
|
-
//
|
|
2207
|
-
//
|
|
2222
|
+
// Fallback value only when a non-void return-in-loop has no statements after
|
|
2223
|
+
// the loop (e.g. `while (true) { ... return e; }`) so the unreachable `none`
|
|
2224
|
+
// branch still type-checks. Readable literals for primitives; everything else
|
|
2225
|
+
// gets a typed `default : T`.
|
|
2208
2226
|
function defaultExprForTy(ty) {
|
|
2209
2227
|
switch (ty.kind) {
|
|
2210
2228
|
case "bool": return { kind: "bool", value: false };
|
|
@@ -2215,25 +2233,53 @@ function defaultExprForTy(ty) {
|
|
|
2215
2233
|
default: return { kind: "default", type: ty };
|
|
2216
2234
|
}
|
|
2217
2235
|
}
|
|
2218
|
-
function eliminateReturnInLoops(stmts, retTy,
|
|
2236
|
+
function eliminateReturnInLoops(stmts, retTy, ensuresExprs, counter = { n: 0 }) {
|
|
2219
2237
|
const out = [];
|
|
2220
2238
|
for (let i = 0; i < stmts.length; i++) {
|
|
2221
2239
|
const s = stmts[i];
|
|
2222
2240
|
if (s.kind === "while" && stmtsContainReturn(s.body)) {
|
|
2223
|
-
const
|
|
2224
|
-
|
|
2225
|
-
const
|
|
2226
|
-
|
|
2227
|
-
|
|
2228
|
-
|
|
2229
|
-
|
|
2230
|
-
|
|
2231
|
-
|
|
2232
|
-
|
|
2233
|
-
|
|
2234
|
-
|
|
2235
|
-
|
|
2236
|
-
|
|
2241
|
+
const suffix = counter.n === 0 ? "" : String(counter.n);
|
|
2242
|
+
counter.n += 1;
|
|
2243
|
+
const retVar = freshName(`_loopRet${suffix}`);
|
|
2244
|
+
const retVal = freshName(`_loopRet${suffix}_val`);
|
|
2245
|
+
const retRef = { kind: "var", name: retVar };
|
|
2246
|
+
const retIsSome = { kind: "field", obj: retRef, field: "isSome" };
|
|
2247
|
+
const retUnwrap = { kind: "checkedUnwrap", expr: retRef };
|
|
2248
|
+
const resultInvariants = ensuresExprs.map(e => ({
|
|
2249
|
+
kind: "implies",
|
|
2250
|
+
premises: [retIsSome],
|
|
2251
|
+
conclusion: replaceVar(e, "\\result", retUnwrap),
|
|
2252
|
+
}));
|
|
2253
|
+
out.push({
|
|
2254
|
+
kind: "let",
|
|
2255
|
+
name: retVar,
|
|
2256
|
+
type: { kind: "optional", inner: retTy },
|
|
2257
|
+
mutable: true,
|
|
2258
|
+
value: { kind: "app", fn: "None", args: [] },
|
|
2259
|
+
});
|
|
2260
|
+
// Guard each postcondition invariant with `_loopRet.isSome → P[_loopRet.get / \result]`:
|
|
2261
|
+
// it holds vacuously while `_loopRet = none`, and Velvet checks `P[e / \result]`
|
|
2262
|
+
// at each `_loopRet := some e; break`.
|
|
2263
|
+
out.push({
|
|
2264
|
+
...s,
|
|
2265
|
+
invariants: [...s.invariants, ...resultInvariants],
|
|
2266
|
+
body: replaceReturnsWithBreak(s.body, retVar),
|
|
2267
|
+
});
|
|
2268
|
+
const rest = stmts.slice(i + 1);
|
|
2269
|
+
const noneBody = rest.length > 0
|
|
2270
|
+
? eliminateReturnInLoops(rest, retTy, ensuresExprs, counter)
|
|
2271
|
+
: retTy.kind === "void"
|
|
2272
|
+
? []
|
|
2273
|
+
: [{ kind: "return", value: defaultExprForTy(retTy) }];
|
|
2274
|
+
out.push({
|
|
2275
|
+
kind: "match",
|
|
2276
|
+
scrutinee: retRef,
|
|
2277
|
+
arms: [
|
|
2278
|
+
{ pattern: pCtor("some", retVal), body: [{ kind: "return", value: { kind: "var", name: retVal } }] },
|
|
2279
|
+
{ pattern: pCtor("none"), body: noneBody },
|
|
2280
|
+
],
|
|
2281
|
+
});
|
|
2282
|
+
break;
|
|
2237
2283
|
}
|
|
2238
2284
|
else {
|
|
2239
2285
|
out.push(s);
|
|
@@ -2274,10 +2320,12 @@ function matchToIfChains(stmts) {
|
|
|
2274
2320
|
if (arms.some(a => a.pattern.kind === "literal"))
|
|
2275
2321
|
return [{ ...s, arms }];
|
|
2276
2322
|
const ctorArms = arms.filter(a => a.pattern.kind === "ctor");
|
|
2277
|
-
|
|
2278
|
-
|
|
2323
|
+
// Only user-union matches carry `unionType` (from `emitMatchStmt` / `emitSwitchStmt`);
|
|
2324
|
+
// leave `Option` matches and other non-union matches alone even if a user union
|
|
2325
|
+
// happens to define `"some"` / `"none"` variants.
|
|
2326
|
+
const decl = s.unionType ? declOf(_typeDecls, tyBaseName(s.unionType)) : undefined;
|
|
2279
2327
|
if (!decl)
|
|
2280
|
-
return [{ ...s, arms }];
|
|
2328
|
+
return [{ ...s, arms }];
|
|
2281
2329
|
const scrutExpr = s.scrutinee;
|
|
2282
2330
|
const defaultArm = arms.find(a => a.pattern.kind === "wild");
|
|
2283
2331
|
const declaredCtors = decl.kind === "discriminated-union"
|
|
@@ -2288,8 +2336,10 @@ function matchToIfChains(stmts) {
|
|
|
2288
2336
|
let elseBranch = defaultArm ? defaultArm.body : [];
|
|
2289
2337
|
for (let k = ctorArms.length - 1; k >= 0; k--) {
|
|
2290
2338
|
const armBody = ctorArms[k].body;
|
|
2291
|
-
|
|
2292
|
-
|
|
2339
|
+
// Only skip an empty arm when there is no fallback branch to fall into;
|
|
2340
|
+
// otherwise skipping it would execute `elseBranch` instead of doing nothing.
|
|
2341
|
+
if (armBody.length === 0 && elseBranch.length === 0)
|
|
2342
|
+
continue;
|
|
2293
2343
|
const ctor = patternCtor(ctorArms[k].pattern) ?? "";
|
|
2294
2344
|
const binders = patternBinders(ctorArms[k].pattern);
|
|
2295
2345
|
const variant = decl.variants?.find(v => v.name === ctor);
|
|
@@ -3014,7 +3064,7 @@ function emitMatchStmt(scrutinee, typeName, cases, fallthrough, typeDecls) {
|
|
|
3014
3064
|
arms.push({ pattern: pWild(), body: transformStmts(fallthrough, typeDecls) });
|
|
3015
3065
|
}
|
|
3016
3066
|
}
|
|
3017
|
-
return { kind: "match", scrutinee: transformExpr(scrutinee), arms };
|
|
3067
|
+
return { kind: "match", scrutinee: transformExpr(scrutinee), arms, unionType: typeName };
|
|
3018
3068
|
}
|
|
3019
3069
|
/** `switch(obj.field)` is stripped at extraction to scrutinee `obj` + discriminant
|
|
3020
3070
|
* `field`, assuming `obj` is a discriminated union with `field` as its
|
|
@@ -3072,7 +3122,7 @@ function emitSwitchStmt(s, typeDecls) {
|
|
|
3072
3122
|
if (s.defaultBody.length > 0)
|
|
3073
3123
|
arms.push({ pattern: pWild(), body: transformStmts(s.defaultBody, typeDecls) });
|
|
3074
3124
|
const scrutinee = ef ? ef.scrutinee : transformExpr(s.expr);
|
|
3075
|
-
return { kind: "match", scrutinee, arms };
|
|
3125
|
+
return { kind: "match", scrutinee, arms, ...(ctorDecl ? { unionType: ctorDecl.name } : {}) };
|
|
3076
3126
|
}
|
|
3077
3127
|
function asTAccessPath(e) {
|
|
3078
3128
|
if (e.kind === "var")
|
|
@@ -3574,8 +3624,8 @@ export function transformModule(mod, specImport, moduleBaseOverride) {
|
|
|
3574
3624
|
// since loom's default loop-exit fact `¬guard` does not hold across a break.
|
|
3575
3625
|
if (_opts.backend === "lean" && !pureDefNames.has(fn.name)) {
|
|
3576
3626
|
body = matchToIfChains(body);
|
|
3577
|
-
const
|
|
3578
|
-
body = eliminateReturnInLoops(body, fn.returnTy,
|
|
3627
|
+
const ensuresExprs = fn.ensures.map(e => transformSpecExpr(e));
|
|
3628
|
+
body = eliminateReturnInLoops(body, fn.returnTy, ensuresExprs);
|
|
3579
3629
|
requireDoneWithForBreaks(body, fn.name);
|
|
3580
3630
|
}
|
|
3581
3631
|
// Shadow reassigned parameters with mutable locals (including parameters
|