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.
@@ -9,6 +9,7 @@ import { anyExprInStmts, pWild, pCtor, pLiteral, patternBinders, patternBinds, p
9
9
  import { parseTsType } from "./types.js";
10
10
  import { freshName } from "./names.js";
11
11
  import { builtinSpec } from "./builtins.js";
12
+ import { lowerIndexedCallback } from "./callback-lowering.js";
12
13
  import { isFalsyCapableTy } from "./condition-facts.js";
13
14
  import { declOf, declOfKind, declOfTy, unionDeclOfTy, declWithVariant, tyBaseName } from "./typedecls.js";
14
15
  // ── Generic IR walkers ──────────────────────────────────────
@@ -40,12 +41,14 @@ function mapExpr(e, f) {
40
41
  case "app": return { ...e, args: e.args.map(r) };
41
42
  case "field": return { ...e, obj: r(e.obj) };
42
43
  case "toNat": return { ...e, expr: r(e.expr) };
44
+ case "toInt": return { ...e, expr: r(e.expr) };
43
45
  case "toReal": return { ...e, expr: r(e.expr) };
44
46
  case "index": return { ...e, arr: r(e.arr), idx: r(e.idx) };
45
47
  case "tupleLiteral": return { ...e, elems: e.elems.map(r) };
46
48
  case "tupleProj": return { ...e, obj: r(e.obj) };
47
49
  case "record": return { ...e, spread: e.spread ? r(e.spread) : null, fields: e.fields.map(fi => ({ ...fi, value: r(fi.value) })) };
48
50
  case "arrayLiteral": return { ...e, elems: e.elems.map(r) };
51
+ case "arrayRange": return { ...e, length: r(e.length) };
49
52
  case "if": return { ...e, cond: r(e.cond), then: r(e.then), else: r(e.else) };
50
53
  case "match": {
51
54
  const scr = r(e.scrutinee);
@@ -467,7 +470,11 @@ function lowerExpr(e, binds) {
467
470
  }
468
471
  switch (e.kind) {
469
472
  case "var": return { kind: "var", name: e.name };
470
- case "num": return { kind: "num", value: e.value };
473
+ case "num": {
474
+ const literal = { kind: "num", value: e.value };
475
+ return e.ty.kind === "real" && Number.isInteger(e.value)
476
+ ? { kind: "toReal", expr: literal } : literal;
477
+ }
471
478
  case "bigint": return { kind: "bigint", value: e.value };
472
479
  case "bool": return { kind: "bool", value: e.value };
473
480
  case "str":
@@ -478,8 +485,9 @@ function lowerExpr(e, binds) {
478
485
  // Only `num` folds. A `bigint` payload is a string, so negating it here
479
486
  // would coerce through `Number` and round: `-9007199254740993n` stays a
480
487
  // structural `unop("-", bigint(...))` and is negated by the emitter.
488
+ // Keep the resolved type so a contextually real literal retains its cast.
481
489
  if (e.op === "-" && e.expr.kind === "num")
482
- return { kind: "num", value: -e.expr.value };
490
+ return lowerExpr({ ...e.expr, value: -e.expr.value, ty: e.ty }, binds);
483
491
  // String truthiness: !str → str == ""
484
492
  if (e.op === "!" && e.expr.ty.kind === "string")
485
493
  return { kind: "binop", op: "=", left: lowerExpr(e.expr, binds), right: { kind: "str", value: "" } };
@@ -845,14 +853,35 @@ function lowerExpr(e, binds) {
845
853
  e.fn.field === "fromCharCode" && e.args.length === 1) {
846
854
  return { kind: "app", fn: "StringFromCharCode", args: [lowerExpr(e.args[0], binds)] };
847
855
  }
848
- // Math.abs/min/max → preamble functions
856
+ // Number.isSafeInteger(n) on an integer: a bigint is never a safe integer
857
+ // in JS, so the result is false. A `number` is an unbounded integer in the
858
+ // model, so the JS bound -(2^53 - 1) <= n <= 2^53 - 1 must be stated.
859
+ if (e.fn.kind === "field" && e.fn.obj.kind === "var" && e.fn.obj.name === "Number" &&
860
+ e.fn.field === "isSafeInteger" && e.args.length === 1 && isIntegral(e.args[0].ty)) {
861
+ if (e.args[0].ty.kind === "int" && e.args[0].ty.big)
862
+ return { kind: "bool", value: false };
863
+ const n = lowerExpr(e.args[0], binds);
864
+ const max = 9007199254740991;
865
+ return {
866
+ kind: "binop", op: "∧",
867
+ left: { kind: "binop", op: "≤", left: { kind: "num", value: -max }, right: n },
868
+ right: { kind: "binop", op: "≤", left: n, right: { kind: "num", value: max } },
869
+ };
870
+ }
871
+ // Math.abs/min/max preserve the resolved numeric type. Mixed operands
872
+ // need explicit int/nat→real coercions, just like real binary operations.
849
873
  if (e.fn.kind === "field" && e.fn.obj.kind === "var" && e.fn.obj.name === "Math") {
850
- if (e.fn.field === "abs" && e.args.length === 1)
851
- return { kind: "app", fn: "MathAbs", args: [lowerExpr(e.args[0], binds)] };
852
- if (e.fn.field === "min" && e.args.length === 2)
853
- return { kind: "app", fn: "MathMin", args: e.args.map(a => lowerExpr(a, binds)) };
854
- if (e.fn.field === "max" && e.args.length === 2)
855
- return { kind: "app", fn: "MathMax", args: e.args.map(a => lowerExpr(a, binds)) };
874
+ const fn = e.fn.field === "abs" && e.args.length === 1 ? "MathAbs"
875
+ : e.fn.field === "min" && e.args.length === 2 ? "MathMin"
876
+ : e.fn.field === "max" && e.args.length === 2 ? "MathMax" : null;
877
+ if (fn) {
878
+ const real = e.ty.kind === "real";
879
+ const args = e.args.map((arg) => {
880
+ const lowered = lowerExpr(arg, binds);
881
+ return real && isIntegral(arg.ty) ? { kind: "toReal", expr: lowered } : lowered;
882
+ });
883
+ return { kind: "app", fn: real ? `${fn}Real` : fn, args };
884
+ }
856
885
  }
857
886
  // Math.ceil(x): CeilReal on real args, identity on int
858
887
  if (e.fn.kind === "field" && e.fn.field === "ceil" && e.fn.obj.kind === "var" && e.fn.obj.name === "Math" && e.args.length === 1) {
@@ -927,7 +956,8 @@ function lowerExpr(e, binds) {
927
956
  }
928
957
  // Check if any lambda arg has monadic body
929
958
  const needsMonadic = _opts.monadic && args.some(a => a.kind === "lambda" && isMonadicBody(a.body));
930
- const result = { kind: "methodCall", obj: recv, objTy: e.fn.obj.ty, method, args, monadic: needsMonadic };
959
+ const indexed = spec?.hof ? lowerIndexedCallback(recv, e.fn.obj.ty, method, args, spec.hof.shape, needsMonadic, _callbackCounter++) : null;
960
+ const result = indexed ?? { kind: "methodCall", obj: recv, objTy: e.fn.obj.ty, method, args, monadic: needsMonadic };
931
961
  // Monadic HOF call is itself monadic — lift via binds like a method call
932
962
  if (_opts.monadic && needsMonadic && binds) {
933
963
  const name = freshName(`_t${_liftCounter++}`);
@@ -1051,6 +1081,9 @@ function lowerExpr(e, binds) {
1051
1081
  return { kind: "tupleLiteral", elems: e.elems.map(el => lowerExpr(el, binds)) };
1052
1082
  return { kind: "arrayLiteral", elems: e.elems.map(el => lowerExpr(el, binds)) };
1053
1083
  case "lambda": {
1084
+ if (e.params.some(p => p.rest || p.defaultValue)) {
1085
+ throw new Error("lambda rest/default bindings require a known callback argument list");
1086
+ }
1054
1087
  // Pass the module typeDecls (not []), so type lookups inside the lambda
1055
1088
  // body — e.g. a `switch`'s variant fields — resolve. A bare `[]` left a
1056
1089
  // discriminated-union switch in a lambda with binderless patterns.
@@ -1669,6 +1702,7 @@ function transformStmts(stmts, typeDecls) {
1669
1702
  return result;
1670
1703
  }
1671
1704
  let _liftCounter = 0;
1705
+ let _callbackCounter = 0;
1672
1706
  // Branch results must not renumber the existing lifted-call temporaries.
1673
1707
  let _branchCounter = 0;
1674
1708
  function liftMethodCalls(e) {
@@ -1726,7 +1760,6 @@ function transformStmt(s, typeDecls) {
1726
1760
  const idxName = freshName(`_${param}_idx`);
1727
1761
  const idx = { kind: "var", name: idxName };
1728
1762
  const arrSize = { kind: "field", obj: arrIR, field: "size" };
1729
- const elemVar = { kind: "var", name: param };
1730
1763
  const keyIR = transformExpr(keyExpr);
1731
1764
  const valIR = transformExpr(valExpr);
1732
1765
  const mapSet = { kind: "methodCall", obj: { kind: "var", name: s.name }, objTy: s.ty, method: "set", args: [keyIR, valIR], monadic: false };
@@ -1874,10 +1907,6 @@ function transformStmt(s, typeDecls) {
1874
1907
  return [emitMatchStmt(s.scrutinee, s.typeName, s.cases, s.fallthrough, typeDecls)];
1875
1908
  }
1876
1909
  }
1877
- /** Apply an expression transform to all expressions in a statement (convenience wrapper). */
1878
- function mapStmtExprs(s, r) {
1879
- return mapStmt(s, e => r(e));
1880
- }
1881
1910
  /** Build match arms from variant cases — shared by imperative and pure paths.
1882
1911
  * Looks up variant fields from typeDecls, builds patterns via buildMatchPattern,
1883
1912
  * and delegates body transformation to the caller-provided function.
@@ -2142,22 +2171,6 @@ function projectStructuralCallArgsInTStmts(stmts, varName, fields) {
2142
2171
  return changed ? { ...e, args } : null;
2143
2172
  }));
2144
2173
  }
2145
- /** Replace obj.field → replacement var in typed IR expressions (before lowering).
2146
- * Mirrors replaceFieldsInTStmts but operates on a single TExpr tree. */
2147
- function replaceFieldInTExpr(expr, objName, replacements) {
2148
- if (replacements.length === 0)
2149
- return expr;
2150
- return mapTExpr(expr, e => {
2151
- if (e.kind === "field" && e.obj.kind === "var" && e.obj.name === objName) {
2152
- const r = replacements.find(r => r.fieldName === e.field);
2153
- if (r) {
2154
- const ty = e.ty.kind !== "unknown" ? e.ty : r.fallbackTy;
2155
- return { kind: "var", name: r.newName, ty };
2156
- }
2157
- }
2158
- return null;
2159
- });
2160
- }
2161
2174
  function asTAccessPath(e) {
2162
2175
  if (e.kind === "var")
2163
2176
  return { rootVar: e.name, fields: [] };
@@ -2192,13 +2205,6 @@ function replacePathInTStmts(stmts, path, binder, binderTy) {
2192
2205
  return stmts.map(s => mapTStmt(s, e => matchesAccessPath(e, path)
2193
2206
  ? { kind: "var", name: binder, ty: binderTy } : null));
2194
2207
  }
2195
- /** Unwrap optional type on match-bound variables in TExpr.
2196
- * After replaceFieldInTExpr, the replaced variable carries the original optional
2197
- * type from the field declaration. The match binding unwraps it to the inner type. */
2198
- function fixBoundType(expr, boundName) {
2199
- return mapTExpr(expr, e => e.kind === "var" && e.name === boundName && e.ty.kind === "optional"
2200
- ? { ...e, ty: e.ty.inner } : null);
2201
- }
2202
2208
  // ── Pure function generation ─────────────────────────────────
2203
2209
  function transformPureBody(stmts, typeDecls) {
2204
2210
  // tagMatch (from narrow's discriminant detection) is the leading stmt and consumes the rest.
@@ -2489,6 +2495,7 @@ export function transformModuleDafny(mod) {
2489
2495
  export function transformModule(mod, specImport, moduleBaseOverride) {
2490
2496
  _forofCounters.clear();
2491
2497
  _liftCounter = 0;
2498
+ _callbackCounter = 0;
2492
2499
  _branchCounter = 0;
2493
2500
  _typeDecls = mod.typeDecls;
2494
2501
  _neededKindHelpers = new Map();
@@ -1,8 +1,8 @@
1
1
  /**
2
- * Type mapping — TS types → Lean types.
2
+ * Type mapping — TS type strings → backend-neutral `Ty`.
3
3
  *
4
- * Single source of truth for type-related decisions.
5
- * The transform phase imports this.
4
+ * Single source of truth for type-related decisions; resolve, transform, and
5
+ * both emitters import this.
6
6
  */
7
7
  import { tyEqual } from "./typedir.js";
8
8
  import { Node, Project, SyntaxKind } from "ts-morph";