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.
package/tools/dist/ir.js CHANGED
@@ -75,7 +75,8 @@ export function anyExpr(e, pred) {
75
75
  case "unop":
76
76
  case "toNat":
77
77
  case "toInt":
78
- case "toReal": return anyExpr(e.expr, pred);
78
+ case "toReal":
79
+ case "checkedUnwrap": return anyExpr(e.expr, pred);
79
80
  case "app": return e.args.some(a => anyExpr(a, pred));
80
81
  case "field": return anyExpr(e.obj, pred);
81
82
  case "index": return anyExpr(e.arr, pred) || anyExpr(e.idx, pred);
@@ -432,6 +432,21 @@ function emitExpr(e, parentPrec) {
432
432
  : _boolCtx && e.op === "∧" ? "&&"
433
433
  : _boolCtx && e.op === "∨" ? "||"
434
434
  : e.op;
435
+ // In Lean 4, `&&`, `||`, `∧`, and `∨` are non-dependent, so
436
+ // `checkedUnwrap` (`(x).get (by grind)`) in the right operand has no
437
+ // hypothesis in context. Emit dependent `if _h : ...` when the RHS contains
438
+ // a `checkedUnwrap` so Lean puts the presence guard in scope for `grind`.
439
+ if ((e.op === "∧" || e.op === "∨") && anyExpr(e.right, x => x.kind === "checkedUnwrap")) {
440
+ const l = emitExpr(e.left);
441
+ const r = emitExpr(e.right);
442
+ const condProp = isPropValued(e.left) ? l : `(${l}) = true`;
443
+ const tVal = _boolCtx ? "true" : "True";
444
+ const fVal = _boolCtx ? "false" : "False";
445
+ const rExpr = _boolCtx && isPropValued(e.right) ? `decide (${r})` : r;
446
+ return e.op === "∧"
447
+ ? `(if _h : ${condProp} then (${rExpr}) else ${fVal})`
448
+ : `(if _h : ${condProp} then ${tVal} else (${rExpr}))`;
449
+ }
435
450
  // Comparisons and ↔ do not chain in Lean. In particular, a Boolean
436
451
  // postcondition `res = (s = t)` must keep its inner equality grouped.
437
452
  const childPrec = ["↔", "=", "≠", "<", "≤", ">", "≥"].includes(e.op)
@@ -524,6 +539,8 @@ function emitExpr(e, parentPrec) {
524
539
  return wrap ? `(${inner}).toNat` : `${inner}.toNat`;
525
540
  }
526
541
  case "toInt": return `(Int.ofNat (${emitExpr(e.expr)}))`;
542
+ case "checkedUnwrap":
543
+ return `((${emitExpr(e.expr)}).get (by grind))`;
527
544
  case "toReal":
528
545
  // A real value reached the Lean backend via coercion (e.g. number `/`).
529
546
  // Same unsupported-real story as the `real` type case in tyToLean.
@@ -544,8 +561,19 @@ function emitExpr(e, parentPrec) {
544
561
  return `{ ${emitExpr(e.spread)} with ${fields.join(", ")} }`;
545
562
  return `{ ${fields.join(", ")} }`;
546
563
  }
547
- case "if":
564
+ case "if": {
565
+ const hasCU = anyExpr(e.then, x => x.kind === "checkedUnwrap") || anyExpr(e.else, x => x.kind === "checkedUnwrap");
566
+ if (hasCU) {
567
+ const c = emitExpr(e.cond);
568
+ const condProp = isPropValued(e.cond) ? c : `(${c}) = true`;
569
+ const t = emitExpr(e.then);
570
+ const f = emitExpr(e.else);
571
+ const tExpr = _boolCtx && isPropValued(e.then) ? `decide (${t})` : t;
572
+ const fExpr = _boolCtx && isPropValued(e.else) ? `decide (${f})` : f;
573
+ return `(if _h : ${condProp} then (${tExpr}) else (${fExpr}))`;
574
+ }
548
575
  return `if ${emitExpr(e.cond)} then ${emitExpr(e.then)} else ${emitExpr(e.else)}`;
576
+ }
549
577
  case "match": {
550
578
  // Always parenthesize inline matches — Lean parses alternatives greedily,
551
579
  // so any token after an arm body (`→`, another match's `|`, etc.) would
@@ -556,7 +584,11 @@ function emitExpr(e, parentPrec) {
556
584
  }
557
585
  case "forall": return `∀ ${e.var} : ${tyToLean(e.type)}, ${emitExpr(e.body)}`;
558
586
  case "exists": return `∃ ${e.var} : ${tyToLean(e.type)}, ${emitExpr(e.body)}`;
559
- case "let": return `let ${e.name}${e.type ? ` : ${tyToLean(e.type)}` : ""} := ${emitExpr(e.value)}\n${emitExpr(e.body)}`;
587
+ case "let":
588
+ if (e.name.startsWith("_cmp")) {
589
+ return `(let ${e.name}${e.type ? ` : ${tyToLean(e.type)}` : ""} := ${emitExpr(e.value)}; ${emitExpr(e.body)})`;
590
+ }
591
+ return `let ${e.name}${e.type ? ` : ${tyToLean(e.type)}` : ""} := ${emitExpr(e.value)}\n${emitExpr(e.body)}`;
560
592
  default: throw new Error(`Unsupported Lean expression: ${e.kind}`);
561
593
  }
562
594
  }
@@ -0,0 +1,212 @@
1
+ import { Node, SyntaxKind, ts } from "ts-morph";
2
+ import { reserveName } from "./names.js";
3
+ import { renameSpecVariables } from "./specparser.js";
4
+ function functionLike(node) {
5
+ return Node.isFunctionDeclaration(node) || Node.isMethodDeclaration(node)
6
+ || Node.isArrowFunction(node) || Node.isFunctionExpression(node);
7
+ }
8
+ function scopeOf(node) {
9
+ return node.getFirstAncestor(n => Node.isBlock(n) || Node.isCaseBlock(n)
10
+ || Node.isForStatement(n) || Node.isForOfStatement(n) || Node.isForInStatement(n)
11
+ || functionLike(n)) ?? node.getSourceFile();
12
+ }
13
+ function bindings(node) {
14
+ if (Node.isIdentifier(node))
15
+ return [node];
16
+ if (Node.isObjectBindingPattern(node) || Node.isArrayBindingPattern(node)) {
17
+ return node.getElements().flatMap(e => Node.isBindingElement(e) ? bindings(e.getNameNode()) : []);
18
+ }
19
+ return [];
20
+ }
21
+ /** `recv.method(callback)`: backends may emit the receiver inside the scope
22
+ * of the callback's parameter (a comprehension), so the parameter must not
23
+ * share a name with anything the receiver mentions, library globals included. */
24
+ function receiverMentions(callback, name) {
25
+ const call = callback.getParent();
26
+ if (!Node.isCallExpression(call) || !call.getArguments().includes(callback))
27
+ return false;
28
+ const callee = call.getExpression();
29
+ if (!Node.isPropertyAccessExpression(callee))
30
+ return false;
31
+ const receiver = callee.getExpression();
32
+ return [receiver, ...receiver.getDescendantsOfKind(SyntaxKind.Identifier)]
33
+ .some(n => Node.isIdentifier(n) && n.getText() === name);
34
+ }
35
+ function valueSymbol(node) {
36
+ const parent = node.getParent();
37
+ return Node.isShorthandPropertyAssignment(parent) ? parent.getValueSymbol() : node.getSymbol();
38
+ }
39
+ /** Bare blocks and counting-for initializers lose their braces in extraction.
40
+ * Branch blocks keep separate arms but can absorb their parent's continuation.
41
+ * `mayCapture` marks a scope that can therefore reach names outside the
42
+ * function. Loop and lambda scopes remain barriers; siblings there need no
43
+ * rename, but a binding that shadows an enclosing one always gets one. */
44
+ function loweredScope(decl) {
45
+ let scope = scopeOf(decl);
46
+ let mayCapture = Node.isForStatement(scope) || Node.isCaseBlock(scope);
47
+ if (Node.isForStatement(scope))
48
+ scope = scopeOf(scope);
49
+ while (Node.isBlock(scope) && Node.isBlock(scope.getParent())) {
50
+ mayCapture = true;
51
+ scope = scope.getParentOrThrow();
52
+ }
53
+ const parent = scope.getParent();
54
+ if (parent && (Node.isIfStatement(parent) || Node.isCaseClause(parent) || Node.isDefaultClause(parent)))
55
+ mayCapture = true;
56
+ return { scope, mayCapture };
57
+ }
58
+ /** After extraction no binding in a function shadows another: a local, loop
59
+ * variable, or callback parameter that reuses an enclosing name is renamed.
60
+ * Later passes may therefore identify a variable by its name alone.
61
+ * Allocate before extracting any expressions, without mutating the TS tree.
62
+ * Unambiguous locals and public parameter names keep their existing spelling. */
63
+ export class LexicalNames {
64
+ renamed = new Map();
65
+ used = new Set();
66
+ sourceNames;
67
+ taken;
68
+ ghosts = new Map();
69
+ aliases = new Map();
70
+ constructor(root) {
71
+ this.sourceNames = new Set(root.getDescendantsOfKind(SyntaxKind.Identifier).map(i => i.getText()));
72
+ // Include spec-only identifiers, including quantifier and ghost binders.
73
+ // A fresh source name must not capture one when annotations are rewritten.
74
+ const specNames = (root.getFullText().match(/\/\/@[^\r\n]*/g) ?? [])
75
+ .flatMap(comment => comment.match(/[A-Za-z_]\w*/g) ?? []);
76
+ this.taken = new Set([...this.sourceNames, ...specNames]);
77
+ // Names bound outside the function. A scope that keeps its braces cannot
78
+ // capture a library global, so only this file's own declarations count there.
79
+ const outer = new Set(), moduleNames = new Set();
80
+ const file = root.getSourceFile();
81
+ for (const symbol of root.getSymbolsInScope(ts.SymbolFlags.Value)) {
82
+ const declarations = symbol.getDeclarations();
83
+ if (declarations.some(d => d.getAncestors().includes(root)))
84
+ continue;
85
+ outer.add(symbol.getName());
86
+ if (declarations.some(d => d.getSourceFile() === file))
87
+ moduleNames.add(symbol.getName());
88
+ }
89
+ const locals = [];
90
+ // Prefer enclosing locals even if they occur later in source order. This
91
+ // also preserves the existing names of counters hoisted out of for-loops.
92
+ // Callback parameters are bindings too; the function's own stay public.
93
+ const declarations = [...root.getDescendantsOfKind(SyntaxKind.VariableDeclaration),
94
+ ...root.getDescendantsOfKind(SyntaxKind.Parameter).filter(p => {
95
+ const owner = p.getParent();
96
+ return owner !== root && functionLike(owner);
97
+ })].sort((a, b) => scopeOf(a).getAncestors().length - scopeOf(b).getAncestors().length || a.getStart() - b.getStart());
98
+ for (const decl of declarations) {
99
+ const owner = Node.isParameterDeclaration(decl) ? decl.getParent() : undefined;
100
+ for (const id of bindings(decl.getNameNode())) {
101
+ const name = id.getText();
102
+ const { scope, mayCapture } = loweredScope(decl);
103
+ const parameterClash = decl.getAncestors().some(a => a !== owner && functionLike(a)
104
+ && a.getChildrenOfKind(SyntaxKind.Parameter).some(p => bindings(p.getNameNode()).some(b => b.getText() === name)));
105
+ const symbol = id.getSymbol();
106
+ const localClash = locals.some(l => l.name === name && (l.scope === scope || scope.getAncestors().includes(l.scope)));
107
+ let emitted = name;
108
+ if (symbol && ((mayCapture ? outer : moduleNames).has(name) || parameterClash || localClash
109
+ || (owner && receiverMentions(owner, name)))) {
110
+ const fresh = this.fresh(name);
111
+ emitted = fresh;
112
+ this.renamed.set(symbol.compilerSymbol, fresh);
113
+ this.aliases.set(name, [...this.aliases.get(name) ?? [], fresh]);
114
+ }
115
+ locals.push({ name: emitted, scope });
116
+ this.used.add(name);
117
+ }
118
+ }
119
+ }
120
+ fresh(base) {
121
+ let suffix = 2;
122
+ while (this.taken.has(`${base}_${suffix}`))
123
+ suffix++;
124
+ const name = `${base}_${suffix}`;
125
+ this.taken.add(name);
126
+ reserveName(name);
127
+ return name;
128
+ }
129
+ name(node) {
130
+ if (Node.isIdentifier(node)) {
131
+ const symbol = valueSymbol(node);
132
+ return symbol && this.renamed.get(symbol.compilerSymbol) || node.getText();
133
+ }
134
+ // Assignment targets are still strings in Raw IR; rename their root only.
135
+ if (Node.isPropertyAccessExpression(node))
136
+ return `${this.name(node.getExpression())}.${node.getName()}`;
137
+ return node.getText();
138
+ }
139
+ /** A local type override follows every renamed binding of that source name. */
140
+ typeNames(name) {
141
+ return [name, ...this.aliases.get(name) ?? []];
142
+ }
143
+ withScope(action) {
144
+ const outer = this.ghosts;
145
+ this.ghosts = new Map(outer);
146
+ try {
147
+ return action();
148
+ }
149
+ finally {
150
+ this.ghosts = outer;
151
+ }
152
+ }
153
+ ghost(name, location, pos) {
154
+ const emitted = this.used.has(name) || this.sourceNames.has(name) ? this.fresh(name) : name;
155
+ this.used.add(name);
156
+ reserveName(emitted);
157
+ this.ghosts.set(name, { name: emitted, scope: scopeOf(location), pos });
158
+ return emitted;
159
+ }
160
+ specName(name, location, pos = location.getStart()) {
161
+ // `_x_idx` is the position of for-of variable `x`; it follows x's rename.
162
+ const index = /^_(.+)_idx$/.exec(name);
163
+ if (index && !this.sourceNames.has(name))
164
+ return `_${this.specName(index[1], location, pos)}_idx`;
165
+ // Leading comments belong to the statement's enclosing scope, including
166
+ // when the statement itself is a block or another loop.
167
+ const symbol = location.getProject().getTypeChecker().resolveName(name, location.getParent(), ts.SymbolFlags.Value, false);
168
+ const ghost = this.ghosts.get(name);
169
+ if (ghost) {
170
+ // A nested source binding shadows an outer ghost in specs. In the same
171
+ // scope, the most recent declaration wins. Runtime reads always use the
172
+ // TS symbol, never this separate ghost environment.
173
+ const shadowed = symbol?.getDeclarations().some(d => {
174
+ const scope = scopeOf(d);
175
+ return scope === ghost.scope ? d.getStart() > ghost.pos && d.getStart() < pos
176
+ : scope.getAncestors().includes(ghost.scope);
177
+ });
178
+ if (!shadowed)
179
+ return ghost.name;
180
+ }
181
+ return symbol && this.renamed.get(symbol.compilerSymbol) || name;
182
+ }
183
+ spec(text, location, pos) {
184
+ if (this.renamed.size === 0 && this.ghosts.size === 0)
185
+ return text;
186
+ return renameSpecVariables(text, name => this.specName(name, location, pos));
187
+ }
188
+ }
189
+ /** Backend lambdas cannot capture a local that is declared later. Checking
190
+ * symbols here avoids silently binding the closure to an outer namesake.
191
+ * Callback parameter defaults have their own initialization model in resolve. */
192
+ export function rejectForwardLocalCaptures(arrow) {
193
+ const body = arrow.getBody();
194
+ const identifiers = Node.isIdentifier(body) ? [body] : body.getDescendantsOfKind(SyntaxKind.Identifier);
195
+ for (const id of identifiers) {
196
+ if (id.getAncestors().some(n => ts.isTypeNode(n.compilerNode)))
197
+ continue;
198
+ for (const binding of valueSymbol(id)?.getDeclarations() ?? []) {
199
+ const decl = Node.isVariableDeclaration(binding) ? binding
200
+ : Node.isBindingElement(binding) ? binding.getFirstAncestorByKind(SyntaxKind.VariableDeclaration) : undefined;
201
+ if (!decl || decl.getStart() <= arrow.getStart() || decl.getAncestors().includes(arrow))
202
+ continue;
203
+ const list = decl.getParent();
204
+ if (!Node.isVariableDeclarationList(list) || list.getDeclarationKind() === "var")
205
+ continue;
206
+ if (Node.isSourceFile(scopeOf(decl)))
207
+ continue;
208
+ throw new Error(`Unsupported forward capture '${id.getText()}' at line ${arrow.getStartLineNumber()}: `
209
+ + `closure captures a local declared later at line ${decl.getStartLineNumber()}`);
210
+ }
211
+ }
212
+ }
package/tools/dist/lsc.js CHANGED
@@ -10,6 +10,7 @@ import { createRequire } from "module";
10
10
  import path from "path";
11
11
  import { extractModule } from "./extract.js";
12
12
  import { resolveModule } from "./resolve.js";
13
+ import { assertNoLiveAliasMutations } from "./alias-check-pass.js";
13
14
  import { narrowModule } from "./narrow.js";
14
15
  import { autoHavocModule } from "./autohavoc.js";
15
16
  import { transformModuleLean, transformModuleDafny } from "./transform.js";
@@ -336,7 +337,7 @@ function runFile(cmd, filePath, backend, timeLimit, extraFlags, noVerify = false
336
337
  return;
337
338
  }
338
339
  // Resolve: Raw IR → Typed IR
339
- const resolved = resolveModule(raw);
340
+ const resolved = assertNoLiveAliasMutations(resolveModule(raw));
340
341
  // Narrow: Typed IR → Typed IR (rewrites optional-narrowing patterns to someMatch)
341
342
  // auto-havoc (//@ autohavoc): replace unmodellable expressions with arbitrary
342
343
  // values so verification rests only on the declared contracts (a sound
@@ -387,18 +388,18 @@ function runFile(cmd, filePath, backend, timeLimit, extraFlags, noVerify = false
387
388
  ? new RunLog({ logDir: resolveLogDir(absPath, configFile), cmd: logCmd, sourcePath: absPath, extraFlags, lscVersion: safely(lscVersion) })
388
389
  : undefined;
389
390
  if (cmd === "gen") {
390
- dafnyGen(genPath, dfyPath, text);
391
+ dafnyGen(genPath, dfyPath, text, basePath);
391
392
  return;
392
393
  }
393
394
  if (cmd === "gen-check") {
394
- dafnyGen(genPath, dfyPath, text);
395
- if (!dafnyCheckDiff(genPath, dfyPath))
395
+ dafnyGen(genPath, dfyPath, text, basePath);
396
+ if (!dafnyCheckDiff(genPath, dfyPath, undefined, basePath))
396
397
  process.exit(1);
397
398
  return;
398
399
  }
399
400
  if (cmd === "check") {
400
- dafnyGen(genPath, dfyPath, text);
401
- if (!dafnyCheckDiff(genPath, dfyPath, log))
401
+ dafnyGen(genPath, dfyPath, text, basePath);
402
+ if (!dafnyCheckDiff(genPath, dfyPath, log, basePath))
402
403
  process.exit(1);
403
404
  if (!dafnyVerify(dfyPath, artifactDir, timeLimit, extraFlags, log))
404
405
  process.exit(1);
@@ -31,6 +31,10 @@ let _userNames = new Set();
31
31
  export function setUserNames(names) {
32
32
  _userNames = names;
33
33
  }
34
+ /** A renamed source/ghost binding must also be avoided by later passes. */
35
+ export function reserveName(name) {
36
+ _userNames.add(name);
37
+ }
34
38
  export function isUserName(name) {
35
39
  return _userNames.has(name);
36
40
  }