lemmascript 0.6.13 → 0.6.15
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 +10 -0
- package/package.json +1 -1
- package/tools/dist/alias-check-pass.js +13 -1
- package/tools/dist/builtins.js +20 -20
- package/tools/dist/checked-reads.js +125 -38
- package/tools/dist/condition-facts.js +113 -31
- package/tools/dist/config.js +42 -6
- package/tools/dist/dafny-commands.js +22 -6
- package/tools/dist/dafny-emit.js +35 -4
- package/tools/dist/dafny-proof-additions.js +1 -1
- package/tools/dist/extract.js +34 -13
- package/tools/dist/lean-emit.js +164 -25
- package/tools/dist/lsc.js +10 -5
- package/tools/dist/narrow-checks.js +9 -3
- package/tools/dist/narrow.js +42 -41
- package/tools/dist/place-lowering.js +22 -63
- package/tools/dist/resolve.js +752 -224
- package/tools/dist/run-log.js +15 -1
- package/tools/dist/specparser.js +10 -6
- package/tools/dist/transform.js +971 -440
- package/tools/dist/typedecls.js +7 -0
- package/tools/dist/typedir.js +19 -1
- package/tools/dist/types.js +52 -15
package/tools/dist/lean-emit.js
CHANGED
|
@@ -4,8 +4,8 @@
|
|
|
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";
|
|
8
|
-
import { freshName, freshNameWhere } from "./names.js";
|
|
7
|
+
import { anyExpr, anyExprInStmts, decimalNumberLiteral, usesName, usesNameInDecl, patternBinders } from "./ir.js";
|
|
8
|
+
import { freshName, freshNameWhere, isUserName } from "./names.js";
|
|
9
9
|
// ── Ty → Lean type string ──────────────────────────────────
|
|
10
10
|
function tyToLean(ty) {
|
|
11
11
|
switch (ty.kind) {
|
|
@@ -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,9 +57,14 @@ 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
|
-
const params = ty.params.map(p => {
|
|
67
|
+
const params = ty.params.length === 0 ? ["Unit"] : ty.params.map(p => {
|
|
62
68
|
const s = tyToLean(p);
|
|
63
69
|
return s.includes(" ") ? `(${s})` : s;
|
|
64
70
|
});
|
|
@@ -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
|
|
@@ -391,7 +419,9 @@ function emitExpr(e, parentPrec) {
|
|
|
391
419
|
return emitMethodCall(e.objTy.kind, e.method, e.monadic, receiver, args);
|
|
392
420
|
}
|
|
393
421
|
case "lambda": {
|
|
394
|
-
const params = e.params.
|
|
422
|
+
const params = e.params.length === 0
|
|
423
|
+
? (e.typedParams ? "(_ : Unit)" : "()")
|
|
424
|
+
: e.params.map(p => e.typedParams ? `(${p.name} : ${tyToLean(p.type)})` : p.name).join(" ");
|
|
395
425
|
// Single return statement → expression lambda
|
|
396
426
|
if (e.body.length === 1 && e.body[0].kind === "return") {
|
|
397
427
|
return `(fun ${params} => ${emitExpr(e.body[0].value)})`;
|
|
@@ -440,12 +470,13 @@ function emitExpr(e, parentPrec) {
|
|
|
440
470
|
const l = emitExpr(e.left);
|
|
441
471
|
const r = emitExpr(e.right);
|
|
442
472
|
const condProp = isPropValued(e.left) ? l : `(${l}) = true`;
|
|
473
|
+
const h = `_h${_depIfCounter++}`;
|
|
443
474
|
const tVal = _boolCtx ? "true" : "True";
|
|
444
475
|
const fVal = _boolCtx ? "false" : "False";
|
|
445
476
|
const rExpr = _boolCtx && isPropValued(e.right) ? `decide (${r})` : r;
|
|
446
477
|
return e.op === "∧"
|
|
447
|
-
? `(if
|
|
448
|
-
: `(if
|
|
478
|
+
? `(if ${h} : ${condProp} then (${rExpr}) else ${fVal})`
|
|
479
|
+
: `(if ${h} : ${condProp} then ${tVal} else (${rExpr}))`;
|
|
449
480
|
}
|
|
450
481
|
// Comparisons and ↔ do not chain in Lean. In particular, a Boolean
|
|
451
482
|
// postcondition `res = (s = t)` must keep its inner equality grouped.
|
|
@@ -463,10 +494,26 @@ function emitExpr(e, parentPrec) {
|
|
|
463
494
|
// parens (→ is right-associative, so `(a → b) → c` ≠ `a → b → c`), and
|
|
464
495
|
// ↔ binds looser than → in Lean. The conclusion is the right-assoc tail,
|
|
465
496
|
// where a nested implication is safe bare — only ↔ needs parens there.
|
|
497
|
+
// When any later premise or the conclusion contains `checkedUnwrap`
|
|
498
|
+
// (`(x).get (by grind)`), bind earlier premises dependently via
|
|
499
|
+
// `∀ (_hN : p), ...` so Lean puts each premise in local proof context.
|
|
466
500
|
const wrapIff = (x) => x.kind === "binop" && x.op === "↔" ? `(${emitExpr(x)})` : undefined;
|
|
467
|
-
const
|
|
468
|
-
|
|
469
|
-
|
|
501
|
+
const tailHasCU = (idx) => anyExpr(e.conclusion, x => x.kind === "checkedUnwrap") ||
|
|
502
|
+
e.premises.slice(idx + 1).some(p => anyExpr(p, x => x.kind === "checkedUnwrap"));
|
|
503
|
+
let acc = wrapIff(e.conclusion) ?? emitExpr(e.conclusion);
|
|
504
|
+
for (let i = e.premises.length - 1; i >= 0; i--) {
|
|
505
|
+
const p = e.premises[i];
|
|
506
|
+
if (tailHasCU(i)) {
|
|
507
|
+
const pStr = emitExpr(p);
|
|
508
|
+
const pProp = isPropValued(p) ? pStr : `(${pStr}) = true`;
|
|
509
|
+
const h = `_h${_depIfCounter++}`;
|
|
510
|
+
acc = `∀ (${h} : ${pProp}), ${acc}`;
|
|
511
|
+
}
|
|
512
|
+
else {
|
|
513
|
+
acc = `${wrapOperand(p, prec("→"))} → ${acc}`;
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
return parentPrec !== undefined ? `(${acc})` : acc;
|
|
470
517
|
}
|
|
471
518
|
case "app": {
|
|
472
519
|
// A bare negative literal argument (`f -7 2`) parses as subtraction in Lean.
|
|
@@ -516,15 +563,29 @@ function emitExpr(e, parentPrec) {
|
|
|
516
563
|
// access with a discriminator test, so that branch is never reached.
|
|
517
564
|
if (e.fromUnion) {
|
|
518
565
|
const ctors = _unionCtors.get(e.fromUnion);
|
|
519
|
-
// Pin the owning ctor when given (field names repeat across variants
|
|
520
|
-
//
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
566
|
+
// Pin the owning ctor when given (field names repeat across variants
|
|
567
|
+
// with distinct types or narrowed provenance); otherwise project the
|
|
568
|
+
// field from every constructor carrying it with a common Lean type so
|
|
569
|
+
// reads after reassignment return the live variant's value rather than `default`.
|
|
570
|
+
let owners = e.ctor
|
|
571
|
+
? ctors?.filter(c => c.name === e.ctor)
|
|
572
|
+
: ctors?.filter(c => c.fields.some(f => f.name === e.field));
|
|
573
|
+
if (owners && owners.length > 0 && ctors) {
|
|
574
|
+
const firstIdx = owners[0].fields.findIndex(f => f.name === e.field);
|
|
575
|
+
const fty = tyToLean(owners[0].fields[firstIdx].type);
|
|
576
|
+
const compatible = Boolean(e.ctor) || owners.every(c => {
|
|
577
|
+
const idx = c.fields.findIndex(f => f.name === e.field);
|
|
578
|
+
return idx >= 0 && tyToLean(c.fields[idx].type) === fty;
|
|
579
|
+
});
|
|
580
|
+
if (compatible) {
|
|
581
|
+
const arms = owners.map(owner => {
|
|
582
|
+
const idx = owner.fields.findIndex(f => f.name === e.field);
|
|
583
|
+
const pats = owner.fields.map((_, i) => (i === idx ? "_v" : "_")).join(" ");
|
|
584
|
+
return `| .${leanCtorName(owner.name)} ${pats} => _v`;
|
|
585
|
+
});
|
|
586
|
+
const fallback = owners.length < ctors.length ? ` | _ => (default : ${fty})` : "";
|
|
587
|
+
return `(match ${emitExpr(e.obj)} with ${arms.join(" ")}${fallback})`;
|
|
588
|
+
}
|
|
528
589
|
}
|
|
529
590
|
}
|
|
530
591
|
const obj = emitExpr(e.obj);
|
|
@@ -556,6 +617,41 @@ function emitExpr(e, parentPrec) {
|
|
|
556
617
|
return `${wrap ? `(${arr})` : arr}[${emitExpr(e.idx)}]!`;
|
|
557
618
|
}
|
|
558
619
|
case "record": {
|
|
620
|
+
if (e.spread && e.ctorOf && _unionCtors.has(e.ctorOf)) {
|
|
621
|
+
const ctors = _unionCtors.get(e.ctorOf);
|
|
622
|
+
const hasAllFields = (c) => e.fields.every(f => c.fields.some(cf => cf.name === f.name));
|
|
623
|
+
const targetCtors = (e.ctor ? ctors.filter(c => c.name === e.ctor) : ctors).filter(hasAllFields);
|
|
624
|
+
if (targetCtors.length > 0) {
|
|
625
|
+
const updatesByName = new Map(e.fields.map(f => [f.name, emitExpr(f.value)]));
|
|
626
|
+
const updText = [...updatesByName.values()].join(" ");
|
|
627
|
+
const arms = targetCtors.map(c => {
|
|
628
|
+
const pats = [];
|
|
629
|
+
const args = [];
|
|
630
|
+
const usedBinders = new Set();
|
|
631
|
+
c.fields.forEach((cf, i) => {
|
|
632
|
+
const upd = updatesByName.get(cf.name);
|
|
633
|
+
if (upd !== undefined) {
|
|
634
|
+
pats.push("_");
|
|
635
|
+
args.push(`(${upd})`);
|
|
636
|
+
}
|
|
637
|
+
else {
|
|
638
|
+
const bv = freshNameWhere(`_f${i}`, name => isUserName(name) ||
|
|
639
|
+
usedBinders.has(name) ||
|
|
640
|
+
e.fields.some(f => usesName(f.value, name)) ||
|
|
641
|
+
updText.includes(name));
|
|
642
|
+
usedBinders.add(bv);
|
|
643
|
+
pats.push(bv);
|
|
644
|
+
args.push(bv);
|
|
645
|
+
}
|
|
646
|
+
});
|
|
647
|
+
const patStr = pats.length > 0 ? `.${leanCtorName(c.name)} ${pats.join(" ")}` : `.${leanCtorName(c.name)}`;
|
|
648
|
+
const rhsStr = args.length > 0 ? `${e.ctorOf}.${leanCtorName(c.name)} ${args.join(" ")}` : `${e.ctorOf}.${leanCtorName(c.name)}`;
|
|
649
|
+
return `| ${patStr} => ${rhsStr}`;
|
|
650
|
+
});
|
|
651
|
+
const fallback = targetCtors.length < ctors.length ? " | _other => _other" : "";
|
|
652
|
+
return `(match ${emitExpr(e.spread)} with ${arms.join(" ")}${fallback})`;
|
|
653
|
+
}
|
|
654
|
+
}
|
|
559
655
|
const fields = e.fields.map(f => `${escapeName(f.name)} := ${emitExpr(f.value)}`);
|
|
560
656
|
if (e.spread)
|
|
561
657
|
return `{ ${emitExpr(e.spread)} with ${fields.join(", ")} }`;
|
|
@@ -566,11 +662,12 @@ function emitExpr(e, parentPrec) {
|
|
|
566
662
|
if (hasCU) {
|
|
567
663
|
const c = emitExpr(e.cond);
|
|
568
664
|
const condProp = isPropValued(e.cond) ? c : `(${c}) = true`;
|
|
665
|
+
const h = `_h${_depIfCounter++}`;
|
|
569
666
|
const t = emitExpr(e.then);
|
|
570
667
|
const f = emitExpr(e.else);
|
|
571
668
|
const tExpr = _boolCtx && isPropValued(e.then) ? `decide (${t})` : t;
|
|
572
669
|
const fExpr = _boolCtx && isPropValued(e.else) ? `decide (${f})` : f;
|
|
573
|
-
return `(if
|
|
670
|
+
return `(if ${h} : ${condProp} then (${tExpr}) else (${fExpr}))`;
|
|
574
671
|
}
|
|
575
672
|
return `if ${emitExpr(e.cond)} then ${emitExpr(e.then)} else ${emitExpr(e.else)}`;
|
|
576
673
|
}
|
|
@@ -612,7 +709,26 @@ function isPropValued(e) {
|
|
|
612
709
|
}
|
|
613
710
|
// ── Statement emission ──────────────────────────────────────
|
|
614
711
|
function emitStmts(stmts, indent) {
|
|
615
|
-
|
|
712
|
+
const pad = " ".repeat(indent);
|
|
713
|
+
const out = [];
|
|
714
|
+
for (let i = 0; i < stmts.length; i++) {
|
|
715
|
+
const s = stmts[i];
|
|
716
|
+
const rest = stmts.slice(i + 1);
|
|
717
|
+
// Early-exit `if` followed by statements containing `checkedUnwrap`:
|
|
718
|
+
// nest the continuation in the `else` branch of a dependent `if _hN : ...`
|
|
719
|
+
// so Lean keeps the negated guard in local proof context for `grind`.
|
|
720
|
+
if (s.kind === "if" && s.else.length === 0 && rest.length > 0 && s.then.length > 0 &&
|
|
721
|
+
["return", "break", "continue"].includes(s.then[s.then.length - 1].kind) &&
|
|
722
|
+
anyExprInStmts(rest, x => x.kind === "checkedUnwrap")) {
|
|
723
|
+
const c = emitExpr(s.cond);
|
|
724
|
+
const condProp = isPropValued(s.cond) ? c : `(${c}) = true`;
|
|
725
|
+
const h = `_h${_depIfCounter++}`;
|
|
726
|
+
out.push(`${pad}if ${h} : ${condProp} then\n${emitStmts(s.then, indent + 1)}\n${pad}else\n${emitStmts(rest, indent + 1)}`);
|
|
727
|
+
break;
|
|
728
|
+
}
|
|
729
|
+
out.push(emitStmt(s, indent));
|
|
730
|
+
}
|
|
731
|
+
return out.join("\n");
|
|
616
732
|
}
|
|
617
733
|
function emitStmt(s, indent) {
|
|
618
734
|
const pad = " ".repeat(indent);
|
|
@@ -655,9 +771,18 @@ function emitStmt(s, indent) {
|
|
|
655
771
|
case "break": return `${pad}break`;
|
|
656
772
|
case "continue": return `${pad}continue`;
|
|
657
773
|
case "if": {
|
|
658
|
-
|
|
774
|
+
const hasCU = anyExprInStmts(s.then, x => x.kind === "checkedUnwrap") ||
|
|
775
|
+
anyExprInStmts(s.else, x => x.kind === "checkedUnwrap");
|
|
776
|
+
const condText = hasCU
|
|
777
|
+
? (() => {
|
|
778
|
+
const c = emitExpr(s.cond);
|
|
779
|
+
const condProp = isPropValued(s.cond) ? c : `(${c}) = true`;
|
|
780
|
+
return `_h${_depIfCounter++} : ${condProp}`;
|
|
781
|
+
})()
|
|
782
|
+
: emitExpr(s.cond);
|
|
783
|
+
let out = `${pad}if ${condText} then\n${emitStmts(s.then, indent + 1)}`;
|
|
659
784
|
if (s.else.length > 0) {
|
|
660
|
-
if (s.else.length === 1 && s.else[0].kind === "if") {
|
|
785
|
+
if (!hasCU && s.else.length === 1 && s.else[0].kind === "if") {
|
|
661
786
|
const ei = s.else[0];
|
|
662
787
|
out += `\n${pad}else if ${emitExpr(ei.cond)} then\n${emitStmts(ei.then, indent + 1)}`;
|
|
663
788
|
if (ei.else.length > 0)
|
|
@@ -920,8 +1045,16 @@ function emitDecl(d) {
|
|
|
920
1045
|
function emitPureExpr(e, indent) {
|
|
921
1046
|
const pad = " ".repeat(indent);
|
|
922
1047
|
switch (e.kind) {
|
|
923
|
-
case "if":
|
|
1048
|
+
case "if": {
|
|
1049
|
+
const hasCU = anyExpr(e.then, x => x.kind === "checkedUnwrap") || anyExpr(e.else, x => x.kind === "checkedUnwrap");
|
|
1050
|
+
if (hasCU) {
|
|
1051
|
+
const c = emitExpr(e.cond);
|
|
1052
|
+
const condProp = isPropValued(e.cond) ? c : `(${c}) = true`;
|
|
1053
|
+
const h = `_h${_depIfCounter++}`;
|
|
1054
|
+
return `${pad}if ${h} : ${condProp} then\n${emitPureExpr(e.then, indent + 1)}\n${pad}else\n${emitPureExpr(e.else, indent + 1)}`;
|
|
1055
|
+
}
|
|
924
1056
|
return `${pad}if ${emitExpr(e.cond)} then\n${emitPureExpr(e.then, indent + 1)}\n${pad}else\n${emitPureExpr(e.else, indent + 1)}`;
|
|
1057
|
+
}
|
|
925
1058
|
case "match": {
|
|
926
1059
|
const lines = [`${pad}match ${emitExpr(e.scrutinee)} with`];
|
|
927
1060
|
for (const arm of e.arms) {
|
|
@@ -947,15 +1080,19 @@ export function resetLeanModule() {
|
|
|
947
1080
|
_typeRefs.clear();
|
|
948
1081
|
_taintedTypes.clear();
|
|
949
1082
|
_needsJSString = false;
|
|
1083
|
+
_needsNullish = false;
|
|
950
1084
|
_needsUnknown = false;
|
|
951
1085
|
_unknownEmitted = false;
|
|
1086
|
+
_depIfCounter = 0;
|
|
952
1087
|
_boolCtx = false;
|
|
953
1088
|
}
|
|
954
1089
|
export function emitLeanFile(file) {
|
|
955
1090
|
_needsJSString = false;
|
|
1091
|
+
_needsNullish = false;
|
|
956
1092
|
_needsUnknown = false;
|
|
1093
|
+
_depIfCounter = 0;
|
|
957
1094
|
registerInductives(file.decls);
|
|
958
|
-
// Emit declarations first so _needsJSString / _needsUnknown are set
|
|
1095
|
+
// Emit declarations first so _needsJSString / _needsNullish / _needsUnknown are set
|
|
959
1096
|
const declLines = [];
|
|
960
1097
|
for (const decl of file.decls) {
|
|
961
1098
|
declLines.push("");
|
|
@@ -976,6 +1113,8 @@ export function emitLeanFile(file) {
|
|
|
976
1113
|
lines.push(`import ${imp}`);
|
|
977
1114
|
if (_needsJSString && !file.imports.includes("LemmaScript.JSString"))
|
|
978
1115
|
lines.push("import LemmaScript.JSString");
|
|
1116
|
+
if (_needsNullish && !file.imports.includes("LemmaScript.Nullish"))
|
|
1117
|
+
lines.push("import LemmaScript.Nullish");
|
|
979
1118
|
if (file.options.length > 0)
|
|
980
1119
|
lines.push("");
|
|
981
1120
|
for (const opt of file.options)
|
package/tools/dist/lsc.js
CHANGED
|
@@ -17,14 +17,14 @@ import { transformModuleLean, transformModuleDafny } from "./transform.js";
|
|
|
17
17
|
import { peepholeModule } from "./peephole.js";
|
|
18
18
|
import { emitLeanFile, resetLeanModule } from "./lean-emit.js";
|
|
19
19
|
import { emitDafnyFile, emittedNameMap } from "./dafny-emit.js";
|
|
20
|
-
import { dafnyGen, dafnyCheckDiff, dafnyVerify, dafnyRegen } from "./dafny-commands.js";
|
|
20
|
+
import { dafnyGen, dafnyCheckDiff, dafnyVerify, dafnyRegen, readDafnyProofFiles } from "./dafny-commands.js";
|
|
21
21
|
import { leanGen, leanCheck } from "./lean-commands.js";
|
|
22
22
|
import { runInfo, runTypedInfo } from "./info-command.js";
|
|
23
23
|
import { RunLog, resolveLogDir, runLogEnabled, safely } from "./run-log.js";
|
|
24
24
|
import { runRuns } from "./runs-command.js";
|
|
25
25
|
import { runGuard } from "./guard-command.js";
|
|
26
26
|
import { SourceProjects } from "./source-projects.js";
|
|
27
|
-
import { loadConfigOptions, parseFileOptions, resolveDafnyArtifactDir, resolveOptions, } from "./config.js";
|
|
27
|
+
import { loadConfigOptions, parseFileOptions, resolveDafnyArtifactDir, resolveDafnyProofFiles, resolveOptions, } from "./config.js";
|
|
28
28
|
/** Version of the lemmascript package — the root package.json sits two levels
|
|
29
29
|
* above this module from both tools/src/ (tsx) and tools/dist/ (installed). */
|
|
30
30
|
function lscVersion() {
|
|
@@ -383,14 +383,19 @@ function runFile(cmd, filePath, backend, timeLimit, extraFlags, noVerify = false
|
|
|
383
383
|
mkdirSync(artifactDir, { recursive: true });
|
|
384
384
|
// Record check/regen runs in the run log. Created after the proof-dir guard
|
|
385
385
|
// so an aborted run leaves no snapshot; each helper records the stage it detects.
|
|
386
|
+
const proofFiles = resolveDafnyProofFiles(absPath, configFile, options);
|
|
386
387
|
const logCmd = cmd === "check" || cmd === "regen" ? cmd : null;
|
|
387
388
|
const log = logCmd && runLogOn
|
|
388
|
-
? new RunLog({
|
|
389
|
+
? new RunLog({
|
|
390
|
+
logDir: resolveLogDir(absPath, configFile), cmd: logCmd, sourcePath: absPath,
|
|
391
|
+
proofFiles, extraFlags, lscVersion: safely(lscVersion),
|
|
392
|
+
})
|
|
389
393
|
: undefined;
|
|
390
394
|
if (cmd === "gen") {
|
|
391
395
|
dafnyGen(genPath, dfyPath, text, basePath);
|
|
392
396
|
return;
|
|
393
397
|
}
|
|
398
|
+
const proofs = readDafnyProofFiles(proofFiles, dfyPath, log);
|
|
394
399
|
if (cmd === "gen-check") {
|
|
395
400
|
dafnyGen(genPath, dfyPath, text, basePath);
|
|
396
401
|
if (!dafnyCheckDiff(genPath, dfyPath, undefined, basePath))
|
|
@@ -401,12 +406,12 @@ function runFile(cmd, filePath, backend, timeLimit, extraFlags, noVerify = false
|
|
|
401
406
|
dafnyGen(genPath, dfyPath, text, basePath);
|
|
402
407
|
if (!dafnyCheckDiff(genPath, dfyPath, log, basePath))
|
|
403
408
|
process.exit(1);
|
|
404
|
-
if (!dafnyVerify(dfyPath, artifactDir, timeLimit, extraFlags, log))
|
|
409
|
+
if (!dafnyVerify(dfyPath, artifactDir, timeLimit, extraFlags, log, proofs))
|
|
405
410
|
process.exit(1);
|
|
406
411
|
return;
|
|
407
412
|
}
|
|
408
413
|
if (cmd === "regen") {
|
|
409
|
-
dafnyRegen(genPath, dfyPath, basePath, text, artifactDir, timeLimit, extraFlags, noVerify, log);
|
|
414
|
+
dafnyRegen(genPath, dfyPath, basePath, text, artifactDir, timeLimit, extraFlags, noVerify, log, proofs);
|
|
410
415
|
return;
|
|
411
416
|
}
|
|
412
417
|
console.error(`Unknown command: ${cmd}`);
|
|
@@ -113,7 +113,7 @@ function declaredTy(e, scope, ctx) {
|
|
|
113
113
|
if (e.kind !== "field")
|
|
114
114
|
return null;
|
|
115
115
|
const objTy = declaredTy(e.obj, scope, ctx);
|
|
116
|
-
if (!objTy || objTy.kind === "optional")
|
|
116
|
+
if (!objTy || objTy.kind === "optional" || objTy.kind === "nullish")
|
|
117
117
|
return null;
|
|
118
118
|
return fieldTy(objTy, e.field, e.ofVariant, ctx);
|
|
119
119
|
}
|
|
@@ -147,9 +147,15 @@ function fieldInfoTy(f) {
|
|
|
147
147
|
if (!f)
|
|
148
148
|
return null;
|
|
149
149
|
const ty = f.type ?? parseTsType(f.tsType);
|
|
150
|
-
|
|
150
|
+
if (!f.optionalKey)
|
|
151
|
+
return ty;
|
|
152
|
+
if (ty.kind === "nullish")
|
|
153
|
+
return ty;
|
|
154
|
+
if (ty.kind === "optional")
|
|
155
|
+
return ty.absent === "null" ? { kind: "nullish", inner: ty.inner } : ty;
|
|
156
|
+
return { kind: "optional", inner: ty };
|
|
151
157
|
}
|
|
152
|
-
const isOptional = (ty) => ty?.kind === "optional";
|
|
158
|
+
const isOptional = (ty) => ty?.kind === "optional" || ty?.kind === "nullish";
|
|
153
159
|
/** The type to judge a value by: declared for an access path, otherwise the stamp. */
|
|
154
160
|
function valueTy(e, scope, ctx) {
|
|
155
161
|
return declaredTy(e, scope, ctx) ?? exprTy(e);
|
package/tools/dist/narrow.js
CHANGED
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
*/
|
|
36
36
|
import { isTerminatorKind } from "./typedir.js";
|
|
37
37
|
import { builtinSpec } from "./builtins.js";
|
|
38
|
-
import {
|
|
38
|
+
import { optionalPresentFact, leadingPresent, leadingIsArray, flattenOr, noneDetector, excludesUndefined, bindPresentFact, freshPathBinder, binderHintForMapAccess, freshOcBinder, applyChain, restoreDiscriminantFlag, arrayBoundsCond, exprEqual, isArrayFact, typeofStringFact, variantFact, negVariantFact, presentMatchStmts, presentMatchExpr, } from "./condition-facts.js";
|
|
39
39
|
import { insertCheckedUnwraps } from "./checked-reads.js";
|
|
40
40
|
// ── Walkers ──────────────────────────────────────────────────
|
|
41
41
|
function walkExpr(e, ctx) {
|
|
@@ -170,52 +170,43 @@ function exprPathStr(e) {
|
|
|
170
170
|
return null;
|
|
171
171
|
}
|
|
172
172
|
/** True if `stmts` contains an assignment to `pathStr` (or any prefix of
|
|
173
|
-
* `pathStr`, e.g. `box = ...` when narrowing `box.val`)
|
|
174
|
-
*
|
|
175
|
-
*
|
|
176
|
-
|
|
173
|
+
* `pathStr`, e.g. `box = ...` when narrowing `box.val`). Direct reassignment
|
|
174
|
+
* of a `someMatch` scrutinee (`x = 5`, `x = undefined`, `box = newBox`) would
|
|
175
|
+
* either assign to an immutable Dafny match binder or leave the binder stale;
|
|
176
|
+
* deferring to `if` + `checkedUnwrap` keeps all reads and writes on live storage. */
|
|
177
|
+
function stmtsMayReassignPath(stmts, pathStr) {
|
|
177
178
|
for (const s of stmts) {
|
|
178
179
|
if (s.kind === "assign") {
|
|
179
|
-
if (s.target === pathStr) {
|
|
180
|
-
const isSomeWrap = s.value.kind === "call" && s.value.fn.kind === "var" &&
|
|
181
|
-
s.value.fn.name === "Some" && s.value.args.length === 1;
|
|
182
|
-
if (!isSomeWrap && (s.value.ty.kind === "optional" || s.value.ty.kind === "void" ||
|
|
183
|
-
(s.value.kind === "var" && s.value.name === "undefined"))) {
|
|
184
|
-
return true;
|
|
185
|
-
}
|
|
186
|
-
}
|
|
187
|
-
else if (pathStr.startsWith(`${s.target}.`)) {
|
|
188
|
-
// Reassigning a container prefix (e.g. `box = newBox`) can replace the
|
|
189
|
-
// narrowed field with None, making a binder on `box.val` stale.
|
|
180
|
+
if (s.target === pathStr || pathStr.startsWith(`${s.target}.`)) {
|
|
190
181
|
return true;
|
|
191
182
|
}
|
|
192
183
|
}
|
|
193
184
|
else if (s.kind === "if") {
|
|
194
|
-
if (
|
|
185
|
+
if (stmtsMayReassignPath(s.then, pathStr) || stmtsMayReassignPath(s.else, pathStr))
|
|
195
186
|
return true;
|
|
196
187
|
}
|
|
197
188
|
else if (s.kind === "while" || s.kind === "forof") {
|
|
198
|
-
if (
|
|
189
|
+
if (stmtsMayReassignPath(s.body, pathStr))
|
|
199
190
|
return true;
|
|
200
191
|
}
|
|
201
192
|
else if (s.kind === "switch") {
|
|
202
|
-
if (s.cases.some(c =>
|
|
193
|
+
if (s.cases.some(c => stmtsMayReassignPath(c.body, pathStr)) || stmtsMayReassignPath(s.defaultBody, pathStr))
|
|
203
194
|
return true;
|
|
204
195
|
}
|
|
205
196
|
else if (s.kind === "someMatch") {
|
|
206
|
-
if (
|
|
197
|
+
if (stmtsMayReassignPath(s.someBody, pathStr) || stmtsMayReassignPath(s.noneBody, pathStr))
|
|
207
198
|
return true;
|
|
208
199
|
}
|
|
209
200
|
else if (s.kind === "tagMatch") {
|
|
210
|
-
if (s.cases.some(c =>
|
|
201
|
+
if (s.cases.some(c => stmtsMayReassignPath(c.body, pathStr)) || stmtsMayReassignPath(s.fallthrough, pathStr))
|
|
211
202
|
return true;
|
|
212
203
|
}
|
|
213
204
|
}
|
|
214
205
|
return false;
|
|
215
206
|
}
|
|
216
|
-
function
|
|
207
|
+
function scrutineeMayBeReassigned(scrutinee, stmts) {
|
|
217
208
|
const pathStr = exprPathStr(scrutinee);
|
|
218
|
-
return pathStr !== null &&
|
|
209
|
+
return pathStr !== null && stmtsMayReassignPath(stmts, pathStr);
|
|
219
210
|
}
|
|
220
211
|
/** Driver: `if (e !== undefined) then else` — presence fact in if position.
|
|
221
212
|
* → `someMatch e { Some(_e_val) => then, None => else }`. Requires a
|
|
@@ -224,14 +215,14 @@ function scrutineeMayBeCleared(scrutinee, stmts) {
|
|
|
224
215
|
function ruleIfOptionalSimple(s, ctx) {
|
|
225
216
|
if (s.kind !== "if")
|
|
226
217
|
return null;
|
|
227
|
-
const check =
|
|
218
|
+
const check = optionalPresentFact(s.cond);
|
|
228
219
|
if (!check)
|
|
229
220
|
return null;
|
|
230
221
|
const someBody = check.negated ? s.else : s.then;
|
|
231
222
|
const noneBody = check.negated ? s.then : s.else;
|
|
232
223
|
if (someBody.length === 0)
|
|
233
224
|
return null;
|
|
234
|
-
if (
|
|
225
|
+
if (scrutineeMayBeReassigned(check.scrutinee, someBody))
|
|
235
226
|
return null;
|
|
236
227
|
return presentMatchStmts(check, someBody, noneBody, ctx);
|
|
237
228
|
}
|
|
@@ -243,7 +234,7 @@ function ruleEarlyReturnConsume(s, rest, ctx) {
|
|
|
243
234
|
return null;
|
|
244
235
|
if (rest.length === 0)
|
|
245
236
|
return null;
|
|
246
|
-
const check =
|
|
237
|
+
const check = optionalPresentFact(s.cond);
|
|
247
238
|
if (!check)
|
|
248
239
|
return null;
|
|
249
240
|
const someBranch = check.negated ? s.else : s.then;
|
|
@@ -252,7 +243,7 @@ function ruleEarlyReturnConsume(s, rest, ctx) {
|
|
|
252
243
|
return null;
|
|
253
244
|
if (!isTerminating(noneBranch))
|
|
254
245
|
return null;
|
|
255
|
-
if (
|
|
246
|
+
if (scrutineeMayBeReassigned(check.scrutinee, rest))
|
|
256
247
|
return null;
|
|
257
248
|
return presentMatchStmts(check, rest, noneBranch, ctx);
|
|
258
249
|
}
|
|
@@ -293,7 +284,7 @@ function ruleEarlyReturnOrChain(s, rest, ctx) {
|
|
|
293
284
|
}
|
|
294
285
|
if (detectors.length === 0)
|
|
295
286
|
return null;
|
|
296
|
-
if (detectors.some(d =>
|
|
287
|
+
if (detectors.some(d => scrutineeMayBeReassigned(d.scrutinee, rest)))
|
|
297
288
|
return null;
|
|
298
289
|
let inner = residualLeaves.length === 0
|
|
299
290
|
? rest
|
|
@@ -323,11 +314,13 @@ function ruleEarlyReturnOptChainCompare(s, rest, ctx) {
|
|
|
323
314
|
if (c.kind !== "binop" || c.op !== "!==")
|
|
324
315
|
return null;
|
|
325
316
|
const oc = c.left.kind === "optChain" ? c.left : c.right.kind === "optChain" ? c.right : null;
|
|
326
|
-
if (!oc || oc.kind !== "optChain" || oc.obj.ty.kind !== "optional")
|
|
317
|
+
if (!oc || oc.kind !== "optChain" || oc.obj.ty.kind !== "optional" || oc.obj.ty.fromNullish)
|
|
327
318
|
return null;
|
|
328
|
-
if (
|
|
319
|
+
if (scrutineeMayBeReassigned(oc.obj, rest))
|
|
329
320
|
return null;
|
|
330
321
|
const lit = c.left === oc ? c.right : c.left;
|
|
322
|
+
if (!excludesUndefined(lit, ctx.decls, ctx.typeParams))
|
|
323
|
+
return null;
|
|
331
324
|
const innerTy = oc.obj.ty.inner;
|
|
332
325
|
const binder = freshPathBinder(oc.obj, ctx);
|
|
333
326
|
if (binder === null)
|
|
@@ -348,7 +341,7 @@ function ruleEarlyReturnOptChainCompare(s, rest, ctx) {
|
|
|
348
341
|
function ruleConditionalOptionalSimple(e, ctx) {
|
|
349
342
|
if (e.kind !== "conditional")
|
|
350
343
|
return null;
|
|
351
|
-
const check =
|
|
344
|
+
const check = optionalPresentFact(e.cond);
|
|
352
345
|
if (!check)
|
|
353
346
|
return null;
|
|
354
347
|
const someBody = check.negated ? e.else : e.then;
|
|
@@ -373,7 +366,7 @@ function ruleImplOptional(e, ctx) {
|
|
|
373
366
|
restCond = extracted.restCond;
|
|
374
367
|
}
|
|
375
368
|
else {
|
|
376
|
-
const c =
|
|
369
|
+
const c = optionalPresentFact(e.left);
|
|
377
370
|
if (!c || c.negated)
|
|
378
371
|
return null;
|
|
379
372
|
check = c;
|
|
@@ -398,11 +391,14 @@ function ruleImplOptional(e, ctx) {
|
|
|
398
391
|
function ruleNullish(e, ctx) {
|
|
399
392
|
if (e.kind !== "nullish")
|
|
400
393
|
return null;
|
|
401
|
-
//
|
|
394
|
+
// Nullish<T> (and partially narrowed fromNullish) lowers via a 3-arm match in transform.ts.
|
|
395
|
+
if (e.left.ty.kind === "nullish" || (e.left.ty.kind === "optional" && e.left.ty.fromNullish))
|
|
396
|
+
return null;
|
|
397
|
+
// Non-optional left operand (#352): `undefined ?? r` / `null ?? r` -> `r`; plain `x ?? r` -> `x`.
|
|
402
398
|
if (e.left.ty.kind !== "optional") {
|
|
403
|
-
if (e.left.kind === "var" && e.left.name === "undefined")
|
|
399
|
+
if (e.left.kind === "var" && (e.left.name === "undefined" || e.left.name === "null"))
|
|
404
400
|
return e.right;
|
|
405
|
-
if (e.left.ty.kind === "void")
|
|
401
|
+
if (e.left.ty.kind === "void" || e.left.ty.kind === "null")
|
|
406
402
|
return e.right;
|
|
407
403
|
return e.left;
|
|
408
404
|
}
|
|
@@ -481,9 +477,13 @@ function ruleOptionalIndexBinding(s) {
|
|
|
481
477
|
function ruleOptChain(e, ctx) {
|
|
482
478
|
if (e.kind !== "optChain")
|
|
483
479
|
return null;
|
|
484
|
-
//
|
|
480
|
+
// Nullish<T> (and partially narrowed fromNullish) lowers via a 3-arm match in transform.ts.
|
|
481
|
+
if (e.obj.ty.kind === "nullish" || (e.obj.ty.kind === "optional" && e.obj.ty.fromNullish))
|
|
482
|
+
return null;
|
|
483
|
+
// Non-optional receiver (#352): `undefined?.foo` / `null?.foo` -> `undefined`; plain `s?.length` -> `s.length`.
|
|
485
484
|
if (e.obj.ty.kind !== "optional") {
|
|
486
|
-
if ((e.obj.kind === "var" && e.obj.name === "undefined"
|
|
485
|
+
if ((e.obj.kind === "var" && (e.obj.name === "undefined" || e.obj.name === "null")) ||
|
|
486
|
+
e.obj.ty.kind === "void" || e.obj.ty.kind === "null") {
|
|
487
487
|
return { kind: "var", name: "undefined", ty: { kind: "void" } };
|
|
488
488
|
}
|
|
489
489
|
return applyChain(e.obj, e.chain);
|
|
@@ -541,7 +541,7 @@ function ruleConditionalInMap(e, ctx) {
|
|
|
541
541
|
function ruleConditionalOptionalTruthy(e, ctx) {
|
|
542
542
|
if (e.kind !== "conditional")
|
|
543
543
|
return null;
|
|
544
|
-
if (e.cond.ty.kind !== "optional")
|
|
544
|
+
if (e.cond.ty.kind !== "optional" || e.cond.ty.fromNullish)
|
|
545
545
|
return null;
|
|
546
546
|
const binder = freshPathBinder(e.cond, ctx);
|
|
547
547
|
if (binder === null)
|
|
@@ -567,7 +567,7 @@ function ruleIfAndOptional(s, ctx) {
|
|
|
567
567
|
if (!extracted)
|
|
568
568
|
return null;
|
|
569
569
|
const { check, restCond } = extracted;
|
|
570
|
-
if (
|
|
570
|
+
if (scrutineeMayBeReassigned(check.scrutinee, s.then))
|
|
571
571
|
return null;
|
|
572
572
|
const innerIf = { kind: "if", cond: restCond, then: s.then, else: [] };
|
|
573
573
|
return presentMatchStmts(check, [walkStmt(innerIf, ctx)], [], ctx);
|
|
@@ -851,8 +851,9 @@ function narrowFunction(fn, ctx) {
|
|
|
851
851
|
// Contracts and the body bind their payloads in separate generated scopes.
|
|
852
852
|
// Do not reserve a body's names because of a contract's \result (or another
|
|
853
853
|
// function's paths). Keep the shared counter's traversal order unchanged.
|
|
854
|
-
const
|
|
855
|
-
const
|
|
854
|
+
const typeParams = new Set(fn.typeParams.map(tp => tp.replace(/\(.*\)$/, "")));
|
|
855
|
+
const specCtx = { decls: ctx.decls, oc: ctx.oc, typeParams };
|
|
856
|
+
const bodyCtx = { decls: ctx.decls, oc: ctx.oc, typeParams };
|
|
856
857
|
return {
|
|
857
858
|
...fn,
|
|
858
859
|
requires: fn.requires.map(e => walkExpr(e, specCtx)),
|