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/package.json +1 -1
- package/tools/dist/alias-check-pass.js +1038 -0
- package/tools/dist/alias-check.js +67 -0
- package/tools/dist/autohavoc.js +4 -0
- package/tools/dist/checked-reads.js +384 -0
- package/tools/dist/dafny-commands.js +19 -7
- package/tools/dist/dafny-emit.js +28 -23
- package/tools/dist/dafny-proof-additions.js +285 -14
- package/tools/dist/extract.js +118 -260
- package/tools/dist/ir.js +2 -1
- package/tools/dist/lean-emit.js +34 -2
- package/tools/dist/lexical-names.js +212 -0
- package/tools/dist/lsc.js +7 -6
- package/tools/dist/names.js +4 -0
- package/tools/dist/narrow-checks.js +415 -0
- package/tools/dist/narrow.js +93 -7
- package/tools/dist/peephole.js +1 -0
- package/tools/dist/place-lowering.js +219 -0
- package/tools/dist/places.js +123 -0
- package/tools/dist/resolve.js +350 -23
- package/tools/dist/specparser.js +41 -12
- package/tools/dist/transform.js +447 -113
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure live-alias conflict kernel for Milestone 3b
|
|
3
|
+
* (`midspiral/LemmaScript#387`, `robertpenner/LemmaScript#50`).
|
|
4
|
+
*
|
|
5
|
+
* Kept strictly inside the LemmaScript subset so its core conflict-detection
|
|
6
|
+
* and alias-binding contracts are self-verified via
|
|
7
|
+
* `npx lsc check --backend=dafny tools/src/alias-check.ts`.
|
|
8
|
+
*/
|
|
9
|
+
//@ pure
|
|
10
|
+
export function lookupAliasGroup(aliases, name) {
|
|
11
|
+
const g = aliases.get(name);
|
|
12
|
+
return g !== undefined ? g : -1;
|
|
13
|
+
}
|
|
14
|
+
/** Bind `name` to a fresh alias group `groupId` (breaking any prior alias). */
|
|
15
|
+
//@ ensures \result.has(name)
|
|
16
|
+
//@ ensures \result.get(name) == groupId
|
|
17
|
+
export function bindFreshGroup(aliases, name, groupId) {
|
|
18
|
+
const next = new Map(aliases);
|
|
19
|
+
next.set(name, groupId);
|
|
20
|
+
return next;
|
|
21
|
+
}
|
|
22
|
+
/** Bind `dst` to share `src`'s alias group if `src` is tracked, else `fallbackId`. */
|
|
23
|
+
//@ ensures \result.has(dst)
|
|
24
|
+
export function bindCopyGroup(aliases, dst, src, fallbackId) {
|
|
25
|
+
const next = new Map(aliases);
|
|
26
|
+
const srcGroup = aliases.get(src);
|
|
27
|
+
if (srcGroup !== undefined) {
|
|
28
|
+
next.set(dst, srcGroup);
|
|
29
|
+
}
|
|
30
|
+
else {
|
|
31
|
+
next.set(dst, fallbackId);
|
|
32
|
+
}
|
|
33
|
+
return next;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Find the first candidate variable `other` that:
|
|
37
|
+
* 1. is distinct from `mutatedVar`,
|
|
38
|
+
* 2. is live after the mutation (`liveAfter.has(other)`), and
|
|
39
|
+
* 3. shares the same non-negative alias group ID as `mutatedVar`.
|
|
40
|
+
*
|
|
41
|
+
* Returns `""` when no live alias conflict exists (covering both read-only
|
|
42
|
+
* aliases when no mutation occurs and dead-source moves where the aliased
|
|
43
|
+
* variable is not in `liveAfter`).
|
|
44
|
+
*/
|
|
45
|
+
//@ ensures \result != "" ==> \result != mutatedVar && liveAfter.has(\result)
|
|
46
|
+
export function findLiveAliasConflict(mutatedVar, aliases, liveAfter, candidates) {
|
|
47
|
+
const mutGroup = aliases.get(mutatedVar);
|
|
48
|
+
if (mutGroup === undefined)
|
|
49
|
+
return "";
|
|
50
|
+
let i = 0;
|
|
51
|
+
while (i < candidates.length) {
|
|
52
|
+
//@ invariant 0 <= i && i <= candidates.length
|
|
53
|
+
const cand = candidates[i];
|
|
54
|
+
if (cand !== mutatedVar && liveAfter.has(cand)) {
|
|
55
|
+
const candGroup = aliases.get(cand);
|
|
56
|
+
if (candGroup !== undefined && candGroup === mutGroup) {
|
|
57
|
+
return cand;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
i = i + 1;
|
|
61
|
+
}
|
|
62
|
+
return "";
|
|
63
|
+
}
|
|
64
|
+
/** Boolean wrapper over `findLiveAliasConflict`. */
|
|
65
|
+
export function hasLiveAliasConflict(mutatedVar, aliases, liveAfter, candidates) {
|
|
66
|
+
return findLiveAliasConflict(mutatedVar, aliases, liveAfter, candidates) !== "";
|
|
67
|
+
}
|
package/tools/dist/autohavoc.js
CHANGED
|
@@ -82,6 +82,9 @@ function forEachChildExpr(e, f) {
|
|
|
82
82
|
case "unop":
|
|
83
83
|
f(e.expr);
|
|
84
84
|
return;
|
|
85
|
+
case "checkedUnwrap":
|
|
86
|
+
f(e.expr);
|
|
87
|
+
return;
|
|
85
88
|
case "call":
|
|
86
89
|
f(e.fn);
|
|
87
90
|
e.args.forEach(f);
|
|
@@ -354,6 +357,7 @@ function rewriteExpr(e, hoisted) {
|
|
|
354
357
|
case "havoc": return e;
|
|
355
358
|
case "binop": return { ...e, left: rewriteExpr(e.left, hoisted), right: rewriteExpr(e.right, hoisted) };
|
|
356
359
|
case "unop": return { ...e, expr: rewriteExpr(e.expr, hoisted) };
|
|
360
|
+
case "checkedUnwrap": return { ...e, expr: rewriteExpr(e.expr, hoisted) };
|
|
357
361
|
case "call": return { ...e, fn: rewriteExpr(e.fn, hoisted), args: e.args.map(a => rewriteExpr(a, hoisted)) };
|
|
358
362
|
case "index": return { ...e, obj: rewriteExpr(e.obj, hoisted), idx: rewriteExpr(e.idx, hoisted) };
|
|
359
363
|
case "field": return { ...e, obj: rewriteExpr(e.obj, hoisted) };
|
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Post-narrow checked-read insertion (`midspiral/LemmaScript#387`, Milestone 4 /
|
|
3
|
+
* `robertpenner/LemmaScript#52`).
|
|
4
|
+
*
|
|
5
|
+
* After `narrow.ts`'s `someMatch` / `tagMatch` drivers run, any access path
|
|
6
|
+
* that `resolve.ts` proved non-optional (via `&&`/`||` chains, `if ... else`,
|
|
7
|
+
* `while` presence guards, or definite assignment narrowing) whose underlying
|
|
8
|
+
* storage binding is still `Option<T>` is wrapped in an explicit
|
|
9
|
+
* `{ kind: "checkedUnwrap", expr, ty }`.
|
|
10
|
+
*
|
|
11
|
+
* Lowering `checkedUnwrap` emits a backend-checked projection (`.value` in
|
|
12
|
+
* Dafny, `.get (by grind)` in Lean) directly on the live storage variable,
|
|
13
|
+
* without introducing match-binder copies, sequential `if i_branch0` splits,
|
|
14
|
+
* or unnecessary `i_compareN` temporaries.
|
|
15
|
+
*/
|
|
16
|
+
import { parseTsType } from "./types.js";
|
|
17
|
+
const ARITH = new Set(["+", "-", "*", "/", "%", "**"]);
|
|
18
|
+
function pathKey(e) {
|
|
19
|
+
if (e.kind === "var")
|
|
20
|
+
return e.name;
|
|
21
|
+
if (e.kind === "checkedUnwrap")
|
|
22
|
+
return pathKey(e.expr);
|
|
23
|
+
if (e.kind === "field") {
|
|
24
|
+
const inner = pathKey(e.obj);
|
|
25
|
+
return inner === null ? null : `${inner}.${e.field}`;
|
|
26
|
+
}
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
function isOptional(ty) {
|
|
30
|
+
return ty !== null && ty.kind === "optional";
|
|
31
|
+
}
|
|
32
|
+
function fieldInfoTy(f) {
|
|
33
|
+
if (!f)
|
|
34
|
+
return null;
|
|
35
|
+
const ty = f.type ?? parseTsType(f.tsType);
|
|
36
|
+
return f.optionalKey && ty.kind !== "optional" ? { kind: "optional", inner: ty } : ty;
|
|
37
|
+
}
|
|
38
|
+
function declField(decl, field, ofVariant) {
|
|
39
|
+
if (decl.kind === "record")
|
|
40
|
+
return decl.fields?.find(f => f.name === field) ?? null;
|
|
41
|
+
if (decl.kind !== "discriminated-union" || !decl.variants)
|
|
42
|
+
return null;
|
|
43
|
+
const variants = ofVariant ? decl.variants.filter(v => v.name === ofVariant) : decl.variants;
|
|
44
|
+
const found = variants.map(v => v.fields.find(f => f.name === field)).filter((f) => !!f);
|
|
45
|
+
if (found.length === 0)
|
|
46
|
+
return null;
|
|
47
|
+
const optional = found.map(f => isOptional(fieldInfoTy(f)));
|
|
48
|
+
return optional.every(o => o === optional[0]) ? found[0] : null;
|
|
49
|
+
}
|
|
50
|
+
function fieldStorageTy(ty, field, ofVariant, mod, depth = 0) {
|
|
51
|
+
if (depth > 8 || ty.kind !== "user")
|
|
52
|
+
return null;
|
|
53
|
+
const cls = mod.classes.find(c => c.name === ty.name);
|
|
54
|
+
if (cls)
|
|
55
|
+
return cls.fields.find(f => f.name === field)?.ty ?? null;
|
|
56
|
+
const decl = mod.typeDecls.find(d => d.name === ty.name);
|
|
57
|
+
if (!decl || (decl.typeParams && decl.typeParams.length > 0))
|
|
58
|
+
return null;
|
|
59
|
+
if (decl.kind === "alias" && decl.aliasOfTy) {
|
|
60
|
+
return fieldStorageTy(decl.aliasOfTy, field, ofVariant, mod, depth + 1);
|
|
61
|
+
}
|
|
62
|
+
return fieldInfoTy(declField(decl, field, ofVariant));
|
|
63
|
+
}
|
|
64
|
+
function storageTyOf(e, scope, mod) {
|
|
65
|
+
if (e.kind === "checkedUnwrap")
|
|
66
|
+
return e.ty;
|
|
67
|
+
const key = pathKey(e);
|
|
68
|
+
if (key !== null) {
|
|
69
|
+
const bound = scope.types.get(key);
|
|
70
|
+
if (bound)
|
|
71
|
+
return bound;
|
|
72
|
+
}
|
|
73
|
+
if (e.kind !== "field")
|
|
74
|
+
return null;
|
|
75
|
+
const objTy = storageTyOf(e.obj, scope, mod);
|
|
76
|
+
if (!objTy || objTy.kind === "optional")
|
|
77
|
+
return null;
|
|
78
|
+
return fieldStorageTy(objTy, e.field, e.ofVariant, mod);
|
|
79
|
+
}
|
|
80
|
+
function extendScope(scope, names) {
|
|
81
|
+
if (names.length === 0)
|
|
82
|
+
return scope;
|
|
83
|
+
const types = new Map(scope.types);
|
|
84
|
+
for (const n of names) {
|
|
85
|
+
types.set(n.name, n.ty);
|
|
86
|
+
for (const k of [...types.keys()])
|
|
87
|
+
if (k.startsWith(`${n.name}.`))
|
|
88
|
+
types.delete(k);
|
|
89
|
+
}
|
|
90
|
+
return { types };
|
|
91
|
+
}
|
|
92
|
+
function enterSomeMatch(scope, scrutinee, binder, binderTy) {
|
|
93
|
+
const types = new Map(scope.types);
|
|
94
|
+
types.set(binder, binderTy);
|
|
95
|
+
const key = pathKey(scrutinee);
|
|
96
|
+
if (key !== null)
|
|
97
|
+
types.set(key, binderTy);
|
|
98
|
+
return { types };
|
|
99
|
+
}
|
|
100
|
+
function isDefinitelyUnwrappedStamp(ty) {
|
|
101
|
+
return !isOptional(ty) && ty.kind !== "unknown" && ty.kind !== "void";
|
|
102
|
+
}
|
|
103
|
+
/** Rewrite an expression that is the direct operand of `=== undefined` /
|
|
104
|
+
* `!== undefined`: never wrap the operand itself in `checkedUnwrap` (restore
|
|
105
|
+
* its declared optional storage type so `transform.ts` emits an `Option`
|
|
106
|
+
* presence check), while still rewriting any optional receiver prefix. */
|
|
107
|
+
function rewritePresenceOperand(e, scope, mod) {
|
|
108
|
+
const storage = storageTyOf(e, scope, mod);
|
|
109
|
+
if (e.kind === "var" && isOptional(storage)) {
|
|
110
|
+
return { ...e, ty: storage };
|
|
111
|
+
}
|
|
112
|
+
if (e.kind === "field") {
|
|
113
|
+
const obj = rewriteExpr(e.obj, scope, mod);
|
|
114
|
+
const updated = obj === e.obj ? e : { ...e, obj };
|
|
115
|
+
const fStorage = storageTyOf(updated, scope, mod);
|
|
116
|
+
if (isOptional(fStorage))
|
|
117
|
+
return { ...updated, ty: fStorage };
|
|
118
|
+
return updated;
|
|
119
|
+
}
|
|
120
|
+
return rewriteExpr(e, scope, mod);
|
|
121
|
+
}
|
|
122
|
+
function isUndefinedVar(e) {
|
|
123
|
+
return e.kind === "var" && e.name === "undefined";
|
|
124
|
+
}
|
|
125
|
+
function rewriteExpr(e, scope, mod) {
|
|
126
|
+
switch (e.kind) {
|
|
127
|
+
case "var": {
|
|
128
|
+
const storage = storageTyOf(e, scope, mod);
|
|
129
|
+
if (isOptional(storage) && isDefinitelyUnwrappedStamp(e.ty)) {
|
|
130
|
+
return { kind: "checkedUnwrap", expr: { ...e, ty: storage }, ty: e.ty };
|
|
131
|
+
}
|
|
132
|
+
return e;
|
|
133
|
+
}
|
|
134
|
+
case "num":
|
|
135
|
+
case "bigint":
|
|
136
|
+
case "str":
|
|
137
|
+
case "bool":
|
|
138
|
+
case "havoc":
|
|
139
|
+
return e;
|
|
140
|
+
case "checkedUnwrap":
|
|
141
|
+
return { ...e, expr: rewriteExpr(e.expr, scope, mod) };
|
|
142
|
+
case "field": {
|
|
143
|
+
// Rewrite receiver first (so an optional receiver `box` becomes `checkedUnwrap(box)`).
|
|
144
|
+
const obj = rewriteExpr(e.obj, scope, mod);
|
|
145
|
+
const updated = obj === e.obj ? e : { ...e, obj };
|
|
146
|
+
// Check if this field itself is optional by declaration (or bound in scope) while stamped non-optional.
|
|
147
|
+
const storage = storageTyOf(updated, scope, mod);
|
|
148
|
+
if (isOptional(storage) && isDefinitelyUnwrappedStamp(updated.ty)) {
|
|
149
|
+
return { kind: "checkedUnwrap", expr: { ...updated, ty: storage }, ty: updated.ty };
|
|
150
|
+
}
|
|
151
|
+
return updated;
|
|
152
|
+
}
|
|
153
|
+
case "index":
|
|
154
|
+
return { ...e, obj: rewriteExpr(e.obj, scope, mod), idx: rewriteExpr(e.idx, scope, mod) };
|
|
155
|
+
case "binop": {
|
|
156
|
+
let left;
|
|
157
|
+
let right;
|
|
158
|
+
if ((e.op === "===" || e.op === "!==") && (isUndefinedVar(e.left) || isUndefinedVar(e.right))) {
|
|
159
|
+
left = isUndefinedVar(e.right) ? rewritePresenceOperand(e.left, scope, mod) : rewriteExpr(e.left, scope, mod);
|
|
160
|
+
right = isUndefinedVar(e.left) ? rewritePresenceOperand(e.right, scope, mod) : rewriteExpr(e.right, scope, mod);
|
|
161
|
+
}
|
|
162
|
+
else {
|
|
163
|
+
left = rewriteExpr(e.left, scope, mod);
|
|
164
|
+
right = rewriteExpr(e.right, scope, mod);
|
|
165
|
+
}
|
|
166
|
+
let ty = e.ty;
|
|
167
|
+
// Clear stale optional arithmetic stamp once operands are unwrapped.
|
|
168
|
+
if (ARITH.has(e.op) && isOptional(ty) && !isOptional(left.ty) && !isOptional(right.ty)) {
|
|
169
|
+
ty = left.ty;
|
|
170
|
+
}
|
|
171
|
+
return { ...e, left, right, ty };
|
|
172
|
+
}
|
|
173
|
+
case "unop": {
|
|
174
|
+
const expr = rewriteExpr(e.expr, scope, mod);
|
|
175
|
+
let ty = e.ty;
|
|
176
|
+
if (e.op === "-" && isOptional(ty) && !isOptional(expr.ty))
|
|
177
|
+
ty = expr.ty;
|
|
178
|
+
return { ...e, expr, ty };
|
|
179
|
+
}
|
|
180
|
+
case "call":
|
|
181
|
+
return {
|
|
182
|
+
...e,
|
|
183
|
+
fn: rewriteExpr(e.fn, scope, mod),
|
|
184
|
+
args: e.args.map(a => rewriteExpr(a, scope, mod)),
|
|
185
|
+
};
|
|
186
|
+
case "record":
|
|
187
|
+
return {
|
|
188
|
+
...e,
|
|
189
|
+
spread: e.spread ? rewriteExpr(e.spread, scope, mod) : null,
|
|
190
|
+
fields: e.fields.map(f => ({ ...f, value: rewriteExpr(f.value, scope, mod) })),
|
|
191
|
+
};
|
|
192
|
+
case "arrayLiteral":
|
|
193
|
+
return { ...e, elems: e.elems.map(el => rewriteExpr(el, scope, mod)) };
|
|
194
|
+
case "lambda": {
|
|
195
|
+
const inner = extendScope(scope, e.params.map(p => ({ name: p.name, ty: p.ty })));
|
|
196
|
+
return { ...e, body: rewriteStmts(e.body, inner, mod) };
|
|
197
|
+
}
|
|
198
|
+
case "conditional":
|
|
199
|
+
return {
|
|
200
|
+
...e,
|
|
201
|
+
cond: rewriteExpr(e.cond, scope, mod),
|
|
202
|
+
then: rewriteExpr(e.then, scope, mod),
|
|
203
|
+
else: rewriteExpr(e.else, scope, mod),
|
|
204
|
+
};
|
|
205
|
+
case "optChain":
|
|
206
|
+
return {
|
|
207
|
+
...e,
|
|
208
|
+
obj: rewriteExpr(e.obj, scope, mod),
|
|
209
|
+
chain: e.chain.map(st => st.kind === "call"
|
|
210
|
+
? { ...st, args: st.args.map(a => rewriteExpr(a, scope, mod)) }
|
|
211
|
+
: st.kind === "index"
|
|
212
|
+
? { ...st, idx: rewriteExpr(st.idx, scope, mod) }
|
|
213
|
+
: st),
|
|
214
|
+
};
|
|
215
|
+
case "nullish":
|
|
216
|
+
return { ...e, left: rewriteExpr(e.left, scope, mod), right: rewriteExpr(e.right, scope, mod) };
|
|
217
|
+
case "someMatch": {
|
|
218
|
+
// Do NOT unwrap the scrutinee itself (it is supposed to remain Option<T>),
|
|
219
|
+
// but DO rewrite any optional prefix inside a nested scrutinee (e.g. `box.inner`).
|
|
220
|
+
const scrutinee = e.scrutinee.kind === "field"
|
|
221
|
+
? { ...e.scrutinee, obj: rewriteExpr(e.scrutinee.obj, scope, mod) }
|
|
222
|
+
: e.scrutinee;
|
|
223
|
+
const someScope = enterSomeMatch(scope, e.scrutinee, e.binder, e.binderTy);
|
|
224
|
+
return {
|
|
225
|
+
...e,
|
|
226
|
+
scrutinee,
|
|
227
|
+
someBody: rewriteExpr(e.someBody, someScope, mod),
|
|
228
|
+
noneBody: rewriteExpr(e.noneBody, scope, mod),
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
case "tagMatch":
|
|
232
|
+
return {
|
|
233
|
+
...e,
|
|
234
|
+
scrutinee: rewriteExpr(e.scrutinee, scope, mod),
|
|
235
|
+
cases: e.cases.map(c => ({ ...c, body: rewriteExpr(c.body, scope, mod) })),
|
|
236
|
+
fallthrough: e.fallthrough ? rewriteExpr(e.fallthrough, scope, mod) : null,
|
|
237
|
+
};
|
|
238
|
+
case "forall":
|
|
239
|
+
case "exists": {
|
|
240
|
+
const inner = extendScope(scope, [{ name: e.var, ty: e.varTy }]);
|
|
241
|
+
return { ...e, body: rewriteExpr(e.body, inner, mod) };
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
function rewriteStmts(stmts, scope, mod) {
|
|
246
|
+
let cur = scope;
|
|
247
|
+
const out = [];
|
|
248
|
+
for (const s of stmts) {
|
|
249
|
+
switch (s.kind) {
|
|
250
|
+
case "let": {
|
|
251
|
+
const init = rewriteExpr(s.init, cur, mod);
|
|
252
|
+
out.push({ ...s, init });
|
|
253
|
+
cur = extendScope(cur, [{ name: s.name, ty: s.ty }]);
|
|
254
|
+
break;
|
|
255
|
+
}
|
|
256
|
+
case "ghostLet": {
|
|
257
|
+
const init = rewriteExpr(s.init, cur, mod);
|
|
258
|
+
out.push({ ...s, init });
|
|
259
|
+
cur = extendScope(cur, [{ name: s.name, ty: s.ty }]);
|
|
260
|
+
break;
|
|
261
|
+
}
|
|
262
|
+
case "assign":
|
|
263
|
+
out.push({ ...s, value: rewriteExpr(s.value, cur, mod) });
|
|
264
|
+
break;
|
|
265
|
+
case "ghostAssign":
|
|
266
|
+
out.push({ ...s, value: rewriteExpr(s.value, cur, mod) });
|
|
267
|
+
break;
|
|
268
|
+
case "return":
|
|
269
|
+
out.push({ ...s, value: rewriteExpr(s.value, cur, mod) });
|
|
270
|
+
break;
|
|
271
|
+
case "expr":
|
|
272
|
+
out.push({ ...s, expr: rewriteExpr(s.expr, cur, mod) });
|
|
273
|
+
break;
|
|
274
|
+
case "assert":
|
|
275
|
+
out.push({ ...s, expr: rewriteExpr(s.expr, cur, mod) });
|
|
276
|
+
break;
|
|
277
|
+
case "break":
|
|
278
|
+
case "continue":
|
|
279
|
+
case "throw":
|
|
280
|
+
out.push(s);
|
|
281
|
+
break;
|
|
282
|
+
case "if":
|
|
283
|
+
out.push({
|
|
284
|
+
...s,
|
|
285
|
+
cond: rewriteExpr(s.cond, cur, mod),
|
|
286
|
+
then: rewriteStmts(s.then, cur, mod),
|
|
287
|
+
else: rewriteStmts(s.else, cur, mod),
|
|
288
|
+
});
|
|
289
|
+
break;
|
|
290
|
+
case "while":
|
|
291
|
+
out.push({
|
|
292
|
+
...s,
|
|
293
|
+
cond: rewriteExpr(s.cond, cur, mod),
|
|
294
|
+
invariants: s.invariants.map(inv => rewriteExpr(inv, cur, mod)),
|
|
295
|
+
decreases: s.decreases ? rewriteExpr(s.decreases, cur, mod) : null,
|
|
296
|
+
doneWith: s.doneWith ? rewriteExpr(s.doneWith, cur, mod) : null,
|
|
297
|
+
body: rewriteStmts(s.body, cur, mod),
|
|
298
|
+
});
|
|
299
|
+
break;
|
|
300
|
+
case "forof": {
|
|
301
|
+
const iterable = rewriteExpr(s.iterable, cur, mod);
|
|
302
|
+
const loopScope = extendScope(cur, [
|
|
303
|
+
...s.names.map((n, i) => ({ name: n, ty: s.nameTypes[i] ?? { kind: "unknown" } })),
|
|
304
|
+
{ name: s.idx, ty: { kind: "nat" } },
|
|
305
|
+
]);
|
|
306
|
+
out.push({
|
|
307
|
+
...s,
|
|
308
|
+
iterable,
|
|
309
|
+
invariants: s.invariants.map(inv => rewriteExpr(inv, loopScope, mod)),
|
|
310
|
+
doneWith: s.doneWith ? rewriteExpr(s.doneWith, loopScope, mod) : null,
|
|
311
|
+
body: rewriteStmts(s.body, loopScope, mod),
|
|
312
|
+
});
|
|
313
|
+
break;
|
|
314
|
+
}
|
|
315
|
+
case "switch":
|
|
316
|
+
out.push({
|
|
317
|
+
...s,
|
|
318
|
+
expr: rewriteExpr(s.expr, cur, mod),
|
|
319
|
+
cases: s.cases.map(c => ({ ...c, body: rewriteStmts(c.body, cur, mod) })),
|
|
320
|
+
defaultBody: rewriteStmts(s.defaultBody, cur, mod),
|
|
321
|
+
});
|
|
322
|
+
break;
|
|
323
|
+
case "someMatch": {
|
|
324
|
+
const scrutinee = s.scrutinee.kind === "field"
|
|
325
|
+
? { ...s.scrutinee, obj: rewriteExpr(s.scrutinee.obj, cur, mod) }
|
|
326
|
+
: s.scrutinee;
|
|
327
|
+
const someScope = enterSomeMatch(cur, s.scrutinee, s.binder, s.binderTy);
|
|
328
|
+
out.push({
|
|
329
|
+
...s,
|
|
330
|
+
scrutinee,
|
|
331
|
+
someBody: rewriteStmts(s.someBody, someScope, mod),
|
|
332
|
+
noneBody: rewriteStmts(s.noneBody, cur, mod),
|
|
333
|
+
});
|
|
334
|
+
break;
|
|
335
|
+
}
|
|
336
|
+
case "tagMatch":
|
|
337
|
+
out.push({
|
|
338
|
+
...s,
|
|
339
|
+
scrutinee: rewriteExpr(s.scrutinee, cur, mod),
|
|
340
|
+
cases: s.cases.map(c => ({ ...c, body: rewriteStmts(c.body, cur, mod) })),
|
|
341
|
+
fallthrough: rewriteStmts(s.fallthrough, cur, mod),
|
|
342
|
+
});
|
|
343
|
+
break;
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
return out;
|
|
347
|
+
}
|
|
348
|
+
function rewriteFunction(fn, className, globals, mod) {
|
|
349
|
+
const types = new Map(globals);
|
|
350
|
+
for (const p of fn.params)
|
|
351
|
+
types.set(p.name, p.ty);
|
|
352
|
+
if (className !== null)
|
|
353
|
+
types.set("this", { kind: "user", name: className });
|
|
354
|
+
const scope = { types };
|
|
355
|
+
const postTypes = new Map(types);
|
|
356
|
+
postTypes.set("\\result", fn.returnTy);
|
|
357
|
+
const postScope = { types: postTypes };
|
|
358
|
+
return {
|
|
359
|
+
...fn,
|
|
360
|
+
requires: fn.requires.map(r => rewriteExpr(r, scope, mod)),
|
|
361
|
+
decreases: fn.decreases ? rewriteExpr(fn.decreases, scope, mod) : null,
|
|
362
|
+
ensures: fn.ensures.map(e => rewriteExpr(e, postScope, mod)),
|
|
363
|
+
body: rewriteStmts(fn.body, scope, mod),
|
|
364
|
+
};
|
|
365
|
+
}
|
|
366
|
+
/** Reconcile any narrowed-but-not-someMatch-bound optional reads by inserting
|
|
367
|
+
* explicit `checkedUnwrap` nodes. */
|
|
368
|
+
export function insertCheckedUnwraps(mod) {
|
|
369
|
+
const globals = new Map();
|
|
370
|
+
for (const c of mod.constants)
|
|
371
|
+
globals.set(c.name, c.ty);
|
|
372
|
+
return {
|
|
373
|
+
...mod,
|
|
374
|
+
constants: mod.constants.map(c => ({
|
|
375
|
+
...c,
|
|
376
|
+
value: rewriteExpr(c.value, { types: new Map(globals) }, mod),
|
|
377
|
+
})),
|
|
378
|
+
functions: mod.functions.map(fn => rewriteFunction(fn, null, globals, mod)),
|
|
379
|
+
classes: mod.classes.map(cls => ({
|
|
380
|
+
...cls,
|
|
381
|
+
methods: cls.methods.map(m => rewriteFunction(m, cls.name, globals, mod)),
|
|
382
|
+
})),
|
|
383
|
+
};
|
|
384
|
+
}
|
|
@@ -10,18 +10,30 @@ function writeGen(genPath, text) {
|
|
|
10
10
|
writeFileSync(genPath, text);
|
|
11
11
|
console.log(`Generated: ${genPath}`);
|
|
12
12
|
}
|
|
13
|
-
export function dafnyGen(genPath, dfyPath, text) {
|
|
13
|
+
export function dafnyGen(genPath, dfyPath, text, basePath) {
|
|
14
|
+
// Preserve the previous generation as the three-way merge base when overwriting
|
|
15
|
+
// a changed .dfy.gen beside an existing .dfy, so a later `lsc regen` still
|
|
16
|
+
// merges from the generation the proof derives from.
|
|
17
|
+
if (basePath && existsSync(dfyPath) && existsSync(genPath) && !existsSync(basePath)) {
|
|
18
|
+
const oldGen = readFileSync(genPath, "utf-8");
|
|
19
|
+
if (oldGen !== text)
|
|
20
|
+
writeFileSync(basePath, oldGen);
|
|
21
|
+
}
|
|
14
22
|
writeGen(genPath, text);
|
|
15
23
|
if (!existsSync(dfyPath)) {
|
|
16
24
|
writeFileSync(dfyPath, text);
|
|
17
25
|
console.log(`Created: ${dfyPath}`);
|
|
18
26
|
}
|
|
19
27
|
}
|
|
20
|
-
export function dafnyCheckDiff(genPath, dfyPath, log) {
|
|
28
|
+
export function dafnyCheckDiff(genPath, dfyPath, log, basePath) {
|
|
21
29
|
const ok = additionsOnly(genPath, dfyPath);
|
|
22
|
-
if (!ok)
|
|
30
|
+
if (!ok) {
|
|
23
31
|
log?.finish({ stage: "diff", exit: 1, dfyPath });
|
|
24
|
-
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
if (basePath && existsSync(basePath))
|
|
35
|
+
unlinkSync(basePath);
|
|
36
|
+
return true;
|
|
25
37
|
}
|
|
26
38
|
function additionsOnly(genPath, dfyPath) {
|
|
27
39
|
for (const filePath of [genPath, dfyPath]) {
|
|
@@ -44,7 +56,7 @@ function additionsOnly(genPath, dfyPath) {
|
|
|
44
56
|
}
|
|
45
57
|
let diff = "";
|
|
46
58
|
try {
|
|
47
|
-
diff = execFileSync("git", ["diff", "--no-index", "--minimal", "--no-color", "--no-ext-diff", "--no-textconv", "--text", "--", genPath, dfyPath], { encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"] });
|
|
59
|
+
diff = execFileSync("git", ["diff", "--no-index", "--minimal", "--no-color", "--no-ext-diff", "--no-textconv", "--text", "--", genPath, dfyPath], { encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: Infinity });
|
|
48
60
|
}
|
|
49
61
|
catch (e) {
|
|
50
62
|
// `git diff --no-index` exits 1 for a valid, non-empty comparison. Every
|
|
@@ -79,10 +91,10 @@ function additionsOnly(genPath, dfyPath) {
|
|
|
79
91
|
console.error(" " + d);
|
|
80
92
|
return false;
|
|
81
93
|
}
|
|
82
|
-
// Added lines must not bypass the verifier or change
|
|
94
|
+
// Added lines must not bypass the verifier, weaken generated contracts, or change verifier options.
|
|
83
95
|
const violations = proofAdditionViolations(readFileSync(genPath, "utf-8"), readFileSync(dfyPath, "utf-8"), path.basename(dfyPath));
|
|
84
96
|
if (violations.length > 0) {
|
|
85
|
-
console.error(`ERROR: ${path.basename(dfyPath)} has proof additions
|
|
97
|
+
console.error(`ERROR: ${path.basename(dfyPath)} has disallowed proof additions:`);
|
|
86
98
|
for (const v of violations)
|
|
87
99
|
console.error(" " + v);
|
|
88
100
|
return false;
|
package/tools/dist/dafny-emit.js
CHANGED
|
@@ -3,7 +3,6 @@
|
|
|
3
3
|
*/
|
|
4
4
|
import { decimalNumberLiteral, exactIntegerLiteral, usesName, usesNameInDecl, usesNameInStmts } from "./ir.js";
|
|
5
5
|
import { freshNameWhere, userNames } from "./names.js";
|
|
6
|
-
import { renameFreeVar } from "./transform.js";
|
|
7
6
|
import { DEFAULT_OPTIONS, resolveOptions } from "./config.js";
|
|
8
7
|
/** Appended to a function's name for the lemma that carries its `//@ ensures`. */
|
|
9
8
|
export const ENSURES_LEMMA_SUFFIX = "_ensures";
|
|
@@ -15,21 +14,13 @@ export const SPEC_FUNCTION_SUFFIX = "_fun_spec";
|
|
|
15
14
|
function freshBinder(base, ...wrapped) {
|
|
16
15
|
return freshNameWhere(base, name => wrapped.some(w => usesName(w, name)));
|
|
17
16
|
}
|
|
18
|
-
/** Binder
|
|
19
|
-
* receiver is emitted inside the binder's scope.
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
* its free uses in the body); the zero-param default must also dodge free
|
|
24
|
-
* names in the body. */
|
|
17
|
+
/** Binder for lowering a single-return lambda to a comprehension whose
|
|
18
|
+
* receiver is emitted inside the binder's scope. A source parameter is used
|
|
19
|
+
* as is: extraction renames one that shares a name with anything its receiver
|
|
20
|
+
* reads (see LexicalNames), so `mk(n).some(n => …)` arrives as `n_2 => …`.
|
|
21
|
+
* The zero-param default is minted here and must dodge free names itself. */
|
|
25
22
|
function comprehensionBinder(lam, value, receiver) {
|
|
26
|
-
|
|
27
|
-
if (rawName === undefined)
|
|
28
|
-
return { binder: escapeName(freshBinder("x", receiver, value)), body: value };
|
|
29
|
-
if (!usesName(receiver, rawName))
|
|
30
|
-
return { binder: escapeName(rawName), body: value };
|
|
31
|
-
const fresh = freshBinder(rawName, receiver, value);
|
|
32
|
-
return { binder: escapeName(fresh), body: renameFreeVar(value, rawName, fresh) };
|
|
23
|
+
return escapeName(lam.params[0]?.name ?? freshBinder("x", receiver, value));
|
|
33
24
|
}
|
|
34
25
|
// ── Ty → Dafny type string ─────────────────────────────────
|
|
35
26
|
function tyToDafny(ty) {
|
|
@@ -285,7 +276,12 @@ function wrapQuantifier(sub) {
|
|
|
285
276
|
}
|
|
286
277
|
function emitExpr(e) {
|
|
287
278
|
switch (e.kind) {
|
|
288
|
-
case "var":
|
|
279
|
+
case "var":
|
|
280
|
+
if (e.name === "undefined") {
|
|
281
|
+
needPreamble("OptionType");
|
|
282
|
+
return "None";
|
|
283
|
+
}
|
|
284
|
+
return escapeName(e.name);
|
|
289
285
|
case "num": return decimalNumberLiteral(e.value);
|
|
290
286
|
// Already canonical decimal; Dafny's `int` is mathematical, so no `n` suffix.
|
|
291
287
|
case "bigint": return e.value;
|
|
@@ -473,9 +469,8 @@ function emitExpr(e) {
|
|
|
473
469
|
const lam = e.args[0];
|
|
474
470
|
let p, body;
|
|
475
471
|
if (lam.kind === "lambda" && lam.body.length === 1 && lam.body[0].kind === "return") {
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
body = emitExpr(cb.body);
|
|
472
|
+
p = comprehensionBinder(lam, lam.body[0].value, e.obj);
|
|
473
|
+
body = emitExpr(lam.body[0].value);
|
|
479
474
|
}
|
|
480
475
|
else {
|
|
481
476
|
p = escapeName(freshBinder("x", e.obj, e.args[0]));
|
|
@@ -626,8 +621,8 @@ function emitExpr(e) {
|
|
|
626
621
|
const ret = lam.body[0];
|
|
627
622
|
if (ret.kind !== "return")
|
|
628
623
|
throw new Error("unreachable");
|
|
629
|
-
const
|
|
630
|
-
const body = emitExpr(
|
|
624
|
+
const p = comprehensionBinder(lam, ret.value, e.obj);
|
|
625
|
+
const body = emitExpr(ret.value);
|
|
631
626
|
return `(set ${p} | ${p} in ${obj} && ${body})`;
|
|
632
627
|
}
|
|
633
628
|
}
|
|
@@ -652,9 +647,10 @@ function emitExpr(e) {
|
|
|
652
647
|
return `${op}(${emitExpr(e.expr)})`;
|
|
653
648
|
}
|
|
654
649
|
case "binop": {
|
|
655
|
-
// Discriminant check: x == .Ctor → x.Ctor?
|
|
650
|
+
// Discriminant check: x == .Ctor → x.Ctor? (0-arg constructors only;
|
|
651
|
+
// value-carrying constructors like `x == Some(v)` stay full equality).
|
|
656
652
|
const op = mapOp(e.op);
|
|
657
|
-
if ((op === "==" || op === "!=") && e.right.kind === "constructor") {
|
|
653
|
+
if ((op === "==" || op === "!=") && e.right.kind === "constructor" && e.right.args.length === 0) {
|
|
658
654
|
const ctorName = dafnyCtorName(e.right.name.replace(/^\./, ""));
|
|
659
655
|
const pred = `${emitExpr(e.left)}.${ctorName}?`;
|
|
660
656
|
return op === "!=" ? `(!${pred})` : pred;
|
|
@@ -701,6 +697,10 @@ function emitExpr(e) {
|
|
|
701
697
|
}
|
|
702
698
|
case "app": {
|
|
703
699
|
const args = e.args.map(emitExpr);
|
|
700
|
+
// Optional coercions also arrive as applications, including locals
|
|
701
|
+
// whose inferred types never pass through tyToDafny.
|
|
702
|
+
if (!e.ctorOf && (e.fn === "Some" || e.fn === "None"))
|
|
703
|
+
needPreamble("OptionType");
|
|
704
704
|
if (e.fn === "SetToSeq") {
|
|
705
705
|
needPreamble("SetToSeq");
|
|
706
706
|
return `SetToSeq(${args.join(", ")})`;
|
|
@@ -807,6 +807,11 @@ function emitExpr(e) {
|
|
|
807
807
|
case "toInt": return emitExpr(e.expr);
|
|
808
808
|
case "toReal":
|
|
809
809
|
return `(${emitExpr(e.expr)} as real)`;
|
|
810
|
+
case "checkedUnwrap": {
|
|
811
|
+
const inner = emitExpr(e.expr);
|
|
812
|
+
const bare = e.expr.kind === "var" || e.expr.kind === "field" || e.expr.kind === "checkedUnwrap";
|
|
813
|
+
return bare ? `${inner}.value` : `(${inner}).value`;
|
|
814
|
+
}
|
|
810
815
|
case "stringIndex":
|
|
811
816
|
// TS indexing returns a string; Dafny's native string subscript is a
|
|
812
817
|
// char. The singleton sequence preserves the native bounds obligation.
|