lemmascript 0.6.8 → 0.6.10

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.
@@ -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 { name: nameNode.getText(), tsType };
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, body: Array.isArray(e.body) ? renameRawStmts(e.body, from, to) : r(e.body) };
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 tsType = _eraseGenerics(d.getTypeNode()?.getText() ?? typeToString(declType));
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 annotatedText = d.getTypeNode()?.getText();
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 tsType = decl.getTypeNode()?.getText() ?? typeToString(decl.getType());
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 (tn && Node.isUnionTypeNode(tn)) {
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));
@@ -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
  }
@@ -1,47 +1,4 @@
1
1
  import { patternCtor, patternBinders, usesName, usesNameInStmts } from "./ir.js";
2
- // ── Generic walkers (same shape as transform.ts) ─────────────
3
- function mapExpr(e, f) {
4
- const hit = f(e);
5
- if (hit)
6
- return hit;
7
- const r = (x) => mapExpr(x, f);
8
- switch (e.kind) {
9
- case "var":
10
- case "num":
11
- case "bigint":
12
- case "bool":
13
- case "str":
14
- case "constructor":
15
- case "emptyMap":
16
- case "emptySet":
17
- case "havoc":
18
- case "default":
19
- case "mapLiteral": return e;
20
- case "binop": return { ...e, left: r(e.left), right: r(e.right) };
21
- case "unop": return { ...e, expr: r(e.expr) };
22
- case "implies": return { ...e, premises: e.premises.map(r), conclusion: r(e.conclusion) };
23
- case "app": return { ...e, args: e.args.map(r) };
24
- case "field": return { ...e, obj: r(e.obj) };
25
- case "toNat": return { ...e, expr: r(e.expr) };
26
- case "toReal": return { ...e, expr: r(e.expr) };
27
- case "index": return { ...e, arr: r(e.arr), idx: r(e.idx) };
28
- case "tupleLiteral": return { ...e, elems: e.elems.map(r) };
29
- case "tupleProj": return { ...e, obj: r(e.obj) };
30
- case "record": return { ...e, spread: e.spread ? r(e.spread) : null,
31
- fields: e.fields.map(fi => ({ ...fi, value: r(fi.value) })) };
32
- case "arrayLiteral": return { ...e, elems: e.elems.map(r) };
33
- case "if": return { ...e, cond: r(e.cond), then: r(e.then), else: r(e.else) };
34
- case "match": {
35
- const scr = r(e.scrutinee);
36
- return { ...e, scrutinee: scr, arms: e.arms.map(a => ({ ...a, body: r(a.body) })) };
37
- }
38
- case "forall": return { ...e, body: r(e.body) };
39
- case "exists": return { ...e, body: r(e.body) };
40
- case "let": return { ...e, value: r(e.value), body: r(e.body) };
41
- case "methodCall": return { ...e, obj: r(e.obj), args: e.args.map(r) };
42
- case "lambda": return e;
43
- }
44
- }
45
2
  /** Detect map.get(k) — returns { obj, key, objTy } if so, else null. */
46
3
  function isMapGet(e) {
47
4
  if (e.kind !== "methodCall" || e.objTy.kind !== "map" || e.method !== "get" || e.args.length !== 1)
@@ -195,8 +152,8 @@ const STMT_RULES = [ruleMatchOnMapGetStmt];
195
152
  // ── Statement-list rules (pairs of adjacent stmts) ──────────
196
153
  /** Pair rule: let x = m.get(k); match x { Some(v) => sb, None => nb }
197
154
  * → if k in m { var v := m[k]; sb } else { nb }
198
- * Requires x not referenced in any stmt after the match. Bind v once instead
199
- * of substituting, to preserve semantics under mutation of m. */
155
+ * Requires x not referenced in either arm or after the match. Bind v once
156
+ * instead of substituting, to preserve semantics under mutation of m. */
200
157
  function tryLetMatchOnMapGet(s1, s2, restStmts) {
201
158
  if (s1.kind !== "let" || s1.mutable)
202
159
  return null;
@@ -211,7 +168,9 @@ function tryLetMatchOnMapGet(s1, s2, restStmts) {
211
168
  const arms = getSomeNoneArms(s2.arms);
212
169
  if (!arms)
213
170
  return null;
214
- if (usesNameInStmts(restStmts, s1.name))
171
+ if (usesNameInStmts(arms.someArm.body, s1.name) ||
172
+ usesNameInStmts(arms.noneArm.body, s1.name) ||
173
+ usesNameInStmts(restStmts, s1.name))
215
174
  return null;
216
175
  const idx = { kind: "index", arr: get.obj, idx: get.key };
217
176
  const valTy = get.objTy.kind === "map" ? get.objTy.value : { kind: "unknown" };
@@ -274,18 +233,19 @@ function rewriteChildrenExpr(e) {
274
233
  case "bigint":
275
234
  case "bool":
276
235
  case "str":
277
- case "constructor":
278
236
  case "emptyMap":
279
237
  case "emptySet":
280
238
  case "havoc":
281
- case "default":
282
- case "mapLiteral": return e;
239
+ case "default": return e;
240
+ case "constructor": return { ...e, args: e.args.map(r) };
241
+ case "mapLiteral": return { ...e, entries: e.entries.map(en => ({ ...en, key: r(en.key), value: r(en.value) })) };
283
242
  case "binop": return { ...e, left: r(e.left), right: r(e.right) };
284
243
  case "unop": return { ...e, expr: r(e.expr) };
285
244
  case "implies": return { ...e, premises: e.premises.map(r), conclusion: r(e.conclusion) };
286
245
  case "app": return { ...e, args: e.args.map(r) };
287
246
  case "field": return { ...e, obj: r(e.obj) };
288
247
  case "toNat": return { ...e, expr: r(e.expr) };
248
+ case "toInt": return { ...e, expr: r(e.expr) };
289
249
  case "toReal": return { ...e, expr: r(e.expr) };
290
250
  case "index": return { ...e, arr: r(e.arr), idx: r(e.idx) };
291
251
  case "tupleLiteral": return { ...e, elems: e.elems.map(r) };
@@ -293,6 +253,7 @@ function rewriteChildrenExpr(e) {
293
253
  case "record": return { ...e, spread: e.spread ? r(e.spread) : null,
294
254
  fields: e.fields.map(fi => ({ ...fi, value: r(fi.value) })) };
295
255
  case "arrayLiteral": return { ...e, elems: e.elems.map(r) };
256
+ case "arrayRange": return { ...e, length: r(e.length) };
296
257
  case "if": return { ...e, cond: r(e.cond), then: r(e.then), else: r(e.else) };
297
258
  case "match": {
298
259
  const scr = r(e.scrutinee);