lemmascript 0.6.6 → 0.6.7
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 +2 -0
- package/package.json +1 -1
- package/tools/dist/config.js +31 -18
- package/tools/dist/dafny-emit.js +2 -2
- package/tools/dist/extract.js +353 -90
- package/tools/dist/ir.js +19 -0
- package/tools/dist/lean-emit.js +2 -2
- package/tools/dist/lsc.js +7 -12
- package/tools/dist/resolve.js +68 -14
- package/tools/dist/source-projects.js +31 -0
- package/tools/dist/transform.js +36 -2
- package/tools/dist/types.js +17 -1
package/tools/dist/ir.js
CHANGED
|
@@ -19,6 +19,25 @@ export function patternBinds(p, name) {
|
|
|
19
19
|
return patternBinders(p).includes(name);
|
|
20
20
|
}
|
|
21
21
|
// ── Literal queries ──────────────────────────────────────────
|
|
22
|
+
/** Expand JavaScript's shortest decimal spelling without exponent syntax. */
|
|
23
|
+
export function decimalNumberLiteral(value) {
|
|
24
|
+
if (!Number.isFinite(value))
|
|
25
|
+
throw new Error(`Cannot emit non-finite numeric literal: ${value}`);
|
|
26
|
+
const text = String(value);
|
|
27
|
+
const [mantissa, exponent] = text.split("e");
|
|
28
|
+
if (exponent === undefined)
|
|
29
|
+
return text;
|
|
30
|
+
const negative = mantissa.startsWith("-");
|
|
31
|
+
const [whole, fraction = ""] = (negative ? mantissa.slice(1) : mantissa).split(".");
|
|
32
|
+
const digits = whole + fraction;
|
|
33
|
+
const point = whole.length + Number(exponent);
|
|
34
|
+
const expanded = point <= 0
|
|
35
|
+
? `0.${"0".repeat(-point)}${digits}`
|
|
36
|
+
: point >= digits.length
|
|
37
|
+
? digits + "0".repeat(point - digits.length)
|
|
38
|
+
: `${digits.slice(0, point)}.${digits.slice(point)}`;
|
|
39
|
+
return negative ? `-${expanded}` : expanded;
|
|
40
|
+
}
|
|
22
41
|
/** The exact value of an integer-literal operand (possibly negated), or null
|
|
23
42
|
* when `e` isn't one. Answers in compiler-side `bigint` so a backend folding a
|
|
24
43
|
* literal into arithmetic stays exact: JS bitwise operators truncate to 32 bits
|
package/tools/dist/lean-emit.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* opaque-tainted types, discriminator/destructor lowering, method dispatch,
|
|
5
5
|
* and support-import selection.
|
|
6
6
|
*/
|
|
7
|
-
import { anyExpr, usesNameInDecl, patternBinders } from "./ir.js";
|
|
7
|
+
import { anyExpr, decimalNumberLiteral, usesNameInDecl, patternBinders } from "./ir.js";
|
|
8
8
|
import { freshName, freshNameWhere } from "./names.js";
|
|
9
9
|
// ── Ty → Lean type string ──────────────────────────────────
|
|
10
10
|
function tyToLean(ty) {
|
|
@@ -327,7 +327,7 @@ function emitExpr(e, parentPrec) {
|
|
|
327
327
|
switch (e.kind) {
|
|
328
328
|
// `undefined` is the IR's spelling of the absent optional (mirrors dafny-emit's None)
|
|
329
329
|
case "var": return e.name === "undefined" ? "none" : escapeName(e.name);
|
|
330
|
-
case "num": return
|
|
330
|
+
case "num": return decimalNumberLiteral(e.value);
|
|
331
331
|
// Already canonical decimal; Lean's `Int` is mathematical, so no `n` suffix.
|
|
332
332
|
case "bigint": return e.value;
|
|
333
333
|
case "bool": return e.value ? "true" : "false";
|
package/tools/dist/lsc.js
CHANGED
|
@@ -4,7 +4,6 @@
|
|
|
4
4
|
*
|
|
5
5
|
* Pipeline: extract → resolve → narrow → transform → peephole → emit
|
|
6
6
|
*/
|
|
7
|
-
import { Project, ScriptTarget } from "ts-morph";
|
|
8
7
|
import { existsSync, mkdirSync, readFileSync } from "fs";
|
|
9
8
|
import { execFileSync } from "child_process";
|
|
10
9
|
import { createRequire } from "module";
|
|
@@ -22,7 +21,8 @@ import { leanGen, leanCheck } from "./lean-commands.js";
|
|
|
22
21
|
import { runInfo, runTypedInfo } from "./info-command.js";
|
|
23
22
|
import { RunLog, resolveLogDir, runLogEnabled, safely } from "./run-log.js";
|
|
24
23
|
import { runRuns } from "./runs-command.js";
|
|
25
|
-
import {
|
|
24
|
+
import { SourceProjects } from "./source-projects.js";
|
|
25
|
+
import { loadConfigOptions, parseFileOptions, resolveDafnyArtifactDir, resolveOptions, } from "./config.js";
|
|
26
26
|
/** Version of the lemmascript package — the root package.json sits two levels
|
|
27
27
|
* above this module from both tools/src/ (tsx) and tools/dist/ (installed). */
|
|
28
28
|
function lscVersion() {
|
|
@@ -255,15 +255,16 @@ function runBatch(cmd, backend, slow, timeLimit, extraFlags, configPath) {
|
|
|
255
255
|
process.exit(1);
|
|
256
256
|
}
|
|
257
257
|
const verifySlow = slow || timeLimit !== undefined;
|
|
258
|
+
const projects = new SourceProjects();
|
|
258
259
|
for (const e of readEntries()) {
|
|
259
260
|
const timeout = timeLimit ?? e.timeout;
|
|
260
261
|
const flags = extraFlags ?? e.flags;
|
|
261
262
|
if (cmd === "check" && backend === "dafny" && !verifySlow && timeout !== undefined && timeout > 60) {
|
|
262
263
|
console.log(`=== ${path.basename(e.file)} (timeout ${timeout}s > 60s, gen-check only) ===`);
|
|
263
|
-
runFile("gen-check", e.file, backend, undefined, undefined, false, false, configPath);
|
|
264
|
+
runFile("gen-check", e.file, backend, undefined, undefined, false, false, configPath, projects);
|
|
264
265
|
}
|
|
265
266
|
else {
|
|
266
|
-
runFile(cmd, e.file, backend, timeout, flags, false, false, configPath);
|
|
267
|
+
runFile(cmd, e.file, backend, timeout, flags, false, false, configPath, projects);
|
|
267
268
|
}
|
|
268
269
|
}
|
|
269
270
|
}
|
|
@@ -281,19 +282,13 @@ function guardRelocatedDafnyProof(sourceDir, artifactDir, base, targetDfyPath) {
|
|
|
281
282
|
legacyPaths.map(p => ` ${p}`).join("\n") +
|
|
282
283
|
`\nMove the hand-written .dfy to ${targetDfyPath}, inspect or remove stale .dfy.base/.dfy.merged files, then rerun. The .dfy.gen file is regeneratable.`);
|
|
283
284
|
}
|
|
284
|
-
function runFile(cmd, filePath, backend, timeLimit, extraFlags, noVerify = false, typedInfo = false, configPath) {
|
|
285
|
+
function runFile(cmd, filePath, backend, timeLimit, extraFlags, noVerify = false, typedInfo = false, configPath, projects = new SourceProjects()) {
|
|
285
286
|
const absPath = path.resolve(filePath);
|
|
286
287
|
if (!existsSync(absPath)) {
|
|
287
288
|
console.error(`File not found: ${absPath}`);
|
|
288
289
|
process.exit(1);
|
|
289
290
|
}
|
|
290
|
-
|
|
291
|
-
const tsConfigFilePath = findUp("tsconfig.json", absPath) ?? undefined;
|
|
292
|
-
const project = tsConfigFilePath
|
|
293
|
-
? new Project({ tsConfigFilePath })
|
|
294
|
-
: new Project({ compilerOptions: { strict: true, target: ScriptTarget.ESNext, lib: ["lib.esnext.d.ts"] } });
|
|
295
|
-
const sourceFile = project.addSourceFileAtPath(absPath);
|
|
296
|
-
project.resolveSourceFileDependencies();
|
|
291
|
+
const sourceFile = projects.load(absPath);
|
|
297
292
|
const fullText = sourceFile.getFullText();
|
|
298
293
|
const { options, configFile } = effectiveOptions(absPath, fullText, configPath);
|
|
299
294
|
// Checked here, for every command, so a bad LSC_RUN_LOG fails like a bad config value.
|
package/tools/dist/resolve.js
CHANGED
|
@@ -58,6 +58,10 @@ function resolveTsType(tsType, overrides, varName) {
|
|
|
58
58
|
/** Infer a conditional's result type after its branches have been resolved or
|
|
59
59
|
* contextually coerced. A void branch is the source-level null/undefined arm. */
|
|
60
60
|
function conditionalResultTy(thenTy, elseTy) {
|
|
61
|
+
if ((thenTy.kind === "int" || thenTy.kind === "nat") &&
|
|
62
|
+
(elseTy.kind === "int" || elseTy.kind === "nat")) {
|
|
63
|
+
return { ...thenTy, kind: thenTy.kind === "int" || elseTy.kind === "int" ? "int" : "nat" };
|
|
64
|
+
}
|
|
61
65
|
let ty = thenTy.kind !== "unknown" ? thenTy : elseTy;
|
|
62
66
|
if (thenTy.kind === "void" && elseTy.kind !== "void" && elseTy.kind !== "unknown") {
|
|
63
67
|
ty = { kind: "optional", inner: elseTy };
|
|
@@ -272,8 +276,15 @@ function expandAlias(ty, typeDecls, seen = new Set()) {
|
|
|
272
276
|
if (ty.kind === "user") {
|
|
273
277
|
if (seen.has(ty.name))
|
|
274
278
|
return ty;
|
|
279
|
+
const dot = ty.name.lastIndexOf(".");
|
|
280
|
+
const enumDecl = typeDecls.find(d => d.name === ty.name.slice(0, dot));
|
|
281
|
+
if (dot > 0 && enumDecl?.constEnumMembers?.some(m => m.name === ty.name.slice(dot + 1)))
|
|
282
|
+
return { kind: "int" };
|
|
275
283
|
const decl = declOfDotted(typeDecls, ty.name);
|
|
276
284
|
if (decl?.kind === "alias" && decl.aliasOfTy) {
|
|
285
|
+
// Numeric enums must behave as numbers (not truthy user objects).
|
|
286
|
+
if (decl.constEnumMembers)
|
|
287
|
+
return { kind: "int" };
|
|
277
288
|
const target = decl.aliasOfTy;
|
|
278
289
|
if (target.kind === "array" || target.kind === "map" || target.kind === "set" || target.kind === "optional" || target.kind === "user") {
|
|
279
290
|
return expandAlias(target, typeDecls, new Set([...seen, ty.name]));
|
|
@@ -293,6 +304,22 @@ function expandAlias(ty, typeDecls, seen = new Set()) {
|
|
|
293
304
|
return { kind: "map", key: expandAlias(ty.key, typeDecls, seen), value: expandAlias(ty.value, typeDecls, seen) };
|
|
294
305
|
return ty;
|
|
295
306
|
}
|
|
307
|
+
/** Numeric aliases keep their names in declarations but use their underlying
|
|
308
|
+
* types in expressions. Optional payloads need the same treatment for zero's
|
|
309
|
+
* falsiness; collection elements are resolved when read. */
|
|
310
|
+
function numericValueType(ty, typeDecls, seen = new Set()) {
|
|
311
|
+
if (ty.kind === "optional")
|
|
312
|
+
return { ...ty, inner: numericValueType(ty.inner, typeDecls, seen) };
|
|
313
|
+
if (ty.kind !== "user" || seen.has(ty.name))
|
|
314
|
+
return ty;
|
|
315
|
+
const decl = declOfDotted(typeDecls, ty.name);
|
|
316
|
+
if (decl?.kind === "alias" && decl.aliasOfTy) {
|
|
317
|
+
const target = numericValueType(decl.aliasOfTy, typeDecls, new Set([...seen, ty.name]));
|
|
318
|
+
if (target.kind === "int" || target.kind === "nat" || target.kind === "real")
|
|
319
|
+
return target;
|
|
320
|
+
}
|
|
321
|
+
return ty;
|
|
322
|
+
}
|
|
296
323
|
function getDiscriminant(ctx, typeName) {
|
|
297
324
|
return findDecl(ctx, typeName)?.discriminant;
|
|
298
325
|
}
|
|
@@ -657,8 +684,9 @@ function lookupFieldTy(objTy, field, ctx) {
|
|
|
657
684
|
let mergeBinder = 0;
|
|
658
685
|
/** Expand `{ ...base, ...override }` into a faithful field-wise merge. Driven by
|
|
659
686
|
* the result record type's fields: an override field wins when present, else the
|
|
660
|
-
* base's field shows through.
|
|
661
|
-
* (`
|
|
687
|
+
* base's field shows through. `f?:` fields decide presence at runtime (`Some?`);
|
|
688
|
+
* required fields (including `T | null`) are always copied from the override.
|
|
689
|
+
* An `Option`-typed override is the whole merge guarded by its tag. */
|
|
662
690
|
function resolveRecordMerge(base, override, ctx) {
|
|
663
691
|
const tbase = resolveExpr(base, ctx);
|
|
664
692
|
const tover = resolveExpr(override, ctx);
|
|
@@ -683,9 +711,10 @@ function resolveRecordMerge(base, override, ctx) {
|
|
|
683
711
|
fields: fields.map(f => {
|
|
684
712
|
const ft = f.type;
|
|
685
713
|
const ovf = { kind: "field", obj: ov, field: f.name, ty: ft };
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
714
|
+
// A required key is always copied, even when its value is null/undefined.
|
|
715
|
+
if (ft.kind !== "optional" || !f.optionalKey)
|
|
716
|
+
return { name: f.name, value: ovf };
|
|
717
|
+
// `f?:` key: override field wins iff present, else base's field
|
|
689
718
|
const bvf = { kind: "field", obj: bv, field: f.name, ty: ft };
|
|
690
719
|
const binder = freshName(`_m${mergeBinder++}`);
|
|
691
720
|
// someBody is the unwrapped present value; transform re-wraps each arm in
|
|
@@ -753,7 +782,22 @@ function tryRecordIndexByEnum(obj, idx, ctx) {
|
|
|
753
782
|
}
|
|
754
783
|
return expr;
|
|
755
784
|
}
|
|
785
|
+
function resolveConstEnumMember(obj, name, ctx) {
|
|
786
|
+
if (obj.kind !== "var" || lookup(ctx.env, obj.name))
|
|
787
|
+
return undefined;
|
|
788
|
+
const decl = ctx.typeDecls.find(d => d.name === obj.name);
|
|
789
|
+
if (!decl?.constEnumMembers)
|
|
790
|
+
return undefined;
|
|
791
|
+
const member = decl.constEnumMembers.find(m => m.name === name);
|
|
792
|
+
if (!member)
|
|
793
|
+
throw new Error(`Unknown const enum member ${obj.name}.${name}`);
|
|
794
|
+
return resolveExpr({ kind: "num", value: member.value }, ctx);
|
|
795
|
+
}
|
|
756
796
|
function resolveExpr(e, ctx) {
|
|
797
|
+
const expr = resolveExprInner(e, ctx);
|
|
798
|
+
return { ...expr, ty: numericValueType(expr.ty, ctx.typeDecls) };
|
|
799
|
+
}
|
|
800
|
+
function resolveExprInner(e, ctx) {
|
|
757
801
|
switch (e.kind) {
|
|
758
802
|
case "var":
|
|
759
803
|
if (e.name === "undefined")
|
|
@@ -827,7 +871,8 @@ function resolveExpr(e, ctx) {
|
|
|
827
871
|
}
|
|
828
872
|
case "unop": {
|
|
829
873
|
const expr = resolveExpr(e.expr, ctx);
|
|
830
|
-
const ty = e.op === "!" ? { kind: "bool" } : e.op === "typeof" ? { kind: "string" }
|
|
874
|
+
const ty = e.op === "!" ? { kind: "bool" } : e.op === "typeof" ? { kind: "string" }
|
|
875
|
+
: e.op === "-" && expr.ty.kind === "nat" ? { ...expr.ty, kind: "int" } : expr.ty;
|
|
831
876
|
return { kind: "unop", op: e.op, expr, ty };
|
|
832
877
|
}
|
|
833
878
|
case "call": {
|
|
@@ -840,8 +885,7 @@ function resolveExpr(e, ctx) {
|
|
|
840
885
|
throw new Error("perm(a, b) may only be used in //@ specifications");
|
|
841
886
|
const a = resolveExpr(e.args[0], ctx);
|
|
842
887
|
const b = resolveExpr(e.args[1], ctx);
|
|
843
|
-
|
|
844
|
-
throw new Error(`perm(a, b) requires two array arguments (got ${a.ty.kind} and ${b.ty.kind})`);
|
|
888
|
+
// Let the backend check argument types, including calls to proof helpers.
|
|
845
889
|
const fn = { kind: "var", name: "Perm", ty: { kind: "unknown" } };
|
|
846
890
|
return { kind: "call", fn, args: [a, b], ty: { kind: "bool" }, callKind: "pure" };
|
|
847
891
|
}
|
|
@@ -929,6 +973,11 @@ function resolveExpr(e, ctx) {
|
|
|
929
973
|
...(paramTypes ? { paramTys: paramTypes } : {}) };
|
|
930
974
|
}
|
|
931
975
|
case "index": {
|
|
976
|
+
if (e.idx.kind === "str") {
|
|
977
|
+
const member = resolveConstEnumMember(e.obj, e.idx.value, ctx);
|
|
978
|
+
if (member)
|
|
979
|
+
return member;
|
|
980
|
+
}
|
|
932
981
|
const obj = resolveExpr(e.obj, ctx);
|
|
933
982
|
const idx = resolveExpr(e.idx, ctx);
|
|
934
983
|
// Map bracket access: default to Option<V>. But if the enclosing scope has a
|
|
@@ -964,6 +1013,9 @@ function resolveExpr(e, ctx) {
|
|
|
964
1013
|
return { kind: "index", obj, idx, ty: idxTy };
|
|
965
1014
|
}
|
|
966
1015
|
case "field": {
|
|
1016
|
+
const member = resolveConstEnumMember(e.obj, e.field, ctx);
|
|
1017
|
+
if (member)
|
|
1018
|
+
return member;
|
|
967
1019
|
const obj = resolveExpr(e.obj, ctx);
|
|
968
1020
|
let isDiscriminant = false;
|
|
969
1021
|
let ty = { kind: "unknown" };
|
|
@@ -1762,10 +1814,10 @@ function resolveFunction(fn, typeDecls, pureFns, fnParams = new Map(), fnReturns
|
|
|
1762
1814
|
};
|
|
1763
1815
|
}
|
|
1764
1816
|
function resolveClass(cls, typeDecls, pureFns, fnParams = new Map(), fnReturns = new Map(), externs = new Map(), moduleConstants = new Map()) {
|
|
1765
|
-
const fields = cls.fields.map(f => ({ name: f.name, ty: parseTsType(f.tsType) }));
|
|
1817
|
+
const fields = cls.fields.map(f => ({ name: f.name, ty: expandAlias(parseTsType(f.tsType), typeDecls) }));
|
|
1766
1818
|
// Create a synthetic record type for 'this' so field access resolves
|
|
1767
1819
|
const thisType = { kind: "user", name: cls.name };
|
|
1768
|
-
const thisDecl = { name: cls.name, kind: "record", fields: cls.fields.map(f => ({ name: f.name, tsType: f.tsType, type:
|
|
1820
|
+
const thisDecl = { name: cls.name, kind: "record", fields: cls.fields.map((f, i) => ({ name: f.name, tsType: f.tsType, type: fields[i].ty })) };
|
|
1769
1821
|
const allTypeDecls = [...typeDecls, thisDecl];
|
|
1770
1822
|
const methods = cls.methods.map(fn => resolveFunction(fn, allTypeDecls, pureFns, fnParams, fnReturns, externs, moduleConstants, {
|
|
1771
1823
|
thisBinding: { name: "this", ty: thisType },
|
|
@@ -1870,13 +1922,15 @@ export function resolveModule(raw) {
|
|
|
1870
1922
|
});
|
|
1871
1923
|
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: [] };
|
|
1872
1924
|
const constants = (raw.constants ?? []).map(c => {
|
|
1873
|
-
const
|
|
1925
|
+
const declaredTy = expandAlias(parseTsType(c.tsType), raw.typeDecls);
|
|
1874
1926
|
// Propagate the declared type into the value's resolution context so that
|
|
1875
1927
|
// record literals on map-typed constants (e.g. `Record<string, number>`)
|
|
1876
1928
|
// get their `ty` set to `map<...>` rather than `user("...")`.
|
|
1877
|
-
const valueCtx = { ...emptyCtx, returnTy:
|
|
1878
|
-
const value =
|
|
1879
|
-
|
|
1929
|
+
const valueCtx = { ...emptyCtx, returnTy: declaredTy };
|
|
1930
|
+
const value = resolveExpr(c.value, valueCtx);
|
|
1931
|
+
// TypeScript's number defaults to int, but fractional initializers need real.
|
|
1932
|
+
const ty = declaredTy.kind === "int" && value.ty.kind === "real" ? value.ty : declaredTy;
|
|
1933
|
+
return { name: c.name, ty, value: coerceToTargetTy(value, ty, raw.typeDecls) };
|
|
1880
1934
|
});
|
|
1881
1935
|
const moduleConstants = new Map(constants.map(c => [c.name, c.ty]));
|
|
1882
1936
|
return {
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { Project, ScriptTarget } from "ts-morph";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { findUp } from "./config.js";
|
|
4
|
+
/** Full TypeScript projects shared for the duration of one CLI batch. */
|
|
5
|
+
export class SourceProjects {
|
|
6
|
+
projects = new Map();
|
|
7
|
+
load(filePath) {
|
|
8
|
+
const absPath = path.resolve(filePath);
|
|
9
|
+
const tsConfigFilePath = findUp("tsconfig.json", absPath) ?? undefined;
|
|
10
|
+
const cached = tsConfigFilePath ? this.projects.get(tsConfigFilePath) : undefined;
|
|
11
|
+
const existing = cached?.project.getSourceFile(absPath);
|
|
12
|
+
if (existing && cached?.sources.has(existing))
|
|
13
|
+
return existing;
|
|
14
|
+
// Keep every configured file and its dependencies: otherwise ambient
|
|
15
|
+
// declarations and module augmentations can silently change the model.
|
|
16
|
+
const project = tsConfigFilePath
|
|
17
|
+
? new Project({ tsConfigFilePath })
|
|
18
|
+
: new Project({ compilerOptions: { strict: true, target: ScriptTarget.ESNext, lib: ["lib.esnext.d.ts"] } });
|
|
19
|
+
const included = project.getSourceFile(absPath);
|
|
20
|
+
if (tsConfigFilePath && included) {
|
|
21
|
+
this.projects.set(tsConfigFilePath, { project, sources: new Set(project.getSourceFiles()) });
|
|
22
|
+
return included;
|
|
23
|
+
}
|
|
24
|
+
// An explicitly requested file outside the configured graph may introduce
|
|
25
|
+
// globals or augmentations. Give it a fresh project so it cannot affect
|
|
26
|
+
// later entries. Files without a tsconfig likewise remain independent.
|
|
27
|
+
const sourceFile = project.addSourceFileAtPath(absPath);
|
|
28
|
+
project.resolveSourceFileDependencies();
|
|
29
|
+
return sourceFile;
|
|
30
|
+
}
|
|
31
|
+
}
|
package/tools/dist/transform.js
CHANGED
|
@@ -515,6 +515,22 @@ function lowerExpr(e, binds) {
|
|
|
515
515
|
const { premises, conclusion } = flattenImpl(e);
|
|
516
516
|
return { kind: "implies", premises: premises.map(transformExpr), conclusion: transformExpr(conclusion) };
|
|
517
517
|
}
|
|
518
|
+
// Boolean connectives evaluate the RHS only if the left operand selects
|
|
519
|
+
// it. Keep lifted calls in that branch instead of hoisting them eagerly.
|
|
520
|
+
if ((e.op === "&&" || e.op === "||") && e.left.ty.kind === "bool" && e.right.ty.kind === "bool") {
|
|
521
|
+
const left = lowerExpr(e.left, binds);
|
|
522
|
+
const rightBinds = binds ? [] : null;
|
|
523
|
+
const right = lowerExpr(e.right, rightBinds);
|
|
524
|
+
if (binds && rightBinds?.length) {
|
|
525
|
+
const name = freshName(`_branch${_branchCounter++}`);
|
|
526
|
+
const value = { kind: "var", name };
|
|
527
|
+
binds.push({ kind: "let", name, type: { kind: "bool" }, mutable: true, value: left });
|
|
528
|
+
binds.push({ kind: "if", cond: e.op === "&&" ? value : { kind: "unop", op: "¬", expr: value },
|
|
529
|
+
then: [...rightBinds, { kind: "assign", target: name, value: right }], else: [] });
|
|
530
|
+
return value;
|
|
531
|
+
}
|
|
532
|
+
return { kind: "binop", op: OP_MAP[e.op], left, right };
|
|
533
|
+
}
|
|
518
534
|
// Discriminant check: x.discriminant === "foo" → x = .foo (before generic string literal comparison)
|
|
519
535
|
if ((e.op === "===" || e.op === "!==") && e.left.kind === "field" && e.left.isDiscriminant && e.right.kind === "str") {
|
|
520
536
|
const objTy = e.left.obj.ty.kind === "user" ? e.left.obj.ty.name : undefined;
|
|
@@ -1060,12 +1076,25 @@ function lowerExpr(e, binds) {
|
|
|
1060
1076
|
// negation forms (`!s` → `s == ""`). Optional conds are already
|
|
1061
1077
|
// rewritten to someMatch by narrow.ts.
|
|
1062
1078
|
const cond = lowerExpr(asCondition(e.cond), binds);
|
|
1063
|
-
|
|
1064
|
-
|
|
1079
|
+
const thenBinds = binds ? [] : null;
|
|
1080
|
+
const elseBinds = binds ? [] : null;
|
|
1081
|
+
let thenExpr = lowerExpr(e.then, thenBinds);
|
|
1082
|
+
let elseExpr = lowerExpr(e.else, elseBinds);
|
|
1065
1083
|
if (e.ty.kind === "optional") {
|
|
1066
1084
|
thenExpr = wrapOptionalBranch(thenExpr, e.then);
|
|
1067
1085
|
elseExpr = wrapOptionalBranch(elseExpr, e.else);
|
|
1068
1086
|
}
|
|
1087
|
+
if (binds && (thenBinds?.length || elseBinds?.length)) {
|
|
1088
|
+
const name = freshName(`_branch${_branchCounter++}`);
|
|
1089
|
+
// Both arms assign before the result is read. This initializer is not
|
|
1090
|
+
// observable and supplies no assumption about the selected result.
|
|
1091
|
+
binds.push({ kind: "let", name, type: e.ty, mutable: true,
|
|
1092
|
+
value: { kind: _opts.backend === "dafny" ? "havoc" : "default", type: e.ty } });
|
|
1093
|
+
binds.push({ kind: "if", cond,
|
|
1094
|
+
then: [...(thenBinds ?? []), { kind: "assign", target: name, value: thenExpr }],
|
|
1095
|
+
else: [...(elseBinds ?? []), { kind: "assign", target: name, value: elseExpr }] });
|
|
1096
|
+
return { kind: "var", name };
|
|
1097
|
+
}
|
|
1069
1098
|
return { kind: "if", cond, then: thenExpr, else: elseExpr };
|
|
1070
1099
|
}
|
|
1071
1100
|
case "optChain":
|
|
@@ -1640,6 +1669,8 @@ function transformStmts(stmts, typeDecls) {
|
|
|
1640
1669
|
return result;
|
|
1641
1670
|
}
|
|
1642
1671
|
let _liftCounter = 0;
|
|
1672
|
+
// Branch results must not renumber the existing lifted-call temporaries.
|
|
1673
|
+
let _branchCounter = 0;
|
|
1643
1674
|
function liftMethodCalls(e) {
|
|
1644
1675
|
const binds = [];
|
|
1645
1676
|
return { binds, expr: lowerExpr(e, binds) };
|
|
@@ -2458,6 +2489,7 @@ export function transformModuleDafny(mod) {
|
|
|
2458
2489
|
export function transformModule(mod, specImport, moduleBaseOverride) {
|
|
2459
2490
|
_forofCounters.clear();
|
|
2460
2491
|
_liftCounter = 0;
|
|
2492
|
+
_branchCounter = 0;
|
|
2461
2493
|
_typeDecls = mod.typeDecls;
|
|
2462
2494
|
_neededKindHelpers = new Map();
|
|
2463
2495
|
_pureDefNames = new Set(mod.functions.filter(f => f.isPure).map(f => f.name));
|
|
@@ -2649,6 +2681,8 @@ export function transformModule(mod, specImport, moduleBaseOverride) {
|
|
|
2649
2681
|
}
|
|
2650
2682
|
};
|
|
2651
2683
|
const knownTypeNames = new Set(typeDecls.map(d => d.name));
|
|
2684
|
+
for (const cls of mod.classes ?? [])
|
|
2685
|
+
knownTypeNames.add(cls.name);
|
|
2652
2686
|
const allTypeParams = new Set();
|
|
2653
2687
|
// Exclude type params from the *source* decls — the transformed IR drops
|
|
2654
2688
|
// them for aliases (`type Step<S, A> = …`), and a generic alias's params
|
package/tools/dist/types.js
CHANGED
|
@@ -70,6 +70,18 @@ function tyFromTypeNode(tn) {
|
|
|
70
70
|
? { kind: "optional", inner: { kind: "string", values } }
|
|
71
71
|
: { kind: "string", values };
|
|
72
72
|
}
|
|
73
|
+
// Numeric literal unions have the same integer model as number, including
|
|
74
|
+
// in inline annotations and optional types with several numeric arms.
|
|
75
|
+
if (nonNullish.length >= 2 && nonNullish.every(a => {
|
|
76
|
+
if ("syntheticBool" in a)
|
|
77
|
+
return false;
|
|
78
|
+
const ty = tyFromTypeNode(a.node);
|
|
79
|
+
return ty.kind === "int" && !ty.big;
|
|
80
|
+
})) {
|
|
81
|
+
const inner = { kind: "int" };
|
|
82
|
+
return normalized.some(a => !("syntheticBool" in a) && isNullish(a.node))
|
|
83
|
+
? { kind: "optional", inner } : inner;
|
|
84
|
+
}
|
|
73
85
|
if (nonNullish.length === 1 && normalized.length >= 2) {
|
|
74
86
|
const sole = nonNullish[0];
|
|
75
87
|
const inner = "syntheticBool" in sole ? { kind: "bool" } : tyFromTypeNode(sole.node);
|
|
@@ -109,9 +121,13 @@ function tyFromTypeNode(tn) {
|
|
|
109
121
|
return { kind: "fn", params, result };
|
|
110
122
|
}
|
|
111
123
|
if (Node.isLiteralTypeNode(tn)) {
|
|
112
|
-
const
|
|
124
|
+
const literal = tn.getLiteral();
|
|
125
|
+
const lk = literal.getKind();
|
|
113
126
|
if (lk === SyntaxKind.TrueKeyword || lk === SyntaxKind.FalseKeyword)
|
|
114
127
|
return { kind: "bool" };
|
|
128
|
+
if (Node.isNumericLiteral(literal) ||
|
|
129
|
+
(Node.isPrefixUnaryExpression(literal) && Node.isNumericLiteral(literal.getOperand())))
|
|
130
|
+
return { kind: "int" };
|
|
115
131
|
}
|
|
116
132
|
switch (tn.getKind()) {
|
|
117
133
|
case SyntaxKind.NumberKeyword:
|