lemmascript 0.6.11 → 0.6.13

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.
@@ -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.getText() };
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 op = node.getOperatorToken().getText();
509
- // Assignment: a = b → handled at statement level, but can appear in expressions
510
- if (op === "=") {
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.getText(), tsType,
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.getText(),
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: localName,
639
+ name: sourceName(localNode),
625
640
  mutable: false,
626
641
  tsType: null,
627
642
  init: {
@@ -657,9 +672,10 @@ function extractExpr(node) {
657
672
  if (!hasSpread) {
658
673
  return { kind: "arrayLiteral", elems: elems.map(e => extractExpr(e)) };
659
674
  }
660
- // [a, ...b, c] → [a] + b + [c] via shared helper
675
+ // [a, ...b, c] → [a] + b + [c] via shared helper; mark freshClone so
676
+ // `[...arr]` is not misread by alias analysis as a reference alias of `arr`.
661
677
  const result = buildSpreadConcat(elems);
662
- return result;
678
+ return markFreshClone(result);
663
679
  }
664
680
  // Object literal: { res: true, done: false } or { ...obj, res: true }
665
681
  if (Node.isObjectLiteralExpression(node)) {
@@ -675,11 +691,11 @@ function extractExpr(node) {
675
691
  for (const prop of node.getProperties()) {
676
692
  if (Node.isSpreadAssignment(prop)) {
677
693
  const s = extractExpr(prop.getExpression());
678
- acc = acc === null ? s : { kind: "recordMerge", base: acc, override: s };
694
+ acc = acc === null ? markFreshClone(s) : { kind: "recordMerge", base: acc, override: s };
679
695
  }
680
696
  else if (Node.isShorthandPropertyAssignment(prop)) {
681
697
  const name = prop.getName();
682
- update(name, { kind: "var", name });
698
+ update(name, { kind: "var", name: sourceName(prop.getNameNode()) });
683
699
  }
684
700
  else if (Node.isPropertyAssignment(prop)) {
685
701
  const nameNode = prop.getNameNode();
@@ -725,8 +741,9 @@ function extractExpr(node) {
725
741
  const argSymbol = argType.getSymbol()?.getName() ?? argType.getAliasSymbol()?.getName();
726
742
  const argTypeText = _eraseGenerics(typeToString(argType));
727
743
  if (argSymbol === "Map" || argTypeText.startsWith("Record<")) {
728
- // new Map(existingMap) or new Map(record) — identity (Dafny maps are value types)
729
- return extractExpr(args[0]);
744
+ // new Map(existingMap) or new Map(record) — identity (Dafny maps are value types),
745
+ // marked freshClone so alias analysis knows JS allocates a fresh Map.
746
+ return markFreshClone(extractExpr(args[0]));
730
747
  }
731
748
  // new Map(entries) — map-from-array constructor
732
749
  return { kind: "call", fn: { kind: "var", name: "__mapFromArray" }, args: [extractExpr(args[0])] };
@@ -738,9 +755,9 @@ function extractExpr(node) {
738
755
  return { kind: "emptyCollection", collectionType: "Set", tsType, initElems: arg.getElements().map(e => extractExpr(e)) };
739
756
  }
740
757
  const argSymbol = arg.getType().getSymbol()?.getName() ?? arg.getType().getAliasSymbol()?.getName();
741
- // new Set(existingSet) — identity (sets are value types)
758
+ // new Set(existingSet) — identity (sets are value types), marked freshClone.
742
759
  if (argSymbol === "Set")
743
- return extractExpr(arg);
760
+ return markFreshClone(extractExpr(arg));
744
761
  // new Set(arr) — build a deduplicated set from the array's elements
745
762
  return { kind: "call", fn: { kind: "var", name: "__setFromArray" }, args: [extractExpr(arg)] };
746
763
  }
@@ -876,7 +893,8 @@ function collectAnnotations(node, body) {
876
893
  // body alone, unlike `collectAnnotations`, which also reads the node (needed for
877
894
  // functions, whose specs may precede the declaration).
878
895
  function collectLoopAnnotations(body) {
879
- return body.length > 0 ? parseAnnotations(body[0]) : [];
896
+ return body.length > 0 ? parseAnnotations(body[0]).map(a => ["invariant", "decreases", "done_with"].includes(a.kind)
897
+ ? { ...a, expr: _lexicalNames?.spec(a.expr, body[0]) ?? a.expr } : a) : [];
880
898
  }
881
899
  /** All `//@ ` annotations for a function-like node, regardless of whether its
882
900
  * body is a block (annotations on the first statement) or an expression-body
@@ -1342,6 +1360,15 @@ function typeToString(type) {
1342
1360
  }
1343
1361
  return type.getText();
1344
1362
  }
1363
+ function markFreshClone(e) {
1364
+ if (e.kind === "nonNull") {
1365
+ return { ...e, expr: markFreshClone(e.expr) };
1366
+ }
1367
+ if (e.kind === "var" || e.kind === "field" || e.kind === "index" || e.kind === "call") {
1368
+ return { ...e, freshClone: true };
1369
+ }
1370
+ return e;
1371
+ }
1345
1372
  const COMPOUND_OPS = {
1346
1373
  "+=": "+", "-=": "-", "*=": "*", "/=": "/", "%=": "%",
1347
1374
  "<<=": "<<", ">>=": ">>", "|=": "|", "&=": "&", "^=": "^", "**=": "**",
@@ -1352,23 +1379,25 @@ const COMPOUND_OPS = {
1352
1379
  * `ExpressionStatement` extraction (wrapped) and the C-style for-loop
1353
1380
  * incrementor (bare Expression — same shape, no `;` wrapper). */
1354
1381
  function desugarStmtExpr(expr, line) {
1382
+ expr = unwrapParens(expr);
1355
1383
  if (Node.isBinaryExpression(expr)) {
1356
1384
  const opText = expr.getOperatorToken().getText();
1357
- const left = expr.getLeft();
1385
+ const left = unwrapParens(expr.getLeft());
1358
1386
  if (opText === "=" && Node.isElementAccessExpression(left)) {
1359
- const obj = extractExpr(left.getExpression());
1387
+ const receiver = unwrapParens(left.getExpression());
1388
+ const obj = extractExpr(receiver);
1360
1389
  const idx = extractExpr(left.getArgumentExpression());
1361
1390
  const val = extractExpr(expr.getRight());
1362
- const target = left.getExpression().getText();
1391
+ const target = sourceName(receiver);
1363
1392
  const withCall = { kind: "call", fn: { kind: "field", obj, field: "with" }, args: [idx, val] };
1364
1393
  return { kind: "assign", target, value: withCall, line };
1365
1394
  }
1366
1395
  if (opText === "=") {
1367
- return { kind: "assign", target: left.getText(), value: extractExpr(expr.getRight()), line };
1396
+ return { kind: "assign", target: sourceName(left), value: extractExpr(expr.getRight()), line };
1368
1397
  }
1369
1398
  const compound = COMPOUND_OPS[opText];
1370
1399
  if (compound) {
1371
- const target = left.getText();
1400
+ const target = sourceName(left);
1372
1401
  return {
1373
1402
  kind: "assign", target,
1374
1403
  value: { kind: "binop", op: compound, left: { kind: "var", name: target }, right: extractExpr(expr.getRight()) },
@@ -1378,7 +1407,7 @@ function desugarStmtExpr(expr, line) {
1378
1407
  }
1379
1408
  if ((Node.isPostfixUnaryExpression(expr) || Node.isPrefixUnaryExpression(expr)) &&
1380
1409
  (expr.getOperatorToken() === SyntaxKind.PlusPlusToken || expr.getOperatorToken() === SyntaxKind.MinusMinusToken)) {
1381
- const target = expr.getOperand().getText();
1410
+ const target = sourceName(unwrapParens(expr.getOperand()));
1382
1411
  const op = expr.getOperatorToken() === SyntaxKind.PlusPlusToken ? "+" : "-";
1383
1412
  return {
1384
1413
  kind: "assign", target,
@@ -1388,179 +1417,33 @@ function desugarStmtExpr(expr, line) {
1388
1417
  }
1389
1418
  return null;
1390
1419
  }
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
1420
  // ── Statement extraction ─────────────────────────────────────
1529
- /** Parse ghost and assert annotations from comment ranges. */
1530
- function parseSpecComments(ranges, line) {
1531
- const result = [];
1532
- for (const range of ranges) {
1533
- const text = range.getText().trim();
1534
- if (!text.startsWith(PREFIX))
1535
- continue;
1536
- const content = text.slice(PREFIX.length);
1537
- // assert expr
1538
- if (content.startsWith("assert ")) {
1539
- result.push({ kind: "assert", expr: content.slice(7).trim(), line });
1540
- continue;
1541
- }
1542
- // assume expr — trusted form of assert; emitted as `assume P;` in Dafny.
1543
- if (content.startsWith("assume ")) {
1544
- result.push({ kind: "assert", expr: content.slice(7).trim(), line, assumed: true });
1545
- continue;
1546
- }
1547
- if (!content.startsWith("ghost "))
1548
- continue;
1549
- const ghostBody = content.slice(6).trim();
1550
- // ghost let varName: type = expr OR ghost let varName = expr
1551
- // Type segment accepts compound forms like `number[]`, `Map<K,V>`, etc.
1552
- const letMatch = ghostBody.match(/^let\s+(\w+)(?:\s*:\s*([^=]+?))?\s*=\s*(.+)$/);
1553
- if (letMatch) {
1554
- result.push({ kind: "ghostLet", name: letMatch[1], tsType: letMatch[2]?.trim() ?? null, init: letMatch[3].trim(), line });
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;
1421
+ /** Parse ghost and assert annotations in their original lexical scope. */
1422
+ function parseSpecComments(ranges, line, location) {
1423
+ return ranges.flatMap(range => parseSpecComment(range.getText().trim(), line, location, range.getPos()));
1424
+ }
1425
+ function parseSpecComment(text, line, location, pos) {
1426
+ if (!text.startsWith(PREFIX))
1427
+ return [];
1428
+ const content = text.slice(PREFIX.length);
1429
+ const spec = (expr) => _lexicalNames?.spec(expr, location, pos) ?? expr;
1430
+ if (content.startsWith("assert "))
1431
+ return [{ kind: "assert", expr: spec(content.slice(7).trim()), line }];
1432
+ if (content.startsWith("assume "))
1433
+ return [{ kind: "assert", expr: spec(content.slice(7).trim()), line, assumed: true }];
1434
+ if (!content.startsWith("ghost "))
1435
+ return [];
1436
+ const ghostBody = content.slice(6).trim();
1437
+ const letMatch = ghostBody.match(/^let\s+(\w+)(?:\s*:\s*([^=]+?))?\s*=\s*(.+)$/);
1438
+ if (letMatch) {
1439
+ const init = spec(letMatch[3].trim());
1440
+ const name = _lexicalNames?.ghost(letMatch[1], location, pos) ?? letMatch[1];
1441
+ return [{ kind: "ghostLet", name, tsType: letMatch[2]?.trim() ?? null, init, line }];
1442
+ }
1443
+ const assignMatch = ghostBody.match(/^(\w+)\s*=\s*(.+)$/);
1444
+ return assignMatch ? [{ kind: "ghostAssign",
1445
+ target: _lexicalNames?.specName(assignMatch[1], location, pos) ?? assignMatch[1],
1446
+ value: spec(assignMatch[2].trim()), line }] : [];
1564
1447
  }
1565
1448
  /** Splice `update` before each `continue` in the same loop scope. Recurses
1566
1449
  * into `if`/`switch` (same scope) but not nested `while`/`forof` (they own
@@ -1591,12 +1474,15 @@ function insertUpdateBeforeContinue(stmts, update) {
1591
1474
  return out;
1592
1475
  }
1593
1476
  function extractStmts(stmts) {
1477
+ return _lexicalNames ? _lexicalNames.withScope(() => extractScopedStmts(stmts)) : extractScopedStmts(stmts);
1478
+ }
1479
+ function extractScopedStmts(stmts) {
1594
1480
  const result = [];
1595
1481
  for (const s of stmts) {
1596
1482
  const line = s.getStartLineNumber();
1597
1483
  // Ghost annotations from leading comments → inject before this statement
1598
1484
  const leadingComments = s.getLeadingCommentRanges();
1599
- result.push(...parseSpecComments(leadingComments, line));
1485
+ result.push(...parseSpecComments(leadingComments, line, s));
1600
1486
  // //@ skip — omit this statement from the verification model
1601
1487
  if (leadingComments.some(r => r.getText().trim() === "//@ skip")) {
1602
1488
  skipSpan(s);
@@ -1616,8 +1502,8 @@ function extractStmts(stmts) {
1616
1502
  const elements = nameNode.getElements();
1617
1503
  for (let ei = 0; ei < elements.length; ei++) {
1618
1504
  const el = elements[ei];
1619
- const name = el.getName();
1620
- const propType = rhsType.getProperty(name)?.getTypeAtLocation(d);
1505
+ const name = sourceName(el.getNameNode());
1506
+ const propType = rhsType.getProperty(el.getPropertyNameNode()?.getText() ?? el.getName())?.getTypeAtLocation(d);
1621
1507
  const tsType = havocTypes[ei] ?? (propType ? _eraseGenerics(typeToString(propType)) : "unknown");
1622
1508
  result.push({
1623
1509
  kind: "let", name, mutable: s.getDeclarationKind() === "let",
@@ -1653,7 +1539,7 @@ function extractStmts(stmts) {
1653
1539
  if (!Node.isIdentifier(inner)) {
1654
1540
  throw new Error(`nested binding pattern in array destructuring not yet supported: ${el.getText()}`);
1655
1541
  }
1656
- const name = inner.getText();
1542
+ const name = sourceName(inner);
1657
1543
  const isRest = !!el.getDotDotDotToken();
1658
1544
  const elTs = _eraseGenerics(typeToString(el.getType()));
1659
1545
  const init = isRest
@@ -1698,7 +1584,7 @@ function extractStmts(stmts) {
1698
1584
  const elTs = _eraseGenerics(typeToString(el.getType()));
1699
1585
  result.push({
1700
1586
  kind: "let",
1701
- name: localName,
1587
+ name: sourceName(inner),
1702
1588
  mutable: s.getDeclarationKind() === "let",
1703
1589
  tsType: elTs,
1704
1590
  init: { kind: "field", obj: initVar, field: fieldName },
@@ -1731,7 +1617,7 @@ function extractStmts(stmts) {
1731
1617
  const declType = d.getType();
1732
1618
  result.push({
1733
1619
  kind: "let",
1734
- name: restEl.getName(),
1620
+ name: sourceName(restEl.getNameNode()),
1735
1621
  mutable: s.getDeclarationKind() === "let",
1736
1622
  tsType: _eraseGenerics(typeToString(declType)),
1737
1623
  init: deleteInit,
@@ -1802,7 +1688,7 @@ function extractStmts(stmts) {
1802
1688
  ?? (annotatedText ? _eraseGenerics(annotatedText) : (inferred === "any" ? null : inferred));
1803
1689
  result.push({
1804
1690
  kind: "let",
1805
- name: d.getName(),
1691
+ name: sourceName(d.getNameNode()),
1806
1692
  mutable: s.getDeclarationKind() === "let",
1807
1693
  tsType,
1808
1694
  init,
@@ -1839,11 +1725,11 @@ function extractStmts(stmts) {
1839
1725
  if (Node.isOmittedExpression(elem))
1840
1726
  names.push("_");
1841
1727
  else if (Node.isBindingElement(elem))
1842
- names.push(elem.getNameNode().getText());
1728
+ names.push(sourceName(elem.getNameNode()));
1843
1729
  }
1844
1730
  }
1845
1731
  else {
1846
- names.push(decl?.getName() ?? "_");
1732
+ names.push(decl ? sourceName(decl.getNameNode()) : "_");
1847
1733
  }
1848
1734
  }
1849
1735
  else {
@@ -1896,16 +1782,10 @@ function extractStmts(stmts) {
1896
1782
  const annots = collectLoopAnnotations(bodyStmts);
1897
1783
  if (!init || !Node.isVariableDeclarationList(init))
1898
1784
  throw new Error(`for(...) at line ${line}: only variable-declaration init supported`);
1899
- // Hoist the counter declarations, renaming any that would collide once
1900
- // lifted out of the loop scope (see forCounterRename). The renames are
1901
- // then applied to the loop's own desugared pieces below.
1785
+ // Binding names already account for the scope lost by hoisting.
1902
1786
  const hoisted = [];
1903
- const renames = [];
1904
1787
  for (const decl of init.getDeclarations()) {
1905
- const fresh = forCounterRename(decl, s);
1906
- const name = fresh ?? decl.getName();
1907
- if (fresh)
1908
- renames.push([decl.getName(), fresh]);
1788
+ const name = sourceName(decl.getNameNode());
1909
1789
  const typeNode = decl.getTypeNode();
1910
1790
  const tsType = (typeNode && annotationTypeText(typeNode, decl.getType()))
1911
1791
  ?? typeNode?.getText() ?? typeToString(decl.getType());
@@ -1937,15 +1817,6 @@ function extractStmts(stmts) {
1937
1817
  let invariants = annotExprs(annots, "invariant");
1938
1818
  let decreases = firstAnnotExpr(annots, "decreases");
1939
1819
  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
1820
  result.push(...hoisted);
1950
1821
  result.push({
1951
1822
  kind: "while",
@@ -1963,7 +1834,8 @@ function extractStmts(stmts) {
1963
1834
  const init = s.getInitializer();
1964
1835
  let name = "_";
1965
1836
  if (Node.isVariableDeclarationList(init)) {
1966
- name = init.getDeclarations()[0]?.getName() ?? "_";
1837
+ const decl = init.getDeclarations()[0];
1838
+ name = decl ? sourceName(decl.getNameNode()) : "_";
1967
1839
  }
1968
1840
  const bodyNode = s.getStatement();
1969
1841
  const bodyStmts = Node.isBlock(bodyNode) ? bodyNode.getStatements() : [bodyNode];
@@ -2075,16 +1947,17 @@ function extractStmts(stmts) {
2075
1947
  continue;
2076
1948
  }
2077
1949
  if (Node.isExpressionStatement(s)) {
2078
- const expr = s.getExpression();
1950
+ const expr = unwrapParens(s.getExpression());
2079
1951
  // //@ havoc before `x = e` — discard the RHS, assign a nondeterministic
2080
1952
  // value of x's type. Only applies to plain `=` with an identifier LHS;
2081
1953
  // compound assigns, `arr[i] = v`, and `x++` fall through to desugaring.
2082
1954
  const havoc = havocDirective(s);
1955
+ const left = Node.isBinaryExpression(expr) ? unwrapParens(expr.getLeft()) : null;
2083
1956
  if (havoc && !havoc.key && Node.isBinaryExpression(expr)
2084
1957
  && expr.getOperatorToken().getText() === "="
2085
- && Node.isIdentifier(expr.getLeft())) {
2086
- const target = expr.getLeft().getText();
2087
- const tsType = havoc.type ?? _eraseGenerics(typeToString(expr.getLeft().getType()));
1958
+ && left && Node.isIdentifier(left)) {
1959
+ const target = sourceName(left);
1960
+ const tsType = havoc.type ?? _eraseGenerics(typeToString(left.getType()));
2088
1961
  result.push({ kind: "assign", target, value: { kind: "havoc", tsType }, line });
2089
1962
  continue;
2090
1963
  }
@@ -2108,32 +1981,7 @@ function extractStmts(stmts) {
2108
1981
  const last = stmts[stmts.length - 1];
2109
1982
  const line = last.getStartLineNumber();
2110
1983
  for (const sib of last.getNextSiblings()) {
2111
- const text = sib.getText().trim();
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
- }
1984
+ result.push(...parseSpecComment(sib.getText().trim(), line, sib, sib.getStart()));
2137
1985
  }
2138
1986
  }
2139
1987
  return result;
@@ -2141,12 +1989,15 @@ function extractStmts(stmts) {
2141
1989
  // ── Function extraction ──────────────────────────────────────
2142
1990
  function extractFunction(fn, parentAnnotations) {
2143
1991
  const prevInFn = _inFunctionExtraction;
1992
+ const prevNames = _lexicalNames;
1993
+ _lexicalNames = new LexicalNames(fn);
2144
1994
  _inFunctionExtraction = true;
2145
1995
  try {
2146
1996
  return extractFunctionInner(fn, parentAnnotations);
2147
1997
  }
2148
1998
  finally {
2149
1999
  _inFunctionExtraction = prevInFn;
2000
+ _lexicalNames = prevNames;
2150
2001
  }
2151
2002
  }
2152
2003
  function extractFunctionInner(fn, parentAnnotations) {
@@ -2156,7 +2007,6 @@ function extractFunctionInner(fn, parentAnnotations) {
2156
2007
  // can't model as one Dafny type (e.g. `string & {}` tricks), keep T as a Dafny
2157
2008
  // type param instead; such a T must be phantom (any field read won't typecheck).
2158
2009
  _typeParamMap = new Map();
2159
- _reservedForCounterNames = new Set();
2160
2010
  const typeParams = [];
2161
2011
  for (const tp of fn.getTypeParameters?.() ?? []) {
2162
2012
  const constraint = tp.getConstraint();
@@ -2189,7 +2039,9 @@ function extractFunctionInner(fn, parentAnnotations) {
2189
2039
  if (parts.length !== 2)
2190
2040
  continue;
2191
2041
  readExpr(a);
2192
- typeAnnotations.push({ name: parts[0], type: parts[1] });
2042
+ for (const name of _lexicalNames?.typeNames(parts[0]) ?? [parts[0]]) {
2043
+ typeAnnotations.push({ name, type: parts[1] });
2044
+ }
2193
2045
  }
2194
2046
  }
2195
2047
  return {
@@ -2317,8 +2169,8 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
2317
2169
  // tests) must not leak a havoc key, temp-name counter, or function-local maps.
2318
2170
  _havocKey = null;
2319
2171
  _destrCounter = 0;
2172
+ _lexicalNames = null;
2320
2173
  _typeParamMap = new Map();
2321
- _reservedForCounterNames = new Set();
2322
2174
  // Seed the fresh-name check (names.ts) before anything mints: every
2323
2175
  // Identifier token in the module, a deliberate over-approximation.
2324
2176
  setUserNames(new Set(sourceFile.getDescendantsOfKind(SyntaxKind.Identifier).map(i => i.getText())));
@@ -2487,6 +2339,9 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
2487
2339
  const isAnonObject = declTsType.startsWith("__");
2488
2340
  if (init && !isHugeString && !isAnonObject && !Node.isArrowFunction(init)) {
2489
2341
  try {
2342
+ // Callbacks in the initializer get the same no-shadowing names
2343
+ // as those in a function body.
2344
+ _lexicalNames = new LexicalNames(init);
2490
2345
  constants.push({
2491
2346
  name: decl.getName(),
2492
2347
  tsType: declTsType,
@@ -2497,6 +2352,9 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
2497
2352
  const reason = e instanceof Error ? e.message : String(e);
2498
2353
  throw new Error(`Failed to extract const '${decl.getName()}' at ${sourceFile.getBaseName()}:${decl.getStartLineNumber()}: ${reason}`);
2499
2354
  }
2355
+ finally {
2356
+ _lexicalNames = null;
2357
+ }
2500
2358
  }
2501
2359
  }
2502
2360
  }