lemmascript 0.6.10 → 0.6.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/tools/dist/ir.js CHANGED
@@ -79,6 +79,7 @@ export function anyExpr(e, pred) {
79
79
  case "app": return e.args.some(a => anyExpr(a, pred));
80
80
  case "field": return anyExpr(e.obj, pred);
81
81
  case "index": return anyExpr(e.arr, pred) || anyExpr(e.idx, pred);
82
+ case "stringIndex": return anyExpr(e.str, pred) || anyExpr(e.idx, pred);
82
83
  case "tupleLiteral": return e.elems.some(x => anyExpr(x, pred));
83
84
  case "tupleProj": return anyExpr(e.obj, pred);
84
85
  case "implies": return e.premises.some(p => anyExpr(p, pred)) || anyExpr(e.conclusion, pred);
@@ -432,13 +432,14 @@ function emitExpr(e, parentPrec) {
432
432
  : _boolCtx && e.op === "∧" ? "&&"
433
433
  : _boolCtx && e.op === "∨" ? "||"
434
434
  : e.op;
435
- // ↔ does not chain in Lean — a nested iff operand needs parens.
436
- const childPrec = e.op === "↔" ? prec(e.op) + 1 : prec(e.op);
435
+ // Comparisons and ↔ do not chain in Lean. In particular, a Boolean
436
+ // postcondition `res = (s = t)` must keep its inner equality grouped.
437
+ const childPrec = ["↔", "=", "≠", "<", "≤", ">", "≥"].includes(e.op)
438
+ ? prec(e.op) + 1 : prec(e.op);
437
439
  // `-`, `/`, `%` are left-associative and non-associative, so an equal-
438
440
  // precedence right operand must be parenthesized: `a - (b - c)` would
439
441
  // otherwise emit as `a - b - c`, i.e. `(a - b) - c`.
440
- const rightPrec = e.op === "↔" ? childPrec
441
- : ["-", "/", "%"].includes(e.op) ? prec(e.op) + 1 : childPrec;
442
+ const rightPrec = ["-", "/", "%"].includes(e.op) ? prec(e.op) + 1 : childPrec;
442
443
  const s = `${wrapOperand(e.left, childPrec)} ${op} ${wrapOperand(e.right, rightPrec)}`;
443
444
  return (parentPrec !== undefined && prec(e.op) < parentPrec) ? `(${s})` : s;
444
445
  }
@@ -453,7 +454,11 @@ function emitExpr(e, parentPrec) {
453
454
  return parentPrec !== undefined ? `(${s})` : s;
454
455
  }
455
456
  case "app": {
456
- 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));
457
+ // A bare negative literal argument (`f -7 2`) parses as subtraction in Lean.
458
+ const args = e.args.map(a => {
459
+ const s = emitExpr(a);
460
+ return (a.kind === "binop" || a.kind === "unop" || a.kind === "implies" || a.kind === "app" || a.kind === "methodCall" || s.startsWith("-")) ? `(${s})` : s;
461
+ });
457
462
  // Datatype constructor (tagged by transform): Lean needs the qualified name
458
463
  // `BaseType.variant`; a bare `variant` is an unknown identifier. (Dafny keeps
459
464
  // the bare form, so its output is unaffected.)
@@ -486,7 +491,7 @@ function emitExpr(e, parentPrec) {
486
491
  // `perm_append_comm`, and `Perm.count_eq` for the count-invariance payoff).
487
492
  if (e.fn === "Perm" && args.length === 2)
488
493
  return `(${args[0]}.toList).Perm (${args[1]}.toList)`;
489
- return `${e.fn} ${args.join(" ")}`;
494
+ return args.length ? `${e.fn} ${args.join(" ")}` : e.fn;
490
495
  }
