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
|
@@ -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
|
@@ -387,18 +387,18 @@ function runFile(cmd, filePath, backend, timeLimit, extraFlags, noVerify = false
|
|
|
387
387
|
? new RunLog({ logDir: resolveLogDir(absPath, configFile), cmd: logCmd, sourcePath: absPath, extraFlags, lscVersion: safely(lscVersion) })
|
|
388
388
|
: undefined;
|
|
389
389
|
if (cmd === "gen") {
|
|
390
|
-
dafnyGen(genPath, dfyPath, text);
|
|
390
|
+
dafnyGen(genPath, dfyPath, text, basePath);
|
|
391
391
|
return;
|
|
392
392
|
}
|
|
393
393
|
if (cmd === "gen-check") {
|
|
394
|
-
dafnyGen(genPath, dfyPath, text);
|
|
395
|
-
if (!dafnyCheckDiff(genPath, dfyPath))
|
|
394
|
+
dafnyGen(genPath, dfyPath, text, basePath);
|
|
395
|
+
if (!dafnyCheckDiff(genPath, dfyPath, undefined, basePath))
|
|
396
396
|
process.exit(1);
|
|
397
397
|
return;
|
|
398
398
|
}
|
|
399
399
|
if (cmd === "check") {
|
|
400
|
-
dafnyGen(genPath, dfyPath, text);
|
|
401
|
-
if (!dafnyCheckDiff(genPath, dfyPath, log))
|
|
400
|
+
dafnyGen(genPath, dfyPath, text, basePath);
|
|
401
|
+
if (!dafnyCheckDiff(genPath, dfyPath, log, basePath))
|
|
402
402
|
process.exit(1);
|
|
403
403
|
if (!dafnyVerify(dfyPath, artifactDir, timeLimit, extraFlags, log))
|
|
404
404
|
process.exit(1);
|
package/tools/dist/names.js
CHANGED
|
@@ -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
|
}
|
package/tools/dist/resolve.js
CHANGED
|
@@ -24,6 +24,14 @@ function lookup(env, name) {
|
|
|
24
24
|
function extend(env, name, ty) {
|
|
25
25
|
return { name, ty, parent: env };
|
|
26
26
|
}
|
|
27
|
+
/** A quantified variable that reuses the name of a binding in scope is emitted
|
|
28
|
+
* under a fresh name, so no later pass confuses it with that binding. */
|
|
29
|
+
function quantified(env, name, ty) {
|
|
30
|
+
const frame = extend(env, name, ty);
|
|
31
|
+
if (binding(env, name))
|
|
32
|
+
frame.emittedName = freshName(name);
|
|
33
|
+
return frame;
|
|
34
|
+
}
|
|
27
35
|
/** Shadow a binding with a narrowed type, keeping its callback state.
|
|
28
36
|
* Dropping that state would let the body reference a renamed parameter by its
|
|
29
37
|
* source name, which can silently bind an outer variable. The spread is exact
|
|
@@ -1456,12 +1464,14 @@ function resolveExprInner(e, ctx) {
|
|
|
1456
1464
|
case "forall": {
|
|
1457
1465
|
const varTy = e.varType !== "int" ? parseTsType(e.varType)
|
|
1458
1466
|
: inferQuantVarType(e.var, e.body, ctx) ?? { kind: "int" };
|
|
1459
|
-
|
|
1467
|
+
const bound = quantified(ctx.env, e.var, varTy);
|
|
1468
|
+
return { kind: "forall", var: bound.emittedName ?? e.var, varTy, body: resolveExpr(e.body, withEnv(ctx, bound)), ty: { kind: "bool" } };
|
|
1460
1469
|
}
|
|
1461
1470
|
case "exists": {
|
|
1462
1471
|
const varTy = e.varType !== "int" ? parseTsType(e.varType)
|
|
1463
1472
|
: inferQuantVarType(e.var, e.body, ctx) ?? { kind: "int" };
|
|
1464
|
-
|
|
1473
|
+
const bound = quantified(ctx.env, e.var, varTy);
|
|
1474
|
+
return { kind: "exists", var: bound.emittedName ?? e.var, varTy, body: resolveExpr(e.body, withEnv(ctx, bound)), ty: { kind: "bool" } };
|
|
1465
1475
|
}
|
|
1466
1476
|
case "arrayLiteral": {
|
|
1467
1477
|
// Expected-tuple context: type each element against its own slot type and
|
|
@@ -1780,16 +1790,19 @@ function resolveStmt(s, ctx) {
|
|
|
1780
1790
|
for (const _ of s.names)
|
|
1781
1791
|
nameTypes.push({ kind: "unknown" });
|
|
1782
1792
|
}
|
|
1783
|
-
//
|
|
1784
|
-
//
|
|
1785
|
-
|
|
1793
|
+
// The loop counter is minted here, once, and recorded on the loop so
|
|
1794
|
+
// transform emits the same name a spec here refers to. The first loop
|
|
1795
|
+
// over a head name in a function gets `_x_idx`, later ones `_x_idx2`, ….
|
|
1796
|
+
const count = ctx.forofCounts.get(s.names[0]) ?? 0;
|
|
1797
|
+
ctx.forofCounts.set(s.names[0], count + 1);
|
|
1798
|
+
const idxName = freshName(`_${s.names[0]}_idx${count === 0 ? "" : count + 1}`);
|
|
1786
1799
|
env = extend(env, idxName, { kind: "nat" });
|
|
1787
1800
|
for (let j = 0; j < s.names.length; j++) {
|
|
1788
1801
|
env = extend(env, s.names[j], nameTypes[j] ?? { kind: "unknown" });
|
|
1789
1802
|
}
|
|
1790
1803
|
const bodyCtx = withEnv(ctx, env);
|
|
1791
1804
|
return [{
|
|
1792
|
-
kind: "forof", names: s.names, nameTypes, iterable,
|
|
1805
|
+
kind: "forof", names: s.names, nameTypes, iterable, idx: idxName,
|
|
1793
1806
|
invariants: resolveSpecs(s.invariants, { ...bodyCtx, inSpec: true }),
|
|
1794
1807
|
doneWith: s.doneWith ? resolveSpec(s.doneWith, { ...bodyCtx, inSpec: true }) : null,
|
|
1795
1808
|
body: resolveBlock(s.body, bodyCtx),
|
|
@@ -2032,7 +2045,7 @@ function resolveFunction(fn, typeDecls, pureFns, fnParams = new Map(), fnReturns
|
|
|
2032
2045
|
env = extend(env, opts.thisBinding.name, opts.thisBinding.ty);
|
|
2033
2046
|
for (const p of params)
|
|
2034
2047
|
env = extend(env, p.name, p.ty);
|
|
2035
|
-
const baseCtx = { env, typeDecls, overrides, allowResult: false, returnTy, pureFns, fnParams, fnReturns, externs, inSpec: false, inLambda: false, narrowedPaths: [], narrowedIndices: [] };
|
|
2048
|
+
const baseCtx = { env, typeDecls, overrides, allowResult: false, returnTy, pureFns, fnParams, fnReturns, externs, inSpec: false, inLambda: false, narrowedPaths: [], narrowedIndices: [], forofCounts: new Map() };
|
|
2036
2049
|
const requiresCtx = { ...baseCtx, inSpec: true };
|
|
2037
2050
|
const ensuresCtx = { ...baseCtx, env: extend(env, "\\result", returnTy), allowResult: true, inSpec: true };
|
|
2038
2051
|
// Apply type parameter constraints from //@ type T (==) annotations
|
|
@@ -2139,7 +2152,7 @@ export function resolveModule(raw) {
|
|
|
2139
2152
|
for (let i = 0; i < ext.params.length; i++) {
|
|
2140
2153
|
env = extend(env, ext.params[i].name, sig.params[i]);
|
|
2141
2154
|
}
|
|
2142
|
-
const baseCtx = { env, typeDecls: raw.typeDecls, overrides: new Map(), allowResult: false, returnTy: sig.returnTy, pureFns, fnParams, fnReturns, externs, inSpec: true, inLambda: false, narrowedPaths: [], narrowedIndices: [] };
|
|
2155
|
+
const baseCtx = { env, typeDecls: raw.typeDecls, overrides: new Map(), allowResult: false, returnTy: sig.returnTy, pureFns, fnParams, fnReturns, externs, inSpec: true, inLambda: false, narrowedPaths: [], narrowedIndices: [], forofCounts: new Map() };
|
|
2143
2156
|
const ensuresCtx = { ...baseCtx, env: extend(env, "\\result", sig.returnTy), allowResult: true };
|
|
2144
2157
|
const resolveClauses = (kind, ctx) => ext[kind].map(s => {
|
|
2145
2158
|
try {
|
|
@@ -2161,7 +2174,7 @@ export function resolveModule(raw) {
|
|
|
2161
2174
|
impure: ext.impure,
|
|
2162
2175
|
};
|
|
2163
2176
|
});
|
|
2164
|
-
const emptyCtx = { env: null, typeDecls: raw.typeDecls, overrides: new Map(), allowResult: false, returnTy: { kind: "int" }, pureFns, fnParams, fnReturns, externs, inSpec: false, inLambda: false, narrowedPaths: [], narrowedIndices: [] };
|
|
2177
|
+
const emptyCtx = { env: null, typeDecls: raw.typeDecls, overrides: new Map(), allowResult: false, returnTy: { kind: "int" }, pureFns, fnParams, fnReturns, externs, inSpec: false, inLambda: false, narrowedPaths: [], narrowedIndices: [], forofCounts: new Map() };
|
|
2165
2178
|
const constants = (raw.constants ?? []).map(c => {
|
|
2166
2179
|
const declaredTy = expandAlias(parseTsType(c.tsType), raw.typeDecls);
|
|
2167
2180
|
// Propagate the declared type into the value's resolution context so that
|
package/tools/dist/specparser.js
CHANGED
|
@@ -9,17 +9,23 @@ const MULTI_OPS = ["<==>", "==>", "===", "!==", "==", "!=", ">=", "<=", "&&", "|
|
|
|
9
9
|
* allow TypeScript's fractional and exponent forms. */
|
|
10
10
|
const BIGINT_LITERAL = /^(?:(?:0[xX][0-9a-fA-F](?:_?[0-9a-fA-F])*)|(?:0[bB][01](?:_?[01])*)|(?:0[oO][0-7](?:_?[0-7])*)|(?:[0-9](?:_?[0-9])*))n/;
|
|
11
11
|
const NUMBER_LITERAL = /^(?:(?:0[xX][0-9a-fA-F](?:_?[0-9a-fA-F])*)|(?:0[bB][01](?:_?[01])*)|(?:0[oO][0-7](?:_?[0-7])*)|(?:(?:[0-9](?:_?[0-9])*)(?:\.(?:[0-9](?:_?[0-9])*)?)?|\.(?:[0-9](?:_?[0-9])*))(?:[eE][+-]?(?:[0-9](?:_?[0-9])*))?)/;
|
|
12
|
-
function tokenize(input) {
|
|
12
|
+
function tokenize(input, spans) {
|
|
13
13
|
const tokens = [];
|
|
14
14
|
let i = 0;
|
|
15
|
+
let start = 0;
|
|
16
|
+
const push = (token) => {
|
|
17
|
+
tokens.push(token);
|
|
18
|
+
spans?.push({ start, end: i });
|
|
19
|
+
};
|
|
15
20
|
while (i < input.length) {
|
|
16
21
|
if (/\s/.test(input[i])) {
|
|
17
22
|
i++;
|
|
18
23
|
continue;
|
|
19
24
|
}
|
|
25
|
+
start = i;
|
|
20
26
|
if (input[i] === "\\" && input.slice(i + 1, i + 7) === "result") {
|
|
21
|
-
tokens.push({ type: "result", value: undefined });
|
|
22
27
|
i += 7;
|
|
28
|
+
push({ type: "result", value: undefined });
|
|
23
29
|
continue;
|
|
24
30
|
}
|
|
25
31
|
if (input[i] === '"' || input[i] === "'") {
|
|
@@ -44,7 +50,7 @@ function tokenize(input) {
|
|
|
44
50
|
}
|
|
45
51
|
if (i < input.length)
|
|
46
52
|
i++;
|
|
47
|
-
|
|
53
|
+
push({ type: "str", value: s });
|
|
48
54
|
continue;
|
|
49
55
|
}
|
|
50
56
|
if (/[0-9]/.test(input[i]) || (input[i] === "." && /[0-9]/.test(input[i + 1]))) {
|
|
@@ -58,23 +64,23 @@ function tokenize(input) {
|
|
|
58
64
|
// The `n` suffix is meaningful, not noise: a BigInt keeps its exact value
|
|
59
65
|
// as a decimal string instead of being rounded into a double.
|
|
60
66
|
if (bigintMatch)
|
|
61
|
-
|
|
67
|
+
push({ type: "bigint", value: normalizeBigIntLiteral(text) });
|
|
62
68
|
else
|
|
63
|
-
|
|
69
|
+
push({ type: "num", value: Number(text.replace(/_/g, "")) });
|
|
64
70
|
continue;
|
|
65
71
|
}
|
|
66
72
|
if (/[a-zA-Z_]/.test(input[i])) {
|
|
67
73
|
let id = "";
|
|
68
74
|
while (i < input.length && /[a-zA-Z_0-9]/.test(input[i]))
|
|
69
75
|
id += input[i++];
|
|
70
|
-
|
|
76
|
+
push({ type: "ident", value: id });
|
|
71
77
|
continue;
|
|
72
78
|
}
|
|
73
79
|
let matched = false;
|
|
74
80
|
for (const op of MULTI_OPS) {
|
|
75
81
|
if (input.slice(i, i + op.length) === op) {
|
|
76
|
-
tokens.push({ type: "op", value: op });
|
|
77
82
|
i += op.length;
|
|
83
|
+
push({ type: "op", value: op });
|
|
78
84
|
matched = true;
|
|
79
85
|
break;
|
|
80
86
|
}
|
|
@@ -82,25 +88,28 @@ function tokenize(input) {
|
|
|
82
88
|
if (matched)
|
|
83
89
|
continue;
|
|
84
90
|
const ch = input[i];
|
|
91
|
+
i++;
|
|
85
92
|
if ("+-*/%><!?".includes(ch)) {
|
|
86
|
-
|
|
93
|
+
push({ type: "op", value: ch });
|
|
87
94
|
}
|
|
88
95
|
else if ("()[],:.{}".includes(ch)) {
|
|
89
|
-
|
|
96
|
+
push({ type: "punc", value: ch });
|
|
90
97
|
}
|
|
91
98
|
else {
|
|
92
|
-
throw new Error(`Unexpected '${ch}' at ${i} in: ${input}`);
|
|
99
|
+
throw new Error(`Unexpected '${ch}' at ${i - 1} in: ${input}`);
|
|
93
100
|
}
|
|
94
|
-
i++;
|
|
95
101
|
}
|
|
96
102
|
return tokens;
|
|
97
103
|
}
|
|
98
104
|
// ── Parser ───────────────────────────────────────────────────
|
|
99
105
|
class Parser {
|
|
100
106
|
tokens;
|
|
107
|
+
onFreeVariable;
|
|
101
108
|
pos = 0;
|
|
102
|
-
|
|
109
|
+
bound = new Set();
|
|
110
|
+
constructor(tokens, onFreeVariable) {
|
|
103
111
|
this.tokens = tokens;
|
|
112
|
+
this.onFreeVariable = onFreeVariable;
|
|
104
113
|
}
|
|
105
114
|
peek() { return this.tokens[this.pos]; }
|
|
106
115
|
advance() { return this.tokens[this.pos++]; }
|
|
@@ -304,10 +313,15 @@ class Parser {
|
|
|
304
313
|
varType = ty;
|
|
305
314
|
}
|
|
306
315
|
this.expect("punc", ",");
|
|
316
|
+
const outer = this.bound;
|
|
317
|
+
this.bound = new Set([...outer, v]);
|
|
307
318
|
const body = this.parseIff();
|
|
319
|
+
this.bound = outer;
|
|
308
320
|
this.expect("punc", ")");
|
|
309
321
|
return { kind: q, var: v, varType, body };
|
|
310
322
|
}
|
|
323
|
+
if (!this.bound.has(t.value))
|
|
324
|
+
this.onFreeVariable?.(t.value, this.pos);
|
|
311
325
|
this.advance();
|
|
312
326
|
return { kind: "var", name: t.value };
|
|
313
327
|
}
|
|
@@ -350,3 +364,18 @@ class Parser {
|
|
|
350
364
|
export function parseExpr(input) {
|
|
351
365
|
return new Parser(tokenize(input)).parse();
|
|
352
366
|
}
|
|
367
|
+
/** Rewrite only free variable tokens, preserving annotation spelling and
|
|
368
|
+
* leaving fields, record keys, literals, types, and quantifier binders alone. */
|
|
369
|
+
export function renameSpecVariables(input, rename) {
|
|
370
|
+
const spans = [];
|
|
371
|
+
const tokens = tokenize(input, spans);
|
|
372
|
+
const edits = [];
|
|
373
|
+
new Parser(tokens, (name, index) => {
|
|
374
|
+
const replacement = rename(name);
|
|
375
|
+
if (replacement !== name)
|
|
376
|
+
edits.push({ ...spans[index], name: replacement });
|
|
377
|
+
}).parse();
|
|
378
|
+
for (const edit of edits.reverse())
|
|
379
|
+
input = input.slice(0, edit.start) + edit.name + input.slice(edit.end);
|
|
380
|
+
return input;
|
|
381
|
+
}
|
package/tools/dist/transform.js
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* No type lookups, no string parsing, no re-inference.
|
|
6
6
|
*/
|
|
7
7
|
import { isBigInt, tyEqual } from "./typedir.js";
|
|
8
|
-
import { anyExpr, anyExprInStmts, pWild, pCtor, pLiteral, patternBinders,
|
|
8
|
+
import { anyExpr, anyExprInStmts, pWild, pCtor, pLiteral, patternBinders, patternCtor } from "./ir.js";
|
|
9
9
|
import { parseTsType } from "./types.js";
|
|
10
10
|
import { freshName } from "./names.js";
|
|
11
11
|
import { builtinSpec } from "./builtins.js";
|
|
@@ -85,50 +85,7 @@ function mapStmt(s, f) {
|
|
|
85
85
|
case "assert": return { ...s, expr: r(s.expr) };
|
|
86
86
|
}
|
|
87
87
|
}
|
|
88
|
-
/** Rename free occurrences of `from` to `to`, stopping at every construct that
|
|
89
|
-
* rebinds `from` — lambda params, `let`/`let-bind`/`ghostLet` (shadows the
|
|
90
|
-
* rest of the block), `match` arm patterns, `forall`/`exists`, and `for-in`
|
|
91
|
-
* indices. Capture-avoiding: a nested scope that reintroduces `from` keeps its
|
|
92
|
-
* own binding untouched. `mapExpr` doesn't descend into lambda bodies, so this
|
|
93
|
-
* walks them by hand — statement binders are tracked only at that body's top
|
|
94
|
-
* level, which is enough for the sole caller (dafny-emit's
|
|
95
|
-
* `comprehensionBinder`). TODO: generalize if more callers need this. */
|
|
96
88
|
const varE = (name) => ({ kind: "var", name });
|
|
97
|
-
export function renameFreeVar(e, from, to) {
|
|
98
|
-
const f = (x) => {
|
|
99
|
-
if (x.kind === "var")
|
|
100
|
-
return x.name === from ? { ...x, name: to } : x;
|
|
101
|
-
// let-expression: `value` is in the outer scope (rename), `body` sees the
|
|
102
|
-
// rebound `from` (leave it), so handle the recursion here to stop descent.
|
|
103
|
-
if (x.kind === "let" && x.name === from)
|
|
104
|
-
return { ...x, value: mapExpr(x.value, f) };
|
|
105
|
-
if ((x.kind === "forall" || x.kind === "exists") && x.var === from)
|
|
106
|
-
return x;
|
|
107
|
-
if (x.kind === "match") {
|
|
108
|
-
return { ...x, scrutinee: mapExpr(x.scrutinee, f), arms: x.arms.map(a => patternBinds(a.pattern, from) ? a : { ...a, body: mapExpr(a.body, f) }) };
|
|
109
|
-
}
|
|
110
|
-
if (x.kind === "lambda") {
|
|
111
|
-
if (x.params.some(p => p.name === from))
|
|
112
|
-
return x; // param shadows `from`
|
|
113
|
-
const body = [];
|
|
114
|
-
let shadowed = false;
|
|
115
|
-
for (const s of x.body) {
|
|
116
|
-
if (shadowed) {
|
|
117
|
-
body.push(s);
|
|
118
|
-
continue;
|
|
119
|
-
}
|
|
120
|
-
body.push(s.kind === "forin" && s.idx === from
|
|
121
|
-
? { ...s, bound: mapExpr(s.bound, f) } // idx shadows in the loop body
|
|
122
|
-
: mapStmt(s, f));
|
|
123
|
-
if ((s.kind === "let" || s.kind === "let-bind" || s.kind === "ghostLet") && s.name === from)
|
|
124
|
-
shadowed = true;
|
|
125
|
-
}
|
|
126
|
-
return { ...x, body };
|
|
127
|
-
}
|
|
128
|
-
return null;
|
|
129
|
-
};
|
|
130
|
-
return mapExpr(e, f);
|
|
131
|
-
}
|
|
132
89
|
/** Map over all sub-expressions in a TExpr (typed IR). */
|
|
133
90
|
function mapTExpr(e, f) {
|
|
134
91
|
const hit = f(e);
|
|
@@ -176,9 +133,12 @@ function mapTStmt(s, f) {
|
|
|
176
133
|
case "throw": return s;
|
|
177
134
|
case "expr": return { ...s, expr: r(s.expr) };
|
|
178
135
|
case "if": return { ...s, cond: r(s.cond), then: s.then.map(t => mapTStmt(t, f)), else: s.else.map(t => mapTStmt(t, f)) };
|
|
179
|
-
case "while": return { ...s, cond: r(s.cond), invariants: s.invariants.map(r),
|
|
136
|
+
case "while": return { ...s, cond: r(s.cond), invariants: s.invariants.map(r),
|
|
137
|
+
decreases: s.decreases ? r(s.decreases) : null,
|
|
138
|
+
doneWith: s.doneWith ? r(s.doneWith) : null, body: s.body.map(t => mapTStmt(t, f)) };
|
|
180
139
|
case "switch": return { ...s, expr: r(s.expr), cases: s.cases.map(c => ({ ...c, body: c.body.map(t => mapTStmt(t, f)) })), defaultBody: s.defaultBody.map(t => mapTStmt(t, f)) };
|
|
181
|
-
case "forof": return { ...s, iterable: r(s.iterable), invariants: s.invariants.map(r),
|
|
140
|
+
case "forof": return { ...s, iterable: r(s.iterable), invariants: s.invariants.map(r),
|
|
141
|
+
doneWith: s.doneWith ? r(s.doneWith) : null, body: s.body.map(t => mapTStmt(t, f)) };
|
|
182
142
|
case "ghostLet": return { ...s, init: r(s.init) };
|
|
183
143
|
case "ghostAssign": return { ...s, value: r(s.value) };
|
|
184
144
|
case "assert": return { ...s, expr: r(s.expr) };
|
|
@@ -1736,12 +1696,13 @@ function transformStmts(stmts, typeDecls) {
|
|
|
1736
1696
|
const iterExpr = transformExpr(s.iterable);
|
|
1737
1697
|
// All for-of shapes lower to the same range loop `for idx in 0..seq.size`;
|
|
1738
1698
|
// they differ only in (a) which indexable `seq` is iterated and (b) the
|
|
1739
|
-
// per-iteration `let`s that bind the loop names.
|
|
1740
|
-
//
|
|
1699
|
+
// per-iteration `let`s that bind the loop names. The counter name was
|
|
1700
|
+
// minted by resolve, where specs naming it are resolved; the suffix
|
|
1701
|
+
// numbers this loop's helper names. Each shape fills in `seq` + `perIter`.
|
|
1741
1702
|
const count = _forofCounters.get(headName) ?? 0;
|
|
1742
1703
|
_forofCounters.set(headName, count + 1);
|
|
1743
1704
|
const suffix = count === 0 ? "" : `${count + 1}`;
|
|
1744
|
-
const idxName =
|
|
1705
|
+
const idxName = s.idx;
|
|
1745
1706
|
const idxVar = { kind: "var", name: idxName };
|
|
1746
1707
|
let seq;
|
|
1747
1708
|
let perIter;
|
|
@@ -2302,14 +2263,23 @@ function matchesAccessPath(e, path) {
|
|
|
2302
2263
|
return false;
|
|
2303
2264
|
return collected.every((f, i) => f === path.fields[i]);
|
|
2304
2265
|
}
|
|
2305
|
-
/** Replace every
|
|
2266
|
+
/** Replace every read of `path` with `var(binder, binderTy)`. Extraction
|
|
2267
|
+
* leaves no binding that shadows another (see LexicalNames), so the name
|
|
2268
|
+
* identifies the variable, also inside a lambda that captures it. */
|
|
2306
2269
|
function replacePathInTExpr(expr, path, binder, binderTy) {
|
|
2307
|
-
return mapTExpr(expr, e =>
|
|
2308
|
-
|
|
2270
|
+
return mapTExpr(expr, e => {
|
|
2271
|
+
if (matchesAccessPath(e, path))
|
|
2272
|
+
return { kind: "var", name: binder, ty: binderTy };
|
|
2273
|
+
if (e.kind === "lambda")
|
|
2274
|
+
return { ...e,
|
|
2275
|
+
params: e.params.map(p => p.defaultValue
|
|
2276
|
+
? { ...p, defaultValue: replacePathInTExpr(p.defaultValue, path, binder, binderTy) } : p),
|
|
2277
|
+
body: replacePathInTStmts(e.body, path, binder, binderTy) };
|
|
2278
|
+
return null;
|
|
2279
|
+
});
|
|
2309
2280
|
}
|
|
2310
2281
|
function replacePathInTStmts(stmts, path, binder, binderTy) {
|
|
2311
|
-
return stmts.map(s => mapTStmt(s, e =>
|
|
2312
|
-
? { kind: "var", name: binder, ty: binderTy } : null));
|
|
2282
|
+
return stmts.map(s => mapTStmt(s, e => replacePathInTExpr(e, path, binder, binderTy)));
|
|
2313
2283
|
}
|
|
2314
2284
|
// ── Pure function generation ─────────────────────────────────
|
|
2315
2285
|
function transformPureBody(stmts, typeDecls) {
|