lemmascript 0.6.7 → 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/README.md +10 -0
- package/package.json +5 -2
- 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 +47 -9
- package/tools/dist/guard-command.js +36 -0
- package/tools/dist/ir.js +2 -0
- package/tools/dist/lean-emit.js +6 -5
- package/tools/dist/lsc.js +13 -0
- 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/tools/dist/resolve.js
CHANGED
|
@@ -8,9 +8,14 @@ import { isBigInt, tyEqual, isTerminatorKind } from "./typedir.js";
|
|
|
8
8
|
import { parseTsType, tyToCanonical } from "./types.js";
|
|
9
9
|
import { parseExpr } from "./specparser.js";
|
|
10
10
|
import { freshName } from "./names.js";
|
|
11
|
-
import { recognizeBuiltin, builtinSpec } from "./builtins.js";
|
|
11
|
+
import { recognizeBuiltin, builtinSpec, callbackArgumentTypes, callbackBaseArity } from "./builtins.js";
|
|
12
12
|
import { declOf, declOfKind, declOfDotted, declOfTy, tyBaseName } from "./typedecls.js";
|
|
13
13
|
import { presentFact, variantFact } from "./condition-facts.js";
|
|
14
|
+
function binding(env, name) {
|
|
15
|
+
if (!env)
|
|
16
|
+
return undefined;
|
|
17
|
+
return env.name === name ? env : binding(env.parent, name);
|
|
18
|
+
}
|
|
14
19
|
function lookup(env, name) {
|
|
15
20
|
if (!env)
|
|
16
21
|
return undefined;
|
|
@@ -19,14 +24,23 @@ function lookup(env, name) {
|
|
|
19
24
|
function extend(env, name, ty) {
|
|
20
25
|
return { name, ty, parent: env };
|
|
21
26
|
}
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
27
|
+
/** Shadow a binding with a narrowed type, keeping its callback state.
|
|
28
|
+
* Dropping that state would let the body reference a renamed parameter by its
|
|
29
|
+
* source name, which can silently bind an outer variable. The spread is exact
|
|
30
|
+
* because refine always follows a read of the same variable, and that read is
|
|
31
|
+
* what sets `emittedName`; the `argumentPack`/`value` getters are evaluated
|
|
32
|
+
* once, but they belong to rest and beyond-arity frames, whose types (`unknown`,
|
|
33
|
+
* `void`) are never narrowed. */
|
|
34
|
+
function refine(env, name, ty) {
|
|
35
|
+
let entry = binding(env, name);
|
|
36
|
+
if (!entry)
|
|
37
|
+
for (let e = env; e; e = e.parent) {
|
|
38
|
+
if (e.emittedName === name) {
|
|
39
|
+
entry = e;
|
|
40
|
+
break;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return { ...entry, name: entry?.name ?? name, ty, parent: env };
|
|
30
44
|
}
|
|
31
45
|
function asRawAccessPath(e) {
|
|
32
46
|
if (e.kind === "var")
|
|
@@ -106,8 +120,8 @@ function findSynthArrayUnion(name, typeDecls) {
|
|
|
106
120
|
return decl;
|
|
107
121
|
return null;
|
|
108
122
|
}
|
|
109
|
-
/** Coerce `value` to `targetTy` at an assignment-position.
|
|
110
|
-
* for the
|
|
123
|
+
/** Coerce `value` to `targetTy` at an assignment-position. Contextually types
|
|
124
|
+
* real literals, then mirrors TS subtyping for the upcast shapes LS synthesizes:
|
|
111
125
|
* - `T` into `optional<T>` slot → wrap with `Some(...)`
|
|
112
126
|
* - `T[]` into a synth `T[] | U` slot → wrap with `ArrayBranch(...)`
|
|
113
127
|
* - `U` into a synth `T[] | U` slot → wrap with `NonArrayBranch(...)`
|
|
@@ -115,6 +129,22 @@ function findSynthArrayUnion(name, typeDecls) {
|
|
|
115
129
|
* source is unknown, or no rule matches). */
|
|
116
130
|
function coerceToTargetTy(value, targetTy, typeDecls) {
|
|
117
131
|
value = coerceStr(value, targetTy);
|
|
132
|
+
// Real targets also type integer literals, including negative literals and
|
|
133
|
+
// conditional arms. Coerce optional payloads before adding Some wrappers.
|
|
134
|
+
const payloadTy = targetTy.kind === "optional" ? targetTy.inner : targetTy;
|
|
135
|
+
if (payloadTy.kind === "real") {
|
|
136
|
+
if (value.kind === "num") {
|
|
137
|
+
value = { ...value, ty: payloadTy };
|
|
138
|
+
}
|
|
139
|
+
else if (value.kind === "unop" && value.op === "-" && value.expr.kind === "num") {
|
|
140
|
+
value = { ...value, expr: { ...value.expr, ty: payloadTy }, ty: payloadTy };
|
|
141
|
+
}
|
|
142
|
+
else if (value.kind === "conditional") {
|
|
143
|
+
const then_ = coerceToTargetTy(value.then, payloadTy, typeDecls);
|
|
144
|
+
const else_ = coerceToTargetTy(value.else, payloadTy, typeDecls);
|
|
145
|
+
value = { ...value, then: then_, else: else_, ty: conditionalResultTy(then_.ty, else_.ty) };
|
|
146
|
+
}
|
|
147
|
+
}
|
|
118
148
|
if (value.ty.kind === "unknown" || value.ty.kind === "void")
|
|
119
149
|
return value;
|
|
120
150
|
if (targetTy.kind === "optional" && value.ty.kind !== "optional") {
|
|
@@ -239,7 +269,7 @@ function collectAndChainNarrowings(cond, ctx) {
|
|
|
239
269
|
const f = presentFact(cond);
|
|
240
270
|
if (f && !f.negated) {
|
|
241
271
|
if (f.scrutinee.kind === "var") {
|
|
242
|
-
return withEnv(ctx,
|
|
272
|
+
return withEnv(ctx, refine(ctx.env, f.scrutinee.name, f.innerTy));
|
|
243
273
|
}
|
|
244
274
|
const path = asTExprAccessPath(f.scrutinee);
|
|
245
275
|
if (path) {
|
|
@@ -472,12 +502,16 @@ function inferQuantVarType(varName, body, ctx) {
|
|
|
472
502
|
return null;
|
|
473
503
|
}
|
|
474
504
|
function classifyCall(fn, ctx) {
|
|
505
|
+
if (fn.kind === "var" && binding(ctx.env, fn.name))
|
|
506
|
+
return lookup(ctx.env, fn.name)?.kind === "fn" ? "pure" : "method";
|
|
475
507
|
if (fn.kind === "field" && fn.obj.kind === "var" && fn.obj.name === "Math")
|
|
476
508
|
return "pure";
|
|
477
509
|
if (fn.kind === "field" && fn.obj.kind === "var" && fn.obj.name === "Array" && fn.field === "isArray")
|
|
478
510
|
return "pure";
|
|
479
511
|
if (fn.kind === "field" && fn.obj.kind === "var" && fn.obj.name === "String" && fn.field === "fromCharCode")
|
|
480
512
|
return "pure";
|
|
513
|
+
if (fn.kind === "field" && fn.obj.kind === "var" && fn.obj.name === "Number" && fn.field === "isSafeInteger")
|
|
514
|
+
return "pure";
|
|
481
515
|
if (fn.kind === "var" && (ctx.inSpec || ctx.inLambda) && ctx.pureFns.has(fn.name))
|
|
482
516
|
return "spec-pure";
|
|
483
517
|
// Effectively pure bare-name externs are function calls. Impure externs are
|
|
@@ -495,8 +529,6 @@ function classifyCall(fn, ctx) {
|
|
|
495
529
|
return "method";
|
|
496
530
|
}
|
|
497
531
|
}
|
|
498
|
-
if (fn.kind === "var" && lookup(ctx.env, fn.name)?.kind === "fn")
|
|
499
|
-
return "pure";
|
|
500
532
|
if (fn.kind === "var" && ctx.inSpec) {
|
|
501
533
|
// Not a known pure function — could be external (Lean-defined spec helper).
|
|
502
534
|
// Pass through as "pure" and let Lean catch any errors.
|
|
@@ -507,10 +539,7 @@ function classifyCall(fn, ctx) {
|
|
|
507
539
|
return "unknown";
|
|
508
540
|
}
|
|
509
541
|
// ── Call resolution helpers ─────────────────────────────────
|
|
510
|
-
/**
|
|
511
|
-
* AND from function-typed parameters of named callees (e.g., a `Comparator =
|
|
512
|
-
* (a, b) => bool` parameter propagates `string, string` to the lambda's
|
|
513
|
-
* inline params). Returns updated rawArgs with inferred tsType. */
|
|
542
|
+
/** Render a resolved type back to a TS type string, for lambda param inference. */
|
|
514
543
|
function tyToTsStr(ty) {
|
|
515
544
|
if (ty.kind === "user")
|
|
516
545
|
return ty.name;
|
|
@@ -528,46 +557,14 @@ function tyToTsStr(ty) {
|
|
|
528
557
|
}
|
|
529
558
|
return undefined;
|
|
530
559
|
}
|
|
560
|
+
/** Infer lambda param types from function-typed parameters of named callees
|
|
561
|
+
* (e.g., a `Comparator = (a, b) => bool` parameter propagates `string, string` to the lambda's
|
|
562
|
+
* inline params). Returns updated rawArgs with inferred tsType. */
|
|
531
563
|
function inferLambdaParamTypes(fn, rawArgs, ctx) {
|
|
532
|
-
const hofShape = fn.kind === "field"
|
|
533
|
-
? (id => id ? builtinSpec(id).hof?.shape : undefined)(recognizeBuiltin(fn.obj.ty, fn.field))
|
|
534
|
-
: undefined;
|
|
535
|
-
// sort's comparator takes two params, both the element type.
|
|
536
|
-
if (hofShape === "comparator" && fn.kind === "field" && fn.obj.ty.kind === "array" &&
|
|
537
|
-
rawArgs.length >= 1 && rawArgs[0].kind === "lambda" && rawArgs[0].params.length >= 1) {
|
|
538
|
-
const tsType = tyToTsStr(fn.obj.ty.elem);
|
|
539
|
-
if (tsType) {
|
|
540
|
-
const lam = rawArgs[0];
|
|
541
|
-
const updatedParams = lam.params.map(p => (p.tsType ? p : { ...p, tsType }));
|
|
542
|
-
return [{ ...lam, params: updatedParams }, ...rawArgs.slice(1)];
|
|
543
|
-
}
|
|
544
|
-
}
|
|
545
|
-
// reduce's callback is (acc, elem): acc from the init arg's type, elem from the array.
|
|
546
|
-
if (hofShape === "reduce" && fn.kind === "field" && fn.obj.ty.kind === "array" && ctx &&
|
|
547
|
-
rawArgs.length >= 2 && rawArgs[0].kind === "lambda" && rawArgs[0].params.length >= 2) {
|
|
548
|
-
const accTs = tyToTsStr(resolveExpr(rawArgs[1], ctx).ty);
|
|
549
|
-
const elemTs = tyToTsStr(fn.obj.ty.elem);
|
|
550
|
-
if (accTs && elemTs) {
|
|
551
|
-
const lam = rawArgs[0];
|
|
552
|
-
const updatedParams = lam.params.map((p, i) => p.tsType || i > 1 ? p : { ...p, tsType: i === 0 ? accTs : elemTs });
|
|
553
|
-
return [{ ...lam, params: updatedParams }, ...rawArgs.slice(1)];
|
|
554
|
-
}
|
|
555
|
-
}
|
|
556
|
-
if (hofShape === "unary" && fn.kind === "field" && fn.obj.ty.kind === "array" &&
|
|
557
|
-
rawArgs.length >= 1 && rawArgs[0].kind === "lambda" &&
|
|
558
|
-
rawArgs[0].params.length >= 1 && !rawArgs[0].params[0].tsType) {
|
|
559
|
-
const elemTy = fn.obj.ty.elem;
|
|
560
|
-
const tsType = tyToTsStr(elemTy);
|
|
561
|
-
if (tsType) {
|
|
562
|
-
const lam = rawArgs[0];
|
|
563
|
-
const updatedParams = [{ ...lam.params[0], tsType }, ...lam.params.slice(1)];
|
|
564
|
-
return [{ ...lam, params: updatedParams }, ...rawArgs.slice(1)];
|
|
565
|
-
}
|
|
566
|
-
}
|
|
567
564
|
// Named-callee propagation: when an argument position expects a function
|
|
568
565
|
// type, infer the lambda's param types from that function type. Aliases
|
|
569
566
|
// (e.g., `Comparator`) are expanded via the typeDecls.
|
|
570
|
-
if (fn.kind === "var" && ctx?.fnParams.has(fn.name)) {
|
|
567
|
+
if (fn.kind === "var" && ctx?.fnParams.has(fn.name) && !binding(ctx.env, fn.name)) {
|
|
571
568
|
const paramTys = ctx.fnParams.get(fn.name);
|
|
572
569
|
return rawArgs.map((a, i) => {
|
|
573
570
|
if (a.kind !== "lambda" || i >= paramTys.length)
|
|
@@ -588,6 +585,173 @@ function inferLambdaParamTypes(fn, rawArgs, ctx) {
|
|
|
588
585
|
}
|
|
589
586
|
return rawArgs;
|
|
590
587
|
}
|
|
588
|
+
let callbackCounter = 0;
|
|
589
|
+
function callbackDefaultState(ty, ctx, seen = new Set()) {
|
|
590
|
+
if (ty.kind === "void")
|
|
591
|
+
return "missing";
|
|
592
|
+
if (ty.kind === "optional" || ty.kind === "unknown")
|
|
593
|
+
return ty.kind;
|
|
594
|
+
if (ty.kind !== "user" || ty.name === "null")
|
|
595
|
+
return "defined";
|
|
596
|
+
if (seen.has(ty.name))
|
|
597
|
+
return "unknown";
|
|
598
|
+
const decl = declOfDotted(ctx.typeDecls, ty.name);
|
|
599
|
+
if (decl?.kind === "alias" && decl.aliasOfTy)
|
|
600
|
+
return callbackDefaultState(decl.aliasOfTy, ctx, new Set([...seen, ty.name]));
|
|
601
|
+
return decl && decl.kind !== "opaque" ? "defined" : "unknown";
|
|
602
|
+
}
|
|
603
|
+
/** Bind an inline callback against its actual JavaScript argument list.
|
|
604
|
+
* Rest is a symbolic argument pack: observing its length or a fixed position
|
|
605
|
+
* needs no heterogeneous array. Unobserved slots disappear without inspecting
|
|
606
|
+
* identifier spellings or dropping any source computation. */
|
|
607
|
+
function resolveCallback(e, actual, baseArity, ctx) {
|
|
608
|
+
const id = callbackCounter++;
|
|
609
|
+
const used = actual.map(() => false);
|
|
610
|
+
const defaults = actual.map(ty => callbackDefaultState(ty, ctx));
|
|
611
|
+
const slots = actual.map((ty, i) => {
|
|
612
|
+
const p = e.params[i];
|
|
613
|
+
return {
|
|
614
|
+
name: p && !p.rest && !(p.defaultValue && defaults[i] === "missing") ? p.name : freshName(`_callbackArg${id}_${i}`),
|
|
615
|
+
ty: p && !p.rest && p.tsType ? parseTsType(p.tsType)
|
|
616
|
+
: ty.kind === "nat" ? { ...ty, kind: "int" } : ty,
|
|
617
|
+
};
|
|
618
|
+
});
|
|
619
|
+
const read = (i) => {
|
|
620
|
+
if (i >= slots.length)
|
|
621
|
+
return { kind: "var", name: "undefined", ty: { kind: "void" } };
|
|
622
|
+
used[i] = true;
|
|
623
|
+
return { kind: "var", ...slots[i] };
|
|
624
|
+
};
|
|
625
|
+
const executesDefault = (i) => !!e.params[i].defaultValue &&
|
|
626
|
+
(i >= actual.length || defaults[i] === "missing");
|
|
627
|
+
const ready = new Set();
|
|
628
|
+
const eagerReads = new Set();
|
|
629
|
+
let captures;
|
|
630
|
+
const prefix = [];
|
|
631
|
+
const pending = new Map();
|
|
632
|
+
// All parameter names are in scope before any initializer. The frames are
|
|
633
|
+
// binding identities; nested declarations shadow them through ordinary lookup.
|
|
634
|
+
let env = ctx.env;
|
|
635
|
+
const frames = e.params.map((p, i) => {
|
|
636
|
+
const frame = {
|
|
637
|
+
name: p.name, parent: env,
|
|
638
|
+
ty: executesDefault(i) ? expandAlias(parseTsType(p.inferredTsType ?? p.tsType ?? "unknown"), ctx.typeDecls)
|
|
639
|
+
: p.rest ? { kind: "unknown" } : slots[i]?.ty ?? { kind: "void" },
|
|
640
|
+
onRead: () => {
|
|
641
|
+
captures?.add(i);
|
|
642
|
+
// A forward reference must never resolve to an outer variable if
|
|
643
|
+
// ordinary backend lowering cannot represent its initialization order.
|
|
644
|
+
if (!ready.has(i)) {
|
|
645
|
+
frame.emittedName ??= freshName(`_callbackParam${id}_${i}`);
|
|
646
|
+
// Keep the read itself: e.g. !array can later fold to false and erase
|
|
647
|
+
// an unresolved reference. An ordinary let retains the scope check.
|
|
648
|
+
if (!captures && !eagerReads.has(i)) {
|
|
649
|
+
eagerReads.add(i);
|
|
650
|
+
prefix.push({ kind: "let", name: freshName(`_callbackRead${id}_${i}`), ty: frame.ty,
|
|
651
|
+
mutable: false, init: { kind: "var", name: frame.emittedName, ty: frame.ty } });
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
if (!p.rest && !executesDefault(i) && i < actual.length)
|
|
655
|
+
used[i] = true;
|
|
656
|
+
},
|
|
657
|
+
get argumentPack() {
|
|
658
|
+
// Folding an eager read of an uninitialized rest binding to a constant
|
|
659
|
+
// would erase a JavaScript error. Leave that read to ordinary lowering.
|
|
660
|
+
return p.rest && (ready.has(i) || captures)
|
|
661
|
+
? { length: Math.max(0, actual.length - i), at: (k) => read(i + k) } : undefined;
|
|
662
|
+
},
|
|
663
|
+
get value() {
|
|
664
|
+
return !p.rest && !executesDefault(i) && i >= actual.length && (ready.has(i) || captures)
|
|
665
|
+
? { kind: "var", name: "undefined", ty: { kind: "void" } } : undefined;
|
|
666
|
+
},
|
|
667
|
+
};
|
|
668
|
+
env = frame;
|
|
669
|
+
return frame;
|
|
670
|
+
});
|
|
671
|
+
const emit = (i, init) => {
|
|
672
|
+
const frame = frames[i];
|
|
673
|
+
prefix.push({ kind: "let", name: frame.emittedName ?? frame.name, ty: frame.ty, mutable: false, init });
|
|
674
|
+
ready.add(i);
|
|
675
|
+
};
|
|
676
|
+
const flush = () => {
|
|
677
|
+
let progress = true;
|
|
678
|
+
while (progress) {
|
|
679
|
+
progress = false;
|
|
680
|
+
for (const [i, p] of pending) {
|
|
681
|
+
if (![...p.captures].every(j => ready.has(j)))
|
|
682
|
+
continue;
|
|
683
|
+
emit(i, p.init);
|
|
684
|
+
pending.delete(i);
|
|
685
|
+
progress = true;
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
};
|
|
689
|
+
for (const [i, p] of e.params.entries()) {
|
|
690
|
+
if (executesDefault(i)) {
|
|
691
|
+
// Only literal lambda creation is deferred; all source computations keep
|
|
692
|
+
// their order. Resolution is synchronous, so this local collector also
|
|
693
|
+
// sees reads through nested lambdas without threading capture maps in Ctx.
|
|
694
|
+
captures = p.defaultValue.kind === "lambda" ? new Set() : undefined;
|
|
695
|
+
const init = resolveExpr(p.defaultValue, { ...ctx, env, inLambda: true });
|
|
696
|
+
const dependencies = captures;
|
|
697
|
+
captures = undefined;
|
|
698
|
+
if (!frames[i].emittedName)
|
|
699
|
+
frames[i].ty = init.ty;
|
|
700
|
+
if (dependencies)
|
|
701
|
+
pending.set(i, { init, captures: dependencies });
|
|
702
|
+
else
|
|
703
|
+
emit(i, init);
|
|
704
|
+
}
|
|
705
|
+
else {
|
|
706
|
+
// A supplied non-optional value never evaluates a default. An Option
|
|
707
|
+
// cannot distinguish null from undefined, and an unknown value may be
|
|
708
|
+
// either; dropping the initializer could erase a call obligation.
|
|
709
|
+
if (p.defaultValue && defaults[i] === "optional") {
|
|
710
|
+
throw new Error(`callback default for '${p.name}' needs a distinction between null and undefined`);
|
|
711
|
+
}
|
|
712
|
+
if (p.defaultValue && defaults[i] === "unknown") {
|
|
713
|
+
throw new Error(`callback default for '${p.name}' needs a known argument type to decide whether the initializer executes`);
|
|
714
|
+
}
|
|
715
|
+
// Supplied argument slots are backend lambda parameters. A forward source
|
|
716
|
+
// reference needs its own local binding, initialized at the right position.
|
|
717
|
+
if (frames[i].emittedName && !p.rest && i < actual.length)
|
|
718
|
+
emit(i, read(i));
|
|
719
|
+
else
|
|
720
|
+
ready.add(i);
|
|
721
|
+
}
|
|
722
|
+
flush();
|
|
723
|
+
}
|
|
724
|
+
// Cycles and uses before closure construction stay in ordinary lowering.
|
|
725
|
+
// Hygienic names make unsupported scope references backend errors, rather
|
|
726
|
+
// than silently capturing an unrelated outer binding. No source call moves.
|
|
727
|
+
for (const [i, p] of pending)
|
|
728
|
+
emit(i, p.init);
|
|
729
|
+
const returnTy = e.returnTsType ? parseTsType(e.returnTsType) : { kind: "unknown" };
|
|
730
|
+
const lambdaCtx = { ...ctx, env, inLambda: true, returnTy };
|
|
731
|
+
const body = [...prefix, ...(Array.isArray(e.body) ? resolveBlock(e.body, lambdaCtx)
|
|
732
|
+
: [{ kind: "return", value: resolveExpr(e.body, lambdaCtx) }])];
|
|
733
|
+
const arity = Math.max(baseArity, used.lastIndexOf(true) + 1);
|
|
734
|
+
const params = slots.slice(0, arity);
|
|
735
|
+
const ty = e.returnTsType ? { kind: "fn", params: params.map(p => p.ty), result: returnTy } : { kind: "unknown" };
|
|
736
|
+
return { kind: "lambda", params, body, ty };
|
|
737
|
+
}
|
|
738
|
+
function callbackContext(fn, initial) {
|
|
739
|
+
if (fn.kind !== "field")
|
|
740
|
+
return undefined;
|
|
741
|
+
const id = recognizeBuiltin(fn.obj.ty, fn.field);
|
|
742
|
+
if (!id)
|
|
743
|
+
return undefined;
|
|
744
|
+
const spec = builtinSpec(id);
|
|
745
|
+
const actual = callbackArgumentTypes(spec, fn.obj.ty, initial?.ty);
|
|
746
|
+
return actual && spec.hof ? { actual, baseArity: callbackBaseArity(spec.hof.shape) } : undefined;
|
|
747
|
+
}
|
|
748
|
+
function argumentPack(e, ctx) {
|
|
749
|
+
const entry = e.kind === "var" ? binding(ctx.env, e.name) : undefined;
|
|
750
|
+
const pack = entry?.argumentPack;
|
|
751
|
+
if (pack)
|
|
752
|
+
entry.onRead?.();
|
|
753
|
+
return pack;
|
|
754
|
+
}
|
|
591
755
|
/** A defined-check filter predicate: `(x) => x !== undefined` (expression or
|
|
592
756
|
* single-return body). Detected on the raw IR before narrowing rewrites it. */
|
|
593
757
|
function isDefinedCheckRawLambda(raw) {
|
|
@@ -605,7 +769,7 @@ function isDefinedCheckRawLambda(raw) {
|
|
|
605
769
|
}
|
|
606
770
|
/** Coerce call arguments to their declared parameter slots and pad missing optional args. */
|
|
607
771
|
function coerceCallArgs(args, fn, ctx) {
|
|
608
|
-
if (fn.kind !== "var" || !ctx.fnParams.has(fn.name))
|
|
772
|
+
if (fn.kind !== "var" || binding(ctx.env, fn.name) || !ctx.fnParams.has(fn.name))
|
|
609
773
|
return args;
|
|
610
774
|
const paramTys = ctx.fnParams.get(fn.name);
|
|
611
775
|
args = args.map((a, i) => {
|
|
@@ -635,6 +799,9 @@ function inferMethodReturnTy(fn, args, ctx) {
|
|
|
635
799
|
if (fn.obj.kind === "var" && fn.obj.name === "String" && fn.field === "fromCharCode") {
|
|
636
800
|
return { kind: "string" };
|
|
637
801
|
}
|
|
802
|
+
if (fn.obj.kind === "var" && fn.obj.name === "Number" && fn.field === "isSafeInteger") {
|
|
803
|
+
return { kind: "bool" };
|
|
804
|
+
}
|
|
638
805
|
// Math.* numeric builtins: abs/min/max preserve the operand's numeric type
|
|
639
806
|
// (real if any operand is real); floor/ceil/round/trunc return an integer.
|
|
640
807
|
if (fn.obj.kind === "var" && fn.obj.name === "Math") {
|
|
@@ -799,10 +966,16 @@ function resolveExpr(e, ctx) {
|
|
|
799
966
|
}
|
|
800
967
|
function resolveExprInner(e, ctx) {
|
|
801
968
|
switch (e.kind) {
|
|
802
|
-
case "var":
|
|
969
|
+
case "var": {
|
|
803
970
|
if (e.name === "undefined")
|
|
804
971
|
return { kind: "var", name: "undefined", ty: { kind: "void" } };
|
|
805
|
-
|
|
972
|
+
const entry = binding(ctx.env, e.name);
|
|
973
|
+
if (entry?.argumentPack) {
|
|
974
|
+
throw new Error(`cannot materialize callback rest parameter '${e.name}'; use its length or a constant indexed read`);
|
|
975
|
+
}
|
|
976
|
+
entry?.onRead?.();
|
|
977
|
+
return entry?.value ?? { kind: "var", name: entry?.emittedName ?? e.name, ty: entry?.ty ?? { kind: "unknown" } };
|
|
978
|
+
}
|
|
806
979
|
case "num":
|
|
807
980
|
if (!Number.isInteger(e.value))
|
|
808
981
|
return { kind: "num", value: e.value, ty: { kind: "real" } };
|
|
@@ -930,14 +1103,19 @@ function resolveExprInner(e, ctx) {
|
|
|
930
1103
|
}
|
|
931
1104
|
// Propagate parameter types to arguments for record literal resolution
|
|
932
1105
|
// (enables inline discriminated union construction in function arguments)
|
|
933
|
-
const paramTypes = fn.kind === "var" && ctx.
|
|
1106
|
+
const paramTypes = fn.kind === "var" && !binding(ctx.env, fn.name) ? ctx.fnParams.get(fn.name) ?? null : null;
|
|
1107
|
+
const initial = fn.kind === "field" && fn.field === "reduce" && rawArgs.length >= 2
|
|
1108
|
+
? resolveExpr(rawArgs[1], argCtx) : undefined;
|
|
1109
|
+
const callback = callbackContext(fn, initial);
|
|
934
1110
|
let args = coerceCallArgs(rawArgs.map((a, i) => {
|
|
935
1111
|
let aCtx = argCtx;
|
|
936
1112
|
if (paramTypes && i < paramTypes.length &&
|
|
937
1113
|
(paramTypes[i].kind === "user" || paramTypes[i].kind === "array" || paramTypes[i].kind === "optional")) {
|
|
938
1114
|
aCtx = { ...aCtx, returnTy: paramTypes[i] };
|
|
939
1115
|
}
|
|
940
|
-
|
|
1116
|
+
if (i === 0 && a.kind === "lambda" && callback)
|
|
1117
|
+
return resolveCallback(a, callback.actual, callback.baseArity, aCtx);
|
|
1118
|
+
return i === 1 && initial ? initial : resolveExpr(a, aCtx);
|
|
941
1119
|
}), fn, ctx);
|
|
942
1120
|
// Array method `.with(i, v)`: coerce the value arg to the element type
|
|
943
1121
|
// so `arr[i] = v` on `(T|null)[]` wraps `T` → `Some(T)` (and similarly
|
|
@@ -948,15 +1126,17 @@ function resolveExprInner(e, ctx) {
|
|
|
948
1126
|
}
|
|
949
1127
|
let ty = inferMethodReturnTy(fn, args, ctx);
|
|
950
1128
|
// For same-file function calls, use the known return type
|
|
951
|
-
if (ty.kind === "unknown" && fn.kind === "var" && ctx.fnReturns.has(fn.name)) {
|
|
1129
|
+
if (ty.kind === "unknown" && fn.kind === "var" && !binding(ctx.env, fn.name) && ctx.fnReturns.has(fn.name)) {
|
|
952
1130
|
ty = ctx.fnReturns.get(fn.name);
|
|
953
1131
|
}
|
|
954
|
-
//
|
|
955
|
-
if (ty.kind === "unknown" && fn.kind === "var")
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
ty = varTy.result;
|
|
1132
|
+
// BigInt(n) / Number(n) between integer types: identity on the model's int.
|
|
1133
|
+
if (ty.kind === "unknown" && fn.kind === "var" && (fn.name === "BigInt" || fn.name === "Number") &&
|
|
1134
|
+
args.length === 1 && (args[0].ty.kind === "int" || args[0].ty.kind === "nat")) {
|
|
1135
|
+
ty = fn.name === "BigInt" ? { kind: "int", big: true } : { kind: "int" };
|
|
959
1136
|
}
|
|
1137
|
+
// Call through a function-typed value: its fn type carries the result
|
|
1138
|
+
if (ty.kind === "unknown" && fn.ty.kind === "fn")
|
|
1139
|
+
ty = fn.ty.result;
|
|
960
1140
|
// filterMap: `seqOfOption.filter(x => x !== undefined)` (a defined-check,
|
|
961
1141
|
// typically with an `x is T` type guard) drops the Nones AND unwraps to
|
|
962
1142
|
// seq<T>. Rewrite to a synthetic `filterSome` call lowered to the proven
|
|
@@ -973,6 +1153,10 @@ function resolveExprInner(e, ctx) {
|
|
|
973
1153
|
...(paramTypes ? { paramTys: paramTypes } : {}) };
|
|
974
1154
|
}
|
|
975
1155
|
case "index": {
|
|
1156
|
+
const pack = argumentPack(e.obj, ctx);
|
|
1157
|
+
if (pack && e.idx.kind === "num" && Number.isInteger(e.idx.value) && e.idx.value >= 0) {
|
|
1158
|
+
return pack.at(e.idx.value);
|
|
1159
|
+
}
|
|
976
1160
|
if (e.idx.kind === "str") {
|
|
977
1161
|
const member = resolveConstEnumMember(e.obj, e.idx.value, ctx);
|
|
978
1162
|
if (member)
|
|
@@ -1013,6 +1197,9 @@ function resolveExprInner(e, ctx) {
|
|
|
1013
1197
|
return { kind: "index", obj, idx, ty: idxTy };
|
|
1014
1198
|
}
|
|
1015
1199
|
case "field": {
|
|
1200
|
+
const pack = argumentPack(e.obj, ctx);
|
|
1201
|
+
if (pack && e.field === "length")
|
|
1202
|
+
return { kind: "num", value: pack.length, ty: { kind: "nat" } };
|
|
1016
1203
|
const member = resolveConstEnumMember(e.obj, e.field, ctx);
|
|
1017
1204
|
if (member)
|
|
1018
1205
|
return member;
|
|
@@ -1106,7 +1293,11 @@ function resolveExprInner(e, ctx) {
|
|
|
1106
1293
|
const fakeObj = { kind: "var", name: "_chain_recv", ty: priorInTy };
|
|
1107
1294
|
const fakeFn = { kind: "field", obj: fakeObj, field: lastField.name, ty: lastField.ty };
|
|
1108
1295
|
rawArgs = inferLambdaParamTypes(fakeFn, rawArgs);
|
|
1109
|
-
const
|
|
1296
|
+
const initial = lastField.name === "reduce" && rawArgs.length >= 2 ? resolveExpr(rawArgs[1], ctx) : undefined;
|
|
1297
|
+
const callback = callbackContext(fakeFn, initial);
|
|
1298
|
+
const args = rawArgs.map((a, i) => i === 0 && a.kind === "lambda" && callback
|
|
1299
|
+
? resolveCallback(a, callback.actual, callback.baseArity, ctx)
|
|
1300
|
+
: i === 1 && initial ? initial : resolveExpr(a, ctx));
|
|
1110
1301
|
callTy = inferMethodReturnTy(fakeFn, args, ctx);
|
|
1111
1302
|
callKind = "method";
|
|
1112
1303
|
const builtinId = recognizeBuiltin(priorInTy, lastField.name);
|
|
@@ -1244,6 +1435,8 @@ function resolveExprInner(e, ctx) {
|
|
|
1244
1435
|
const params = e.params.map(p => ({
|
|
1245
1436
|
name: p.name,
|
|
1246
1437
|
ty: p.tsType ? parseTsType(p.tsType) : { kind: "unknown" },
|
|
1438
|
+
...(p.rest ? { rest: true } : {}),
|
|
1439
|
+
...(p.defaultValue ? { defaultValue: resolveExpr(p.defaultValue, ctx) } : {}),
|
|
1247
1440
|
}));
|
|
1248
1441
|
// Extend env with lambda params
|
|
1249
1442
|
let lambdaEnv = ctx.env;
|
|
@@ -1276,16 +1469,16 @@ function resolveExprInner(e, ctx) {
|
|
|
1276
1469
|
let elseCtx = ctx;
|
|
1277
1470
|
// Truthiness — cond itself is optional (`opt ? a : b`), only for simple vars.
|
|
1278
1471
|
if (cond.ty.kind === "optional" && cond.kind === "var") {
|
|
1279
|
-
thenCtx = withEnv(thenCtx,
|
|
1472
|
+
thenCtx = withEnv(thenCtx, refine(thenCtx.env, cond.name, cond.ty.inner));
|
|
1280
1473
|
}
|
|
1281
1474
|
// Single === undefined check narrows the else-branch.
|
|
1282
1475
|
const single = negatedVarPresence(cond);
|
|
1283
1476
|
if (single) {
|
|
1284
|
-
elseCtx = withEnv(elseCtx,
|
|
1477
|
+
elseCtx = withEnv(elseCtx, refine(elseCtx.env, single.varName, single.innerTy));
|
|
1285
1478
|
}
|
|
1286
1479
|
if (!single && cond.kind === "binop" && cond.op === "||") {
|
|
1287
1480
|
for (const n of collectEarlyReturnNarrowings(cond)) {
|
|
1288
|
-
elseCtx = withEnv(elseCtx,
|
|
1481
|
+
elseCtx = withEnv(elseCtx, refine(elseCtx.env, n.varName, n.innerTy));
|
|
1289
1482
|
}
|
|
1290
1483
|
}
|
|
1291
1484
|
// Map-index narrowing: `k in m` in the cond narrows the then-branch; `!(k in m)`
|
|
@@ -1347,7 +1540,7 @@ function resolveBlock(stmts, ctx) {
|
|
|
1347
1540
|
if (s.kind === "if" && s.then.length > 0 && isTerminatorKind(s.then[s.then.length - 1].kind) && s.else.length === 0) {
|
|
1348
1541
|
if (typed.kind === "if") {
|
|
1349
1542
|
for (const n of collectEarlyReturnNarrowings(typed.cond)) {
|
|
1350
|
-
env =
|
|
1543
|
+
env = refine(env, n.varName, n.innerTy);
|
|
1351
1544
|
}
|
|
1352
1545
|
const nv = negatedVariantCheck(typed.cond);
|
|
1353
1546
|
if (nv)
|
|
@@ -1433,6 +1626,11 @@ function resolveStmt(s, ctx) {
|
|
|
1433
1626
|
return [{ kind: "let", name: s.name, ty, mutable, init }, extend(ctx.env, s.name, ty)];
|
|
1434
1627
|
}
|
|
1435
1628
|
case "assign": {
|
|
1629
|
+
const entry = binding(ctx.env, s.target);
|
|
1630
|
+
if (entry?.argumentPack || entry?.value) {
|
|
1631
|
+
throw new Error(`assignment to callback binding '${s.target}' requires materializing its argument value`);
|
|
1632
|
+
}
|
|
1633
|
+
entry?.onRead?.();
|
|
1436
1634
|
const targetTy = lookup(ctx.env, s.target) ?? { kind: "unknown" };
|
|
1437
1635
|
// Propagate the target's type as returnTy, mirroring the annotated-let
|
|
1438
1636
|
// case, so record/union literals and array literals in the RHS resolve
|
|
@@ -1440,7 +1638,7 @@ function resolveStmt(s, ctx) {
|
|
|
1440
1638
|
const valueCtx = (targetTy.kind === "user" || targetTy.kind === "array" || targetTy.kind === "optional")
|
|
1441
1639
|
? { ...ctx, returnTy: targetTy } : ctx;
|
|
1442
1640
|
const value = coerceToTargetTy(resolveExpr(s.value, valueCtx), targetTy, ctx.typeDecls);
|
|
1443
|
-
return [{ kind: "assign", target: s.target, value }, ctx.env];
|
|
1641
|
+
return [{ kind: "assign", target: entry?.emittedName ?? s.target, value }, ctx.env];
|
|
1444
1642
|
}
|
|
1445
1643
|
case "return": {
|
|
1446
1644
|
const value = coerceToTargetTy(resolveExpr(s.value, ctx), ctx.returnTy, ctx.typeDecls);
|
|
@@ -1462,7 +1660,7 @@ function resolveStmt(s, ctx) {
|
|
|
1462
1660
|
let elseCtx = ctx;
|
|
1463
1661
|
const single = negatedVarPresence(resolvedCond);
|
|
1464
1662
|
if (single) {
|
|
1465
|
-
elseCtx = withEnv(ctx,
|
|
1663
|
+
elseCtx = withEnv(ctx, refine(ctx.env, single.varName, single.innerTy));
|
|
1466
1664
|
}
|
|
1467
1665
|
// Narrow map index access across `k in m` / `!(k in m)` in the cond:
|
|
1468
1666
|
// positive atoms (from `k in m` or &&-chains containing it) → then-branch;
|
|
@@ -1634,6 +1832,9 @@ function collectCallsExpr(e, fns, out) {
|
|
|
1634
1832
|
collectCallsExpr(el, fns, out);
|
|
1635
1833
|
return;
|
|
1636
1834
|
case "lambda":
|
|
1835
|
+
for (const p of e.params)
|
|
1836
|
+
if (p.defaultValue)
|
|
1837
|
+
collectCallsExpr(p.defaultValue, fns, out);
|
|
1637
1838
|
if (Array.isArray(e.body))
|
|
1638
1839
|
collectCallsStmts(e.body, fns, out);
|
|
1639
1840
|
else
|
|
@@ -1748,30 +1949,6 @@ function computePureFns(functions, externDecls) {
|
|
|
1748
1949
|
}
|
|
1749
1950
|
return new Set(functions.map(fn => fn.name).filter(name => !nonPure.has(name)));
|
|
1750
1951
|
}
|
|
1751
|
-
function hasReturnInLoop(stmts) {
|
|
1752
|
-
for (const s of stmts) {
|
|
1753
|
-
if ((s.kind === "while" || s.kind === "forof") && containsReturn(s.body))
|
|
1754
|
-
return true;
|
|
1755
|
-
if (s.kind === "if" && (hasReturnInLoop(s.then) || hasReturnInLoop(s.else)))
|
|
1756
|
-
return true;
|
|
1757
|
-
if (s.kind === "switch" && (s.cases.some(c => hasReturnInLoop(c.body)) || hasReturnInLoop(s.defaultBody)))
|
|
1758
|
-
return true;
|
|
1759
|
-
}
|
|
1760
|
-
return false;
|
|
1761
|
-
}
|
|
1762
|
-
function containsReturn(stmts) {
|
|
1763
|
-
for (const s of stmts) {
|
|
1764
|
-
if (s.kind === "return")
|
|
1765
|
-
return true;
|
|
1766
|
-
if (s.kind === "if" && (containsReturn(s.then) || containsReturn(s.else)))
|
|
1767
|
-
return true;
|
|
1768
|
-
if ((s.kind === "while" || s.kind === "forof") && containsReturn(s.body))
|
|
1769
|
-
return true;
|
|
1770
|
-
if (s.kind === "switch" && (s.cases.some(c => containsReturn(c.body)) || containsReturn(s.defaultBody)))
|
|
1771
|
-
return true;
|
|
1772
|
-
}
|
|
1773
|
-
return false;
|
|
1774
|
-
}
|
|
1775
1952
|
// ── Resolve function / module ────────────────────────────────
|
|
1776
1953
|
function resolveFunction(fn, typeDecls, pureFns, fnParams = new Map(), fnReturns = new Map(), externs = new Map(), moduleConstants = new Map(), opts) {
|
|
1777
1954
|
const overrides = new Map(fn.typeAnnotations.map(a => [a.name, a.type]));
|
|
@@ -1857,6 +2034,8 @@ function precomputeFieldTypesInner(typeDecls) {
|
|
|
1857
2034
|
}
|
|
1858
2035
|
}
|
|
1859
2036
|
export function resolveModule(raw) {
|
|
2037
|
+
callbackCounter = 0;
|
|
2038
|
+
mergeBinder = 0;
|
|
1860
2039
|
_warnedRefEq.clear();
|
|
1861
2040
|
precomputeFieldTypes(raw.typeDecls);
|
|
1862
2041
|
const pureFns = computePureFns(raw.functions, raw.externs ?? []);
|
|
@@ -1893,30 +2072,23 @@ export function resolveModule(raw) {
|
|
|
1893
2072
|
}
|
|
1894
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: [] };
|
|
1895
2074
|
const ensuresCtx = { ...baseCtx, env: extend(env, "\\result", sig.returnTy), allowResult: true };
|
|
1896
|
-
const
|
|
2075
|
+
const resolveClauses = (kind, ctx) => ext[kind].map(s => {
|
|
1897
2076
|
try {
|
|
1898
|
-
return resolveSpec(s,
|
|
2077
|
+
return resolveSpec(s, ctx);
|
|
1899
2078
|
}
|
|
1900
|
-
catch {
|
|
1901
|
-
|
|
2079
|
+
catch (e) {
|
|
2080
|
+
const reason = e instanceof Error ? e.message : String(e);
|
|
2081
|
+
throw new Error(`extern ${ext.qualified}: //@ ${kind} ${s}: ${reason}`);
|
|
1902
2082
|
}
|
|
1903
|
-
})
|
|
1904
|
-
const ensures = ext.ensures.map(s => {
|
|
1905
|
-
try {
|
|
1906
|
-
return resolveSpec(s, ensuresCtx);
|
|
1907
|
-
}
|
|
1908
|
-
catch {
|
|
1909
|
-
return null;
|
|
1910
|
-
}
|
|
1911
|
-
}).filter((e) => e !== null);
|
|
2083
|
+
});
|
|
1912
2084
|
return {
|
|
1913
2085
|
qualified: ext.qualified,
|
|
1914
2086
|
flat: ext.flat,
|
|
1915
2087
|
typeParams: ext.typeParams,
|
|
1916
2088
|
params: ext.params.map((p, i) => ({ name: p.name, ty: sig.params[i] })),
|
|
1917
2089
|
returnTy: sig.returnTy,
|
|
1918
|
-
requires,
|
|
1919
|
-
ensures,
|
|
2090
|
+
requires: resolveClauses("requires", baseCtx),
|
|
2091
|
+
ensures: resolveClauses("ensures", ensuresCtx),
|
|
1920
2092
|
impure: ext.impure,
|
|
1921
2093
|
};
|
|
1922
2094
|
});
|