lemmascript 0.6.10 → 0.6.12
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/dafny-commands.js +26 -5
- package/tools/dist/dafny-emit.js +151 -37
- package/tools/dist/dafny-proof-additions.js +468 -0
- package/tools/dist/extract.js +132 -255
- package/tools/dist/ir.js +1 -0
- package/tools/dist/lean-emit.js +15 -7
- package/tools/dist/lexical-names.js +212 -0
- package/tools/dist/lsc.js +5 -5
- package/tools/dist/names.js +4 -0
- package/tools/dist/peephole.js +1 -0
- package/tools/dist/resolve.js +108 -26
- package/tools/dist/specparser.js +41 -12
- package/tools/dist/transform.js +161 -61
- package/tools/dist/types.js +2 -2
package/tools/dist/extract.js
CHANGED
|
@@ -9,6 +9,7 @@ import { Project, Node, SyntaxKind, ScriptTarget, ts } from "ts-morph";
|
|
|
9
9
|
import { initTypeParser } from "./types.js";
|
|
10
10
|
import { normalizeBigIntLiteral } from "./rawir.js";
|
|
11
11
|
import { setUserNames, freshName } from "./names.js";
|
|
12
|
+
import { LexicalNames, rejectForwardLocalCaptures } from "./lexical-names.js";
|
|
12
13
|
import { DEFAULT_OPTIONS, fileCommentLines, isOptionDirective } from "./config.js";
|
|
13
14
|
// ── Expression extraction ────────────────────────────────────
|
|
14
15
|
/** When set, calls whose function/method name matches this key are replaced with havoc. */
|
|
@@ -61,6 +62,8 @@ let _validateDependency = () => { };
|
|
|
61
62
|
/** Counter for synthetic names used by let-statement array destructuring
|
|
62
63
|
* when the initializer isn't a bare variable (single-eval temp). */
|
|
63
64
|
let _destrCounter = 0;
|
|
65
|
+
let _lexicalNames = null;
|
|
66
|
+
const sourceName = (node) => _lexicalNames?.name(node) ?? node.getText();
|
|
64
67
|
/** Register the call's callee as a cross-file extern if applicable, then
|
|
65
68
|
* walk the source declaration's body for nested cross-file calls (so the
|
|
66
69
|
* lifted `requires`/`ensures` see all the symbols they reference). Idempotent
|
|
@@ -338,10 +341,6 @@ function _tsTypeFromUnionNode(tn) {
|
|
|
338
341
|
}
|
|
339
342
|
/** Generic bounds erasure map — set during extractFunction, applied in extractStmts. */
|
|
340
343
|
let _typeParamMap = new Map();
|
|
341
|
-
// Fresh for-counter names allocated in the current function — so two sibling
|
|
342
|
-
// loops that both need renaming don't independently pick the same `<name>_N`
|
|
343
|
-
// (detection is read-only, so the source still shows the original names).
|
|
344
|
-
let _reservedForCounterNames = new Set();
|
|
345
344
|
function _eraseGenerics(tsType) {
|
|
346
345
|
if (_typeParamMap.size === 0)
|
|
347
346
|
return tsType;
|
|
@@ -355,6 +354,17 @@ function _eraseGenerics(tsType) {
|
|
|
355
354
|
return _typeParamMap.get(tsType);
|
|
356
355
|
return tsType;
|
|
357
356
|
}
|
|
357
|
+
function unwrapParens(expr) {
|
|
358
|
+
while (Node.isParenthesizedExpression(expr))
|
|
359
|
+
expr = expr.getExpression();
|
|
360
|
+
return expr;
|
|
361
|
+
}
|
|
362
|
+
function unsupportedAssignmentExpr(node) {
|
|
363
|
+
const source = node.getSourceFile();
|
|
364
|
+
const { line, column } = source.getLineAndColumnAtPos(node.getStart());
|
|
365
|
+
const kind = Node.isBinaryExpression(node) ? "assignment" : "update";
|
|
366
|
+
throw new Error(`Unsupported ${kind} expression at ${source.getFilePath()}:${line}:${column}: ${node.getText().slice(0, 80)}. Use a separate assignment statement.`);
|
|
367
|
+
}
|
|
358
368
|
function extractExpr(node) {
|
|
359
369
|
// Havoc key matching: replace matching calls or new expressions with havoc expression
|
|
360
370
|
if (_havocKey && (Node.isCallExpression(node) || Node.isNewExpression(node))) {
|
|
@@ -411,7 +421,7 @@ function extractExpr(node) {
|
|
|
411
421
|
return { kind: "bool", value: false };
|
|
412
422
|
// Identifier
|
|
413
423
|
if (Node.isIdentifier(node)) {
|
|
414
|
-
return { kind: "var", name: node
|
|
424
|
+
return { kind: "var", name: sourceName(node) };
|
|
415
425
|
}
|
|
416
426
|
// this
|
|
417
427
|
if (node.getKind() === SyntaxKind.ThisKeyword) {
|
|
@@ -505,18 +515,22 @@ function extractExpr(node) {
|
|
|
505
515
|
}
|
|
506
516
|
// Binary expression: a + b, a === b, etc.
|
|
507
517
|
if (Node.isBinaryExpression(node)) {
|
|
508
|
-
const
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
// This is an assignment expression; extract as binop for now
|
|
512
|
-
return { kind: "binop", op: "=", left: extractExpr(node.getLeft()), right: extractExpr(node.getRight()) };
|
|
518
|
+
const token = node.getOperatorToken().getKind();
|
|
519
|
+
if (token >= SyntaxKind.FirstAssignment && token <= SyntaxKind.LastAssignment) {
|
|
520
|
+
unsupportedAssignmentExpr(node);
|
|
513
521
|
}
|
|
522
|
+
const op = node.getOperatorToken().getText();
|
|
514
523
|
// Nullish coalescing: a ?? b — single-eval, narrow rewrites to someMatch
|
|
515
524
|
if (op === "??") {
|
|
516
525
|
return { kind: "nullish", left: extractExpr(node.getLeft()), right: extractExpr(node.getRight()) };
|
|
517
526
|
}
|
|
518
527
|
return { kind: "binop", op, left: extractExpr(node.getLeft()), right: extractExpr(node.getRight()) };
|
|
519
528
|
}
|
|
529
|
+
// Updates are supported only where desugarStmtExpr can preserve the write.
|
|
530
|
+
if ((Node.isPrefixUnaryExpression(node) || Node.isPostfixUnaryExpression(node)) &&
|
|
531
|
+
(node.getOperatorToken() === SyntaxKind.PlusPlusToken || node.getOperatorToken() === SyntaxKind.MinusMinusToken)) {
|
|
532
|
+
unsupportedAssignmentExpr(node);
|
|
533
|
+
}
|
|
520
534
|
// Prefix unary: !x, -x
|
|
521
535
|
if (Node.isPrefixUnaryExpression(node)) {
|
|
522
536
|
const opToken = node.getOperatorToken();
|
|
@@ -541,6 +555,7 @@ function extractExpr(node) {
|
|
|
541
555
|
}
|
|
542
556
|
// Arrow function: (x) => expr or (x) => { stmts }
|
|
543
557
|
if (Node.isArrowFunction(node)) {
|
|
558
|
+
rejectForwardLocalCaptures(node);
|
|
544
559
|
// A binding pattern is not an identifier in either backend. Keep the
|
|
545
560
|
// callback arity unchanged by replacing a flat object pattern with one
|
|
546
561
|
// synthetic parameter and binding its fields at the start of the body:
|
|
@@ -559,14 +574,42 @@ function extractExpr(node) {
|
|
|
559
574
|
const nameNode = p.getNameNode();
|
|
560
575
|
if (Node.isIdentifier(nameNode))
|
|
561
576
|
return {
|
|
562
|
-
name: nameNode
|
|
577
|
+
name: sourceName(nameNode), tsType,
|
|
563
578
|
...(p.isRestParameter() ? { rest: true } : {}),
|
|
564
579
|
...(p.getInitializer() ? { defaultValue: extractExpr(p.getInitializer()),
|
|
565
580
|
inferredTsType: p.getType().getCallSignatures().length
|
|
566
581
|
? p.getType().getText(p) : typeToString(p.getType()) } : {}),
|
|
567
582
|
};
|
|
568
583
|
if (Node.isArrayBindingPattern(nameNode)) {
|
|
569
|
-
|
|
584
|
+
// ([a, , c]) => e binds each named position by index, like the
|
|
585
|
+
// `const [a, , c] = arr` lowering; an elided position binds nothing.
|
|
586
|
+
if (p.getInitializer()) {
|
|
587
|
+
throw new Error(`defaulted array binding pattern in arrow parameter not yet supported: ${p.getText()}`);
|
|
588
|
+
}
|
|
589
|
+
const paramName = freshName(`_lambdaParam${paramIndex}`);
|
|
590
|
+
nameNode.getElements().forEach((el, i) => {
|
|
591
|
+
if (Node.isOmittedExpression(el))
|
|
592
|
+
return;
|
|
593
|
+
if (el.getDotDotDotToken()) {
|
|
594
|
+
throw new Error(`rest element in arrow parameter destructuring not yet supported: ${el.getText()}`);
|
|
595
|
+
}
|
|
596
|
+
if (el.getInitializer()) {
|
|
597
|
+
throw new Error(`default value in arrow parameter destructuring not yet supported: ${el.getText()}`);
|
|
598
|
+
}
|
|
599
|
+
const localNode = el.getNameNode();
|
|
600
|
+
if (!Node.isIdentifier(localNode)) {
|
|
601
|
+
throw new Error(`nested binding pattern in arrow parameter destructuring not yet supported: ${el.getText()}`);
|
|
602
|
+
}
|
|
603
|
+
destructureBindings.push({
|
|
604
|
+
kind: "let",
|
|
605
|
+
name: sourceName(localNode),
|
|
606
|
+
mutable: false,
|
|
607
|
+
tsType: null,
|
|
608
|
+
init: { kind: "index", obj: { kind: "var", name: paramName }, idx: { kind: "num", value: i } },
|
|
609
|
+
line: p.getStartLineNumber(),
|
|
610
|
+
});
|
|
611
|
+
});
|
|
612
|
+
return { name: paramName, tsType };
|
|
570
613
|
}
|
|
571
614
|
if (!Node.isObjectBindingPattern(nameNode)) {
|
|
572
615
|
throw new Error(`unsupported arrow parameter binding: ${p.getName()}`);
|
|
@@ -593,7 +636,7 @@ function extractExpr(node) {
|
|
|
593
636
|
}
|
|
594
637
|
destructureBindings.push({
|
|
595
638
|
kind: "let",
|
|
596
|
-
name:
|
|
639
|
+
name: sourceName(localNode),
|
|
597
640
|
mutable: false,
|
|
598
641
|
tsType: null,
|
|
599
642
|
init: {
|
|
@@ -651,7 +694,7 @@ function extractExpr(node) {
|
|
|
651
694
|
}
|
|
652
695
|
else if (Node.isShorthandPropertyAssignment(prop)) {
|
|
653
696
|
const name = prop.getName();
|
|
654
|
-
update(name, { kind: "var", name });
|
|
697
|
+
update(name, { kind: "var", name: sourceName(prop.getNameNode()) });
|
|
655
698
|
}
|
|
656
699
|
else if (Node.isPropertyAssignment(prop)) {
|
|
657
700
|
const nameNode = prop.getNameNode();
|
|
@@ -719,9 +762,11 @@ function extractExpr(node) {
|
|
|
719
762
|
return { kind: "emptyCollection", collectionType: name, tsType };
|
|
720
763
|
}
|
|
721
764
|
}
|
|
722
|
-
// As-expression: expr as T — strip the type assertion
|
|
723
765
|
if (Node.isAsExpression(node)) {
|
|
724
|
-
|
|
766
|
+
const expr = extractExpr(node.getExpression());
|
|
767
|
+
return expr.kind === "record" && !expr.spread
|
|
768
|
+
? { ...expr, assertedTsType: typeToString(node.getType()) }
|
|
769
|
+
: expr;
|
|
725
770
|
}
|
|
726
771
|
// delete obj[key] → map delete expression
|
|
727
772
|
if (Node.isDeleteExpression(node)) {
|
|
@@ -846,7 +891,8 @@ function collectAnnotations(node, body) {
|
|
|
846
891
|
// body alone, unlike `collectAnnotations`, which also reads the node (needed for
|
|
847
892
|
// functions, whose specs may precede the declaration).
|
|
848
893
|
function collectLoopAnnotations(body) {
|
|
849
|
-
return body.length > 0 ? parseAnnotations(body[0])
|
|
894
|
+
return body.length > 0 ? parseAnnotations(body[0]).map(a => ["invariant", "decreases", "done_with"].includes(a.kind)
|
|
895
|
+
? { ...a, expr: _lexicalNames?.spec(a.expr, body[0]) ?? a.expr } : a) : [];
|
|
850
896
|
}
|
|
851
897
|
/** All `//@ ` annotations for a function-like node, regardless of whether its
|
|
852
898
|
* body is a block (annotations on the first statement) or an expression-body
|
|
@@ -1322,23 +1368,25 @@ const COMPOUND_OPS = {
|
|
|
1322
1368
|
* `ExpressionStatement` extraction (wrapped) and the C-style for-loop
|
|
1323
1369
|
* incrementor (bare Expression — same shape, no `;` wrapper). */
|
|
1324
1370
|
function desugarStmtExpr(expr, line) {
|
|
1371
|
+
expr = unwrapParens(expr);
|
|
1325
1372
|
if (Node.isBinaryExpression(expr)) {
|
|
1326
1373
|
const opText = expr.getOperatorToken().getText();
|
|
1327
|
-
const left = expr.getLeft();
|
|
1374
|
+
const left = unwrapParens(expr.getLeft());
|
|
1328
1375
|
if (opText === "=" && Node.isElementAccessExpression(left)) {
|
|
1329
|
-
const
|
|
1376
|
+
const receiver = unwrapParens(left.getExpression());
|
|
1377
|
+
const obj = extractExpr(receiver);
|
|
1330
1378
|
const idx = extractExpr(left.getArgumentExpression());
|
|
1331
1379
|
const val = extractExpr(expr.getRight());
|
|
1332
|
-
const target =
|
|
1380
|
+
const target = sourceName(receiver);
|
|
1333
1381
|
const withCall = { kind: "call", fn: { kind: "field", obj, field: "with" }, args: [idx, val] };
|
|
1334
1382
|
return { kind: "assign", target, value: withCall, line };
|
|
1335
1383
|
}
|
|
1336
1384
|
if (opText === "=") {
|
|
1337
|
-
return { kind: "assign", target: left
|
|
1385
|
+
return { kind: "assign", target: sourceName(left), value: extractExpr(expr.getRight()), line };
|
|
1338
1386
|
}
|
|
1339
1387
|
const compound = COMPOUND_OPS[opText];
|
|
1340
1388
|
if (compound) {
|
|
1341
|
-
const target = left
|
|
1389
|
+
const target = sourceName(left);
|
|
1342
1390
|
return {
|
|
1343
1391
|
kind: "assign", target,
|
|
1344
1392
|
value: { kind: "binop", op: compound, left: { kind: "var", name: target }, right: extractExpr(expr.getRight()) },
|
|
@@ -1348,7 +1396,7 @@ function desugarStmtExpr(expr, line) {
|
|
|
1348
1396
|
}
|
|
1349
1397
|
if ((Node.isPostfixUnaryExpression(expr) || Node.isPrefixUnaryExpression(expr)) &&
|
|
1350
1398
|
(expr.getOperatorToken() === SyntaxKind.PlusPlusToken || expr.getOperatorToken() === SyntaxKind.MinusMinusToken)) {
|
|
1351
|
-
const target = expr.getOperand()
|
|
1399
|
+
const target = sourceName(unwrapParens(expr.getOperand()));
|
|
1352
1400
|
const op = expr.getOperatorToken() === SyntaxKind.PlusPlusToken ? "+" : "-";
|
|
1353
1401
|
return {
|
|
1354
1402
|
kind: "assign", target,
|
|
@@ -1358,179 +1406,33 @@ function desugarStmtExpr(expr, line) {
|
|
|
1358
1406
|
}
|
|
1359
1407
|
return null;
|
|
1360
1408
|
}
|
|
1361
|
-
// A C-style `for (let i …)` counter is hoisted out of its loop scope into the
|
|
1362
|
-
// enclosing block (the desugar runs `init; while (cond) { body; update }`). If
|
|
1363
|
-
// another binding of that name shares the hoisted scope — a sibling `let i`, or
|
|
1364
|
-
// an enclosing for-loop whose own `i` stays live where the inner counter and the
|
|
1365
|
-
// outer update sit — the two collapse to one Dafny `var i` ("Duplicate
|
|
1366
|
-
// local-variable name", or a silently-misbound update). When that happens we
|
|
1367
|
-
// rename this counter to a fresh `<name>_N` in the loop's own desugared pieces.
|
|
1368
|
-
//
|
|
1369
|
-
// `forCounterRename` is a read-only scope check (no AST mutation): it returns the
|
|
1370
|
-
// fresh name when this counter would collide, else null — so a non-conflicting
|
|
1371
|
-
// loop keeps its name and output is byte-identical. The rename itself is applied
|
|
1372
|
-
// to the extracted Raw IR by `renameRawStmts` / `renameRawExpr` (code) and
|
|
1373
|
-
// `renameSpec` (the `//@` strings, still unparsed at this phase).
|
|
1374
|
-
function forCounterRename(decl, forStmt) {
|
|
1375
|
-
const name = decl.getName();
|
|
1376
|
-
const fnLike = forStmt.getFirstAncestor(a => Node.isFunctionDeclaration(a) || Node.isArrowFunction(a) ||
|
|
1377
|
-
Node.isFunctionExpression(a) || Node.isMethodDeclaration(a));
|
|
1378
|
-
const scopeRoot = fnLike ?? forStmt.getSourceFile();
|
|
1379
|
-
const isScope = (a) => Node.isBlock(a) || Node.isSourceFile(a) ||
|
|
1380
|
-
Node.isForStatement(a) || Node.isForOfStatement(a) || Node.isForInStatement(a);
|
|
1381
|
-
// A counting-`for` counter is hoisted out of its `for`, so its real scope is
|
|
1382
|
-
// the nearest enclosing block, not the `for` itself.
|
|
1383
|
-
const hoistScope = (d) => {
|
|
1384
|
-
const owner = d.getParent()?.getParent();
|
|
1385
|
-
return owner && Node.isForStatement(owner) && owner.getInitializer() === d.getParent()
|
|
1386
|
-
? d.getFirstAncestor(a => Node.isBlock(a) || Node.isSourceFile(a))
|
|
1387
|
-
: undefined;
|
|
1388
|
-
};
|
|
1389
|
-
// Scopes that enclose this loop — its counter, once hoisted, lives in one of
|
|
1390
|
-
// these, so a same-named binding scoped here would collide.
|
|
1391
|
-
const enclosing = new Set(forStmt.getAncestors());
|
|
1392
|
-
const paramClash = fnLike?.getParameters?.().some((p) => p.getName() === name) ?? false;
|
|
1393
|
-
const declClash = scopeRoot.getDescendantsOfKind(SyntaxKind.VariableDeclaration).some(d => {
|
|
1394
|
-
if (d === decl || d.getName() !== name)
|
|
1395
|
-
return false;
|
|
1396
|
-
// Two sibling for-counters hoisting into the same block: rename only the
|
|
1397
|
-
// later loop, so the first keeps its name. Any other clash (e.g. a `let`) yields.
|
|
1398
|
-
const counterScope = hoistScope(d);
|
|
1399
|
-
if (counterScope)
|
|
1400
|
-
return enclosing.has(counterScope) && d.getStart() < decl.getStart();
|
|
1401
|
-
const scope = d.getFirstAncestor(isScope);
|
|
1402
|
-
return !!scope && enclosing.has(scope);
|
|
1403
|
-
});
|
|
1404
|
-
if (!paramClash && !declClash)
|
|
1405
|
-
return null;
|
|
1406
|
-
const used = new Set(scopeRoot.getDescendantsOfKind(SyntaxKind.Identifier).map(i => i.getText()));
|
|
1407
|
-
let n = 2;
|
|
1408
|
-
while (used.has(`${name}_${n}`) || _reservedForCounterNames.has(`${name}_${n}`))
|
|
1409
|
-
n++;
|
|
1410
|
-
const fresh = `${name}_${n}`;
|
|
1411
|
-
_reservedForCounterNames.add(fresh);
|
|
1412
|
-
return fresh;
|
|
1413
|
-
}
|
|
1414
|
-
/** Whole-word rename of an identifier inside an unparsed `//@` spec string. */
|
|
1415
|
-
function renameSpec(s, from, to) {
|
|
1416
|
-
return s.replace(new RegExp(`\\b${from}\\b`, "g"), to);
|
|
1417
|
-
}
|
|
1418
|
-
/** Rename free references to `from` → `to` in a Raw expression, stopping under a
|
|
1419
|
-
* lambda / quantifier that re-binds the name (it shadows). */
|
|
1420
|
-
function renameRawExpr(e, from, to) {
|
|
1421
|
-
const r = (x) => renameRawExpr(x, from, to);
|
|
1422
|
-
switch (e.kind) {
|
|
1423
|
-
case "var": return e.name === from ? { kind: "var", name: to } : e;
|
|
1424
|
-
case "num":
|
|
1425
|
-
case "bigint":
|
|
1426
|
-
case "str":
|
|
1427
|
-
case "bool":
|
|
1428
|
-
case "result":
|
|
1429
|
-
case "havoc":
|
|
1430
|
-
case "emptyCollection": return e;
|
|
1431
|
-
case "binop": return { ...e, left: r(e.left), right: r(e.right) };
|
|
1432
|
-
case "unop": return { ...e, expr: r(e.expr) };
|
|
1433
|
-
case "call": return { ...e, fn: r(e.fn), args: e.args.map(r) };
|
|
1434
|
-
case "index": return { ...e, obj: r(e.obj), idx: r(e.idx) };
|
|
1435
|
-
case "field": return { ...e, obj: r(e.obj) };
|
|
1436
|
-
case "record": return { ...e, spread: e.spread ? r(e.spread) : null, fields: e.fields.map(f => ({ ...f, value: r(f.value) })) };
|
|
1437
|
-
case "recordMerge": return { ...e, base: r(e.base), override: r(e.override) };
|
|
1438
|
-
case "arrayLiteral": return { ...e, elems: e.elems.map(r) };
|
|
1439
|
-
case "conditional": return { ...e, cond: r(e.cond), then: r(e.then), else: r(e.else) };
|
|
1440
|
-
case "nullish": return { ...e, left: r(e.left), right: r(e.right) };
|
|
1441
|
-
case "nonNull": return { ...e, expr: r(e.expr) };
|
|
1442
|
-
case "optChain": return { ...e, obj: r(e.obj), chain: e.chain.map(c => c.kind === "call" ? { ...c, args: c.args.map(r) } : c.kind === "index" ? { ...c, idx: r(c.idx) } : c) };
|
|
1443
|
-
case "lambda": return e.params.some(p => p.name === from) ? e
|
|
1444
|
-
: { ...e, params: e.params.map(p => p.defaultValue ? { ...p, defaultValue: r(p.defaultValue) } : p),
|
|
1445
|
-
body: Array.isArray(e.body) ? renameRawStmts(e.body, from, to) : r(e.body) };
|
|
1446
|
-
case "forall":
|
|
1447
|
-
case "exists": return e.var === from ? e : { ...e, body: r(e.body) };
|
|
1448
|
-
}
|
|
1449
|
-
}
|
|
1450
|
-
/** Rename references to `from` → `to` across a Raw statement (code refs via
|
|
1451
|
-
* `renameRawExpr`, `//@` strings via `renameSpec`). Statement lists stop
|
|
1452
|
-
* renaming once a `let from` re-declares the name (it shadows). */
|
|
1453
|
-
function renameRawStmt(s, from, to) {
|
|
1454
|
-
const r = (x) => renameRawExpr(x, from, to);
|
|
1455
|
-
const sp = (x) => renameSpec(x, from, to);
|
|
1456
|
-
switch (s.kind) {
|
|
1457
|
-
case "let": return { ...s, init: r(s.init) }; // name kept: a shadowing binding is a different variable
|
|
1458
|
-
case "assign": return { ...s, target: s.target === from ? to : s.target, value: r(s.value) };
|
|
1459
|
-
case "return": return { ...s, value: r(s.value) };
|
|
1460
|
-
case "expr": return { ...s, expr: r(s.expr) };
|
|
1461
|
-
case "if": return { ...s, cond: r(s.cond), then: renameRawStmts(s.then, from, to), else: renameRawStmts(s.else, from, to) };
|
|
1462
|
-
case "while": return { ...s, cond: r(s.cond), invariants: s.invariants.map(sp),
|
|
1463
|
-
decreases: s.decreases ? sp(s.decreases) : null, doneWith: s.doneWith ? sp(s.doneWith) : null,
|
|
1464
|
-
body: renameRawStmts(s.body, from, to) };
|
|
1465
|
-
case "forof": return e_forof(s);
|
|
1466
|
-
case "switch": return { ...s, expr: r(s.expr), cases: s.cases.map(c => ({ ...c, body: renameRawStmts(c.body, from, to) })),
|
|
1467
|
-
defaultBody: renameRawStmts(s.defaultBody, from, to) };
|
|
1468
|
-
case "ghostLet": return { ...s, init: sp(s.init) };
|
|
1469
|
-
case "ghostAssign": return { ...s, target: s.target === from ? to : s.target, value: sp(s.value) };
|
|
1470
|
-
case "assert": return { ...s, expr: sp(s.expr) };
|
|
1471
|
-
case "break":
|
|
1472
|
-
case "continue":
|
|
1473
|
-
case "throw": return s;
|
|
1474
|
-
}
|
|
1475
|
-
function e_forof(f) {
|
|
1476
|
-
// for-of names bind in the body; if one shadows `from`, leave the body alone.
|
|
1477
|
-
const body = f.names.includes(from) ? f.body : renameRawStmts(f.body, from, to);
|
|
1478
|
-
return { ...f, iterable: r(f.iterable), invariants: f.invariants.map(sp),
|
|
1479
|
-
doneWith: f.doneWith ? sp(f.doneWith) : null, body };
|
|
1480
|
-
}
|
|
1481
|
-
}
|
|
1482
|
-
/** Rename `from` → `to` through a statement list, stopping after a `let from`
|
|
1483
|
-
* shadows it (subsequent references are a different variable). */
|
|
1484
|
-
function renameRawStmts(stmts, from, to) {
|
|
1485
|
-
const out = [];
|
|
1486
|
-
let active = true;
|
|
1487
|
-
for (const s of stmts) {
|
|
1488
|
-
if (!active) {
|
|
1489
|
-
out.push(s);
|
|
1490
|
-
continue;
|
|
1491
|
-
}
|
|
1492
|
-
out.push(renameRawStmt(s, from, to));
|
|
1493
|
-
if (s.kind === "let" && s.name === from)
|
|
1494
|
-
active = false;
|
|
1495
|
-
}
|
|
1496
|
-
return out;
|
|
1497
|
-
}
|
|
1498
1409
|
// ── Statement extraction ─────────────────────────────────────
|
|
1499
|
-
/** Parse ghost and assert annotations
|
|
1500
|
-
function parseSpecComments(ranges, line) {
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
}
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
continue;
|
|
1526
|
-
}
|
|
1527
|
-
// ghost varName = expr
|
|
1528
|
-
const assignMatch = ghostBody.match(/^(\w+)\s*=\s*(.+)$/);
|
|
1529
|
-
if (assignMatch) {
|
|
1530
|
-
result.push({ kind: "ghostAssign", target: assignMatch[1], value: assignMatch[2].trim(), line });
|
|
1531
|
-
}
|
|
1532
|
-
}
|
|
1533
|
-
return result;
|
|
1410
|
+
/** Parse ghost and assert annotations in their original lexical scope. */
|
|
1411
|
+
function parseSpecComments(ranges, line, location) {
|
|
1412
|
+
return ranges.flatMap(range => parseSpecComment(range.getText().trim(), line, location, range.getPos()));
|
|
1413
|
+
}
|
|
1414
|
+
function parseSpecComment(text, line, location, pos) {
|
|
1415
|
+
if (!text.startsWith(PREFIX))
|
|
1416
|
+
return [];
|
|
1417
|
+
const content = text.slice(PREFIX.length);
|
|
1418
|
+
const spec = (expr) => _lexicalNames?.spec(expr, location, pos) ?? expr;
|
|
1419
|
+
if (content.startsWith("assert "))
|
|
1420
|
+
return [{ kind: "assert", expr: spec(content.slice(7).trim()), line }];
|
|
1421
|
+
if (content.startsWith("assume "))
|
|
1422
|
+
return [{ kind: "assert", expr: spec(content.slice(7).trim()), line, assumed: true }];
|
|
1423
|
+
if (!content.startsWith("ghost "))
|
|
1424
|
+
return [];
|
|
1425
|
+
const ghostBody = content.slice(6).trim();
|
|
1426
|
+
const letMatch = ghostBody.match(/^let\s+(\w+)(?:\s*:\s*([^=]+?))?\s*=\s*(.+)$/);
|
|
1427
|
+
if (letMatch) {
|
|
1428
|
+
const init = spec(letMatch[3].trim());
|
|
1429
|
+
const name = _lexicalNames?.ghost(letMatch[1], location, pos) ?? letMatch[1];
|
|
1430
|
+
return [{ kind: "ghostLet", name, tsType: letMatch[2]?.trim() ?? null, init, line }];
|
|
1431
|
+
}
|
|
1432
|
+
const assignMatch = ghostBody.match(/^(\w+)\s*=\s*(.+)$/);
|
|
1433
|
+
return assignMatch ? [{ kind: "ghostAssign",
|
|
1434
|
+
target: _lexicalNames?.specName(assignMatch[1], location, pos) ?? assignMatch[1],
|
|
1435
|
+
value: spec(assignMatch[2].trim()), line }] : [];
|
|
1534
1436
|
}
|
|
1535
1437
|
/** Splice `update` before each `continue` in the same loop scope. Recurses
|
|
1536
1438
|
* into `if`/`switch` (same scope) but not nested `while`/`forof` (they own
|
|
@@ -1561,12 +1463,15 @@ function insertUpdateBeforeContinue(stmts, update) {
|
|
|
1561
1463
|
return out;
|
|
1562
1464
|
}
|
|
1563
1465
|
function extractStmts(stmts) {
|
|
1466
|
+
return _lexicalNames ? _lexicalNames.withScope(() => extractScopedStmts(stmts)) : extractScopedStmts(stmts);
|
|
1467
|
+
}
|
|
1468
|
+
function extractScopedStmts(stmts) {
|
|
1564
1469
|
const result = [];
|
|
1565
1470
|
for (const s of stmts) {
|
|
1566
1471
|
const line = s.getStartLineNumber();
|
|
1567
1472
|
// Ghost annotations from leading comments → inject before this statement
|
|
1568
1473
|
const leadingComments = s.getLeadingCommentRanges();
|
|
1569
|
-
result.push(...parseSpecComments(leadingComments, line));
|
|
1474
|
+
result.push(...parseSpecComments(leadingComments, line, s));
|
|
1570
1475
|
// //@ skip — omit this statement from the verification model
|
|
1571
1476
|
if (leadingComments.some(r => r.getText().trim() === "//@ skip")) {
|
|
1572
1477
|
skipSpan(s);
|
|
@@ -1586,8 +1491,8 @@ function extractStmts(stmts) {
|
|
|
1586
1491
|
const elements = nameNode.getElements();
|
|
1587
1492
|
for (let ei = 0; ei < elements.length; ei++) {
|
|
1588
1493
|
const el = elements[ei];
|
|
1589
|
-
const name = el.
|
|
1590
|
-
const propType = rhsType.getProperty(
|
|
1494
|
+
const name = sourceName(el.getNameNode());
|
|
1495
|
+
const propType = rhsType.getProperty(el.getPropertyNameNode()?.getText() ?? el.getName())?.getTypeAtLocation(d);
|
|
1591
1496
|
const tsType = havocTypes[ei] ?? (propType ? _eraseGenerics(typeToString(propType)) : "unknown");
|
|
1592
1497
|
result.push({
|
|
1593
1498
|
kind: "let", name, mutable: s.getDeclarationKind() === "let",
|
|
@@ -1623,7 +1528,7 @@ function extractStmts(stmts) {
|
|
|
1623
1528
|
if (!Node.isIdentifier(inner)) {
|
|
1624
1529
|
throw new Error(`nested binding pattern in array destructuring not yet supported: ${el.getText()}`);
|
|
1625
1530
|
}
|
|
1626
|
-
const name = inner
|
|
1531
|
+
const name = sourceName(inner);
|
|
1627
1532
|
const isRest = !!el.getDotDotDotToken();
|
|
1628
1533
|
const elTs = _eraseGenerics(typeToString(el.getType()));
|
|
1629
1534
|
const init = isRest
|
|
@@ -1668,7 +1573,7 @@ function extractStmts(stmts) {
|
|
|
1668
1573
|
const elTs = _eraseGenerics(typeToString(el.getType()));
|
|
1669
1574
|
result.push({
|
|
1670
1575
|
kind: "let",
|
|
1671
|
-
name:
|
|
1576
|
+
name: sourceName(inner),
|
|
1672
1577
|
mutable: s.getDeclarationKind() === "let",
|
|
1673
1578
|
tsType: elTs,
|
|
1674
1579
|
init: { kind: "field", obj: initVar, field: fieldName },
|
|
@@ -1701,7 +1606,7 @@ function extractStmts(stmts) {
|
|
|
1701
1606
|
const declType = d.getType();
|
|
1702
1607
|
result.push({
|
|
1703
1608
|
kind: "let",
|
|
1704
|
-
name: restEl.
|
|
1609
|
+
name: sourceName(restEl.getNameNode()),
|
|
1705
1610
|
mutable: s.getDeclarationKind() === "let",
|
|
1706
1611
|
tsType: _eraseGenerics(typeToString(declType)),
|
|
1707
1612
|
init: deleteInit,
|
|
@@ -1772,7 +1677,7 @@ function extractStmts(stmts) {
|
|
|
1772
1677
|
?? (annotatedText ? _eraseGenerics(annotatedText) : (inferred === "any" ? null : inferred));
|
|
1773
1678
|
result.push({
|
|
1774
1679
|
kind: "let",
|
|
1775
|
-
name: d.
|
|
1680
|
+
name: sourceName(d.getNameNode()),
|
|
1776
1681
|
mutable: s.getDeclarationKind() === "let",
|
|
1777
1682
|
tsType,
|
|
1778
1683
|
init,
|
|
@@ -1809,11 +1714,11 @@ function extractStmts(stmts) {
|
|
|
1809
1714
|
if (Node.isOmittedExpression(elem))
|
|
1810
1715
|
names.push("_");
|
|
1811
1716
|
else if (Node.isBindingElement(elem))
|
|
1812
|
-
names.push(elem.getNameNode()
|
|
1717
|
+
names.push(sourceName(elem.getNameNode()));
|
|
1813
1718
|
}
|
|
1814
1719
|
}
|
|
1815
1720
|
else {
|
|
1816
|
-
names.push(decl
|
|
1721
|
+
names.push(decl ? sourceName(decl.getNameNode()) : "_");
|
|
1817
1722
|
}
|
|
1818
1723
|
}
|
|
1819
1724
|
else {
|
|
@@ -1866,16 +1771,10 @@ function extractStmts(stmts) {
|
|
|
1866
1771
|
const annots = collectLoopAnnotations(bodyStmts);
|
|
1867
1772
|
if (!init || !Node.isVariableDeclarationList(init))
|
|
1868
1773
|
throw new Error(`for(...) at line ${line}: only variable-declaration init supported`);
|
|
1869
|
-
//
|
|
1870
|
-
// lifted out of the loop scope (see forCounterRename). The renames are
|
|
1871
|
-
// then applied to the loop's own desugared pieces below.
|
|
1774
|
+
// Binding names already account for the scope lost by hoisting.
|
|
1872
1775
|
const hoisted = [];
|
|
1873
|
-
const renames = [];
|
|
1874
1776
|
for (const decl of init.getDeclarations()) {
|
|
1875
|
-
const
|
|
1876
|
-
const name = fresh ?? decl.getName();
|
|
1877
|
-
if (fresh)
|
|
1878
|
-
renames.push([decl.getName(), fresh]);
|
|
1777
|
+
const name = sourceName(decl.getNameNode());
|
|
1879
1778
|
const typeNode = decl.getTypeNode();
|
|
1880
1779
|
const tsType = (typeNode && annotationTypeText(typeNode, decl.getType()))
|
|
1881
1780
|
?? typeNode?.getText() ?? typeToString(decl.getType());
|
|
@@ -1907,15 +1806,6 @@ function extractStmts(stmts) {
|
|
|
1907
1806
|
let invariants = annotExprs(annots, "invariant");
|
|
1908
1807
|
let decreases = firstAnnotExpr(annots, "decreases");
|
|
1909
1808
|
let doneWith = firstAnnotExpr(annots, "done_with");
|
|
1910
|
-
for (const [from, to] of renames) {
|
|
1911
|
-
for (let k = 0; k < hoisted.length; k++)
|
|
1912
|
-
hoisted[k] = renameRawStmt(hoisted[k], from, to);
|
|
1913
|
-
condExpr = renameRawExpr(condExpr, from, to);
|
|
1914
|
-
extractedBody = renameRawStmts(extractedBody, from, to);
|
|
1915
|
-
invariants = invariants.map(inv => renameSpec(inv, from, to));
|
|
1916
|
-
decreases = decreases ? renameSpec(decreases, from, to) : null;
|
|
1917
|
-
doneWith = doneWith ? renameSpec(doneWith, from, to) : null;
|
|
1918
|
-
}
|
|
1919
1809
|
result.push(...hoisted);
|
|
1920
1810
|
result.push({
|
|
1921
1811
|
kind: "while",
|
|
@@ -1933,7 +1823,8 @@ function extractStmts(stmts) {
|
|
|
1933
1823
|
const init = s.getInitializer();
|
|
1934
1824
|
let name = "_";
|
|
1935
1825
|
if (Node.isVariableDeclarationList(init)) {
|
|
1936
|
-
|
|
1826
|
+
const decl = init.getDeclarations()[0];
|
|
1827
|
+
name = decl ? sourceName(decl.getNameNode()) : "_";
|
|
1937
1828
|
}
|
|
1938
1829
|
const bodyNode = s.getStatement();
|
|
1939
1830
|
const bodyStmts = Node.isBlock(bodyNode) ? bodyNode.getStatements() : [bodyNode];
|
|
@@ -2045,16 +1936,17 @@ function extractStmts(stmts) {
|
|
|
2045
1936
|
continue;
|
|
2046
1937
|
}
|
|
2047
1938
|
if (Node.isExpressionStatement(s)) {
|
|
2048
|
-
const expr = s.getExpression();
|
|
1939
|
+
const expr = unwrapParens(s.getExpression());
|
|
2049
1940
|
// //@ havoc before `x = e` — discard the RHS, assign a nondeterministic
|
|
2050
1941
|
// value of x's type. Only applies to plain `=` with an identifier LHS;
|
|
2051
1942
|
// compound assigns, `arr[i] = v`, and `x++` fall through to desugaring.
|
|
2052
1943
|
const havoc = havocDirective(s);
|
|
1944
|
+
const left = Node.isBinaryExpression(expr) ? unwrapParens(expr.getLeft()) : null;
|
|
2053
1945
|
if (havoc && !havoc.key && Node.isBinaryExpression(expr)
|
|
2054
1946
|
&& expr.getOperatorToken().getText() === "="
|
|
2055
|
-
&& Node.isIdentifier(
|
|
2056
|
-
const target =
|
|
2057
|
-
const tsType = havoc.type ?? _eraseGenerics(typeToString(
|
|
1947
|
+
&& left && Node.isIdentifier(left)) {
|
|
1948
|
+
const target = sourceName(left);
|
|
1949
|
+
const tsType = havoc.type ?? _eraseGenerics(typeToString(left.getType()));
|
|
2058
1950
|
result.push({ kind: "assign", target, value: { kind: "havoc", tsType }, line });
|
|
2059
1951
|
continue;
|
|
2060
1952
|
}
|
|
@@ -2078,32 +1970,7 @@ function extractStmts(stmts) {
|
|
|
2078
1970
|
const last = stmts[stmts.length - 1];
|
|
2079
1971
|
const line = last.getStartLineNumber();
|
|
2080
1972
|
for (const sib of last.getNextSiblings()) {
|
|
2081
|
-
|
|
2082
|
-
if (!text.startsWith(PREFIX))
|
|
2083
|
-
continue;
|
|
2084
|
-
const content = text.slice(PREFIX.length);
|
|
2085
|
-
// assert expr
|
|
2086
|
-
if (content.startsWith("assert ")) {
|
|
2087
|
-
result.push({ kind: "assert", expr: content.slice(7).trim(), line });
|
|
2088
|
-
continue;
|
|
2089
|
-
}
|
|
2090
|
-
// assume expr — trusted form of assert; emitted as `assume P;` in Dafny.
|
|
2091
|
-
if (content.startsWith("assume ")) {
|
|
2092
|
-
result.push({ kind: "assert", expr: content.slice(7).trim(), line, assumed: true });
|
|
2093
|
-
continue;
|
|
2094
|
-
}
|
|
2095
|
-
if (!content.startsWith("ghost "))
|
|
2096
|
-
continue;
|
|
2097
|
-
const ghostBody = content.slice(6).trim();
|
|
2098
|
-
const letMatch = ghostBody.match(/^let\s+(\w+)(?:\s*:\s*([^=]+?))?\s*=\s*(.+)$/);
|
|
2099
|
-
if (letMatch) {
|
|
2100
|
-
result.push({ kind: "ghostLet", name: letMatch[1], tsType: letMatch[2]?.trim() ?? null, init: letMatch[3].trim(), line });
|
|
2101
|
-
continue;
|
|
2102
|
-
}
|
|
2103
|
-
const assignMatch = ghostBody.match(/^(\w+)\s*=\s*(.+)$/);
|
|
2104
|
-
if (assignMatch) {
|
|
2105
|
-
result.push({ kind: "ghostAssign", target: assignMatch[1], value: assignMatch[2].trim(), line });
|
|
2106
|
-
}
|
|
1973
|
+
result.push(...parseSpecComment(sib.getText().trim(), line, sib, sib.getStart()));
|
|
2107
1974
|
}
|
|
2108
1975
|
}
|
|
2109
1976
|
return result;
|
|
@@ -2111,12 +1978,15 @@ function extractStmts(stmts) {
|
|
|
2111
1978
|
// ── Function extraction ──────────────────────────────────────
|
|
2112
1979
|
function extractFunction(fn, parentAnnotations) {
|
|
2113
1980
|
const prevInFn = _inFunctionExtraction;
|
|
1981
|
+
const prevNames = _lexicalNames;
|
|
1982
|
+
_lexicalNames = new LexicalNames(fn);
|
|
2114
1983
|
_inFunctionExtraction = true;
|
|
2115
1984
|
try {
|
|
2116
1985
|
return extractFunctionInner(fn, parentAnnotations);
|
|
2117
1986
|
}
|
|
2118
1987
|
finally {
|
|
2119
1988
|
_inFunctionExtraction = prevInFn;
|
|
1989
|
+
_lexicalNames = prevNames;
|
|
2120
1990
|
}
|
|
2121
1991
|
}
|
|
2122
1992
|
function extractFunctionInner(fn, parentAnnotations) {
|
|
@@ -2126,7 +1996,6 @@ function extractFunctionInner(fn, parentAnnotations) {
|
|
|
2126
1996
|
// can't model as one Dafny type (e.g. `string & {}` tricks), keep T as a Dafny
|
|
2127
1997
|
// type param instead; such a T must be phantom (any field read won't typecheck).
|
|
2128
1998
|
_typeParamMap = new Map();
|
|
2129
|
-
_reservedForCounterNames = new Set();
|
|
2130
1999
|
const typeParams = [];
|
|
2131
2000
|
for (const tp of fn.getTypeParameters?.() ?? []) {
|
|
2132
2001
|
const constraint = tp.getConstraint();
|
|
@@ -2159,7 +2028,9 @@ function extractFunctionInner(fn, parentAnnotations) {
|
|
|
2159
2028
|
if (parts.length !== 2)
|
|
2160
2029
|
continue;
|
|
2161
2030
|
readExpr(a);
|
|
2162
|
-
|
|
2031
|
+
for (const name of _lexicalNames?.typeNames(parts[0]) ?? [parts[0]]) {
|
|
2032
|
+
typeAnnotations.push({ name, type: parts[1] });
|
|
2033
|
+
}
|
|
2163
2034
|
}
|
|
2164
2035
|
}
|
|
2165
2036
|
return {
|
|
@@ -2287,8 +2158,8 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
|
|
|
2287
2158
|
// tests) must not leak a havoc key, temp-name counter, or function-local maps.
|
|
2288
2159
|
_havocKey = null;
|
|
2289
2160
|
_destrCounter = 0;
|
|
2161
|
+
_lexicalNames = null;
|
|
2290
2162
|
_typeParamMap = new Map();
|
|
2291
|
-
_reservedForCounterNames = new Set();
|
|
2292
2163
|
// Seed the fresh-name check (names.ts) before anything mints: every
|
|
2293
2164
|
// Identifier token in the module, a deliberate over-approximation.
|
|
2294
2165
|
setUserNames(new Set(sourceFile.getDescendantsOfKind(SyntaxKind.Identifier).map(i => i.getText())));
|
|
@@ -2457,6 +2328,9 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
|
|
|
2457
2328
|
const isAnonObject = declTsType.startsWith("__");
|
|
2458
2329
|
if (init && !isHugeString && !isAnonObject && !Node.isArrowFunction(init)) {
|
|
2459
2330
|
try {
|
|
2331
|
+
// Callbacks in the initializer get the same no-shadowing names
|
|
2332
|
+
// as those in a function body.
|
|
2333
|
+
_lexicalNames = new LexicalNames(init);
|
|
2460
2334
|
constants.push({
|
|
2461
2335
|
name: decl.getName(),
|
|
2462
2336
|
tsType: declTsType,
|
|
@@ -2467,6 +2341,9 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
|
|
|
2467
2341
|
const reason = e instanceof Error ? e.message : String(e);
|
|
2468
2342
|
throw new Error(`Failed to extract const '${decl.getName()}' at ${sourceFile.getBaseName()}:${decl.getStartLineNumber()}: ${reason}`);
|
|
2469
2343
|
}
|
|
2344
|
+
finally {
|
|
2345
|
+
_lexicalNames = null;
|
|
2346
|
+
}
|
|
2470
2347
|
}
|
|
2471
2348
|
}
|
|
2472
2349
|
}
|