491
496
  case "field": {
492
497
  // Union destructor (tagged by transform): `x.field` where x is a
@@ -518,11 +523,14 @@ function emitExpr(e, parentPrec) {
518
523
  const wrap = e.expr.kind !== "var" && e.expr.kind !== "num" && e.expr.kind !== "bigint";
519
524
  return wrap ? `(${inner}).toNat` : `${inner}.toNat`;
520
525
  }
521
- case "toInt": return `(Int.ofNat ${emitExpr(e.expr)})`;
526
+ case "toInt": return `(Int.ofNat (${emitExpr(e.expr)}))`;
522
527
  case "toReal":
523
528
  // A real value reached the Lean backend via coercion (e.g. number `/`).
524
529
  // Same unsupported-real story as the `real` type case in tyToLean.
525
530
  throw new Error("real arithmetic is not supported by the Lean backend (needs noncomputable ℝ / Mathlib).");
531
+ case "stringIndex":
532
+ _needsJSString = true;
533
+ return `(JSString.index (${emitExpr(e.str)}) (${emitExpr(e.idx)}))`;
526
534
  case "index": {
527
535
  const arr = emitExpr(e.arr);
528
536
  // Parenthesize a low-precedence array expr (e.g. a function application)
@@ -0,0 +1,212 @@
1
+ import { Node, SyntaxKind, ts } from "ts-morph";
2
+ import { reserveName } from "./names.js";
3
+ import { renameSpecVariables } from "./specparser.js";
4
+ function functionLike(node) {
5
+ return Node.isFunctionDeclaration(node) || Node.isMethodDeclaration(node)
6
+ || Node.isArrowFunction(node) || Node.isFunctionExpression(node);
7
+ }
8
+ function scopeOf(node) {
9
+ return node.getFirstAncestor(n => Node.isBlock(n) || Node.isCaseBlock(n)
10
+ || Node.isForStatement(n) || Node.isForOfStatement(n) || Node.isForInStatement(n)
11
+ || functionLike(n)) ?? node.getSourceFile();
12
+ }
13
+ function bindings(node) {
14
+ if (Node.isIdentifier(node))
15
+ return [node];
16
+ if (Node.isObjectBindingPattern(node) || Node.isArrayBindingPattern(node)) {
17
+ return node.getElements().flatMap(e => Node.isBindingElement(e) ? bindings(e.getNameNode()) : []);
18
+ }
19
+ return [];
20
+ }
21
+ /** `recv.method(callback)`: backends may emit the receiver inside the scope
22
+ * of the callback's parameter (a comprehension), so the parameter must not
23
+ * share a name with anything the receiver mentions, library globals included. */
24
+ function receiverMentions(callback, name) {
25
+ const call = callback.getParent();
26
+ if (!Node.isCallExpression(call) || !call.getArguments().includes(callback))
27
+ return false;
28
+ const callee = call.getExpression();
29
+ if (!Node.isPropertyAccessExpression(callee))
30
+ return false;
31
+ const receiver = callee.getExpression();
32
+ return [receiver, ...receiver.getDescendantsOfKind(SyntaxKind.Identifier)]
33
+ .some(n => Node.isIdentifier(n) && n.getText() === name);
34
+ }
35
+ function valueSymbol(node) {
36
+ const parent = node.getParent();
37
+ return Node.isShorthandPropertyAssignment(parent) ? parent.getValueSymbol() : node.getSymbol();
38
+ }
39
+ /** Bare blocks and counting-for initializers lose their braces in extraction.
40
+ * Branch blocks keep separate arms but can absorb their parent's continuation.
41
+ * `mayCapture` marks a scope that can therefore reach names outside the
42
+ * function. Loop and lambda scopes remain barriers; siblings there need no
43
+ * rename, but a binding that shadows an enclosing one always gets one. */
44
+ function loweredScope(decl) {
45
+ let scope = scopeOf(decl);
46
+ let mayCapture = Node.isForStatement(scope) || Node.isCaseBlock(scope);
47
+ if (Node.isForStatement(scope))
48
+ scope = scopeOf(scope);
49
+ while (Node.isBlock(scope) && Node.isBlock(scope.getParent())) {
50
+ mayCapture = true;
51
+ scope = scope.getParentOrThrow();
52
+ }
53
+ const parent = scope.getParent();
54
+ if (parent && (Node.isIfStatement(parent) || Node.isCaseClause(parent) || Node.isDefaultClause(parent)))
55
+ mayCapture = true;
56
+ return { scope, mayCapture };
57
+ }
58
+ /** After extraction no binding in a function shadows another: a local, loop
59
+ * variable, or callback parameter that reuses an enclosing name is renamed.
60
+ * Later passes may therefore identify a variable by its name alone.
61
+ * Allocate before extracting any expressions, without mutating the TS tree.
62
+ * Unambiguous locals and public parameter names keep their existing spelling. */
63
+ export class LexicalNames {
64
+ renamed = new Map();
65
+ used = new Set();
66
+ sourceNames;
67
+ taken;
68
+ ghosts = new Map();
69
+ aliases = new Map();
70
+ constructor(root) {
71
+ this.sourceNames = new Set(root.getDescendantsOfKind(SyntaxKind.Identifier).map(i => i.getText()));
72
+ // Include spec-only identifiers, including quantifier and ghost binders.
73
+ // A fresh source name must not capture one when annotations are rewritten.
74
+ const specNames = (root.getFullText().match(/\/\/@[^\r\n]*/g) ?? [])
75
+ .flatMap(comment => comment.match(/[A-Za-z_]\w*/g) ?? []);
76
+ this.taken = new Set([...this.sourceNames, ...specNames]);
77
+ // Names bound outside the function. A scope that keeps its braces cannot
78
+ // capture a library global, so only this file's own declarations count there.
79
+ const outer = new Set(), moduleNames = new Set();
80
+ const file = root.getSourceFile();
81
+ for (const symbol of root.getSymbolsInScope(ts.SymbolFlags.Value)) {
82
+ const declarations = symbol.getDeclarations();
83
+ if (declarations.some(d => d.getAncestors().includes(root)))
84
+ continue;
85
+ outer.add(symbol.getName());
86
+ if (declarations.some(d => d.getSourceFile() === file))
87
+ moduleNames.add(symbol.getName());
88
+ }
89
+ const locals = [];
90
+ // Prefer enclosing locals even if they occur later in source order. This
91
+ // also preserves the existing names of counters hoisted out of for-loops.
92
+ // Callback parameters are bindings too; the function's own stay public.
93
+ const declarations = [...root.getDescendantsOfKind(SyntaxKind.VariableDeclaration),
94
+ ...root.getDescendantsOfKind(SyntaxKind.Parameter).filter(p => {
95
+ const owner = p.getParent();
96
+ return owner !== root && functionLike(owner);
97
+ })].sort((a, b) => scopeOf(a).getAncestors().length - scopeOf(b).getAncestors().length || a.getStart() - b.getStart());
98
+ for (const decl of declarations) {
99
+ const owner = Node.isParameterDeclaration(decl) ? decl.getParent() : undefined;
100
+ for (const id of bindings(decl.getNameNode())) {
101
+ const name = id.getText();
102
+ const { scope, mayCapture } = loweredScope(decl);
103
+ const parameterClash = decl.getAncestors().some(a => a !== owner && functionLike(a)
104
+ && a.getChildrenOfKind(SyntaxKind.Parameter).some(p => bindings(p.getNameNode()).some(b => b.getText() === name)));
105
+ const symbol = id.getSymbol();
106
+ const localClash = locals.some(l => l.name === name && (l.scope === scope || scope.getAncestors().includes(l.scope)));
107
+ let emitted = name;
108
+ if (symbol && ((mayCapture ? outer : moduleNames).has(name) || parameterClash || localClash
109
+ || (owner && receiverMentions(owner, name)))) {
110
+ const fresh = this.fresh(name);
111
+ emitted = fresh;
112
+ this.renamed.set(symbol.compilerSymbol, fresh);
113
+ this.aliases.set(name, [...this.aliases.get(name) ?? [], fresh]);
114
+ }
115
+ locals.push({ name: emitted, scope });
116
+ this.used.add(name);
117
+ }
118
+ }
119
+ }
120
+ fresh(base) {
121
+ let suffix = 2;
122
+ while (this.taken.has(`${base}_${suffix}`))
123
+ suffix++;
124
+ const name = `${base}_${suffix}`;
125
+ this.taken.add(name);
126
+ reserveName(name);
127
+ return name;
128
+ }
129
+ name(node) {
130
+ if (Node.isIdentifier(node)) {
131
+ const symbol = valueSymbol(node);
132
+ return symbol && this.renamed.get(symbol.compilerSymbol) || node.getText();
133
+ }
134
+ // Assignment targets are still strings in Raw IR; rename their root only.
135
+ if (Node.isPropertyAccessExpression(node))
136
+ return `${this.name(node.getExpression())}.${node.getName()}`;
137
+ return node.getText();
138
+ }
139
+ /** A local type override follows every renamed binding of that source name. */
140
+ typeNames(name) {
141
+ return [name, ...this.aliases.get(name) ?? []];
142
+ }
143
+ withScope(action) {
144
+ const outer = this.ghosts;
145
+ this.ghosts = new Map(outer);
146
+ try {
147
+ return action();
148
+ }
149
+ finally {
150
+ this.ghosts = outer;
151
+ }
152
+ }
153
+ ghost(name, location, pos) {
154
+ const emitted = this.used.has(name) || this.sourceNames.has(name) ? this.fresh(name) : name;
155
+ this.used.add(name);
156
+ reserveName(emitted);
157
+ this.ghosts.set(name, { name: emitted, scope: scopeOf(location), pos });
158
+ return emitted;
159
+ }
160
+ specName(name, location, pos = location.getStart()) {
161
+ // `_x_idx` is the position of for-of variable `x`; it follows x's rename.
162
+ const index = /^_(.+)_idx$/.exec(name);
163
+ if (index && !this.sourceNames.has(name))
164
+ return `_${this.specName(index[1], location, pos)}_idx`;
165
+ // Leading comments belong to the statement's enclosing scope, including
166
+ // when the statement itself is a block or another loop.
167
+ const symbol = location.getProject().getTypeChecker().resolveName(name, location.getParent(), ts.SymbolFlags.Value, false);
168
+ const ghost = this.ghosts.get(name);
169
+ if (ghost) {
170
+ // A nested source binding shadows an outer ghost in specs. In the same
171
+ // scope, the most recent declaration wins. Runtime reads always use the
172
+ // TS symbol, never this separate ghost environment.
173
+ const shadowed = symbol?.getDeclarations().some(d => {
174
+ const scope = scopeOf(d);
175
+ return scope === ghost.scope ? d.getStart() > ghost.pos && d.getStart() < pos
176
+ : scope.getAncestors().includes(ghost.scope);
177
+ });
178
+ if (!shadowed)
179
+ return ghost.name;
180
+ }
181
+ return symbol && this.renamed.get(symbol.compilerSymbol) || name;
182
+ }
183
+ spec(text, location, pos) {
184
+ if (this.renamed.size === 0 && this.ghosts.size === 0)
185
+ return text;
186
+ return renameSpecVariables(text, name => this.specName(name, location, pos));
187
+ }
188
+ }
189
+ /** Backend lambdas cannot capture a local that is declared later. Checking
190
+ * symbols here avoids silently binding the closure to an outer namesake.
191
+ * Callback parameter defaults have their own initialization model in resolve. */
192
+ export function rejectForwardLocalCaptures(arrow) {
193
+ const body = arrow.getBody();
194
+ const identifiers = Node.isIdentifier(body) ? [body] : body.getDescendantsOfKind(SyntaxKind.Identifier);
195
+ for (const id of identifiers) {
196
+ if (id.getAncestors().some(n => ts.isTypeNode(n.compilerNode)))
197
+ continue;
198
+ for (const binding of valueSymbol(id)?.getDeclarations() ?? []) {
199
+ const decl = Node.isVariableDeclaration(binding) ? binding
200
+ : Node.isBindingElement(binding) ? binding.getFirstAncestorByKind(SyntaxKind.VariableDeclaration) : undefined;
201
+ if (!decl || decl.getStart() <= arrow.getStart() || decl.getAncestors().includes(arrow))
202
+ continue;
203
+ const list = decl.getParent();
204
+ if (!Node.isVariableDeclarationList(list) || list.getDeclarationKind() === "var")
205
+ continue;
206
+ if (Node.isSourceFile(scopeOf(decl)))
207
+ continue;
208
+ throw new Error(`Unsupported forward capture '${id.getText()}' at line ${arrow.getStartLineNumber()}: `
209
+ + `closure captures a local declared later at line ${decl.getStartLineNumber()}`);
210
+ }
211
+ }
212
+ }
package/tools/dist/lsc.js CHANGED
@@ -387,18 +387,18 @@ function runFile(cmd, filePath, backend, timeLimit, extraFlags, noVerify = false
387
387
  ? new RunLog({ logDir: resolveLogDir(absPath, configFile), cmd: logCmd, sourcePath: absPath, extraFlags, lscVersion: safely(lscVersion) })
388
388
  : undefined;
389
389
  if (cmd === "gen") {
390
- dafnyGen(genPath, dfyPath, text);
390
+ dafnyGen(genPath, dfyPath, text, basePath);
391
391
  return;
392
392
  }
393
393
  if (cmd === "gen-check") {
394
- dafnyGen(genPath, dfyPath, text);
395
- if (!dafnyCheckDiff(genPath, dfyPath))
394
+ dafnyGen(genPath, dfyPath, text, basePath);
395
+ if (!dafnyCheckDiff(genPath, dfyPath, undefined, basePath))
396
396
  process.exit(1);
397
397
  return;
398
398
  }
399
399
  if (cmd === "check") {
400
- dafnyGen(genPath, dfyPath, text);
401
- if (!dafnyCheckDiff(genPath, dfyPath, log))
400
+ dafnyGen(genPath, dfyPath, text, basePath);
401
+ if (!dafnyCheckDiff(genPath, dfyPath, log, basePath))
402
402
  process.exit(1);
403
403
  if (!dafnyVerify(dfyPath, artifactDir, timeLimit, extraFlags, log))
404
404
  process.exit(1);
@@ -31,6 +31,10 @@ let _userNames = new Set();
31
31
  export function setUserNames(names) {
32
32
  _userNames = names;
33
33
  }
34
+ /** A renamed source/ghost binding must also be avoided by later passes. */
35
+ export function reserveName(name) {
36
+ _userNames.add(name);
37
+ }
34
38
  export function isUserName(name) {
35
39
  return _userNames.has(name);
36
40
  }
@@ -248,6 +248,7 @@ function rewriteChildrenExpr(e) {
248
248
  case "toInt": return { ...e, expr: r(e.expr) };
249
249
  case "toReal": return { ...e, expr: r(e.expr) };
250
250
  case "index": return { ...e, arr: r(e.arr), idx: r(e.idx) };
251
+ case "stringIndex": return { ...e, str: r(e.str), idx: r(e.idx) };
251
252
  case "tupleLiteral": return { ...e, elems: e.elems.map(r) };
252
253
  case "tupleProj": return { ...e, obj: r(e.obj) };
253
254
  case "record": return { ...e, spread: e.spread ? r(e.spread) : null,
@@ -24,6 +24,14 @@ function lookup(env, name) {
24
24
  function extend(env, name, ty) {
25
25
  return { name, ty, parent: env };
26
26
  }
27
+ /** A quantified variable that reuses the name of a binding in scope is emitted
28
+ * under a fresh name, so no later pass confuses it with that binding. */
29
+ function quantified(env, name, ty) {
30
+ const frame = extend(env, name, ty);
31
+ if (binding(env, name))
32
+ frame.emittedName = freshName(name);
33
+ return frame;
34
+ }
27
35
  /** Shadow a binding with a narrowed type, keeping its callback state.
28
36
  * Dropping that state would let the body reference a renamed parameter by its
29
37
  * source name, which can silently bind an outer variable. The spread is exact
@@ -91,16 +99,21 @@ function conditionalResultTy(thenTy, elseTy) {
91
99
  }
92
100
  return ty;
93
101
  }
94
- /** Contextually type string literals as constructors. Ternary branches inherit
102
+ /** Contextually type string literals as string-union constructors. Ternary branches inherit
95
103
  * the ternary's target, and an optional target contributes its payload type —
96
104
  * the caller adds the Some wrapper only after the payload has been coerced. */
97
- function coerceStr(expr, targetTy) {
105
+ function coerceStr(expr, targetTy, typeDecls) {
98
106
  const payloadTy = targetTy.kind === "optional" ? targetTy.inner : targetTy;
99
- if (expr.kind === "str" && payloadTy.kind === "user")
100
- return { ...expr, ty: payloadTy };
107
+ if (expr.kind === "str" && payloadTy.kind === "user") {
108
+ const enumTy = expandAlias(payloadTy, typeDecls);
109
+ // A synthesized string/array union has a string payload, not a constructor
110
+ // for each literal. Leave it for coerceToTargetTy to inject into its branch.
111
+ if (enumTy.kind === "user" && declOfDotted(typeDecls, enumTy.name)?.kind === "string-union")
112
+ return { ...expr, ty: payloadTy };
113
+ }
101
114
  if (expr.kind === "conditional") {
102
- const then_ = coerceStr(expr.then, payloadTy);
103
- const else_ = coerceStr(expr.else, payloadTy);
115
+ const then_ = coerceStr(expr.then, payloadTy, typeDecls);
116
+ const else_ = coerceStr(expr.else, payloadTy, typeDecls);
104
117
  return { ...expr, then: then_, else: else_, ty: conditionalResultTy(then_.ty, else_.ty) };
105
118
  }
106
119
  return expr;
@@ -128,7 +141,7 @@ function findSynthArrayUnion(name, typeDecls) {
128
141
  * Returns `value` unchanged if no coercion applies (types already match,
129
142
  * source is unknown, or no rule matches). */
130
143
  function coerceToTargetTy(value, targetTy, typeDecls) {
131
- value = coerceStr(value, targetTy);
144
+ value = coerceStr(value, targetTy, typeDecls);
132
145
  // Real targets also type integer literals, including negative literals and
133
146
  // conditional arms. Coerce optional payloads before adding Some wrappers.
134
147
  const payloadTy = targetTy.kind === "optional" ? targetTy.inner : targetTy;
@@ -151,6 +164,8 @@ function coerceToTargetTy(value, targetTy, typeDecls) {
151
164
  return wrapSome(value, targetTy);
152
165
  }
153
166
  if (targetTy.kind === "user") {
167
+ if (value.ty.kind === "user" && value.ty.name === targetTy.name)
168
+ return value;
154
169
  const synth = findSynthArrayUnion(targetTy.name, typeDecls);
155
170
  if (synth && synth.variants && synth.variants.length === 2) {
156
171
  const arrVariant = synth.variants.find(v => v.name === "ArrayBranch");
@@ -785,6 +800,41 @@ function coerceCallArgs(args, fn, ctx) {
785
800
  }
786
801
  return args;
787
802
  }
803
+ /** Join Math.min/max operands without losing bigint or depending on their order. */
804
+ function minMaxNumericTy(types, name) {
805
+ for (const ty of types) {
806
+ if (isBigInt(ty))
807
+ throw new Error(`${name} does not accept bigint operands (JavaScript throws TypeError)`);
808
+ if (ty.kind !== "int" && ty.kind !== "nat" && ty.kind !== "real")
809
+ throw new Error(`${name} requires numeric operands, got ${tyToCanonical(ty)}`);
810
+ }
811
+ return types.some(ty => ty.kind === "real") ? { kind: "real" }
812
+ : types.length > 0 && types.every(ty => ty.kind === "nat") ? { kind: "nat" } : { kind: "int" };
813
+ }
814
+ /** Resolve the concat tree built by extract for Math.min/max spreads. Numeric
815
+ * literal segments are sequences even when their elements mix int/nat/real;
816
+ * ordinary array inference would turn those into heterogeneous tuples.
817
+ * Empty literals contribute no operand type to the surrounding concat. */
818
+ function resolveMinMaxSequence(raw, ctx, name) {
819
+ if (raw.kind === "binop" && raw.op === "arrayConcat") {
820
+ const left = resolveMinMaxSequence(raw.left, ctx, name);
821
+ const right = resolveMinMaxSequence(raw.right, ctx, name);
822
+ const types = [...left.types, ...right.types];
823
+ return { expr: { kind: "binop", op: "arrayConcat", left: left.expr, right: right.expr,
824
+ ty: { kind: "array", elem: minMaxNumericTy(types, name) } }, types };
825
+ }
826
+ if (raw.kind === "arrayLiteral") {
827
+ const elems = raw.elems.map(e => resolveExpr(e, ctx));
828
+ const types = elems.map(e => e.ty);
829
+ return { expr: { kind: "arrayLiteral", elems,
830
+ ty: { kind: "array", elem: minMaxNumericTy(types, name) } }, types };
831
+ }
832
+ const expr = resolveExpr(raw, ctx);
833
+ if (expr.ty.kind !== "array")
834
+ throw new Error(`${name} spread requires a numeric array`);
835
+ minMaxNumericTy([expr.ty.elem], name);
836
+ return { expr, types: [expr.ty.elem] };
837
+ }
788
838
  /** Infer return type for collection/string method calls. */
789
839
  function inferMethodReturnTy(fn, args, ctx) {
790
840
  if (fn.kind !== "field")
@@ -807,8 +857,15 @@ function inferMethodReturnTy(fn, args, ctx) {
807
857
  if (fn.obj.kind === "var" && fn.obj.name === "Math") {
808
858
  if (fn.field === "abs" && args.length === 1)
809
859
  return args[0].ty;
810
- if ((fn.field === "min" || fn.field === "max") && args.length >= 1)
811
- return args.some(a => a.ty.kind === "real") ? { kind: "real" } : args[0].ty;
860
+ if (fn.field === "min" || fn.field === "max") {
861
+ if (args.length === 0)
862
+ throw new Error(`Math.${fn.field}() with zero arguments returns ${fn.field === "max" ? "-Infinity" : "Infinity"}, which is not supported by the numeric model`);
863
+ return minMaxNumericTy(args.map(a => a.ty), `Math.${fn.field}`);
864
+ }
865
+ // trunc/round are the identity on an integer, so a nat argument stays nat.
866
+ if ((fn.field === "trunc" || fn.field === "round") && args.length === 1 &&
867
+ args[0].ty.kind === "nat")
868
+ return { kind: "nat" };
812
869
  if (["floor", "ceil", "round", "trunc"].includes(fn.field))
813
870
  return { kind: "int" };
814
871
  }
@@ -1009,8 +1066,8 @@ function resolveExprInner(e, ctx) {
1009
1066
  }
1010
1067
  let right = resolveExpr(rawRight, rightCtx);
1011
1068
  if (e.op === "===" || e.op === "!==") {
1012
- left = coerceStr(left, right.ty);
1013
- right = coerceStr(right, left.ty);
1069
+ left = coerceStr(left, right.ty, ctx.typeDecls);
1070
+ right = coerceStr(right, left.ty, ctx.typeDecls);
1014
1071
  // Spec (`//@`) comparisons are proof-only, so they can't diverge at
1015
1072
  // runtime; only warn on executable code.
1016
1073
  if (!ctx.inSpec && refEqHazard(left.ty, ctx.typeDecls) && refEqHazard(right.ty, ctx.typeDecls)) {
@@ -1049,6 +1106,19 @@ function resolveExprInner(e, ctx) {
1049
1106
  return { kind: "unop", op: e.op, expr, ty };
1050
1107
  }
1051
1108
  case "call": {
1109
+ // Extract rewrites spread min/max calls to a single sequence argument.
1110
+ if (e.fn.kind === "var" && (e.fn.name === "MaxOfSeq" || e.fn.name === "MinOfSeq") && e.args.length === 1) {
1111
+ const name = e.fn.name === "MaxOfSeq" ? "Math.max" : "Math.min";
1112
+ const { expr, types } = resolveMinMaxSequence(e.args[0], ctx, name);
1113
+ // Integral spreads retain the existing int helper/result, including
1114
+ // empty literals (whose nonemptiness obligation will fail verification).
1115
+ const ty = minMaxNumericTy(types, name).kind === "real" ? { kind: "real" } : { kind: "int" };
1116
+ // Integral helpers keep their historical call classification so method
1117
+ // temporaries in existing proof files remain byte-identical. Real calls
1118
+ // use the specialized lowering that promotes their sequence segments.
1119
+ return { kind: "call", fn: { kind: "var", name: e.fn.name, ty: { kind: "unknown" } },
1120
+ args: [expr], ty, callKind: ty.kind === "real" ? "pure" : classifyCall(e.fn, ctx) };
1121
+ }
1052
1122
  // perm(a, b): spec-only permutation predicate — true iff `a` and `b` are
1053
1123
  // reorderings of each other (equal as multisets). Lowers to the `Perm`
1054
1124
  // preamble (Dafny `multiset(a) == multiset(b)`; Lean `a.toList ~ b.toList`).
@@ -1172,6 +1242,9 @@ function resolveExprInner(e, ctx) {
1172
1242
  if (obj.ty.kind === "array") {
1173
1243
  idxTy = obj.ty.elem;
1174
1244
  }
1245
+ else if (obj.ty.kind === "string") {
1246
+ idxTy = { kind: "string" };
1247
+ }
1175
1248
  else if (obj.ty.kind === "tuple") {
1176
1249
  // Tuple projection: the position must be a literal — a tuple has a
1177
1250
  // distinct type per slot, so a runtime index has no single result type
@@ -1271,8 +1344,9 @@ function resolveExprInner(e, ctx) {
1271
1344
  else if (step.kind === "index") {
1272
1345
  const idx = resolveExpr(step.idx, ctx);
1273
1346
  const idxTy = stepInTy.kind === "array" ? stepInTy.elem
1274
- : stepInTy.kind === "map" ? { kind: "optional", inner: stepInTy.value }
1275
- : { kind: "unknown" };
1347
+ : stepInTy.kind === "string" ? { kind: "string" }
1348
+ : stepInTy.kind === "map" ? { kind: "optional", inner: stepInTy.value }
1349
+ : { kind: "unknown" };
1276
1350
  chain.push({ kind: "index", idx, ty: idxTy });
1277
1351
  stepInTy = idxTy;
1278
1352
  }
@@ -1317,7 +1391,10 @@ function resolveExprInner(e, ctx) {
1317
1391
  }
1318
1392
  case "record": {
1319
1393
  const spread = e.spread ? resolveExpr(e.spread, ctx) : null;
1320
- const ty = spread ? spread.ty : { kind: "unknown" };
1394
+ const asserted = e.assertedTsType && expandAlias(parseTsType(e.assertedTsType), ctx.typeDecls);
1395
+ const assertedUnion = asserted && asserted.kind === "user" &&
1396
+ declOfKind(ctx.typeDecls, asserted.name, "discriminated-union");
1397
+ const ty = spread ? spread.ty : assertedUnion ? asserted : { kind: "unknown" };
1321
1398
  // Record literal in map-typed context (e.g. `const M: Record<string, V> = {a: ...}`):
1322
1399
  // attach the map type so transform/emit can produce a map literal.
1323
1400
  if (!spread && ctx.returnTy.kind === "map") {
@@ -1387,12 +1464,14 @@ function resolveExprInner(e, ctx) {
1387
1464
  case "forall": {
1388
1465
  const varTy = e.varType !== "int" ? parseTsType(e.varType)
1389
1466
  : inferQuantVarType(e.var, e.body, ctx) ?? { kind: "int" };
1390
- return { kind: "forall", var: e.var, varTy, body: resolveExpr(e.body, withEnv(ctx, extend(ctx.env, e.var, varTy))), ty: { kind: "bool" } };
1467
+ const bound = quantified(ctx.env, e.var, varTy);
1468
+ return { kind: "forall", var: bound.emittedName ?? e.var, varTy, body: resolveExpr(e.body, withEnv(ctx, bound)), ty: { kind: "bool" } };
1391
1469
  }
1392
1470
  case "exists": {
1393
1471
  const varTy = e.varType !== "int" ? parseTsType(e.varType)
1394
1472
  : inferQuantVarType(e.var, e.body, ctx) ?? { kind: "int" };
1395
- return { kind: "exists", var: e.var, varTy, body: resolveExpr(e.body, withEnv(ctx, extend(ctx.env, e.var, varTy))), ty: { kind: "bool" } };
1473
+ const bound = quantified(ctx.env, e.var, varTy);
1474
+ return { kind: "exists", var: bound.emittedName ?? e.var, varTy, body: resolveExpr(e.body, withEnv(ctx, bound)), ty: { kind: "bool" } };
1396
1475
  }
1397
1476
  case "arrayLiteral": {
1398
1477
  // Expected-tuple context: type each element against its own slot type and
@@ -1487,8 +1566,8 @@ function resolveExprInner(e, ctx) {
1487
1566
  elseCtx = withInAtoms(elseCtx, extractInAtomsNegated(cond));
1488
1567
  let then_ = resolveExpr(e.then, thenCtx);
1489
1568
  let else_ = resolveExpr(e.else, elseCtx);
1490
- then_ = coerceStr(then_, else_.ty);
1491
- else_ = coerceStr(else_, then_.ty);
1569
+ then_ = coerceStr(then_, else_.ty, ctx.typeDecls);
1570
+ else_ = coerceStr(else_, then_.ty, ctx.typeDecls);
1492
1571
  const ty = conditionalResultTy(then_.ty, else_.ty);
1493
1572
  return { kind: "conditional", cond, then: then_, else: else_, ty };
1494
1573
  }
@@ -1586,7 +1665,7 @@ function resolveStmt(s, ctx) {
1586
1665
  // one optional level when consulting returnTy.
1587
1666
  const initCtx = (declTy.kind === "user" || declTy.kind === "array" || declTy.kind === "optional")
1588
1667
  ? { ...ctx, returnTy: declTy } : ctx;
1589
- let init = coerceStr(resolveExpr(s.init, initCtx), declTy);
1668
+ let init = coerceStr(resolveExpr(s.init, initCtx), declTy, ctx.typeDecls);
1590
1669
  // Under noUncheckedIndexedAccess, TS gives `const e = arr[i]` type T | undefined
1591
1670
  // while the index expression itself resolves to T. Leave that mismatch intact:
1592
1671
  // narrow.ts's ruleOptionalIndexBinding adds the runtime bounds guard and the
@@ -1711,16 +1790,19 @@ function resolveStmt(s, ctx) {
1711
1790
  for (const _ of s.names)
1712
1791
  nameTypes.push({ kind: "unknown" });
1713
1792
  }
1714
- // Must match the freshened counter transform mints for this loop, so a
1715
- // spec referencing the loop index resolves to the same name.
1716
- const idxName = freshName(`_${s.names[0]}_idx`);
1793
+ // The loop counter is minted here, once, and recorded on the loop so
1794
+ // transform emits the same name a spec here refers to. The first loop
1795
+ // over a head name in a function gets `_x_idx`, later ones `_x_idx2`, ….
1796
+ const count = ctx.forofCounts.get(s.names[0]) ?? 0;
1797
+ ctx.forofCounts.set(s.names[0], count + 1);
1798
+ const idxName = freshName(`_${s.names[0]}_idx${count === 0 ? "" : count + 1}`);
1717
1799
  env = extend(env, idxName, { kind: "nat" });
1718
1800
  for (let j = 0; j < s.names.length; j++) {
1719
1801
  env = extend(env, s.names[j], nameTypes[j] ?? { kind: "unknown" });
1720
1802
  }
1721
1803
  const bodyCtx = withEnv(ctx, env);
1722
1804
  return [{
1723
- kind: "forof", names: s.names, nameTypes, iterable,
1805
+ kind: "forof", names: s.names, nameTypes, iterable, idx: idxName,
1724
1806
  invariants: resolveSpecs(s.invariants, { ...bodyCtx, inSpec: true }),
1725
1807
  doneWith: s.doneWith ? resolveSpec(s.doneWith, { ...bodyCtx, inSpec: true }) : null,
1726
1808
  body: resolveBlock(s.body, bodyCtx),
@@ -1963,7 +2045,7 @@ function resolveFunction(fn, typeDecls, pureFns, fnParams = new Map(), fnReturns
1963
2045
  env = extend(env, opts.thisBinding.name, opts.thisBinding.ty);
1964
2046
  for (const p of params)
1965
2047
  env = extend(env, p.name, p.ty);
1966
- const baseCtx = { env, typeDecls, overrides, allowResult: false, returnTy, pureFns, fnParams, fnReturns, externs, inSpec: false, inLambda: false, narrowedPaths: [], narrowedIndices: [] };
2048
+ const baseCtx = { env, typeDecls, overrides, allowResult: false, returnTy, pureFns, fnParams, fnReturns, externs, inSpec: false, inLambda: false, narrowedPaths: [], narrowedIndices: [], forofCounts: new Map() };
1967
2049
  const requiresCtx = { ...baseCtx, inSpec: true };
1968
2050
  const ensuresCtx = { ...baseCtx, env: extend(env, "\\result", returnTy), allowResult: true, inSpec: true };
1969
2051
  // Apply type parameter constraints from //@ type T (==) annotations
@@ -2070,7 +2152,7 @@ export function resolveModule(raw) {
2070
2152
  for (let i = 0; i < ext.params.length; i++) {
2071
2153
  env = extend(env, ext.params[i].name, sig.params[i]);
2072
2154
  }
2073
- const baseCtx = { env, typeDecls: raw.typeDecls, overrides: new Map(), allowResult: false, returnTy: sig.returnTy, pureFns, fnParams, fnReturns, externs, inSpec: true, inLambda: false, narrowedPaths: [], narrowedIndices: [] };
2155
+ const baseCtx = { env, typeDecls: raw.typeDecls, overrides: new Map(), allowResult: false, returnTy: sig.returnTy, pureFns, fnParams, fnReturns, externs, inSpec: true, inLambda: false, narrowedPaths: [], narrowedIndices: [], forofCounts: new Map() };
2074
2156
  const ensuresCtx = { ...baseCtx, env: extend(env, "\\result", sig.returnTy), allowResult: true };
2075
2157
  const resolveClauses = (kind, ctx) => ext[kind].map(s => {
2076
2158
  try {
@@ -2092,7 +2174,7 @@ export function resolveModule(raw) {
2092
2174
  impure: ext.impure,
2093
2175
  };
2094
2176
  });
2095
- const emptyCtx = { env: null, typeDecls: raw.typeDecls, overrides: new Map(), allowResult: false, returnTy: { kind: "int" }, pureFns, fnParams, fnReturns, externs, inSpec: false, inLambda: false, narrowedPaths: [], narrowedIndices: [] };
2177
+ const emptyCtx = { env: null, typeDecls: raw.typeDecls, overrides: new Map(), allowResult: false, returnTy: { kind: "int" }, pureFns, fnParams, fnReturns, externs, inSpec: false, inLambda: false, narrowedPaths: [], narrowedIndices: [], forofCounts: new Map() };
2096
2178
  const constants = (raw.constants ?? []).map(c => {
2097
2179
  const declaredTy = expandAlias(parseTsType(c.tsType), raw.typeDecls);
2098
2180
  // Propagate the declared type into the value's resolution context so that