lemmascript 0.6.11 → 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 +19 -7
- package/tools/dist/dafny-emit.js +20 -21
- package/tools/dist/dafny-proof-additions.js +285 -14
- package/tools/dist/extract.js +100 -253
- 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/resolve.js +22 -9
- package/tools/dist/specparser.js +41 -12
- package/tools/dist/transform.js +24 -54
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,7 +574,7 @@ 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
|
|
@@ -587,7 +602,7 @@ function extractExpr(node) {
|
|
|
587
602
|
}
|
|
588
603
|
destructureBindings.push({
|
|
589
604
|
kind: "let",
|
|
590
|
-
name: localNode
|
|
605
|
+
name: sourceName(localNode),
|
|
591
606
|
mutable: false,
|
|
592
607
|
tsType: null,
|
|
593
608
|
init: { kind: "index", obj: { kind: "var", name: paramName }, idx: { kind: "num", value: i } },
|
|
@@ -621,7 +636,7 @@ function extractExpr(node) {
|
|
|
621
636
|
}
|
|
622
637
|
destructureBindings.push({
|
|
623
638
|
kind: "let",
|
|
624
|
-
name:
|
|
639
|
+
name: sourceName(localNode),
|
|
625
640
|
mutable: false,
|
|
626
641
|
tsType: null,
|
|
627
642
|
init: {
|
|
@@ -679,7 +694,7 @@ function extractExpr(node) {
|
|
|
679
694
|
}
|
|
680
695
|
else if (Node.isShorthandPropertyAssignment(prop)) {
|
|
681
696
|
const name = prop.getName();
|
|
682
|
-
update(name, { kind: "var", name });
|
|
697
|
+
update(name, { kind: "var", name: sourceName(prop.getNameNode()) });
|
|
683
698
|
}
|
|
684
699
|
else if (Node.isPropertyAssignment(prop)) {
|
|
685
700
|
const nameNode = prop.getNameNode();
|
|
@@ -876,7 +891,8 @@ function collectAnnotations(node, body) {
|
|
|
876
891
|
// body alone, unlike `collectAnnotations`, which also reads the node (needed for
|
|
877
892
|
// functions, whose specs may precede the declaration).
|
|
878
893
|
function collectLoopAnnotations(body) {
|
|
879
|
-
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) : [];
|
|
880
896
|
}
|
|
881
897
|
/** All `//@ ` annotations for a function-like node, regardless of whether its
|
|
882
898
|
* body is a block (annotations on the first statement) or an expression-body
|
|
@@ -1352,23 +1368,25 @@ const COMPOUND_OPS = {
|
|
|
1352
1368
|
* `ExpressionStatement` extraction (wrapped) and the C-style for-loop
|
|
1353
1369
|
* incrementor (bare Expression — same shape, no `;` wrapper). */
|
|
1354
1370
|
function desugarStmtExpr(expr, line) {
|
|
1371
|
+
expr = unwrapParens(expr);
|
|
1355
1372
|
if (Node.isBinaryExpression(expr)) {
|
|
1356
1373
|
const opText = expr.getOperatorToken().getText();
|
|
1357
|
-
const left = expr.getLeft();
|
|
1374
|
+
const left = unwrapParens(expr.getLeft());
|
|
1358
1375
|
if (opText === "=" && Node.isElementAccessExpression(left)) {
|
|
1359
|
-
const
|
|
1376
|
+
const receiver = unwrapParens(left.getExpression());
|
|
1377
|
+
const obj = extractExpr(receiver);
|
|
1360
1378
|
const idx = extractExpr(left.getArgumentExpression());
|
|
1361
1379
|
const val = extractExpr(expr.getRight());
|
|
1362
|
-
const target =
|
|
1380
|
+
const target = sourceName(receiver);
|
|
1363
1381
|
const withCall = { kind: "call", fn: { kind: "field", obj, field: "with" }, args: [idx, val] };
|
|
1364
1382
|
return { kind: "assign", target, value: withCall, line };
|
|
1365
1383
|
}
|
|
1366
1384
|
if (opText === "=") {
|
|
1367
|
-
return { kind: "assign", target: left
|
|
1385
|
+
return { kind: "assign", target: sourceName(left), value: extractExpr(expr.getRight()), line };
|
|
1368
1386
|
}
|
|
1369
1387
|
const compound = COMPOUND_OPS[opText];
|
|
1370
1388
|
if (compound) {
|
|
1371
|
-
const target = left
|
|
1389
|
+
const target = sourceName(left);
|
|
1372
1390
|
return {
|
|
1373
1391
|
kind: "assign", target,
|
|
1374
1392
|
value: { kind: "binop", op: compound, left: { kind: "var", name: target }, right: extractExpr(expr.getRight()) },
|
|
@@ -1378,7 +1396,7 @@ function desugarStmtExpr(expr, line) {
|
|
|
1378
1396
|
}
|
|
1379
1397
|
if ((Node.isPostfixUnaryExpression(expr) || Node.isPrefixUnaryExpression(expr)) &&
|
|
1380
1398
|
(expr.getOperatorToken() === SyntaxKind.PlusPlusToken || expr.getOperatorToken() === SyntaxKind.MinusMinusToken)) {
|
|
1381
|
-
const target = expr.getOperand()
|
|
1399
|
+
const target = sourceName(unwrapParens(expr.getOperand()));
|
|
1382
1400
|
const op = expr.getOperatorToken() === SyntaxKind.PlusPlusToken ? "+" : "-";
|
|
1383
1401
|
return {
|
|
1384
1402
|
kind: "assign", target,
|
|
@@ -1388,179 +1406,33 @@ function desugarStmtExpr(expr, line) {
|
|
|
1388
1406
|
}
|
|
1389
1407
|
return null;
|
|
1390
1408
|
}
|
|
1391
|
-
// A C-style `for (let i …)` counter is hoisted out of its loop scope into the
|
|
1392
|
-
// enclosing block (the desugar runs `init; while (cond) { body; update }`). If
|
|
1393
|
-
// another binding of that name shares the hoisted scope — a sibling `let i`, or
|
|
1394
|
-
// an enclosing for-loop whose own `i` stays live where the inner counter and the
|
|
1395
|
-
// outer update sit — the two collapse to one Dafny `var i` ("Duplicate
|
|
1396
|
-
// local-variable name", or a silently-misbound update). When that happens we
|
|
1397
|
-
// rename this counter to a fresh `<name>_N` in the loop's own desugared pieces.
|
|
1398
|
-
//
|
|
1399
|
-
// `forCounterRename` is a read-only scope check (no AST mutation): it returns the
|
|
1400
|
-
// fresh name when this counter would collide, else null — so a non-conflicting
|
|
1401
|
-
// loop keeps its name and output is byte-identical. The rename itself is applied
|
|
1402
|
-
// to the extracted Raw IR by `renameRawStmts` / `renameRawExpr` (code) and
|
|
1403
|
-
// `renameSpec` (the `//@` strings, still unparsed at this phase).
|
|
1404
|
-
function forCounterRename(decl, forStmt) {
|
|
1405
|
-
const name = decl.getName();
|
|
1406
|
-
const fnLike = forStmt.getFirstAncestor(a => Node.isFunctionDeclaration(a) || Node.isArrowFunction(a) ||
|
|
1407
|
-
Node.isFunctionExpression(a) || Node.isMethodDeclaration(a));
|
|
1408
|
-
const scopeRoot = fnLike ?? forStmt.getSourceFile();
|
|
1409
|
-
const isScope = (a) => Node.isBlock(a) || Node.isSourceFile(a) ||
|
|
1410
|
-
Node.isForStatement(a) || Node.isForOfStatement(a) || Node.isForInStatement(a);
|
|
1411
|
-
// A counting-`for` counter is hoisted out of its `for`, so its real scope is
|
|
1412
|
-
// the nearest enclosing block, not the `for` itself.
|
|
1413
|
-
const hoistScope = (d) => {
|
|
1414
|
-
const owner = d.getParent()?.getParent();
|
|
1415
|
-
return owner && Node.isForStatement(owner) && owner.getInitializer() === d.getParent()
|
|
1416
|
-
? d.getFirstAncestor(a => Node.isBlock(a) || Node.isSourceFile(a))
|
|
1417
|
-
: undefined;
|
|
1418
|
-
};
|
|
1419
|
-
// Scopes that enclose this loop — its counter, once hoisted, lives in one of
|
|
1420
|
-
// these, so a same-named binding scoped here would collide.
|
|
1421
|
-
const enclosing = new Set(forStmt.getAncestors());
|
|
1422
|
-
const paramClash = fnLike?.getParameters?.().some((p) => p.getName() === name) ?? false;
|
|
1423
|
-
const declClash = scopeRoot.getDescendantsOfKind(SyntaxKind.VariableDeclaration).some(d => {
|
|
1424
|
-
if (d === decl || d.getName() !== name)
|
|
1425
|
-
return false;
|
|
1426
|
-
// Two sibling for-counters hoisting into the same block: rename only the
|
|
1427
|
-
// later loop, so the first keeps its name. Any other clash (e.g. a `let`) yields.
|
|
1428
|
-
const counterScope = hoistScope(d);
|
|
1429
|
-
if (counterScope)
|
|
1430
|
-
return enclosing.has(counterScope) && d.getStart() < decl.getStart();
|
|
1431
|
-
const scope = d.getFirstAncestor(isScope);
|
|
1432
|
-
return !!scope && enclosing.has(scope);
|
|
1433
|
-
});
|
|
1434
|
-
if (!paramClash && !declClash)
|
|
1435
|
-
return null;
|
|
1436
|
-
const used = new Set(scopeRoot.getDescendantsOfKind(SyntaxKind.Identifier).map(i => i.getText()));
|
|
1437
|
-
let n = 2;
|
|
1438
|
-
while (used.has(`${name}_${n}`) || _reservedForCounterNames.has(`${name}_${n}`))
|
|
1439
|
-
n++;
|
|
1440
|
-
const fresh = `${name}_${n}`;
|
|
1441
|
-
_reservedForCounterNames.add(fresh);
|
|
1442
|
-
return fresh;
|
|
1443
|
-
}
|
|
1444
|
-
/** Whole-word rename of an identifier inside an unparsed `//@` spec string. */
|
|
1445
|
-
function renameSpec(s, from, to) {
|
|
1446
|
-
return s.replace(new RegExp(`\\b${from}\\b`, "g"), to);
|
|
1447
|
-
}
|
|
1448
|
-
/** Rename free references to `from` → `to` in a Raw expression, stopping under a
|
|
1449
|
-
* lambda / quantifier that re-binds the name (it shadows). */
|
|
1450
|
-
function renameRawExpr(e, from, to) {
|
|
1451
|
-
const r = (x) => renameRawExpr(x, from, to);
|
|
1452
|
-
switch (e.kind) {
|
|
1453
|
-
case "var": return e.name === from ? { kind: "var", name: to } : e;
|
|
1454
|
-
case "num":
|
|
1455
|
-
case "bigint":
|
|
1456
|
-
case "str":
|
|
1457
|
-
case "bool":
|
|
1458
|
-
case "result":
|
|
1459
|
-
case "havoc":
|
|
1460
|
-
case "emptyCollection": return e;
|
|
1461
|
-
case "binop": return { ...e, left: r(e.left), right: r(e.right) };
|
|
1462
|
-
case "unop": return { ...e, expr: r(e.expr) };
|
|
1463
|
-
case "call": return { ...e, fn: r(e.fn), args: e.args.map(r) };
|
|
1464
|
-
case "index": return { ...e, obj: r(e.obj), idx: r(e.idx) };
|
|
1465
|
-
case "field": return { ...e, obj: r(e.obj) };
|
|
1466
|
-
case "record": return { ...e, spread: e.spread ? r(e.spread) : null, fields: e.fields.map(f => ({ ...f, value: r(f.value) })) };
|
|
1467
|
-
case "recordMerge": return { ...e, base: r(e.base), override: r(e.override) };
|
|
1468
|
-
case "arrayLiteral": return { ...e, elems: e.elems.map(r) };
|
|
1469
|
-
case "conditional": return { ...e, cond: r(e.cond), then: r(e.then), else: r(e.else) };
|
|
1470
|
-
case "nullish": return { ...e, left: r(e.left), right: r(e.right) };
|
|
1471
|
-
case "nonNull": return { ...e, expr: r(e.expr) };
|
|
1472
|
-
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) };
|
|
1473
|
-
case "lambda": return e.params.some(p => p.name === from) ? e
|
|
1474
|
-
: { ...e, params: e.params.map(p => p.defaultValue ? { ...p, defaultValue: r(p.defaultValue) } : p),
|
|
1475
|
-
body: Array.isArray(e.body) ? renameRawStmts(e.body, from, to) : r(e.body) };
|
|
1476
|
-
case "forall":
|
|
1477
|
-
case "exists": return e.var === from ? e : { ...e, body: r(e.body) };
|
|
1478
|
-
}
|
|
1479
|
-
}
|
|
1480
|
-
/** Rename references to `from` → `to` across a Raw statement (code refs via
|
|
1481
|
-
* `renameRawExpr`, `//@` strings via `renameSpec`). Statement lists stop
|
|
1482
|
-
* renaming once a `let from` re-declares the name (it shadows). */
|
|
1483
|
-
function renameRawStmt(s, from, to) {
|
|
1484
|
-
const r = (x) => renameRawExpr(x, from, to);
|
|
1485
|
-
const sp = (x) => renameSpec(x, from, to);
|
|
1486
|
-
switch (s.kind) {
|
|
1487
|
-
case "let": return { ...s, init: r(s.init) }; // name kept: a shadowing binding is a different variable
|
|
1488
|
-
case "assign": return { ...s, target: s.target === from ? to : s.target, value: r(s.value) };
|
|
1489
|
-
case "return": return { ...s, value: r(s.value) };
|
|
1490
|
-
case "expr": return { ...s, expr: r(s.expr) };
|
|
1491
|
-
case "if": return { ...s, cond: r(s.cond), then: renameRawStmts(s.then, from, to), else: renameRawStmts(s.else, from, to) };
|
|
1492
|
-
case "while": return { ...s, cond: r(s.cond), invariants: s.invariants.map(sp),
|
|
1493
|
-
decreases: s.decreases ? sp(s.decreases) : null, doneWith: s.doneWith ? sp(s.doneWith) : null,
|
|
1494
|
-
body: renameRawStmts(s.body, from, to) };
|
|
1495
|
-
case "forof": return e_forof(s);
|
|
1496
|
-
case "switch": return { ...s, expr: r(s.expr), cases: s.cases.map(c => ({ ...c, body: renameRawStmts(c.body, from, to) })),
|
|
1497
|
-
defaultBody: renameRawStmts(s.defaultBody, from, to) };
|
|
1498
|
-
case "ghostLet": return { ...s, init: sp(s.init) };
|
|
1499
|
-
case "ghostAssign": return { ...s, target: s.target === from ? to : s.target, value: sp(s.value) };
|
|
1500
|
-
case "assert": return { ...s, expr: sp(s.expr) };
|
|
1501
|
-
case "break":
|
|
1502
|
-
case "continue":
|
|
1503
|
-
case "throw": return s;
|
|
1504
|
-
}
|
|
1505
|
-
function e_forof(f) {
|
|
1506
|
-
// for-of names bind in the body; if one shadows `from`, leave the body alone.
|
|
1507
|
-
const body = f.names.includes(from) ? f.body : renameRawStmts(f.body, from, to);
|
|
1508
|
-
return { ...f, iterable: r(f.iterable), invariants: f.invariants.map(sp),
|
|
1509
|
-
doneWith: f.doneWith ? sp(f.doneWith) : null, body };
|
|
1510
|
-
}
|
|
1511
|
-
}
|
|
1512
|
-
/** Rename `from` → `to` through a statement list, stopping after a `let from`
|
|
1513
|
-
* shadows it (subsequent references are a different variable). */
|
|
1514
|
-
function renameRawStmts(stmts, from, to) {
|
|
1515
|
-
const out = [];
|
|
1516
|
-
let active = true;
|
|
1517
|
-
for (const s of stmts) {
|
|
1518
|
-
if (!active) {
|
|
1519
|
-
out.push(s);
|
|
1520
|
-
continue;
|
|
1521
|
-
}
|
|
1522
|
-
out.push(renameRawStmt(s, from, to));
|
|
1523
|
-
if (s.kind === "let" && s.name === from)
|
|
1524
|
-
active = false;
|
|
1525
|
-
}
|
|
1526
|
-
return out;
|
|
1527
|
-
}
|
|
1528
1409
|
// ── Statement extraction ─────────────────────────────────────
|
|
1529
|
-
/** Parse ghost and assert annotations
|
|
1530
|
-
function parseSpecComments(ranges, line) {
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
}
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
continue;
|
|
1556
|
-
}
|
|
1557
|
-
// ghost varName = expr
|
|
1558
|
-
const assignMatch = ghostBody.match(/^(\w+)\s*=\s*(.+)$/);
|
|
1559
|
-
if (assignMatch) {
|
|
1560
|
-
result.push({ kind: "ghostAssign", target: assignMatch[1], value: assignMatch[2].trim(), line });
|
|
1561
|
-
}
|
|
1562
|
-
}
|
|
1563
|
-
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 }] : [];
|
|
1564
1436
|
}
|
|
1565
1437
|
/** Splice `update` before each `continue` in the same loop scope. Recurses
|
|
1566
1438
|
* into `if`/`switch` (same scope) but not nested `while`/`forof` (they own
|
|
@@ -1591,12 +1463,15 @@ function insertUpdateBeforeContinue(stmts, update) {
|
|
|
1591
1463
|
return out;
|
|
1592
1464
|
}
|
|
1593
1465
|
function extractStmts(stmts) {
|
|
1466
|
+
return _lexicalNames ? _lexicalNames.withScope(() => extractScopedStmts(stmts)) : extractScopedStmts(stmts);
|
|
1467
|
+
}
|
|
1468
|
+
function extractScopedStmts(stmts) {
|
|
1594
1469
|
const result = [];
|
|
1595
1470
|
for (const s of stmts) {
|
|
1596
1471
|
const line = s.getStartLineNumber();
|
|
1597
1472
|
// Ghost annotations from leading comments → inject before this statement
|
|
1598
1473
|
const leadingComments = s.getLeadingCommentRanges();
|
|
1599
|
-
result.push(...parseSpecComments(leadingComments, line));
|
|
1474
|
+
result.push(...parseSpecComments(leadingComments, line, s));
|
|
1600
1475
|
// //@ skip — omit this statement from the verification model
|
|
1601
1476
|
if (leadingComments.some(r => r.getText().trim() === "//@ skip")) {
|
|
1602
1477
|
skipSpan(s);
|
|
@@ -1616,8 +1491,8 @@ function extractStmts(stmts) {
|
|
|
1616
1491
|
const elements = nameNode.getElements();
|
|
1617
1492
|
for (let ei = 0; ei < elements.length; ei++) {
|
|
1618
1493
|
const el = elements[ei];
|
|
1619
|
-
const name = el.
|
|
1620
|
-
const propType = rhsType.getProperty(
|
|
1494
|
+
const name = sourceName(el.getNameNode());
|
|
1495
|
+
const propType = rhsType.getProperty(el.getPropertyNameNode()?.getText() ?? el.getName())?.getTypeAtLocation(d);
|
|
1621
1496
|
const tsType = havocTypes[ei] ?? (propType ? _eraseGenerics(typeToString(propType)) : "unknown");
|
|
1622
1497
|
result.push({
|
|
1623
1498
|
kind: "let", name, mutable: s.getDeclarationKind() === "let",
|
|
@@ -1653,7 +1528,7 @@ function extractStmts(stmts) {
|
|
|
1653
1528
|
if (!Node.isIdentifier(inner)) {
|
|
1654
1529
|
throw new Error(`nested binding pattern in array destructuring not yet supported: ${el.getText()}`);
|
|
1655
1530
|
}
|
|
1656
|
-
const name = inner
|
|
1531
|
+
const name = sourceName(inner);
|
|
1657
1532
|
const isRest = !!el.getDotDotDotToken();
|
|
1658
1533
|
const elTs = _eraseGenerics(typeToString(el.getType()));
|
|
1659
1534
|
const init = isRest
|
|
@@ -1698,7 +1573,7 @@ function extractStmts(stmts) {
|
|
|
1698
1573
|
const elTs = _eraseGenerics(typeToString(el.getType()));
|
|
1699
1574
|
result.push({
|
|
1700
1575
|
kind: "let",
|
|
1701
|
-
name:
|
|
1576
|
+
name: sourceName(inner),
|
|
1702
1577
|
mutable: s.getDeclarationKind() === "let",
|
|
1703
1578
|
tsType: elTs,
|
|
1704
1579
|
init: { kind: "field", obj: initVar, field: fieldName },
|
|
@@ -1731,7 +1606,7 @@ function extractStmts(stmts) {
|
|
|
1731
1606
|
const declType = d.getType();
|
|
1732
1607
|
result.push({
|
|
1733
1608
|
kind: "let",
|
|
1734
|
-
name: restEl.
|
|
1609
|
+
name: sourceName(restEl.getNameNode()),
|
|
1735
1610
|
mutable: s.getDeclarationKind() === "let",
|
|
1736
1611
|
tsType: _eraseGenerics(typeToString(declType)),
|
|
1737
1612
|
init: deleteInit,
|
|
@@ -1802,7 +1677,7 @@ function extractStmts(stmts) {
|
|
|
1802
1677
|
?? (annotatedText ? _eraseGenerics(annotatedText) : (inferred === "any" ? null : inferred));
|
|
1803
1678
|
result.push({
|
|
1804
1679
|
kind: "let",
|
|
1805
|
-
name: d.
|
|
1680
|
+
name: sourceName(d.getNameNode()),
|
|
1806
1681
|
mutable: s.getDeclarationKind() === "let",
|
|
1807
1682
|
tsType,
|
|
1808
1683
|
init,
|
|
@@ -1839,11 +1714,11 @@ function extractStmts(stmts) {
|
|
|
1839
1714
|
if (Node.isOmittedExpression(elem))
|
|
1840
1715
|
names.push("_");
|
|
1841
1716
|
else if (Node.isBindingElement(elem))
|
|
1842
|
-
names.push(elem.getNameNode()
|
|
1717
|
+
names.push(sourceName(elem.getNameNode()));
|
|
1843
1718
|
}
|
|
1844
1719
|
}
|
|
1845
1720
|
else {
|
|
1846
|
-
names.push(decl
|
|
1721
|
+
names.push(decl ? sourceName(decl.getNameNode()) : "_");
|
|
1847
1722
|
}
|
|
1848
1723
|
}
|
|
1849
1724
|
else {
|
|
@@ -1896,16 +1771,10 @@ function extractStmts(stmts) {
|
|
|
1896
1771
|
const annots = collectLoopAnnotations(bodyStmts);
|
|
1897
1772
|
if (!init || !Node.isVariableDeclarationList(init))
|
|
1898
1773
|
throw new Error(`for(...) at line ${line}: only variable-declaration init supported`);
|
|
1899
|
-
//
|
|
1900
|
-
// lifted out of the loop scope (see forCounterRename). The renames are
|
|
1901
|
-
// then applied to the loop's own desugared pieces below.
|
|
1774
|
+
// Binding names already account for the scope lost by hoisting.
|
|
1902
1775
|
const hoisted = [];
|
|
1903
|
-
const renames = [];
|
|
1904
1776
|
for (const decl of init.getDeclarations()) {
|
|
1905
|
-
const
|
|
1906
|
-
const name = fresh ?? decl.getName();
|
|
1907
|
-
if (fresh)
|
|
1908
|
-
renames.push([decl.getName(), fresh]);
|
|
1777
|
+
const name = sourceName(decl.getNameNode());
|
|
1909
1778
|
const typeNode = decl.getTypeNode();
|
|
1910
1779
|
const tsType = (typeNode && annotationTypeText(typeNode, decl.getType()))
|
|
1911
1780
|
?? typeNode?.getText() ?? typeToString(decl.getType());
|
|
@@ -1937,15 +1806,6 @@ function extractStmts(stmts) {
|
|
|
1937
1806
|
let invariants = annotExprs(annots, "invariant");
|
|
1938
1807
|
let decreases = firstAnnotExpr(annots, "decreases");
|
|
1939
1808
|
let doneWith = firstAnnotExpr(annots, "done_with");
|
|
1940
|
-
for (const [from, to] of renames) {
|
|
1941
|
-
for (let k = 0; k < hoisted.length; k++)
|
|
1942
|
-
hoisted[k] = renameRawStmt(hoisted[k], from, to);
|
|
1943
|
-
condExpr = renameRawExpr(condExpr, from, to);
|
|
1944
|
-
extractedBody = renameRawStmts(extractedBody, from, to);
|
|
1945
|
-
invariants = invariants.map(inv => renameSpec(inv, from, to));
|
|
1946
|
-
decreases = decreases ? renameSpec(decreases, from, to) : null;
|
|
1947
|
-
doneWith = doneWith ? renameSpec(doneWith, from, to) : null;
|
|
1948
|
-
}
|
|
1949
1809
|
result.push(...hoisted);
|
|
1950
1810
|
result.push({
|
|
1951
1811
|
kind: "while",
|
|
@@ -1963,7 +1823,8 @@ function extractStmts(stmts) {
|
|
|
1963
1823
|
const init = s.getInitializer();
|
|
1964
1824
|
let name = "_";
|
|
1965
1825
|
if (Node.isVariableDeclarationList(init)) {
|
|
1966
|
-
|
|
1826
|
+
const decl = init.getDeclarations()[0];
|
|
1827
|
+
name = decl ? sourceName(decl.getNameNode()) : "_";
|
|
1967
1828
|
}
|
|
1968
1829
|
const bodyNode = s.getStatement();
|
|
1969
1830
|
const bodyStmts = Node.isBlock(bodyNode) ? bodyNode.getStatements() : [bodyNode];
|
|
@@ -2075,16 +1936,17 @@ function extractStmts(stmts) {
|
|
|
2075
1936
|
continue;
|
|
2076
1937
|
}
|
|
2077
1938
|
if (Node.isExpressionStatement(s)) {
|
|
2078
|
-
const expr = s.getExpression();
|
|
1939
|
+
const expr = unwrapParens(s.getExpression());
|
|
2079
1940
|
// //@ havoc before `x = e` — discard the RHS, assign a nondeterministic
|
|
2080
1941
|
// value of x's type. Only applies to plain `=` with an identifier LHS;
|
|
2081
1942
|
// compound assigns, `arr[i] = v`, and `x++` fall through to desugaring.
|
|
2082
1943
|
const havoc = havocDirective(s);
|
|
1944
|
+
const left = Node.isBinaryExpression(expr) ? unwrapParens(expr.getLeft()) : null;
|
|
2083
1945
|
if (havoc && !havoc.key && Node.isBinaryExpression(expr)
|
|
2084
1946
|
&& expr.getOperatorToken().getText() === "="
|
|
2085
|
-
&& Node.isIdentifier(
|
|
2086
|
-
const target =
|
|
2087
|
-
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()));
|
|
2088
1950
|
result.push({ kind: "assign", target, value: { kind: "havoc", tsType }, line });
|
|
2089
1951
|
continue;
|
|
2090
1952
|
}
|
|
@@ -2108,32 +1970,7 @@ function extractStmts(stmts) {
|
|
|
2108
1970
|
const last = stmts[stmts.length - 1];
|
|
2109
1971
|
const line = last.getStartLineNumber();
|
|
2110
1972
|
for (const sib of last.getNextSiblings()) {
|
|
2111
|
-
|
|
2112
|
-
if (!text.startsWith(PREFIX))
|
|
2113
|
-
continue;
|
|
2114
|
-
const content = text.slice(PREFIX.length);
|
|
2115
|
-
// assert expr
|
|
2116
|
-
if (content.startsWith("assert ")) {
|
|
2117
|
-
result.push({ kind: "assert", expr: content.slice(7).trim(), line });
|
|
2118
|
-
continue;
|
|
2119
|
-
}
|
|
2120
|
-
// assume expr — trusted form of assert; emitted as `assume P;` in Dafny.
|
|
2121
|
-
if (content.startsWith("assume ")) {
|
|
2122
|
-
result.push({ kind: "assert", expr: content.slice(7).trim(), line, assumed: true });
|
|
2123
|
-
continue;
|
|
2124
|
-
}
|
|
2125
|
-
if (!content.startsWith("ghost "))
|
|
2126
|
-
continue;
|
|
2127
|
-
const ghostBody = content.slice(6).trim();
|
|
2128
|
-
const letMatch = ghostBody.match(/^let\s+(\w+)(?:\s*:\s*([^=]+?))?\s*=\s*(.+)$/);
|
|
2129
|
-
if (letMatch) {
|
|
2130
|
-
result.push({ kind: "ghostLet", name: letMatch[1], tsType: letMatch[2]?.trim() ?? null, init: letMatch[3].trim(), line });
|
|
2131
|
-
continue;
|
|
2132
|
-
}
|
|
2133
|
-
const assignMatch = ghostBody.match(/^(\w+)\s*=\s*(.+)$/);
|
|
2134
|
-
if (assignMatch) {
|
|
2135
|
-
result.push({ kind: "ghostAssign", target: assignMatch[1], value: assignMatch[2].trim(), line });
|
|
2136
|
-
}
|
|
1973
|
+
result.push(...parseSpecComment(sib.getText().trim(), line, sib, sib.getStart()));
|
|
2137
1974
|
}
|
|
2138
1975
|
}
|
|
2139
1976
|
return result;
|
|
@@ -2141,12 +1978,15 @@ function extractStmts(stmts) {
|
|
|
2141
1978
|
// ── Function extraction ──────────────────────────────────────
|
|
2142
1979
|
function extractFunction(fn, parentAnnotations) {
|
|
2143
1980
|
const prevInFn = _inFunctionExtraction;
|
|
1981
|
+
const prevNames = _lexicalNames;
|
|
1982
|
+
_lexicalNames = new LexicalNames(fn);
|
|
2144
1983
|
_inFunctionExtraction = true;
|
|
2145
1984
|
try {
|
|
2146
1985
|
return extractFunctionInner(fn, parentAnnotations);
|
|
2147
1986
|
}
|
|
2148
1987
|
finally {
|
|
2149
1988
|
_inFunctionExtraction = prevInFn;
|
|
1989
|
+
_lexicalNames = prevNames;
|
|
2150
1990
|
}
|
|
2151
1991
|
}
|
|
2152
1992
|
function extractFunctionInner(fn, parentAnnotations) {
|
|
@@ -2156,7 +1996,6 @@ function extractFunctionInner(fn, parentAnnotations) {
|
|
|
2156
1996
|
// can't model as one Dafny type (e.g. `string & {}` tricks), keep T as a Dafny
|
|
2157
1997
|
// type param instead; such a T must be phantom (any field read won't typecheck).
|
|
2158
1998
|
_typeParamMap = new Map();
|
|
2159
|
-
_reservedForCounterNames = new Set();
|
|
2160
1999
|
const typeParams = [];
|
|
2161
2000
|
for (const tp of fn.getTypeParameters?.() ?? []) {
|
|
2162
2001
|
const constraint = tp.getConstraint();
|
|
@@ -2189,7 +2028,9 @@ function extractFunctionInner(fn, parentAnnotations) {
|
|
|
2189
2028
|
if (parts.length !== 2)
|
|
2190
2029
|
continue;
|
|
2191
2030
|
readExpr(a);
|
|
2192
|
-
|
|
2031
|
+
for (const name of _lexicalNames?.typeNames(parts[0]) ?? [parts[0]]) {
|
|
2032
|
+
typeAnnotations.push({ name, type: parts[1] });
|
|
2033
|
+
}
|
|
2193
2034
|
}
|
|
2194
2035
|
}
|
|
2195
2036
|
return {
|
|
@@ -2317,8 +2158,8 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
|
|
|
2317
2158
|
// tests) must not leak a havoc key, temp-name counter, or function-local maps.
|
|
2318
2159
|
_havocKey = null;
|
|
2319
2160
|
_destrCounter = 0;
|
|
2161
|
+
_lexicalNames = null;
|
|
2320
2162
|
_typeParamMap = new Map();
|
|
2321
|
-
_reservedForCounterNames = new Set();
|
|
2322
2163
|
// Seed the fresh-name check (names.ts) before anything mints: every
|
|
2323
2164
|
// Identifier token in the module, a deliberate over-approximation.
|
|
2324
2165
|
setUserNames(new Set(sourceFile.getDescendantsOfKind(SyntaxKind.Identifier).map(i => i.getText())));
|
|
@@ -2487,6 +2328,9 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
|
|
|
2487
2328
|
const isAnonObject = declTsType.startsWith("__");
|
|
2488
2329
|
if (init && !isHugeString && !isAnonObject && !Node.isArrowFunction(init)) {
|
|
2489
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);
|
|
2490
2334
|
constants.push({
|
|
2491
2335
|
name: decl.getName(),
|
|
2492
2336
|
tsType: declTsType,
|
|
@@ -2497,6 +2341,9 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
|
|
|
2497
2341
|
const reason = e instanceof Error ? e.message : String(e);
|
|
2498
2342
|
throw new Error(`Failed to extract const '${decl.getName()}' at ${sourceFile.getBaseName()}:${decl.getStartLineNumber()}: ${reason}`);
|
|
2499
2343
|
}
|
|
2344
|
+
finally {
|
|
2345
|
+
_lexicalNames = null;
|
|
2346
|
+
}
|
|
2500
2347
|
}
|
|
2501
2348
|
}
|
|
2502
2349
|
}
|