lemmascript 0.6.8 → 0.6.9
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/builtins.js +22 -8
- package/tools/dist/callback-lowering.js +67 -0
- package/tools/dist/condition-facts.js +4 -2
- package/tools/dist/dafny-emit.js +100 -12
- package/tools/dist/extract.js +44 -7
- package/tools/dist/ir.js +2 -0
- package/tools/dist/lean-emit.js +6 -5
- package/tools/dist/peephole.js +5 -46
- package/tools/dist/resolve.js +283 -111
- package/tools/dist/transform.js +45 -38
- package/tools/dist/types.js +3 -3
package/package.json
CHANGED
package/tools/dist/builtins.js
CHANGED
|
@@ -43,22 +43,22 @@ export const BUILTINS = {
|
|
|
43
43
|
"array.sort": { ret: self, pure: false,
|
|
44
44
|
hof: { shape: "comparator" } },
|
|
45
45
|
"array.filter": { ret: self, pure: false,
|
|
46
|
-
hof: { shape: "
|
|
46
|
+
hof: { shape: "element" } },
|
|
47
47
|
"array.every": { ret: BOOL, pure: false,
|
|
48
|
-
hof: { shape: "
|
|
48
|
+
hof: { shape: "element" } },
|
|
49
49
|
"array.some": { ret: BOOL, pure: false,
|
|
50
|
-
hof: { shape: "
|
|
50
|
+
hof: { shape: "element" } },
|
|
51
51
|
"array.reduce": { pure: false,
|
|
52
52
|
hof: { shape: "reduce" },
|
|
53
53
|
ret: (_objTy, args) => args.length === 2 ? args[1].ty : UNKNOWN },
|
|
54
54
|
"array.find": { ret: optElem, pure: false,
|
|
55
|
-
hof: { shape: "
|
|
55
|
+
hof: { shape: "element" } },
|
|
56
56
|
"array.findLast": { ret: optElem, pure: false,
|
|
57
|
-
hof: { shape: "
|
|
57
|
+
hof: { shape: "element" } },
|
|
58
58
|
"array.findIndex": { ret: INT, pure: false,
|
|
59
|
-
hof: { shape: "
|
|
59
|
+
hof: { shape: "element" } },
|
|
60
60
|
"array.findLastIndex": { ret: INT,
|
|
61
|
-
pure: false, hof: { shape: "
|
|
61
|
+
pure: false, hof: { shape: "element" } },
|
|
62
62
|
"array.flat": { pure: true,
|
|
63
63
|
ret: (objTy) => objTy.kind === "array" && objTy.elem.kind === "array"
|
|
64
64
|
? { kind: "array", elem: objTy.elem.elem } : UNKNOWN },
|
|
@@ -67,7 +67,7 @@ export const BUILTINS = {
|
|
|
67
67
|
ret: (objTy) => objTy.kind === "array" && objTy.elem.kind === "string"
|
|
68
68
|
? STRING() : UNKNOWN },
|
|
69
69
|
"array.map": { pure: false,
|
|
70
|
-
hof: { shape: "
|
|
70
|
+
hof: { shape: "element" },
|
|
71
71
|
// Prefer the lambda's declared return type (handles multi-statement bodies
|
|
72
72
|
// where body[0] is an `if`, not a `return`); fall back to the body's return.
|
|
73
73
|
ret: (_objTy, args) => {
|
|
@@ -123,3 +123,17 @@ export function recognizeBuiltin(objTy, method) {
|
|
|
123
123
|
export function builtinSpec(id) {
|
|
124
124
|
return BUILTINS[id];
|
|
125
125
|
}
|
|
126
|
+
/** The actual arguments passed by JavaScript, independently of which ones a
|
|
127
|
+
* callback declares or observes. Array indices are JS numbers (modeled ints). */
|
|
128
|
+
export function callbackArgumentTypes(spec, receiver, initial) {
|
|
129
|
+
if (!spec.hof || receiver.kind !== "array")
|
|
130
|
+
return undefined;
|
|
131
|
+
switch (spec.hof.shape) {
|
|
132
|
+
case "element": return [receiver.elem, { kind: "int" }, receiver];
|
|
133
|
+
case "comparator": return [receiver.elem, receiver.elem];
|
|
134
|
+
case "reduce": return initial ? [initial, receiver.elem, { kind: "int" }, receiver] : undefined;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
export function callbackBaseArity(shape) {
|
|
138
|
+
return shape === "element" ? 1 : 2;
|
|
139
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { pCtor, usesNameInStmts } from "./ir.js";
|
|
2
|
+
import { callbackBaseArity } from "./builtins.js";
|
|
3
|
+
import { freshName } from "./names.js";
|
|
4
|
+
const INT = { kind: "int" };
|
|
5
|
+
const INDICES = { kind: "array", elem: INT };
|
|
6
|
+
const variable = (name) => ({ kind: "var", name });
|
|
7
|
+
export function lowerIndexedCallback(receiver, receiverTy, method, args, shape, monadic, id) {
|
|
8
|
+
const callback = args[0];
|
|
9
|
+
if (receiverTy.kind !== "array" || callback?.kind !== "lambda" ||
|
|
10
|
+
callback.params.length <= callbackBaseArity(shape))
|
|
11
|
+
return null;
|
|
12
|
+
const sourceName = freshName(`_callbackSource${id}`);
|
|
13
|
+
const indexName = freshName(`_callbackIndex${id}`);
|
|
14
|
+
const accName = freshName(`_callbackAcc${id}`);
|
|
15
|
+
const source = variable(sourceName), index = variable(indexName);
|
|
16
|
+
const element = { kind: "index", arr: source, idx: { kind: "toNat", expr: index } };
|
|
17
|
+
const values = shape === "reduce" ? [variable(accName), element, index, source] : [element, index, source];
|
|
18
|
+
const elementPosition = shape === "reduce" ? 1 : 0;
|
|
19
|
+
if (receiverTy.elem.kind === "nat" && callback.params[elementPosition].type.kind === "int") {
|
|
20
|
+
values[elementPosition] = { kind: "toInt", expr: element };
|
|
21
|
+
}
|
|
22
|
+
const bindings = callback.params.flatMap((p, i) => usesNameInStmts(callback.body, p.name)
|
|
23
|
+
? [{ kind: "let", name: p.name, type: p.type, mutable: false, value: values[i] }]
|
|
24
|
+
: []);
|
|
25
|
+
// Keep the body expression-shaped when possible, as required by Dafny's
|
|
26
|
+
// collection operations. These bindings evaluate only already-bound values.
|
|
27
|
+
let body = callback.body;
|
|
28
|
+
if (body.length === 1 && body[0].kind === "return") {
|
|
29
|
+
let value = body[0].value;
|
|
30
|
+
for (const s of [...bindings].reverse()) {
|
|
31
|
+
if (s.kind === "let")
|
|
32
|
+
value = { kind: "let", name: s.name, type: s.type, value: s.value, body: value };
|
|
33
|
+
}
|
|
34
|
+
// Backend collection helpers take total callbacks. Extend the callback
|
|
35
|
+
// outside its actual index domain without evaluating its body there.
|
|
36
|
+
// map and some inline the body under membership/bounds instead.
|
|
37
|
+
if (method !== "map" && method !== "some") {
|
|
38
|
+
const valid = { kind: "binop", op: "∧",
|
|
39
|
+
left: { kind: "binop", op: "≤", left: { kind: "num", value: 0 }, right: index },
|
|
40
|
+
right: { kind: "binop", op: "<", left: index, right: { kind: "field", obj: source, field: "size" } } };
|
|
41
|
+
value = { kind: "if", cond: valid, then: value,
|
|
42
|
+
else: shape === "reduce" ? variable(accName) : { kind: "bool", value: false } };
|
|
43
|
+
}
|
|
44
|
+
body = [{ kind: "return", value }];
|
|
45
|
+
}
|
|
46
|
+
else
|
|
47
|
+
body = [...bindings, ...body];
|
|
48
|
+
const adapted = { kind: "lambda", body, typedParams: true, params: shape === "reduce"
|
|
49
|
+
? [{ name: accName, type: callback.params[0].type }, { name: indexName, type: INT }]
|
|
50
|
+
: [{ name: indexName, type: INT }] };
|
|
51
|
+
const positions = { kind: "arrayRange", length: { kind: "field", obj: source, field: "size" } };
|
|
52
|
+
let result = { kind: "methodCall", obj: positions, objTy: INDICES,
|
|
53
|
+
method, args: [adapted, ...args.slice(1)], monadic };
|
|
54
|
+
// Selection methods return elements; their index-domain versions return
|
|
55
|
+
// positions. Translate the result back without changing order or witnesses.
|
|
56
|
+
if (method === "filter") {
|
|
57
|
+
result = { kind: "methodCall", obj: result, objTy: INDICES, method: "map", monadic: false,
|
|
58
|
+
args: [{ kind: "lambda", typedParams: true, params: [{ name: indexName, type: INT }], body: [{ kind: "return", value: element }] }] };
|
|
59
|
+
}
|
|
60
|
+
else if (method === "find" || method === "findLast") {
|
|
61
|
+
result = { kind: "match", scrutinee: result, arms: [
|
|
62
|
+
{ pattern: pCtor("some", indexName), body: { kind: "constructor", name: "some", args: [element] } },
|
|
63
|
+
{ pattern: pCtor("none"), body: { kind: "constructor", name: "none", args: [] } },
|
|
64
|
+
] };
|
|
65
|
+
}
|
|
66
|
+
return { kind: "let", name: sourceName, type: receiverTy, value: receiver, body: result };
|
|
67
|
+
}
|
|
@@ -69,9 +69,11 @@ export function bindPresentFact(f, ctx) {
|
|
|
69
69
|
}
|
|
70
70
|
/** Detect optional checks: `e !== undefined`, `e === undefined`, `!e`, or a
|
|
71
71
|
* bare optional `e` — for a pure-access-path optional-typed `e`. `!e` and
|
|
72
|
-
* bare `e` are truthiness forms.
|
|
73
|
-
* narrow; complex scrutinees return null. */
|
|
72
|
+
* bare `e` are truthiness forms. `!!c` is the same check as `c`. Following
|
|
73
|
+
* TS, only pure access paths narrow; complex scrutinees return null. */
|
|
74
74
|
export function presentFact(cond) {
|
|
75
|
+
if (cond.kind === "unop" && cond.op === "!" && cond.expr.kind === "unop" && cond.expr.op === "!")
|
|
76
|
+
return presentFact(cond.expr.expr);
|
|
75
77
|
// `!e` where e is optional — a truthiness form: false iff e is absent OR its
|
|
76
78
|
// inner value is itself falsy (so `Some(0)`/`Some("")` count as falsy too).
|
|
77
79
|
if (cond.kind === "unop" && cond.op === "!" && cond.expr.ty.kind === "optional") {
|
package/tools/dist/dafny-emit.js
CHANGED
|
@@ -216,6 +216,21 @@ const OP_MAP = {
|
|
|
216
216
|
"∧": "&&", "∨": "||", "¬": "!", "↔": "<==>",
|
|
217
217
|
"arrayConcat": "+",
|
|
218
218
|
};
|
|
219
|
+
/** Escape controls and line separators while preserving printable Unicode. */
|
|
220
|
+
function escapeDafnyScalarString(value) {
|
|
221
|
+
return value.replace(/["\\\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, char => {
|
|
222
|
+
switch (char) {
|
|
223
|
+
case '"': return '\\"';
|
|
224
|
+
case "\\": return "\\\\";
|
|
225
|
+
case "\0": return "\\0";
|
|
226
|
+
case "\n": return "\\n";
|
|
227
|
+
case "\r": return "\\r";
|
|
228
|
+
case "\t": return "\\t";
|
|
229
|
+
// Dafny has no short escapes for controls such as backspace or form feed.
|
|
230
|
+
default: return `\\U{${char.charCodeAt(0).toString(16).toUpperCase().padStart(4, "0")}}`;
|
|
231
|
+
}
|
|
232
|
+
});
|
|
233
|
+
}
|
|
219
234
|
/** Render a JavaScript string without losing its UTF-16 representation.
|
|
220
235
|
*
|
|
221
236
|
* JavaScript iteration by index exposes UTF-16 code units, including unpaired
|
|
@@ -273,11 +288,9 @@ function emitExpr(e) {
|
|
|
273
288
|
case "bigint": return e.value;
|
|
274
289
|
case "bool": return e.value ? "true" : "false";
|
|
275
290
|
case "str":
|
|
276
|
-
// Under the default profile the literal is written exactly as before;
|
|
277
|
-
// only the UTF-16 profile needs code-unit escapes (DESIGN_STRINGS.md §3).
|
|
278
291
|
return isUtf16()
|
|
279
292
|
? `"${escapeDafnyUTF16String(e.value)}"`
|
|
280
|
-
: `"${e.value
|
|
293
|
+
: `"${escapeDafnyScalarString(e.value)}"`;
|
|
281
294
|
case "constructor": {
|
|
282
295
|
// Option constructors (Some/None) may appear in inferred positions
|
|
283
296
|
// (e.g. lambda result) without an explicit `optional<T>` in any
|
|
@@ -293,6 +306,9 @@ function emitExpr(e) {
|
|
|
293
306
|
if (e.elems.length === 0)
|
|
294
307
|
return `[]`;
|
|
295
308
|
return `[${e.elems.map(emitExpr).join(", ")}]`;
|
|
309
|
+
case "arrayRange":
|
|
310
|
+
needPreamble("CallbackIndices");
|
|
311
|
+
return `CallbackIndices(${emitExpr(e.length)})`;
|
|
296
312
|
case "tupleLiteral": return `(${e.elems.map(emitExpr).join(", ")})`;
|
|
297
313
|
case "tupleProj": return `${emitExpr(e.obj)}.${e.index}`;
|
|
298
314
|
case "emptyMap": return `map[]`;
|
|
@@ -333,17 +349,15 @@ function emitExpr(e) {
|
|
|
333
349
|
// the copy is just the seq itself (the idiom for "copy then mutate").
|
|
334
350
|
if (e.method === "slice" && args.length === 0)
|
|
335
351
|
return obj;
|
|
336
|
-
if (e.method === "slice" && args.length === 1)
|
|
337
|
-
return `${obj}[${args[0]}..]`;
|
|
338
|
-
if (e.method === "slice" && args.length === 2) {
|
|
352
|
+
if (e.method === "slice" && (args.length === 1 || args.length === 2)) {
|
|
339
353
|
// JS slice clamps both bounds; Dafny requires `0 <= lo <= hi <= |s|`.
|
|
340
354
|
// Direct slice is default (matches existing case studies that wrote
|
|
341
355
|
// bounded calls). Files needing JS clamping opt in via `//@ safe-slice`.
|
|
342
356
|
if (_useSafeSlice) {
|
|
343
357
|
needPreamble("SafeSlice");
|
|
344
|
-
return `SafeSlice(${obj}, ${args[0]}, ${args[1]})`;
|
|
358
|
+
return `SafeSlice(${obj}, ${args[0]}, ${args[1] ?? `|${obj}|`})`;
|
|
345
359
|
}
|
|
346
|
-
return `${obj}[${args[0]}..${args[1]}]`;
|
|
360
|
+
return args.length === 1 ? `${obj}[${args[0]}..]` : `${obj}[${args[0]}..${args[1]}]`;
|
|
347
361
|
}
|
|
348
362
|
if (e.method === "map") {
|
|
349
363
|
// Always a seq comprehension: Seq.Map would hide the element access
|
|
@@ -355,8 +369,9 @@ function emitExpr(e) {
|
|
|
355
369
|
// comprehension mentions it three times, and splicing would make
|
|
356
370
|
// any closure literal inside it (e.g. a Filter predicate) three
|
|
357
371
|
// distinct closures, unprovably equal through an opaque callee.
|
|
358
|
-
// Name freshness is a local IR-level check
|
|
359
|
-
// allocator
|
|
372
|
+
// Name freshness is a local IR-level check (`usesName`), not the
|
|
373
|
+
// Dafny-namespace allocator (`escapeGeneratedName`): a user identifier
|
|
374
|
+
// that *escapes* to `i_map`/`s_map` (e.g. `_map`) is still captured.
|
|
360
375
|
const lam = e.args[0];
|
|
361
376
|
const fresh = (base, taken) => {
|
|
362
377
|
let name = base;
|
|
@@ -367,6 +382,17 @@ function emitExpr(e) {
|
|
|
367
382
|
const taken = (n) => usesName(e.obj, n) || usesName(lam, n) ||
|
|
368
383
|
(lam.kind === "lambda" && (lam.params.some(pp => pp.name === n) ||
|
|
369
384
|
usesNameInStmts(lam.body, n)));
|
|
385
|
+
// Mapping over positions (an indexed callback): the comprehension
|
|
386
|
+
// index is the position itself, so no CallbackIndices sequence is
|
|
387
|
+
// needed. Keep the callback's declared type so the binding is `int`.
|
|
388
|
+
if (e.obj.kind === "arrayRange" && lam.kind === "lambda" && lam.params.length === 1 &&
|
|
389
|
+
lam.body.length === 1 && lam.body[0].kind === "return") {
|
|
390
|
+
const n = emitExpr(e.obj.length);
|
|
391
|
+
const idx = fresh("i_map", taken);
|
|
392
|
+
const p = lam.params[0];
|
|
393
|
+
const ty = lam.typedParams ? tyToDafny(p.type) : "int";
|
|
394
|
+
return `seq(${n}, ${idx} requires 0 <= ${idx} < ${n} => var ${escapeName(p.name)}: ${ty} := ${idx}; ${emitExpr(lam.body[0].value)})`;
|
|
395
|
+
}
|
|
370
396
|
const bind = e.obj.kind !== "var";
|
|
371
397
|
const s = bind ? fresh("s_map", taken) : obj;
|
|
372
398
|
const idx = fresh("i_map", n => taken(n) || n === s);
|
|
@@ -460,6 +486,14 @@ function emitExpr(e) {
|
|
|
460
486
|
}
|
|
461
487
|
return `StringIndexOf(${obj}, ${args[0]})`;
|
|
462
488
|
}
|
|
489
|
+
if (e.method === "lastIndexOf") {
|
|
490
|
+
needPreamble("StringLastIndexOf");
|
|
491
|
+
if (args.length === 2) {
|
|
492
|
+
needPreamble("StringSearchPosition");
|
|
493
|
+
return `StringLastIndexOfFrom(${obj}, ${args[0]}, StringSearchPosition(${obj}, ${args[1]}))`;
|
|
494
|
+
}
|
|
495
|
+
return `StringLastIndexOf(${obj}, ${args[0]})`;
|
|
496
|
+
}
|
|
463
497
|
if (e.method === "split") {
|
|
464
498
|
needPreamble("StringSplit");
|
|
465
499
|
return `StringSplit(${obj}, ${args[0]})`;
|
|
@@ -685,6 +719,12 @@ function emitExpr(e) {
|
|
|
685
719
|
needPreamble("MathMin");
|
|
686
720
|
if (e.fn === "MathMax")
|
|
687
721
|
needPreamble("MathMax");
|
|
722
|
+
if (e.fn === "MathAbsReal")
|
|
723
|
+
needPreamble("MathAbsReal");
|
|
724
|
+
if (e.fn === "MathMinReal")
|
|
725
|
+
needPreamble("MathMinReal");
|
|
726
|
+
if (e.fn === "MathMaxReal")
|
|
727
|
+
needPreamble("MathMaxReal");
|
|
688
728
|
if (e.fn === "MaxOfSeq") {
|
|
689
729
|
needPreamble("MathMax");
|
|
690
730
|
needPreamble("MaxOfSeq");
|
|
@@ -733,6 +773,7 @@ function emitExpr(e) {
|
|
|
733
773
|
case "toNat":
|
|
734
774
|
// Dafny doesn't need toNat — just emit the inner expression
|
|
735
775
|
return emitExpr(e.expr);
|
|
776
|
+
case "toInt": return emitExpr(e.expr);
|
|
736
777
|
case "toReal":
|
|
737
778
|
return `(${emitExpr(e.expr)} as real)`;
|
|
738
779
|
case "index": {
|
|
@@ -809,7 +850,7 @@ function emitExpr(e) {
|
|
|
809
850
|
}
|
|
810
851
|
case "forall": return emitQuantifier(e, "forall");
|
|
811
852
|
case "exists": return emitQuantifier(e, "exists");
|
|
812
|
-
case "let": return `(var ${escapeName(e.name)} := ${emitExpr(e.value)}; ${emitExpr(e.body)})`;
|
|
853
|
+
case "let": return `(var ${escapeName(e.name)}${e.type ? `: ${tyToDafny(e.type)}` : ""} := ${emitExpr(e.value)}; ${emitExpr(e.body)})`;
|
|
813
854
|
case "havoc": return "*";
|
|
814
855
|
// No Dafny producer: the only `default` source is the Lean return-in-loop
|
|
815
856
|
// rewrite, which never runs on the Dafny path (native in-loop returns).
|
|
@@ -833,7 +874,7 @@ function emitPureExpr(e, indent) {
|
|
|
833
874
|
return lines.join("\n");
|
|
834
875
|
}
|
|
835
876
|
case "let":
|
|
836
|
-
return `${pad}var ${escapeName(e.name)} := ${emitExpr(e.value)};\n${emitPureExpr(e.body, indent)}`;
|
|
877
|
+
return `${pad}var ${escapeName(e.name)}${e.type ? `: ${tyToDafny(e.type)}` : ""} := ${emitExpr(e.value)};\n${emitPureExpr(e.body, indent)}`;
|
|
837
878
|
default:
|
|
838
879
|
return `${pad}${emitExpr(e)}`;
|
|
839
880
|
}
|
|
@@ -1153,6 +1194,13 @@ const CEIL_REAL = `function CeilReal(x: real): int
|
|
|
1153
1194
|
if x == (x.Floor as real) then x.Floor
|
|
1154
1195
|
else x.Floor + 1
|
|
1155
1196
|
}`;
|
|
1197
|
+
const CALLBACK_INDICES = `function CallbackIndices(n: nat): (r: seq<int>)
|
|
1198
|
+
ensures |r| == n
|
|
1199
|
+
ensures forall i :: 0 <= i < n ==> r[i] == i
|
|
1200
|
+
ensures forall i :: i in r <==> 0 <= i < n
|
|
1201
|
+
{
|
|
1202
|
+
if n == 0 then [] else CallbackIndices(n - 1) + [n - 1]
|
|
1203
|
+
}`;
|
|
1156
1204
|
const SEQ_FILTER_SOME = `function SeqFilterSome<T>(xs: seq<Option<T>>): seq<T>
|
|
1157
1205
|
ensures |SeqFilterSome(xs)| <= |xs|
|
|
1158
1206
|
{
|
|
@@ -1162,12 +1210,14 @@ const SEQ_FILTER_SOME = `function SeqFilterSome<T>(xs: seq<Option<T>>): seq<T>
|
|
|
1162
1210
|
const SEQ_FILTER = `function SeqFilter<T(!new)>(p: T -> bool, xs: seq<T>): seq<T>
|
|
1163
1211
|
ensures |SeqFilter(p, xs)| <= |xs|
|
|
1164
1212
|
ensures forall x :: x in SeqFilter(p, xs) <==> x in xs && p(x)
|
|
1213
|
+
ensures forall i :: 0 <= i < |SeqFilter(p, xs)| ==> SeqFilter(p, xs)[i] in xs
|
|
1165
1214
|
decreases |xs|
|
|
1166
1215
|
{
|
|
1167
1216
|
if |xs| == 0 then []
|
|
1168
1217
|
else (if p(xs[0]) then [xs[0]] else []) + SeqFilter(p, xs[1..])
|
|
1169
1218
|
}`;
|
|
1170
1219
|
const SEQ_ALL = `predicate SeqAll<T>(xs: seq<T>, p: T -> bool)
|
|
1220
|
+
ensures SeqAll(xs, p) <==> (forall x :: x in xs ==> p(x))
|
|
1171
1221
|
decreases |xs|
|
|
1172
1222
|
{
|
|
1173
1223
|
|xs| == 0 || (p(xs[0]) && SeqAll(xs[1..], p))
|
|
@@ -1330,6 +1380,36 @@ function StringIndexOfFromN(s: string, sub: string, from: nat): int
|
|
|
1330
1380
|
else if s[from..from + |sub|] == sub then from as int
|
|
1331
1381
|
else StringIndexOfFromN(s, sub, from + 1)
|
|
1332
1382
|
}`;
|
|
1383
|
+
// JS `s.lastIndexOf(sub, position)` searches backward from the clamped
|
|
1384
|
+
// position for the last match starting at or before it. An empty `sub` matches
|
|
1385
|
+
// at that position. The postconditions also state that no later match exists,
|
|
1386
|
+
// which is what lets callers reason about the not-found result.
|
|
1387
|
+
const STRING_LAST_INDEX_OF = `predicate StringMatchesAt(s: string, sub: string, j: int)
|
|
1388
|
+
{
|
|
1389
|
+
0 <= j && j + |sub| <= |s| && s[j..j + |sub|] == sub
|
|
1390
|
+
}
|
|
1391
|
+
|
|
1392
|
+
function StringLastIndexOf(s: string, sub: string): int
|
|
1393
|
+
ensures StringLastIndexOf(s, sub) == -1
|
|
1394
|
+
|| (0 <= StringLastIndexOf(s, sub) <= |s| - |sub| && StringMatchesAt(s, sub, StringLastIndexOf(s, sub)))
|
|
1395
|
+
ensures forall j {:trigger StringMatchesAt(s, sub, j)} ::
|
|
1396
|
+
StringLastIndexOf(s, sub) < j ==> !StringMatchesAt(s, sub, j)
|
|
1397
|
+
{
|
|
1398
|
+
StringLastIndexOfFrom(s, sub, |s|)
|
|
1399
|
+
}
|
|
1400
|
+
|
|
1401
|
+
function StringLastIndexOfFrom(s: string, sub: string, from: nat): int
|
|
1402
|
+
decreases from
|
|
1403
|
+
ensures StringLastIndexOfFrom(s, sub, from) == -1
|
|
1404
|
+
|| (0 <= StringLastIndexOfFrom(s, sub, from) <= from
|
|
1405
|
+
&& StringMatchesAt(s, sub, StringLastIndexOfFrom(s, sub, from)))
|
|
1406
|
+
ensures forall j {:trigger StringMatchesAt(s, sub, j)} ::
|
|
1407
|
+
StringLastIndexOfFrom(s, sub, from) < j <= from ==> !StringMatchesAt(s, sub, j)
|
|
1408
|
+
{
|
|
1409
|
+
if StringMatchesAt(s, sub, from) then from as int
|
|
1410
|
+
else if from == 0 then -1
|
|
1411
|
+
else StringLastIndexOfFrom(s, sub, from - 1)
|
|
1412
|
+
}`;
|
|
1333
1413
|
// `s.split(d)` in TS returns a non-empty sequence of segments. Modeled here as
|
|
1334
1414
|
// an axiom — defining it recursively would force StringIndexOf to grow ensures
|
|
1335
1415
|
// clauses that callers don't need. The two ensures cover what verification
|
|
@@ -1445,6 +1525,8 @@ const STRING_REPEAT = `function StringRepeat(s: string, n: int): string
|
|
|
1445
1525
|
}`;
|
|
1446
1526
|
const MATH_MIN = `function MathMin(a: int, b: int): int { if a <= b then a else b }`;
|
|
1447
1527
|
const MATH_MAX = `function MathMax(a: int, b: int): int { if a >= b then a else b }`;
|
|
1528
|
+
const MATH_MIN_REAL = `function MathMinReal(a: real, b: real): real { if a <= b then a else b }`;
|
|
1529
|
+
const MATH_MAX_REAL = `function MathMaxReal(a: real, b: real): real { if a >= b then a else b }`;
|
|
1448
1530
|
const MAX_OF_SEQ = `function MaxOfSeq(s: seq<int>): int
|
|
1449
1531
|
requires |s| > 0
|
|
1450
1532
|
ensures forall i: nat :: i < |s| ==> s[i] <= MaxOfSeq(s)
|
|
@@ -1504,6 +1586,7 @@ const INT_TO_STRING = `function IntToString(n: int): string
|
|
|
1504
1586
|
if n < 0 then "-" + NatToString(-n) else NatToString(n)
|
|
1505
1587
|
}`;
|
|
1506
1588
|
const MATH_ABS = `function MathAbs(x: int): nat { if x >= 0 then x else -x }`;
|
|
1589
|
+
const MATH_ABS_REAL = `function MathAbsReal(x: real): real { if x >= 0.0 then x else -x }`;
|
|
1507
1590
|
// perm(a, b) — `a` and `b` are reorderings of each other (equal as multisets).
|
|
1508
1591
|
// Transparent (Dafny unfolds it), so hand-proofs can reason with `multiset`
|
|
1509
1592
|
// directly. The `(==)` bound requires the element type to support equality.
|
|
@@ -1551,12 +1634,14 @@ const PREAMBLE_CODE = [
|
|
|
1551
1634
|
["SeqAll", SEQ_ALL],
|
|
1552
1635
|
["SeqFoldLeft", SEQ_FOLD_LEFT],
|
|
1553
1636
|
["SeqFilterSome", SEQ_FILTER_SOME],
|
|
1637
|
+
["CallbackIndices", CALLBACK_INDICES],
|
|
1554
1638
|
["SeqFind", SEQ_FIND],
|
|
1555
1639
|
["SeqFindLast", SEQ_FIND_LAST],
|
|
1556
1640
|
["SeqFlatten", SEQ_FLATTEN],
|
|
1557
1641
|
["SeqJoin", SEQ_JOIN],
|
|
1558
1642
|
["SafeSlice", SAFE_SLICE],
|
|
1559
1643
|
["StringIndexOf", STRING_INDEX_OF],
|
|
1644
|
+
["StringLastIndexOf", STRING_LAST_INDEX_OF],
|
|
1560
1645
|
["StringSearchPosition", STRING_SEARCH_POSITION],
|
|
1561
1646
|
["StringStartsWithAt", STRING_STARTS_WITH_AT],
|
|
1562
1647
|
["StringEndsWithAt", STRING_ENDS_WITH_AT],
|
|
@@ -1573,6 +1658,9 @@ const PREAMBLE_CODE = [
|
|
|
1573
1658
|
["MathAbs", MATH_ABS],
|
|
1574
1659
|
["MathMin", MATH_MIN],
|
|
1575
1660
|
["MathMax", MATH_MAX],
|
|
1661
|
+
["MathAbsReal", MATH_ABS_REAL],
|
|
1662
|
+
["MathMinReal", MATH_MIN_REAL],
|
|
1663
|
+
["MathMaxReal", MATH_MAX_REAL],
|
|
1576
1664
|
["MaxOfSeq", MAX_OF_SEQ],
|
|
1577
1665
|
["MinOfSeq", MIN_OF_SEQ],
|
|
1578
1666
|
["Perm", PERM],
|
package/tools/dist/extract.js
CHANGED
|
@@ -555,10 +555,16 @@ function extractExpr(node) {
|
|
|
555
555
|
const destructureBindings = [];
|
|
556
556
|
const params = node.getParameters().map((p, paramIndex) => {
|
|
557
557
|
const typeNode = p.getTypeNode();
|
|
558
|
-
const tsType = typeNode ? typeNode.getText() : undefined;
|
|
558
|
+
const tsType = typeNode ? annotationTypeText(typeNode, p.getType()) ?? typeNode.getText() : undefined;
|
|
559
559
|
const nameNode = p.getNameNode();
|
|
560
560
|
if (Node.isIdentifier(nameNode))
|
|
561
|
-
return {
|
|
561
|
+
return {
|
|
562
|
+
name: nameNode.getText(), tsType,
|
|
563
|
+
...(p.isRestParameter() ? { rest: true } : {}),
|
|
564
|
+
...(p.getInitializer() ? { defaultValue: extractExpr(p.getInitializer()),
|
|
565
|
+
inferredTsType: p.getType().getCallSignatures().length
|
|
566
|
+
? p.getType().getText(p) : typeToString(p.getType()) } : {}),
|
|
567
|
+
};
|
|
562
568
|
if (Node.isArrayBindingPattern(nameNode)) {
|
|
563
569
|
throw new Error(`array binding pattern in arrow parameter not yet supported: ${nameNode.getText()}`);
|
|
564
570
|
}
|
|
@@ -1196,6 +1202,15 @@ function declaredTypeTextIfBetter(propDecl, tsType) {
|
|
|
1196
1202
|
return tsType;
|
|
1197
1203
|
return text;
|
|
1198
1204
|
}
|
|
1205
|
+
/** The type an annotation names, as text for `parseTsType`. That parser has
|
|
1206
|
+
* no checker, so an indexed access type (`T["k"]`, `T["k"][number]`) would
|
|
1207
|
+
* survive as an opaque name spelled with brackets. When the annotation uses
|
|
1208
|
+
* one, render the checker's resolved type instead. */
|
|
1209
|
+
function annotationTypeText(tn, type) {
|
|
1210
|
+
const indexed = Node.isIndexedAccessTypeNode(tn)
|
|
1211
|
+
|| tn.getFirstDescendantByKind(SyntaxKind.IndexedAccessType) !== undefined;
|
|
1212
|
+
return indexed ? typeToString(type) : undefined;
|
|
1213
|
+
}
|
|
1199
1214
|
function typeToString(type) {
|
|
1200
1215
|
if (constEnumInfo(type))
|
|
1201
1216
|
return "number";
|
|
@@ -1426,7 +1441,8 @@ function renameRawExpr(e, from, to) {
|
|
|
1426
1441
|
case "nonNull": return { ...e, expr: r(e.expr) };
|
|
1427
1442
|
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) };
|
|
1428
1443
|
case "lambda": return e.params.some(p => p.name === from) ? e
|
|
1429
|
-
: { ...e,
|
|
1444
|
+
: { ...e, params: e.params.map(p => p.defaultValue ? { ...p, defaultValue: r(p.defaultValue) } : p),
|
|
1445
|
+
body: Array.isArray(e.body) ? renameRawStmts(e.body, from, to) : r(e.body) };
|
|
1430
1446
|
case "forall":
|
|
1431
1447
|
case "exists": return e.var === from ? e : { ...e, body: r(e.body) };
|
|
1432
1448
|
}
|
|
@@ -1713,7 +1729,9 @@ function extractStmts(stmts) {
|
|
|
1713
1729
|
// Dafny binding `var x: T := <default>;` typechecks. The empty-
|
|
1714
1730
|
// collection cases are picked up by dafny-emit's let case, which
|
|
1715
1731
|
// adds an explicit `: T` annotation for inference.
|
|
1716
|
-
const
|
|
1732
|
+
const typeNode = d.getTypeNode();
|
|
1733
|
+
const tsType = _eraseGenerics((typeNode && annotationTypeText(typeNode, declType))
|
|
1734
|
+
?? typeNode?.getText() ?? typeToString(declType));
|
|
1717
1735
|
const isOptional = / \| (null|undefined)\b/.test(tsType)
|
|
1718
1736
|
|| /^(null|undefined) \| /.test(tsType)
|
|
1719
1737
|
|| tsType.endsWith(" | undefined") || tsType.endsWith(" | null");
|
|
@@ -1746,7 +1764,9 @@ function extractStmts(stmts) {
|
|
|
1746
1764
|
// where the imported declaration's shape is opaque to LS): in that
|
|
1747
1765
|
// case leave null so resolve infers from the initializer's IR type
|
|
1748
1766
|
// (which sees the declare-type stubs).
|
|
1749
|
-
const
|
|
1767
|
+
const annotationNode = d.getTypeNode();
|
|
1768
|
+
const annotatedText = annotationNode
|
|
1769
|
+
? annotationTypeText(annotationNode, declType) ?? annotationNode.getText() : undefined;
|
|
1750
1770
|
const inferred = annotatedText ? null : _eraseGenerics(typeToString(declType));
|
|
1751
1771
|
const tsType = havocType
|
|
1752
1772
|
?? (annotatedText ? _eraseGenerics(annotatedText) : (inferred === "any" ? null : inferred));
|
|
@@ -1856,7 +1876,9 @@ function extractStmts(stmts) {
|
|
|
1856
1876
|
const name = fresh ?? decl.getName();
|
|
1857
1877
|
if (fresh)
|
|
1858
1878
|
renames.push([decl.getName(), fresh]);
|
|
1859
|
-
const
|
|
1879
|
+
const typeNode = decl.getTypeNode();
|
|
1880
|
+
const tsType = (typeNode && annotationTypeText(typeNode, decl.getType()))
|
|
1881
|
+
?? typeNode?.getText() ?? typeToString(decl.getType());
|
|
1860
1882
|
const initExpr = decl.getInitializer();
|
|
1861
1883
|
if (!initExpr)
|
|
1862
1884
|
throw new Error(`for(...) at line ${line}: missing initializer for ${name}`);
|
|
@@ -2192,8 +2214,12 @@ function extractFunctionInner(fn, parentAnnotations) {
|
|
|
2192
2214
|
// when no annotation is present, fall back to the computed type
|
|
2193
2215
|
// (e.g., `eof = false` infers `boolean` from the default value).
|
|
2194
2216
|
const tn = p.getTypeNode();
|
|
2217
|
+
const resolved = tn && annotationTypeText(tn, p.getType());
|
|
2195
2218
|
let tsType;
|
|
2196
|
-
if (
|
|
2219
|
+
if (resolved) {
|
|
2220
|
+
tsType = _eraseGenerics(resolved);
|
|
2221
|
+
}
|
|
2222
|
+
else if (tn && Node.isUnionTypeNode(tn)) {
|
|
2197
2223
|
tsType = _eraseGenerics(_tsTypeFromUnionNode(tn));
|
|
2198
2224
|
}
|
|
2199
2225
|
else if (tn) {
|
|
@@ -2230,6 +2256,9 @@ function extractFunctionInner(fn, parentAnnotations) {
|
|
|
2230
2256
|
// and the type mapper reads the subject name as an opaque type.
|
|
2231
2257
|
if (node && node.getKind() === SyntaxKind.TypePredicate)
|
|
2232
2258
|
return "boolean";
|
|
2259
|
+
const resolved = node && annotationTypeText(node, fn.getReturnType());
|
|
2260
|
+
if (resolved)
|
|
2261
|
+
return _eraseGenerics(resolved);
|
|
2233
2262
|
if (node && Node.isUnionTypeNode(node))
|
|
2234
2263
|
return _eraseGenerics(_tsTypeFromUnionNode(node));
|
|
2235
2264
|
if (node)
|
|
@@ -2254,6 +2283,12 @@ function extractFunctionInner(fn, parentAnnotations) {
|
|
|
2254
2283
|
export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDependency = () => { }) {
|
|
2255
2284
|
_extractOptions = options;
|
|
2256
2285
|
_validateDependency = validateDependency;
|
|
2286
|
+
// Per-module state: a previous module in the same process (batch mode,
|
|
2287
|
+
// tests) must not leak a havoc key, temp-name counter, or function-local maps.
|
|
2288
|
+
_havocKey = null;
|
|
2289
|
+
_destrCounter = 0;
|
|
2290
|
+
_typeParamMap = new Map();
|
|
2291
|
+
_reservedForCounterNames = new Set();
|
|
2257
2292
|
// Seed the fresh-name check (names.ts) before anything mints: every
|
|
2258
2293
|
// Identifier token in the module, a deliberate over-approximation.
|
|
2259
2294
|
setUserNames(new Set(sourceFile.getDescendantsOfKind(SyntaxKind.Identifier).map(i => i.getText())));
|
|
@@ -2878,6 +2913,8 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
|
|
|
2878
2913
|
}
|
|
2879
2914
|
}
|
|
2880
2915
|
if (e.kind === "lambda") {
|
|
2916
|
+
e.params.forEach(p => { if (p.defaultValue)
|
|
2917
|
+
collectNamesExpr(p.defaultValue); });
|
|
2881
2918
|
if (Array.isArray(e.body))
|
|
2882
2919
|
collectNames(e.body);
|
|
2883
2920
|
else
|
package/tools/dist/ir.js
CHANGED
|
@@ -74,6 +74,7 @@ export function anyExpr(e, pred) {
|
|
|
74
74
|
case "binop": return anyExpr(e.left, pred) || anyExpr(e.right, pred);
|
|
75
75
|
case "unop":
|
|
76
76
|
case "toNat":
|
|
77
|
+
case "toInt":
|
|
77
78
|
case "toReal": return anyExpr(e.expr, pred);
|
|
78
79
|
case "app": return e.args.some(a => anyExpr(a, pred));
|
|
79
80
|
case "field": return anyExpr(e.obj, pred);
|
|
@@ -83,6 +84,7 @@ export function anyExpr(e, pred) {
|
|
|
83
84
|
case "implies": return e.premises.some(p => anyExpr(p, pred)) || anyExpr(e.conclusion, pred);
|
|
84
85
|
case "record": return (e.spread ? anyExpr(e.spread, pred) : false) || e.fields.some(f => anyExpr(f.value, pred));
|
|
85
86
|
case "arrayLiteral": return e.elems.some(x => anyExpr(x, pred));
|
|
87
|
+
case "arrayRange": return anyExpr(e.length, pred);
|
|
86
88
|
case "mapLiteral": return e.entries.some(en => anyExpr(en.key, pred) || anyExpr(en.value, pred));
|
|
87
89
|
case "methodCall": return anyExpr(e.obj, pred) || e.args.some(a => anyExpr(a, pred));
|
|
88
90
|
case "lambda": return e.body.some(s => anyExprInStmt(s, pred));
|
package/tools/dist/lean-emit.js
CHANGED
|
@@ -340,13 +340,14 @@ function emitExpr(e, parentPrec) {
|
|
|
340
340
|
const head = e.type ? `${e.type}.${leanCtorName(e.name)}` : `.${leanCtorName(e.name)}`;
|
|
341
341
|
if (!e.args || e.args.length === 0)
|
|
342
342
|
return head;
|
|
343
|
-
const args = e.args.map(a => (a.kind === "binop" || a.kind === "unop" || a.kind === "implies" || a.kind === "app" || a.kind === "methodCall") ? `(${emitExpr(a)})` : emitExpr(a));
|
|
343
|
+
const args = e.args.map(a => (a.kind === "binop" || a.kind === "unop" || a.kind === "implies" || a.kind === "app" || a.kind === "methodCall" || a.kind === "if") ? `(${emitExpr(a)})` : emitExpr(a));
|
|
344
344
|
return `${head} ${args.join(" ")}`;
|
|
345
345
|
}
|
|
346
346
|
case "arrayLiteral":
|
|
347
347
|
if (e.elems.length === 0)
|
|
348
348
|
return `#[]`;
|
|
349
349
|
return `#[${e.elems.map(el => emitExpr(el)).join(", ")}]`;
|
|
350
|
+
case "arrayRange": return `((Array.range ${emitExpr(e.length)}).map Int.ofNat)`;
|
|
350
351
|
case "tupleLiteral":
|
|
351
352
|
return `(${e.elems.map(el => emitExpr(el)).join(", ")})`;
|
|
352
353
|
case "tupleProj": {
|
|
@@ -390,7 +391,7 @@ function emitExpr(e, parentPrec) {
|
|
|
390
391
|
return emitMethodCall(e.objTy.kind, e.method, e.monadic, receiver, args);
|
|
391
392
|
}
|
|
392
393
|
case "lambda": {
|
|
393
|
-
const params = e.params.map(p => p.name).join(" ");
|
|
394
|
+
const params = e.params.map(p => e.typedParams ? `(${p.name} : ${tyToLean(p.type)})` : p.name).join(" ");
|
|
394
395
|
// Single return statement → expression lambda
|
|
395
396
|
if (e.body.length === 1 && e.body[0].kind === "return") {
|
|
396
397
|
return `(fun ${params} => ${emitExpr(e.body[0].value)})`;
|
|
@@ -517,6 +518,7 @@ function emitExpr(e, parentPrec) {
|
|
|
517
518
|
const wrap = e.expr.kind !== "var" && e.expr.kind !== "num" && e.expr.kind !== "bigint";
|
|
518
519
|
return wrap ? `(${inner}).toNat` : `${inner}.toNat`;
|
|
519
520
|
}
|
|
521
|
+
case "toInt": return `(Int.ofNat ${emitExpr(e.expr)})`;
|
|
520
522
|
case "toReal":
|
|
521
523
|
// A real value reached the Lean backend via coercion (e.g. number `/`).
|
|
522
524
|
// Same unsupported-real story as the `real` type case in tyToLean.
|
|
@@ -546,7 +548,7 @@ function emitExpr(e, parentPrec) {
|
|
|
546
548
|
}
|
|
547
549
|
case "forall": return `∀ ${e.var} : ${tyToLean(e.type)}, ${emitExpr(e.body)}`;
|
|
548
550
|
case "exists": return `∃ ${e.var} : ${tyToLean(e.type)}, ${emitExpr(e.body)}`;
|
|
549
|
-
case "let": return `let ${e.name} := ${emitExpr(e.value)}\n${emitExpr(e.body)}`;
|
|
551
|
+
case "let": return `let ${e.name}${e.type ? ` : ${tyToLean(e.type)}` : ""} := ${emitExpr(e.value)}\n${emitExpr(e.body)}`;
|
|
550
552
|
default: throw new Error(`Unsupported Lean expression: ${e.kind}`);
|
|
551
553
|
}
|
|
552
554
|
}
|
|
@@ -570,7 +572,6 @@ function isPropValued(e) {
|
|
|
570
572
|
}
|
|
571
573
|
// ── Statement emission ──────────────────────────────────────
|
|
572
574
|
function emitStmts(stmts, indent) {
|
|
573
|
-
const pad = " ".repeat(indent);
|
|
574
575
|
return stmts.map(s => emitStmt(s, indent)).join("\n");
|
|
575
576
|
}
|
|
576
577
|
function emitStmt(s, indent) {
|
|
@@ -890,7 +891,7 @@ function emitPureExpr(e, indent) {
|
|
|
890
891
|
return lines.join("\n");
|
|
891
892
|
}
|
|
892
893
|
case "let":
|
|
893
|
-
return `${pad}let ${e.name} := ${emitExpr(e.value)}\n${emitPureExpr(e.body, indent)}`;
|
|
894
|
+
return `${pad}let ${e.name}${e.type ? ` : ${tyToLean(e.type)}` : ""} := ${emitExpr(e.value)}\n${emitPureExpr(e.body, indent)}`;
|
|
894
895
|
default:
|
|
895
896
|
return `${pad}${emitExpr(e)}`;
|
|
896
897
|
}
|