lemmascript 0.6.12 → 0.6.14
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/package.json +1 -1
- package/tools/dist/alias-check-pass.js +1049 -0
- package/tools/dist/alias-check.js +67 -0
- package/tools/dist/autohavoc.js +4 -0
- package/tools/dist/builtins.js +1 -1
- package/tools/dist/checked-reads.js +406 -0
- package/tools/dist/condition-facts.js +64 -26
- package/tools/dist/dafny-emit.js +42 -5
- package/tools/dist/extract.js +52 -20
- package/tools/dist/ir.js +2 -1
- package/tools/dist/lean-emit.js +132 -12
- package/tools/dist/lsc.js +2 -1
- package/tools/dist/narrow-checks.js +421 -0
- package/tools/dist/narrow.js +106 -12
- package/tools/dist/peephole.js +1 -0
- package/tools/dist/place-lowering.js +219 -0
- package/tools/dist/places.js +123 -0
- package/tools/dist/resolve.js +591 -103
- package/tools/dist/specparser.js +10 -6
- package/tools/dist/transform.js +922 -113
- package/tools/dist/typedir.js +19 -1
- package/tools/dist/types.js +52 -15
package/tools/dist/dafny-emit.js
CHANGED
|
@@ -31,6 +31,7 @@ function tyToDafny(ty) {
|
|
|
31
31
|
case "bool": return "bool";
|
|
32
32
|
case "string": return "string";
|
|
33
33
|
case "void": return "()";
|
|
34
|
+
case "null": return "()";
|
|
34
35
|
case "array": return `seq<${tyToDafny(ty.elem)}>`;
|
|
35
36
|
case "tuple": return `(${ty.elems.map(tyToDafny).join(", ")})`;
|
|
36
37
|
case "map": return `map<${tyToDafny(ty.key)}, ${tyToDafny(ty.value)}>`;
|
|
@@ -39,6 +40,10 @@ function tyToDafny(ty) {
|
|
|
39
40
|
needPreamble("OptionType");
|
|
40
41
|
return `Option<${tyToDafny(ty.inner)}>`;
|
|
41
42
|
}
|
|
43
|
+
case "nullish": {
|
|
44
|
+
needPreamble("NullishType");
|
|
45
|
+
return `Nullish<${tyToDafny(ty.inner)}>`;
|
|
46
|
+
}
|
|
42
47
|
case "user": return escapeName(ty.name);
|
|
43
48
|
case "fn": return `(${ty.params.map(tyToDafny).join(", ")}) -> ${tyToDafny(ty.result)}`;
|
|
44
49
|
// Out-of-subset (`any`/`unknown`); opaque so real ops on it fail loudly
|
|
@@ -296,6 +301,8 @@ function emitExpr(e) {
|
|
|
296
301
|
// signature, so request the preamble here.
|
|
297
302
|
if (e.type === "Option")
|
|
298
303
|
needPreamble("OptionType");
|
|
304
|
+
if (e.type === "Nullish")
|
|
305
|
+
needPreamble("NullishType");
|
|
299
306
|
const head = qualifyCtor(e.name, e.type);
|
|
300
307
|
if (!e.args || e.args.length === 0)
|
|
301
308
|
return head;
|
|
@@ -583,6 +590,17 @@ function emitExpr(e) {
|
|
|
583
590
|
return `StringRepeat(${obj}, ${args[0]})`;
|
|
584
591
|
}
|
|
585
592
|
}
|
|
593
|
+
// Nullish<T> discriminators (#304)
|
|
594
|
+
if (ty === "nullish") {
|
|
595
|
+
needPreamble("NullishType");
|
|
596
|
+
const recv = e.obj.kind === "var" || e.obj.kind === "field" ? obj : `(${obj})`;
|
|
597
|
+
if (e.method === "isNull")
|
|
598
|
+
return `${recv}.Null?`;
|
|
599
|
+
if (e.method === "isUndefined")
|
|
600
|
+
return `${recv}.Undefined?`;
|
|
601
|
+
if (e.method === "isValue")
|
|
602
|
+
return `${recv}.Value?`;
|
|
603
|
+
}
|
|
586
604
|
// Map methods
|
|
587
605
|
if (ty === "map") {
|
|
588
606
|
if (e.method === "getDirect")
|
|
@@ -647,9 +665,10 @@ function emitExpr(e) {
|
|
|
647
665
|
return `${op}(${emitExpr(e.expr)})`;
|
|
648
666
|
}
|
|
649
667
|
case "binop": {
|
|
650
|
-
// Discriminant check: x == .Ctor → x.Ctor?
|
|
668
|
+
// Discriminant check: x == .Ctor → x.Ctor? (0-arg constructors only;
|
|
669
|
+
// value-carrying constructors like `x == Some(v)` stay full equality).
|
|
651
670
|
const op = mapOp(e.op);
|
|
652
|
-
if ((op === "==" || op === "!=") && e.right.kind === "constructor") {
|
|
671
|
+
if ((op === "==" || op === "!=") && e.right.kind === "constructor" && e.right.args.length === 0) {
|
|
653
672
|
const ctorName = dafnyCtorName(e.right.name.replace(/^\./, ""));
|
|
654
673
|
const pred = `${emitExpr(e.left)}.${ctorName}?`;
|
|
655
674
|
return op === "!=" ? `(!${pred})` : pred;
|
|
@@ -806,6 +825,11 @@ function emitExpr(e) {
|
|
|
806
825
|
case "toInt": return emitExpr(e.expr);
|
|
807
826
|
case "toReal":
|
|
808
827
|
return `(${emitExpr(e.expr)} as real)`;
|
|
828
|
+
case "checkedUnwrap": {
|
|
829
|
+
const inner = emitExpr(e.expr);
|
|
830
|
+
const bare = e.expr.kind === "var" || e.expr.kind === "field" || e.expr.kind === "checkedUnwrap";
|
|
831
|
+
return bare ? `${inner}.value` : `(${inner}).value`;
|
|
832
|
+
}
|
|
809
833
|
case "stringIndex":
|
|
810
834
|
// TS indexing returns a string; Dafny's native string subscript is a
|
|
811
835
|
// char. The singleton sequence preserves the native bounds obligation.
|
|
@@ -835,7 +859,7 @@ function emitExpr(e) {
|
|
|
835
859
|
const fieldNames = new Set(e.fields.map(f => f.name));
|
|
836
860
|
const matches = [];
|
|
837
861
|
for (const [name, fields] of _structureDecls) {
|
|
838
|
-
if (fields.length >= e.fields.length && fields.every(f => fieldNames.has(f.name) || f.type.kind === "optional")) {
|
|
862
|
+
if (fields.length >= e.fields.length && fields.every(f => fieldNames.has(f.name) || f.type.kind === "optional" || f.type.kind === "nullish")) {
|
|
839
863
|
matches.push(name);
|
|
840
864
|
}
|
|
841
865
|
}
|
|
@@ -863,6 +887,10 @@ function emitExpr(e) {
|
|
|
863
887
|
needPreamble("OptionType");
|
|
864
888
|
return "None";
|
|
865
889
|
}
|
|
890
|
+
if (sf.type.kind === "nullish") {
|
|
891
|
+
needPreamble("NullishType");
|
|
892
|
+
return "Nullish.Undefined";
|
|
893
|
+
}
|
|
866
894
|
return `/* missing: ${sf.name} */`;
|
|
867
895
|
});
|
|
868
896
|
return `${ctorName}(${vals.join(", ")})`;
|
|
@@ -1734,6 +1762,7 @@ const SET_TO_SEQ = `method SetToSeq<T>(s: set<T>) returns (res: seq<T>)
|
|
|
1734
1762
|
/** Preamble code keyed by name. Emitted in this order when needed. */
|
|
1735
1763
|
const PREAMBLE_CODE = [
|
|
1736
1764
|
["OptionType", "datatype Option<T> = None | Some(value: T)"],
|
|
1765
|
+
["NullishType", "datatype Nullish<T> = Undefined | Null | Value(value: T)"],
|
|
1737
1766
|
// Opaque carrier for `unknown`-typed values. `(==)` for compare/map-key/match;
|
|
1738
1767
|
// `(0)` (auto-init ⇒ nonempty) so `havoc` (`:= *`) is well-formed.
|
|
1739
1768
|
["UnknownType", "type Unknown(==, 0)"],
|
|
@@ -1876,7 +1905,9 @@ function resolveTy(ty) {
|
|
|
1876
1905
|
if (ty.kind === "user" && !_declaredTypes.has(ty.name))
|
|
1877
1906
|
return { kind: "string" };
|
|
1878
1907
|
if (ty.kind === "optional")
|
|
1879
|
-
return {
|
|
1908
|
+
return { ...ty, inner: resolveTy(ty.inner) };
|
|
1909
|
+
if (ty.kind === "nullish")
|
|
1910
|
+
return { kind: "nullish", inner: resolveTy(ty.inner) };
|
|
1880
1911
|
if (ty.kind === "array")
|
|
1881
1912
|
return { kind: "array", elem: resolveTy(ty.elem) };
|
|
1882
1913
|
if (ty.kind === "tuple")
|
|
@@ -1910,7 +1941,13 @@ function qualifyCtor(name, type) {
|
|
|
1910
1941
|
* literal value → quoted Dafny string
|
|
1911
1942
|
* "_" → "_"
|
|
1912
1943
|
*/
|
|
1913
|
-
const CTOR_MAP = {
|
|
1944
|
+
const CTOR_MAP = {
|
|
1945
|
+
"some": "Some",
|
|
1946
|
+
"none": "None",
|
|
1947
|
+
"nullishUndefined": "Undefined",
|
|
1948
|
+
"nullishNull": "Null",
|
|
1949
|
+
"nullishValue": "Value",
|
|
1950
|
+
};
|
|
1914
1951
|
function translatePattern(p) {
|
|
1915
1952
|
if (p.kind === "wild")
|
|
1916
1953
|
return "_";
|
package/tools/dist/extract.js
CHANGED
|
@@ -672,9 +672,10 @@ function extractExpr(node) {
|
|
|
672
672
|
if (!hasSpread) {
|
|
673
673
|
return { kind: "arrayLiteral", elems: elems.map(e => extractExpr(e)) };
|
|
674
674
|
}
|
|
675
|
-
// [a, ...b, c] → [a] + b + [c] via shared helper
|
|
675
|
+
// [a, ...b, c] → [a] + b + [c] via shared helper; mark freshClone so
|
|
676
|
+
// `[...arr]` is not misread by alias analysis as a reference alias of `arr`.
|
|
676
677
|
const result = buildSpreadConcat(elems);
|
|
677
|
-
return result;
|
|
678
|
+
return markFreshClone(result);
|
|
678
679
|
}
|
|
679
680
|
// Object literal: { res: true, done: false } or { ...obj, res: true }
|
|
680
681
|
if (Node.isObjectLiteralExpression(node)) {
|
|
@@ -690,7 +691,7 @@ function extractExpr(node) {
|
|
|
690
691
|
for (const prop of node.getProperties()) {
|
|
691
692
|
if (Node.isSpreadAssignment(prop)) {
|
|
692
693
|
const s = extractExpr(prop.getExpression());
|
|
693
|
-
acc = acc === null ? s : { kind: "recordMerge", base: acc, override: s };
|
|
694
|
+
acc = acc === null ? markFreshClone(s) : { kind: "recordMerge", base: acc, override: s };
|
|
694
695
|
}
|
|
695
696
|
else if (Node.isShorthandPropertyAssignment(prop)) {
|
|
696
697
|
const name = prop.getName();
|
|
@@ -740,8 +741,9 @@ function extractExpr(node) {
|
|
|
740
741
|
const argSymbol = argType.getSymbol()?.getName() ?? argType.getAliasSymbol()?.getName();
|
|
741
742
|
const argTypeText = _eraseGenerics(typeToString(argType));
|
|
742
743
|
if (argSymbol === "Map" || argTypeText.startsWith("Record<")) {
|
|
743
|
-
// new Map(existingMap) or new Map(record) — identity (Dafny maps are value types)
|
|
744
|
-
|
|
744
|
+
// new Map(existingMap) or new Map(record) — identity (Dafny maps are value types),
|
|
745
|
+
// marked freshClone so alias analysis knows JS allocates a fresh Map.
|
|
746
|
+
return markFreshClone(extractExpr(args[0]));
|
|
745
747
|
}
|
|
746
748
|
// new Map(entries) — map-from-array constructor
|
|
747
749
|
return { kind: "call", fn: { kind: "var", name: "__mapFromArray" }, args: [extractExpr(args[0])] };
|
|
@@ -753,9 +755,9 @@ function extractExpr(node) {
|
|
|
753
755
|
return { kind: "emptyCollection", collectionType: "Set", tsType, initElems: arg.getElements().map(e => extractExpr(e)) };
|
|
754
756
|
}
|
|
755
757
|
const argSymbol = arg.getType().getSymbol()?.getName() ?? arg.getType().getAliasSymbol()?.getName();
|
|
756
|
-
// new Set(existingSet) — identity (sets are value types)
|
|
758
|
+
// new Set(existingSet) — identity (sets are value types), marked freshClone.
|
|
757
759
|
if (argSymbol === "Set")
|
|
758
|
-
return extractExpr(arg);
|
|
760
|
+
return markFreshClone(extractExpr(arg));
|
|
759
761
|
// new Set(arr) — build a deduplicated set from the array's elements
|
|
760
762
|
return { kind: "call", fn: { kind: "var", name: "__setFromArray" }, args: [extractExpr(arg)] };
|
|
761
763
|
}
|
|
@@ -779,9 +781,10 @@ function extractExpr(node) {
|
|
|
779
781
|
};
|
|
780
782
|
}
|
|
781
783
|
}
|
|
782
|
-
// null
|
|
784
|
+
// Preserve `null` distinctly from `undefined` so `T | null | undefined`
|
|
785
|
+
// (`Nullish<T>`) and single-sentinel `T | null` / `T | undefined` stay sound (#304).
|
|
783
786
|
if (Node.isNullLiteral(node)) {
|
|
784
|
-
return { kind: "var", name: "
|
|
787
|
+
return { kind: "var", name: "null" };
|
|
785
788
|
}
|
|
786
789
|
// `typeof X` — only meaningful in a `typeof X === "string"` discriminator over
|
|
787
790
|
// a synth `U | T[]` union (see narrow's parseTypeofStringCheck); any other use
|
|
@@ -1262,6 +1265,8 @@ function typeToString(type) {
|
|
|
1262
1265
|
return "number";
|
|
1263
1266
|
if (type.isUndefined())
|
|
1264
1267
|
return "undefined";
|
|
1268
|
+
if (type.isNull())
|
|
1269
|
+
return "null";
|
|
1265
1270
|
if (type.isNumber() || type.isNumberLiteral())
|
|
1266
1271
|
return "number";
|
|
1267
1272
|
if (type.isBigInt() || type.isBigIntLiteral())
|
|
@@ -1329,9 +1334,17 @@ function typeToString(type) {
|
|
|
1329
1334
|
if (real.length <= 1)
|
|
1330
1335
|
return parts.join(" | ");
|
|
1331
1336
|
// A genuine multi-member union with no tagged-union shape LS can model →
|
|
1332
|
-
// a single opaque type. (See _synthOpaque.) Preserve
|
|
1337
|
+
// a single opaque type. (See _synthOpaque.) Preserve outer null/undefined.
|
|
1333
1338
|
const opaque = _synthOpaque(real);
|
|
1334
|
-
|
|
1339
|
+
const hasNull = parts.includes("null");
|
|
1340
|
+
const hasUndef = parts.includes("undefined");
|
|
1341
|
+
if (hasNull && hasUndef)
|
|
1342
|
+
return `${opaque} | null | undefined`;
|
|
1343
|
+
if (hasNull)
|
|
1344
|
+
return `${opaque} | null`;
|
|
1345
|
+
if (hasUndef)
|
|
1346
|
+
return `${opaque} | undefined`;
|
|
1347
|
+
return opaque;
|
|
1335
1348
|
}
|
|
1336
1349
|
if (type.isTuple()) {
|
|
1337
1350
|
return `[${type.getTupleElements().map(t => typeToString(t)).join(", ")}]`;
|
|
@@ -1358,6 +1371,15 @@ function typeToString(type) {
|
|
|
1358
1371
|
}
|
|
1359
1372
|
return type.getText();
|
|
1360
1373
|
}
|
|
1374
|
+
function markFreshClone(e) {
|
|
1375
|
+
if (e.kind === "nonNull") {
|
|
1376
|
+
return { ...e, expr: markFreshClone(e.expr) };
|
|
1377
|
+
}
|
|
1378
|
+
if (e.kind === "var" || e.kind === "field" || e.kind === "index" || e.kind === "call") {
|
|
1379
|
+
return { ...e, freshClone: true };
|
|
1380
|
+
}
|
|
1381
|
+
return e;
|
|
1382
|
+
}
|
|
1361
1383
|
const COMPOUND_OPS = {
|
|
1362
1384
|
"+=": "+", "-=": "-", "*=": "*", "/=": "/", "%=": "%",
|
|
1363
1385
|
"<<=": "<<", ">>=": ">>", "|=": "|", "&=": "&", "^=": "^", "**=": "**",
|
|
@@ -3048,16 +3070,16 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
|
|
|
3048
3070
|
// already-extracted `fn.returnType` string for nullish suffixes to detect
|
|
3049
3071
|
// the wrap-in-Optional case.
|
|
3050
3072
|
let innerType = null;
|
|
3051
|
-
let wrapOptional = false;
|
|
3052
3073
|
const sourceReturnText = fn.returnType ?? "";
|
|
3053
|
-
const
|
|
3054
|
-
|
|
3055
|
-
|
|
3074
|
+
const sourceHasNull = /(^|\|\s*)null(\s*\||$)/.test(sourceReturnText);
|
|
3075
|
+
const sourceHasUndef = /(^|\|\s*)undefined(\s*\||$)/.test(sourceReturnText);
|
|
3076
|
+
let wrapNull = false;
|
|
3077
|
+
let wrapUndef = false;
|
|
3056
3078
|
const sym = retType.getSymbol();
|
|
3057
3079
|
if ((sym?.getName() === "__type" || sym?.getName() === "__object") && retType.isObject() && !retType.isArray()) {
|
|
3058
3080
|
innerType = retType;
|
|
3059
|
-
|
|
3060
|
-
|
|
3081
|
+
wrapNull = sourceHasNull;
|
|
3082
|
+
wrapUndef = sourceHasUndef;
|
|
3061
3083
|
}
|
|
3062
3084
|
else if (retType.isUnion()) {
|
|
3063
3085
|
const arms = retType.getUnionTypes();
|
|
@@ -3068,15 +3090,25 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
|
|
|
3068
3090
|
const otherSym = onlyOther.getSymbol();
|
|
3069
3091
|
if ((otherSym?.getName() === "__type" || otherSym?.getName() === "__object") && onlyOther.isObject() && !onlyOther.isArray()) {
|
|
3070
3092
|
innerType = onlyOther;
|
|
3071
|
-
|
|
3093
|
+
wrapNull = nullish.some(t => t.isNull());
|
|
3094
|
+
wrapUndef = nullish.some(t => t.isUndefined());
|
|
3072
3095
|
}
|
|
3073
3096
|
}
|
|
3074
3097
|
}
|
|
3098
|
+
const formatReturnNullability = (base) => {
|
|
3099
|
+
if (wrapNull && wrapUndef)
|
|
3100
|
+
return `${base} | null | undefined`;
|
|
3101
|
+
if (wrapNull)
|
|
3102
|
+
return `${base} | null`;
|
|
3103
|
+
if (wrapUndef)
|
|
3104
|
+
return `${base} | undefined`;
|
|
3105
|
+
return base;
|
|
3106
|
+
};
|
|
3075
3107
|
if (innerType) {
|
|
3076
3108
|
// Try typeToString first — it resolves collapsed single-variant unions
|
|
3077
3109
|
const resolved = typeToString(innerType);
|
|
3078
3110
|
if (resolved !== "__type" && !resolved.includes("__type") && knownTypes.has(resolved)) {
|
|
3079
|
-
fn.returnType =
|
|
3111
|
+
fn.returnType = formatReturnNullability(resolved);
|
|
3080
3112
|
continue;
|
|
3081
3113
|
}
|
|
3082
3114
|
const synName = f.owner + fn.name.charAt(0).toUpperCase() + fn.name.slice(1) + "Result";
|
|
@@ -3089,7 +3121,7 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
|
|
|
3089
3121
|
knownTypes.add(synName);
|
|
3090
3122
|
}
|
|
3091
3123
|
}
|
|
3092
|
-
fn.returnType =
|
|
3124
|
+
fn.returnType = formatReturnNullability(synName);
|
|
3093
3125
|
// Also resolve imported types referenced in the return type's fields
|
|
3094
3126
|
for (const prop of innerType.getProperties()) {
|
|
3095
3127
|
resolveType(prop.getTypeAtLocation(f.node), f.node);
|
package/tools/dist/ir.js
CHANGED
|
@@ -75,7 +75,8 @@ export function anyExpr(e, pred) {
|
|
|
75
75
|
case "unop":
|
|
76
76
|
case "toNat":
|
|
77
77
|
case "toInt":
|
|
78
|
-
case "toReal":
|
|
78
|
+
case "toReal":
|
|
79
|
+
case "checkedUnwrap": return anyExpr(e.expr, pred);
|
|
79
80
|
case "app": return e.args.some(a => anyExpr(a, pred));
|
|
80
81
|
case "field": return anyExpr(e.obj, pred);
|
|
81
82
|
case "index": return anyExpr(e.arr, pred) || anyExpr(e.idx, pred);
|
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, decimalNumberLiteral, usesNameInDecl, patternBinders } from "./ir.js";
|
|
7
|
+
import { anyExpr, anyExprInStmts, 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) {
|
|
@@ -30,6 +30,7 @@ function tyToLean(ty) {
|
|
|
30
30
|
case "bool": return "Bool";
|
|
31
31
|
case "string": return "String";
|
|
32
32
|
case "void": return "Unit";
|
|
33
|
+
case "null": return "Unit";
|
|
33
34
|
case "array": {
|
|
34
35
|
const elem = tyToLean(ty.elem);
|
|
35
36
|
return elem.includes(" ") ? `Array (${elem})` : `Array ${elem}`;
|
|
@@ -56,6 +57,11 @@ function tyToLean(ty) {
|
|
|
56
57
|
const inner = tyToLean(ty.inner);
|
|
57
58
|
return inner.includes(" ") ? `Option (${inner})` : `Option ${inner}`;
|
|
58
59
|
}
|
|
60
|
+
case "nullish": {
|
|
61
|
+
_needsNullish = true;
|
|
62
|
+
const inner = tyToLean(ty.inner);
|
|
63
|
+
return inner.includes(" ") ? `Nullish (${inner})` : `Nullish ${inner}`;
|
|
64
|
+
}
|
|
59
65
|
case "user": return ty.name;
|
|
60
66
|
case "fn": {
|
|
61
67
|
const params = ty.params.map(p => {
|
|
@@ -183,8 +189,10 @@ function emitDeriving(name, deriving) {
|
|
|
183
189
|
return der.length > 0 ? `\nderiving ${der.join(", ")}` : "";
|
|
184
190
|
}
|
|
185
191
|
let _needsJSString = false;
|
|
192
|
+
let _needsNullish = false;
|
|
186
193
|
let _needsUnknown = false;
|
|
187
194
|
let _unknownEmitted = false; // across files in one run — the def file imports the types file
|
|
195
|
+
let _depIfCounter = 0;
|
|
188
196
|
// Bool-vs-Prop context. Lean keeps `Bool` and `Prop` distinct; the IR uses the
|
|
189
197
|
// Prop connectives (∧/∨/¬) uniformly. In a computational position the connectives
|
|
190
198
|
// may need to be the Bool ones (&&/||/!). They are only *required* when a connective
|
|
@@ -192,10 +200,19 @@ let _unknownEmitted = false; // across files in one run — the def file imports
|
|
|
192
200
|
// built only from decidable atoms (comparisons, Bool-returning calls) coerces fine
|
|
193
201
|
// and stays in the more proof-friendly Prop form.
|
|
194
202
|
let _boolCtx = false;
|
|
203
|
+
const LEAN_CTOR_MAP = {
|
|
204
|
+
"nullishUndefined": "undefined",
|
|
205
|
+
"nullishNull": "null",
|
|
206
|
+
"nullishValue": "value",
|
|
207
|
+
};
|
|
195
208
|
/** Constructor names come from source strings (string-union values,
|
|
196
209
|
* discriminated-union tags) and may contain non-identifier characters
|
|
197
210
|
* ("spec-pure"); guillemet-quote those — exact and collision-free. */
|
|
198
211
|
function leanCtorName(name) {
|
|
212
|
+
if (Object.hasOwn(LEAN_CTOR_MAP, name)) {
|
|
213
|
+
_needsNullish = true;
|
|
214
|
+
return LEAN_CTOR_MAP[name];
|
|
215
|
+
}
|
|
199
216
|
return /^[A-Za-z_][A-Za-z0-9_'!?]*$/.test(name) ? name : `«${name}»`;
|
|
200
217
|
}
|
|
201
218
|
/** Render a match pattern to Lean syntax: `_`, a quoted literal, or `.ctor args`. */
|
|
@@ -235,9 +252,18 @@ function connectiveHasNonCoercibleOperand(e) {
|
|
|
235
252
|
// so a body with no such operand stays Prop — this keeps arithmetic predicates like
|
|
236
253
|
// `x ≥ 0 ∧ x < n` in `∧` form rather than forcing `&&`.)
|
|
237
254
|
function needsBoolConnectives(e) {
|
|
238
|
-
return anyExpr(e, connectiveHasNonCoercibleOperand)
|
|
255
|
+
return anyExpr(e, x => connectiveHasNonCoercibleOperand(x) ||
|
|
256
|
+
((x.kind === "binop" && (x.op === "∧" || x.op === "∨") && anyExpr(x.right, y => y.kind === "checkedUnwrap")) ||
|
|
257
|
+
(x.kind === "if" && (anyExpr(x.then, y => y.kind === "checkedUnwrap") || anyExpr(x.else, y => y.kind === "checkedUnwrap")))));
|
|
239
258
|
}
|
|
240
259
|
function emitMethodCall(tyKind, method, monadic, obj, args) {
|
|
260
|
+
// Nullish<T> discriminators (#304)
|
|
261
|
+
if (tyKind === "nullish") {
|
|
262
|
+
_needsNullish = true;
|
|
263
|
+
if (method === "isNull" || method === "isUndefined" || method === "isValue") {
|
|
264
|
+
return `(${obj}).${method}`;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
241
267
|
// Array methods
|
|
242
268
|
if (tyKind === "array") {
|
|
243
269
|
if (method === "map")
|
|
@@ -333,6 +359,8 @@ function emitExpr(e, parentPrec) {
|
|
|
333
359
|
case "bool": return e.value ? "true" : "false";
|
|
334
360
|
case "str": return `"${e.value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n')}"`;
|
|
335
361
|
case "constructor": {
|
|
362
|
+
if (e.type === "Nullish")
|
|
363
|
+
_needsNullish = true;
|
|
336
364
|
// With type: emit `Type.name` (unambiguous; needed in expression positions
|
|
337
365
|
// like `match ... | .none => Type.some x` where elaboration can't infer).
|
|
338
366
|
// Without type: emit `.name` (dotted form; works in pattern positions
|
|
@@ -432,6 +460,22 @@ function emitExpr(e, parentPrec) {
|
|
|
432
460
|
: _boolCtx && e.op === "∧" ? "&&"
|
|
433
461
|
: _boolCtx && e.op === "∨" ? "||"
|
|
434
462
|
: e.op;
|
|
463
|
+
// In Lean 4, `&&`, `||`, `∧`, and `∨` are non-dependent, so
|
|
464
|
+
// `checkedUnwrap` (`(x).get (by grind)`) in the right operand has no
|
|
465
|
+
// hypothesis in context. Emit dependent `if _h : ...` when the RHS contains
|
|
466
|
+
// a `checkedUnwrap` so Lean puts the presence guard in scope for `grind`.
|
|
467
|
+
if ((e.op === "∧" || e.op === "∨") && anyExpr(e.right, x => x.kind === "checkedUnwrap")) {
|
|
468
|
+
const l = emitExpr(e.left);
|
|
469
|
+
const r = emitExpr(e.right);
|
|
470
|
+
const condProp = isPropValued(e.left) ? l : `(${l}) = true`;
|
|
471
|
+
const h = `_h${_depIfCounter++}`;
|
|
472
|
+
const tVal = _boolCtx ? "true" : "True";
|
|
473
|
+
const fVal = _boolCtx ? "false" : "False";
|
|
474
|
+
const rExpr = _boolCtx && isPropValued(e.right) ? `decide (${r})` : r;
|
|
475
|
+
return e.op === "∧"
|
|
476
|
+
? `(if ${h} : ${condProp} then (${rExpr}) else ${fVal})`
|
|
477
|
+
: `(if ${h} : ${condProp} then ${tVal} else (${rExpr}))`;
|
|
478
|
+
}
|
|
435
479
|
// Comparisons and ↔ do not chain in Lean. In particular, a Boolean
|
|
436
480
|
// postcondition `res = (s = t)` must keep its inner equality grouped.
|
|
437
481
|
const childPrec = ["↔", "=", "≠", "<", "≤", ">", "≥"].includes(e.op)
|
|
@@ -448,10 +492,26 @@ function emitExpr(e, parentPrec) {
|
|
|
448
492
|
// parens (→ is right-associative, so `(a → b) → c` ≠ `a → b → c`), and
|
|
449
493
|
// ↔ binds looser than → in Lean. The conclusion is the right-assoc tail,
|
|
450
494
|
// where a nested implication is safe bare — only ↔ needs parens there.
|
|
495
|
+
// When any later premise or the conclusion contains `checkedUnwrap`
|
|
496
|
+
// (`(x).get (by grind)`), bind earlier premises dependently via
|
|
497
|
+
// `∀ (_hN : p), ...` so Lean puts each premise in local proof context.
|
|
451
498
|
const wrapIff = (x) => x.kind === "binop" && x.op === "↔" ? `(${emitExpr(x)})` : undefined;
|
|
452
|
-
const
|
|
453
|
-
|
|
454
|
-
|
|
499
|
+
const tailHasCU = (idx) => anyExpr(e.conclusion, x => x.kind === "checkedUnwrap") ||
|
|
500
|
+
e.premises.slice(idx + 1).some(p => anyExpr(p, x => x.kind === "checkedUnwrap"));
|
|
501
|
+
let acc = wrapIff(e.conclusion) ?? emitExpr(e.conclusion);
|
|
502
|
+
for (let i = e.premises.length - 1; i >= 0; i--) {
|
|
503
|
+
const p = e.premises[i];
|
|
504
|
+
if (tailHasCU(i)) {
|
|
505
|
+
const pStr = emitExpr(p);
|
|
506
|
+
const pProp = isPropValued(p) ? pStr : `(${pStr}) = true`;
|
|
507
|
+
const h = `_h${_depIfCounter++}`;
|
|
508
|
+
acc = `∀ (${h} : ${pProp}), ${acc}`;
|
|
509
|
+
}
|
|
510
|
+
else {
|
|
511
|
+
acc = `${wrapOperand(p, prec("→"))} → ${acc}`;
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
return parentPrec !== undefined ? `(${acc})` : acc;
|
|
455
515
|
}
|
|
456
516
|
case "app": {
|
|
457
517
|
// A bare negative literal argument (`f -7 2`) parses as subtraction in Lean.
|
|
@@ -524,6 +584,8 @@ function emitExpr(e, parentPrec) {
|
|
|
524
584
|
return wrap ? `(${inner}).toNat` : `${inner}.toNat`;
|
|
525
585
|
}
|
|
526
586
|
case "toInt": return `(Int.ofNat (${emitExpr(e.expr)}))`;
|
|
587
|
+
case "checkedUnwrap":
|
|
588
|
+
return `((${emitExpr(e.expr)}).get (by grind))`;
|
|
527
589
|
case "toReal":
|
|
528
590
|
// A real value reached the Lean backend via coercion (e.g. number `/`).
|
|
529
591
|
// Same unsupported-real story as the `real` type case in tyToLean.
|
|
@@ -544,8 +606,20 @@ function emitExpr(e, parentPrec) {
|
|
|
544
606
|
return `{ ${emitExpr(e.spread)} with ${fields.join(", ")} }`;
|
|
545
607
|
return `{ ${fields.join(", ")} }`;
|
|
546
608
|
}
|
|
547
|
-
case "if":
|
|
609
|
+
case "if": {
|
|
610
|
+
const hasCU = anyExpr(e.then, x => x.kind === "checkedUnwrap") || anyExpr(e.else, x => x.kind === "checkedUnwrap");
|
|
611
|
+
if (hasCU) {
|
|
612
|
+
const c = emitExpr(e.cond);
|
|
613
|
+
const condProp = isPropValued(e.cond) ? c : `(${c}) = true`;
|
|
614
|
+
const h = `_h${_depIfCounter++}`;
|
|
615
|
+
const t = emitExpr(e.then);
|
|
616
|
+
const f = emitExpr(e.else);
|
|
617
|
+
const tExpr = _boolCtx && isPropValued(e.then) ? `decide (${t})` : t;
|
|
618
|
+
const fExpr = _boolCtx && isPropValued(e.else) ? `decide (${f})` : f;
|
|
619
|
+
return `(if ${h} : ${condProp} then (${tExpr}) else (${fExpr}))`;
|
|
620
|
+
}
|
|
548
621
|
return `if ${emitExpr(e.cond)} then ${emitExpr(e.then)} else ${emitExpr(e.else)}`;
|
|
622
|
+
}
|
|
549
623
|
case "match": {
|
|
550
624
|
// Always parenthesize inline matches — Lean parses alternatives greedily,
|
|
551
625
|
// so any token after an arm body (`→`, another match's `|`, etc.) would
|
|
@@ -556,7 +630,11 @@ function emitExpr(e, parentPrec) {
|
|
|
556
630
|
}
|
|
557
631
|
case "forall": return `∀ ${e.var} : ${tyToLean(e.type)}, ${emitExpr(e.body)}`;
|
|
558
632
|
case "exists": return `∃ ${e.var} : ${tyToLean(e.type)}, ${emitExpr(e.body)}`;
|
|
559
|
-
case "let":
|
|
633
|
+
case "let":
|
|
634
|
+
if (e.name.startsWith("_cmp")) {
|
|
635
|
+
return `(let ${e.name}${e.type ? ` : ${tyToLean(e.type)}` : ""} := ${emitExpr(e.value)}; ${emitExpr(e.body)})`;
|
|
636
|
+
}
|
|
637
|
+
return `let ${e.name}${e.type ? ` : ${tyToLean(e.type)}` : ""} := ${emitExpr(e.value)}\n${emitExpr(e.body)}`;
|
|
560
638
|
default: throw new Error(`Unsupported Lean expression: ${e.kind}`);
|
|
561
639
|
}
|
|
562
640
|
}
|
|
@@ -580,7 +658,26 @@ function isPropValued(e) {
|
|
|
580
658
|
}
|
|
581
659
|
// ── Statement emission ──────────────────────────────────────
|
|
582
660
|
function emitStmts(stmts, indent) {
|
|
583
|
-
|
|
661
|
+
const pad = " ".repeat(indent);
|
|
662
|
+
const out = [];
|
|
663
|
+
for (let i = 0; i < stmts.length; i++) {
|
|
664
|
+
const s = stmts[i];
|
|
665
|
+
const rest = stmts.slice(i + 1);
|
|
666
|
+
// Early-exit `if` followed by statements containing `checkedUnwrap`:
|
|
667
|
+
// nest the continuation in the `else` branch of a dependent `if _hN : ...`
|
|
668
|
+
// so Lean keeps the negated guard in local proof context for `grind`.
|
|
669
|
+
if (s.kind === "if" && s.else.length === 0 && rest.length > 0 && s.then.length > 0 &&
|
|
670
|
+
["return", "break", "continue"].includes(s.then[s.then.length - 1].kind) &&
|
|
671
|
+
anyExprInStmts(rest, x => x.kind === "checkedUnwrap")) {
|
|
672
|
+
const c = emitExpr(s.cond);
|
|
673
|
+
const condProp = isPropValued(s.cond) ? c : `(${c}) = true`;
|
|
674
|
+
const h = `_h${_depIfCounter++}`;
|
|
675
|
+
out.push(`${pad}if ${h} : ${condProp} then\n${emitStmts(s.then, indent + 1)}\n${pad}else\n${emitStmts(rest, indent + 1)}`);
|
|
676
|
+
break;
|
|
677
|
+
}
|
|
678
|
+
out.push(emitStmt(s, indent));
|
|
679
|
+
}
|
|
680
|
+
return out.join("\n");
|
|
584
681
|
}
|
|
585
682
|
function emitStmt(s, indent) {
|
|
586
683
|
const pad = " ".repeat(indent);
|
|
@@ -623,9 +720,18 @@ function emitStmt(s, indent) {
|
|
|
623
720
|
case "break": return `${pad}break`;
|
|
624
721
|
case "continue": return `${pad}continue`;
|
|
625
722
|
case "if": {
|
|
626
|
-
|
|
723
|
+
const hasCU = anyExprInStmts(s.then, x => x.kind === "checkedUnwrap") ||
|
|
724
|
+
anyExprInStmts(s.else, x => x.kind === "checkedUnwrap");
|
|
725
|
+
const condText = hasCU
|
|
726
|
+
? (() => {
|
|
727
|
+
const c = emitExpr(s.cond);
|
|
728
|
+
const condProp = isPropValued(s.cond) ? c : `(${c}) = true`;
|
|
729
|
+
return `_h${_depIfCounter++} : ${condProp}`;
|
|
730
|
+
})()
|
|
731
|
+
: emitExpr(s.cond);
|
|
732
|
+
let out = `${pad}if ${condText} then\n${emitStmts(s.then, indent + 1)}`;
|
|
627
733
|
if (s.else.length > 0) {
|
|
628
|
-
if (s.else.length === 1 && s.else[0].kind === "if") {
|
|
734
|
+
if (!hasCU && s.else.length === 1 && s.else[0].kind === "if") {
|
|
629
735
|
const ei = s.else[0];
|
|
630
736
|
out += `\n${pad}else if ${emitExpr(ei.cond)} then\n${emitStmts(ei.then, indent + 1)}`;
|
|
631
737
|
if (ei.else.length > 0)
|
|
@@ -888,8 +994,16 @@ function emitDecl(d) {
|
|
|
888
994
|
function emitPureExpr(e, indent) {
|
|
889
995
|
const pad = " ".repeat(indent);
|
|
890
996
|
switch (e.kind) {
|
|
891
|
-
case "if":
|
|
997
|
+
case "if": {
|
|
998
|
+
const hasCU = anyExpr(e.then, x => x.kind === "checkedUnwrap") || anyExpr(e.else, x => x.kind === "checkedUnwrap");
|
|
999
|
+
if (hasCU) {
|
|
1000
|
+
const c = emitExpr(e.cond);
|
|
1001
|
+
const condProp = isPropValued(e.cond) ? c : `(${c}) = true`;
|
|
1002
|
+
const h = `_h${_depIfCounter++}`;
|
|
1003
|
+
return `${pad}if ${h} : ${condProp} then\n${emitPureExpr(e.then, indent + 1)}\n${pad}else\n${emitPureExpr(e.else, indent + 1)}`;
|
|
1004
|
+
}
|
|
892
1005
|
return `${pad}if ${emitExpr(e.cond)} then\n${emitPureExpr(e.then, indent + 1)}\n${pad}else\n${emitPureExpr(e.else, indent + 1)}`;
|
|
1006
|
+
}
|
|
893
1007
|
case "match": {
|
|
894
1008
|
const lines = [`${pad}match ${emitExpr(e.scrutinee)} with`];
|
|
895
1009
|
for (const arm of e.arms) {
|
|
@@ -915,15 +1029,19 @@ export function resetLeanModule() {
|
|
|
915
1029
|
_typeRefs.clear();
|
|
916
1030
|
_taintedTypes.clear();
|
|
917
1031
|
_needsJSString = false;
|
|
1032
|
+
_needsNullish = false;
|
|
918
1033
|
_needsUnknown = false;
|
|
919
1034
|
_unknownEmitted = false;
|
|
1035
|
+
_depIfCounter = 0;
|
|
920
1036
|
_boolCtx = false;
|
|
921
1037
|
}
|
|
922
1038
|
export function emitLeanFile(file) {
|
|
923
1039
|
_needsJSString = false;
|
|
1040
|
+
_needsNullish = false;
|
|
924
1041
|
_needsUnknown = false;
|
|
1042
|
+
_depIfCounter = 0;
|
|
925
1043
|
registerInductives(file.decls);
|
|
926
|
-
// Emit declarations first so _needsJSString / _needsUnknown are set
|
|
1044
|
+
// Emit declarations first so _needsJSString / _needsNullish / _needsUnknown are set
|
|
927
1045
|
const declLines = [];
|
|
928
1046
|
for (const decl of file.decls) {
|
|
929
1047
|
declLines.push("");
|
|
@@ -944,6 +1062,8 @@ export function emitLeanFile(file) {
|
|
|
944
1062
|
lines.push(`import ${imp}`);
|
|
945
1063
|
if (_needsJSString && !file.imports.includes("LemmaScript.JSString"))
|
|
946
1064
|
lines.push("import LemmaScript.JSString");
|
|
1065
|
+
if (_needsNullish && !file.imports.includes("LemmaScript.Nullish"))
|
|
1066
|
+
lines.push("import LemmaScript.Nullish");
|
|
947
1067
|
if (file.options.length > 0)
|
|
948
1068
|
lines.push("");
|
|
949
1069
|
for (const opt of file.options)
|
package/tools/dist/lsc.js
CHANGED
|
@@ -10,6 +10,7 @@ import { createRequire } from "module";
|
|
|
10
10
|
import path from "path";
|
|
11
11
|
import { extractModule } from "./extract.js";
|
|
12
12
|
import { resolveModule } from "./resolve.js";
|
|
13
|
+
import { assertNoLiveAliasMutations } from "./alias-check-pass.js";
|
|
13
14
|
import { narrowModule } from "./narrow.js";
|
|
14
15
|
import { autoHavocModule } from "./autohavoc.js";
|
|
15
16
|
import { transformModuleLean, transformModuleDafny } from "./transform.js";
|
|
@@ -336,7 +337,7 @@ function runFile(cmd, filePath, backend, timeLimit, extraFlags, noVerify = false
|
|
|
336
337
|
return;
|
|
337
338
|
}
|
|
338
339
|
// Resolve: Raw IR → Typed IR
|
|
339
|
-
const resolved = resolveModule(raw);
|
|
340
|
+
const resolved = assertNoLiveAliasMutations(resolveModule(raw));
|
|
340
341
|
// Narrow: Typed IR → Typed IR (rewrites optional-narrowing patterns to someMatch)
|
|
341
342
|
// auto-havoc (//@ autohavoc): replace unmodellable expressions with arbitrary
|
|
342
343
|
// values so verification rests only on the declared contracts (a sound
|