pud.dev 0.0.1 → 0.0.2

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.
Files changed (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +53 -27
  3. package/THIRD-PARTY-NOTICES +112 -0
  4. package/chunk-224av1ab.js +10 -0
  5. package/chunk-fstxscck.js +3 -0
  6. package/chunk-h90k6v7w.js +3 -0
  7. package/chunk-k7a83qqm.js +3 -0
  8. package/cli.js +37 -0
  9. package/index.js +2 -0
  10. package/lean/index.js +880 -0
  11. package/package.json +28 -19
  12. package/project-runner.js +2 -0
  13. package/types/assistant.d.ts +200 -0
  14. package/types/check.d.ts +55 -0
  15. package/types/expressions.d.ts +47 -0
  16. package/types/input-scope.d.ts +4 -0
  17. package/types/lean/command.d.ts +14 -0
  18. package/types/lean/index.d.ts +5 -0
  19. package/types/lean/number.d.ts +4 -0
  20. package/types/lean/program.d.ts +26 -0
  21. package/types/lean/replay-predicate.d.ts +5 -0
  22. package/types/lean/replay.d.ts +6 -0
  23. package/types/lean/scalar.d.ts +23 -0
  24. package/types/lean/subject.d.ts +25 -0
  25. package/types/lean/syntax.d.ts +42 -0
  26. package/types/module.d.ts +9 -0
  27. package/types/prover-process.d.ts +7 -0
  28. package/types/run.d.ts +30 -0
  29. package/types/source.d.ts +5 -0
  30. package/types/suite-authoring.d.ts +117 -0
  31. package/types/suite-check.d.ts +10 -0
  32. package/types/suite.d.ts +44 -0
  33. package/CLAUDE.md +0 -106
  34. package/scripts/pack.ts +0 -67
  35. package/scripts/setup-lean.ts +0 -88
  36. package/src/assistant.ts +0 -131
  37. package/src/check.ts +0 -173
  38. package/src/cli.ts +0 -70
  39. package/src/expressions.ts +0 -65
  40. package/src/input-scope.ts +0 -71
  41. package/src/lean/command.ts +0 -40
  42. package/src/lean/index.ts +0 -437
  43. package/src/lean/iteration.lean +0 -145
  44. package/src/lean/lean-assets.d.ts +0 -4
  45. package/src/lean/number.lean +0 -427
  46. package/src/lean/number.ts +0 -25
  47. package/src/lean/program.ts +0 -110
  48. package/src/lean/replay-predicate.ts +0 -95
  49. package/src/lean/replay.ts +0 -136
  50. package/src/lean/scalar.lean +0 -183
  51. package/src/lean/scalar.ts +0 -196
  52. package/src/lean/subject.ts +0 -443
  53. package/src/lean/syntax.ts +0 -287
  54. package/src/module.ts +0 -110
  55. package/src/project-runner.ts +0 -26
  56. package/src/prover-process.ts +0 -16
  57. package/src/reporter.ts +0 -173
  58. package/src/run.ts +0 -60
  59. package/src/source.ts +0 -54
  60. package/src/suite-authoring.ts +0 -135
  61. package/src/suite-check.ts +0 -157
  62. package/src/suite.ts +0 -515
  63. package/src/terminal-progress.ts +0 -145
  64. package/src/terminal.ts +0 -41
  65. package/test/authoring.test.ts +0 -151
  66. package/test/lean.test.ts +0 -394
  67. package/test/module.test.ts +0 -55
  68. package/test/number.test.ts +0 -318
  69. package/test/package.test.ts +0 -170
  70. package/test/suite.test.ts +0 -257
  71. package/tsconfig.json +0 -7
  72. package/tsconfig.pack.json +0 -12
  73. /package/{src/index.ts → types/index.d.ts} +0 -0
@@ -1,136 +0,0 @@
1
- import { traverseFast } from "@babel/types";
2
- import { mkdirSync, writeFileSync } from "node:fs";
3
- import { join } from "node:path";
4
- import type { Counterexample, ProofCall, ProofClaim } from "../assistant.ts";
5
- import { runProver } from "../prover-process.ts";
6
- import type { lowerProgram } from "./program.ts";
7
- import { replayConstraints } from "./replay-predicate.ts";
8
- import type { Sort } from "./syntax.ts";
9
-
10
- type Program = ReturnType<typeof lowerProgram>;
11
- type ReplayValue = bigint | number | boolean | readonly bigint[];
12
- const samples: Partial<Record<Sort, readonly ReplayValue[]>> = {
13
- integer: [0n, 1n, -1n, 2n, 9_007_199_254_740_993n],
14
- number: [0, -0, ...[1, 0.5, 0.25, 0.125, 1 / 16, 1 / 1024, Number.EPSILON, Number.MIN_VALUE,
15
- 2 ** -1022, Number.MAX_SAFE_INTEGER, Number.MAX_VALUE, Infinity].flatMap(x => [x, -x]), NaN],
16
- boolean: [false, true],
17
- integers: [[], [1n], [0n], [2n], [-1n, 2n], [1n, 1n], [9_007_199_254_740_993n]],
18
- };
19
-
20
- function inputsFor(program: Program) {
21
- // Branch literals often reach a path the generic boundary values miss.
22
- const numbers = new Set<number>(), integers = new Set<bigint>();
23
- for (const module of program.modules.values()) traverseFast(module.program, node => {
24
- if (node.type === "NumericLiteral" && numbers.size < 32) {
25
- numbers.add(node.value).add(-node.value);
26
- } else if (node.type === "BigIntLiteral" && integers.size < 32) {
27
- const value = BigInt(node.value);
28
- integers.add(value).add(-value);
29
- }
30
- });
31
- let inputs: ReplayValue[][] = [[]];
32
- for (const { sort } of program.root.params) {
33
- const base = samples[sort];
34
- if (!base) return [];
35
- const literals = sort === "number" ? numbers : sort === "integer" ? integers : [];
36
- const domain = [...base, ...[...literals].filter(value => !base.includes(value))];
37
- inputs = inputs.flatMap(input => domain.map(value => [...input, value])).slice(0, 128);
38
- }
39
- return inputs;
40
- }
41
-
42
- function literal(value: ReplayValue): string {
43
- if (typeof value === "bigint") return `${value}n`;
44
- if (typeof value === "number") return Object.is(value, -0) ? "-0" : String(value);
45
- if (typeof value === "boolean") return String(value);
46
- return `[${value.map(literal).join(", ")}]`;
47
- }
48
-
49
- /** Execute the observation against the same frozen files and resolved imports used by the proof. */
50
- export async function replayClaim(program: Program, claim: ProofClaim, directory: string): Promise<Counterexample | undefined> {
51
- if (claim.kind === "throw") return;
52
- const { params, name } = program.root;
53
- const observed: ProofCall = claim.observation ?? { kind: "call", callee: "subject",
54
- args: params.map(parameter => ({ kind: "parameter", name: parameter.name })),
55
- };
56
- const parameters = new Map(params.map((parameter, index) => [parameter.name, `args[${index}]`]));
57
- const modules = new Map<string, string>();
58
- function call(node: ProofCall): string {
59
- const subject = node.callee === "subject" ? program.root : program.resolve(node.callee.file, node.callee.name);
60
- modules.set(subject.file, modules.get(subject.file) ?? `module${modules.size}`);
61
- const args = node.args.map(arg => arg.kind === "parameter" ? parameters.get(arg.name)! : call(arg));
62
- return `${modules.get(subject.file)}[${JSON.stringify(subject.name)}](${args.join(", ")})`;
63
- }
64
- const premises = replayConstraints(claim.premises, parameters);
65
- const assertions = replayConstraints(claim.assertions, parameters);
66
- if (!premises || !assertions) return;
67
- const actual = call(observed);
68
- const reference = claim.kind === "equal" ? call(claim.reference) : undefined;
69
- const inputs = inputsFor(program);
70
- if (!inputs.length) return;
71
- const resultSort = (observed.callee === "subject" ? program.root : program.resolve(observed.callee.file, observed.callee.name)).result;
72
- const candidates = samples[resultSort]?.map(literal).join(", ") ?? "";
73
- const ambiguityCheck = claim.exactResult ? `
74
- const neighbors = typeof received === "bigint" ? [received + 1n, received - 1n] :
75
- typeof received === "number" ? [received + 1, received - 1, -received] : [!received];
76
- const alternative = [...neighbors, ${candidates}].find(value => !Object.is(received, value) && accepts(value));
77
- if (alternative !== undefined) {
78
- process.stdout.write(JSON.stringify({ index, received: display(received), alternative: display(alternative) }));
79
- break;
80
- }` : "";
81
- const files = new Map([...program.modules.keys()].map((file, index) => [file, `subject-${index}.ts`]));
82
- mkdirSync(directory);
83
- for (const [file, snapshot] of program.modules) {
84
- const rewritten = [...snapshot.resolvedImports].reverse().reduce((contents, entry) =>
85
- contents.slice(0, entry.start) + JSON.stringify(`./${files.get(entry.file)}`) + contents.slice(entry.end), snapshot.source);
86
- writeFileSync(join(directory, files.get(file)!), rewritten);
87
- }
88
-
89
- const imports = [...modules].map(([file, alias]) => `import * as ${alias} from "./${files.get(file)}";`);
90
- writeFileSync(join(directory, "replay.ts"), `${imports.join("\n")}
91
- const inputs = [${inputs.map(values => `[${values.map(literal).join(", ")}]`).join(",\n ")}];
92
- const display = value => typeof value === "bigint" ? String(value) + "n" : Object.is(value, -0) ? "-0" : String(value);
93
- function nearestInteger(x, tiesUp) {
94
- const lower = Math.floor(x), upper = Math.ceil(x);
95
- if (lower === upper) return lower;
96
- const midpoint = lower + 0.5;
97
- return (tiesUp ? x < midpoint : x <= midpoint) ? lower : upper;
98
- }
99
- for (const [index, args] of inputs.entries()) {
100
- if (!(${premises})) continue;
101
- let received;
102
- try { received = ${actual}; } catch { continue; }
103
- ${reference ? `let expected;
104
- try { expected = ${reference}; } catch { continue; }
105
- if (received === expected) continue;
106
- process.stdout.write(JSON.stringify({ index, expected: display(expected), received: display(received) }));` :
107
- `const accepts = received => ${assertions};
108
- if (accepts(received)) {${ambiguityCheck}
109
- continue;
110
- }
111
- process.stdout.write(JSON.stringify({ index, received: display(received) }));`}
112
- break;
113
- }
114
- `);
115
- const run = await runProver(process.execPath, ["--no-env-file", "run", "replay.ts"], {
116
- cwd: directory, timeout: 3_000, maxBuffer: 64 * 1024,
117
- });
118
- if (run.status !== 0) throw new Error(run.stderr.trim() || `Bun exited with status ${run.status}.`);
119
- if (!run.stdout) return;
120
- const { index, expected, received, alternative } = JSON.parse(run.stdout) as {
121
- index: number; expected?: string; received: string; alternative?: string;
122
- };
123
- const witness = inputs[index];
124
- if (!witness || (reference && typeof expected !== "string") || typeof received !== "string") throw new Error("Bun returned an invalid witness.");
125
- return {
126
- summary: alternative !== undefined ? `The result rule permits both ${received} and ${alternative} for the same input.`
127
- : expected === undefined ? `${name} returned ${received}, violating the result assertion in Bun.`
128
- : received === "NaN" && expected === "NaN"
129
- ? "Both calls returned NaN, which fails JavaScript strict equality."
130
- : `${name} returned a different value from the reference in Bun.`,
131
- input: Object.fromEntries(params.map((parameter, i) => [parameter.name, literal(witness[i]!)])),
132
- result: received,
133
- ...(alternative !== undefined && { alternative }),
134
- ...(expected !== undefined && { difference: { subject: name, expected, received } }),
135
- };
136
- }
@@ -1,183 +0,0 @@
1
- import Std
2
-
3
- namespace Pud.Scalar
4
-
5
- inductive Kind where
6
- | integer
7
- | boolean
8
-
9
- abbrev Value : Kind → Type
10
- | .integer => Int
11
- | .boolean => Bool
12
-
13
- inductive Unary : Kind → Kind → Type where
14
- | neg : Unary .integer .integer
15
- | not : Unary .boolean .boolean
16
- | truthy : Unary .integer .boolean
17
- | shift (count : Nat) : Unary .integer .integer
18
- | mask (bits : Nat) : Unary .integer .integer
19
-
20
- def Unary.apply : Unary i o → Value i → Value o
21
- | .neg, value => -value
22
- | .not, value => !value
23
- | .truthy, value => decide (value ≠ 0)
24
- | .shift count, value => value * (2 : Int) ^ count
25
- | .mask bits, value => value % (2 : Int) ^ bits
26
-
27
- -- A mask of low bits selects from the finite two's-complement encoding.
28
- def lowBits (value : Int) (bits : Nat) : Int :=
29
- Int.ofNat ((value % (2 : Int) ^ bits).toNat &&& ((2 : Nat) ^ bits - 1))
30
-
31
- theorem lowBits_preservation (value : Int) (bits : Nat) :
32
- lowBits value bits = value % (2 : Int) ^ bits := by
33
- have positive : 0 < (2 : Int) ^ bits := Int.pow_pos (by decide)
34
- have nonneg := Int.emod_nonneg value (Int.ne_of_gt positive)
35
- have below := Int.emod_lt_of_pos value positive
36
- have bound : (value % (2 : Int) ^ bits).toNat < (2 : Nat) ^ bits := by
37
- apply (Int.toNat_lt nonneg).mpr
38
- rw [Int.natCast_pow]
39
- exact below
40
- simp [lowBits, Nat.mod_eq_of_lt bound, Int.toNat_of_nonneg nonneg]
41
-
42
- def Unary.evaluate : Unary i o → Value i → Value o
43
- | .mask bits, value => lowBits value bits
44
- | op, value => op.apply value
45
-
46
- theorem Unary.preservation (op : Unary i o) (value : Value i) :
47
- op.evaluate value = op.apply value := by
48
- cases op <;> simp [Unary.evaluate, Unary.apply, lowBits_preservation]
49
-
50
- inductive Binary (ε : Type) : Kind → Kind → Type where
51
- | add : Binary ε .integer .integer
52
- | sub : Binary ε .integer .integer
53
- | mul : Binary ε .integer .integer
54
- | divide (zero : ε) : Binary ε .integer .integer
55
- | remainder (zero : ε) : Binary ε .integer .integer
56
- | lt : Binary ε .integer .boolean
57
- | lte : Binary ε .integer .boolean
58
- | gt : Binary ε .integer .boolean
59
- | gte : Binary ε .integer .boolean
60
- | equalInt : Binary ε .integer .boolean
61
- | equalBool : Binary ε .boolean .boolean
62
-
63
- def Binary.lower : Binary ε i o → Value i → Value i → Except ε (Value o)
64
- | .add, lhs, rhs => .ok (lhs + rhs)
65
- | .sub, lhs, rhs => .ok (lhs - rhs)
66
- | .mul, lhs, rhs => .ok (lhs * rhs)
67
- | .divide zero, lhs, rhs => if rhs = 0 then .error zero else .ok (Int.tdiv lhs rhs)
68
- | .remainder zero, lhs, rhs => if rhs = 0 then .error zero else .ok (Int.tmod lhs rhs)
69
- | .lt, lhs, rhs => .ok (decide (lhs < rhs))
70
- | .lte, lhs, rhs => .ok (decide (lhs ≤ rhs))
71
- | .gt, lhs, rhs => .ok (decide (lhs > rhs))
72
- | .gte, lhs, rhs => .ok (decide (lhs ≥ rhs))
73
- | .equalInt, lhs, rhs => .ok (decide (lhs = rhs))
74
- | .equalBool, lhs, rhs => .ok (decide (lhs = rhs))
75
-
76
- -- ECMAScript BigInt division truncates the exact quotient toward zero.
77
- def quotient (lhs rhs : Int) : Int :=
78
- let magnitude : Int := Int.ofNat (lhs.natAbs / rhs.natAbs)
79
- if (lhs < 0) ↔ (rhs < 0) then magnitude else -magnitude
80
-
81
- theorem quotient_eq_tdiv (lhs rhs : Int) : quotient lhs rhs = lhs.tdiv rhs := by
82
- cases lhs <;> cases rhs <;> simp [quotient, Int.tdiv, Int.natAbs, Int.not_lt.mpr (Int.ofNat_nonneg _)]
83
-
84
- -- ECMAScript BigInt remainder subtracts the divisor times the truncated quotient.
85
- theorem remainder_eq_tmod (lhs rhs : Int) :
86
- lhs - rhs * lhs.tdiv rhs = lhs.tmod rhs := by
87
- have := Int.tmod_add_tdiv lhs rhs
88
- omega
89
-
90
- def Binary.evaluate : Binary ε i o → Value i → Value i → Except ε (Value o)
91
- | .divide zero, lhs, rhs => if rhs = 0 then .error zero else .ok (quotient lhs rhs)
92
- | .remainder zero, lhs, rhs => if rhs = 0 then .error zero else .ok (lhs - rhs * quotient lhs rhs)
93
- | op, lhs, rhs => op.lower lhs rhs
94
-
95
- theorem Binary.preservation (op : Binary ε i o) (lhs rhs : Value i) :
96
- op.evaluate lhs rhs = op.lower lhs rhs := by
97
- cases op <;> simp [Binary.evaluate, Binary.lower, quotient_eq_tdiv, remainder_eq_tmod]
98
-
99
- inductive Expr (ε : Type) : Kind → Type where
100
- | integer (value : Int) : Expr ε .integer
101
- | boolean (value : Bool) : Expr ε .boolean
102
- | unary (op : Unary i o) (arg : Expr ε i) : Expr ε o
103
- | binary (op : Binary ε i o) (lhs rhs : Expr ε i) : Expr ε o
104
- | choose (test : Expr ε .boolean) (yes no : Expr ε o) : Expr ε o
105
- | and (lhs rhs : Expr ε .boolean) : Expr ε .boolean
106
- | or (lhs rhs : Expr ε .boolean) : Expr ε .boolean
107
- | bind (arg : Expr ε i) (next : Value i → Expr ε o) : Expr ε o
108
- | thrown (error : ε) : Expr ε o
109
- | handle (attempt recovery : Expr ε o) : Expr ε o
110
-
111
- -- Explicit evaluation order and abrupt completion on the source side.
112
- def evaluate : Expr ε o → Except ε (Value o)
113
- | .integer value => .ok value
114
- | .boolean value => .ok value
115
- | .unary op arg =>
116
- match evaluate arg with
117
- | .error error => .error error
118
- | .ok value => .ok (op.evaluate value)
119
- | .binary op lhs rhs =>
120
- match evaluate lhs with
121
- | .error error => .error error
122
- | .ok left =>
123
- match evaluate rhs with
124
- | .error error => .error error
125
- | .ok right => op.evaluate left right
126
- | .choose test yes no =>
127
- match evaluate test with
128
- | .error error => .error error
129
- | .ok value => if value then evaluate yes else evaluate no
130
- | .and lhs rhs =>
131
- match evaluate lhs with
132
- | .error error => .error error
133
- | .ok value => if value then evaluate rhs else .ok false
134
- | .or lhs rhs =>
135
- match evaluate lhs with
136
- | .error error => .error error
137
- | .ok value => if value then .ok true else evaluate rhs
138
- | .bind arg next =>
139
- match evaluate arg with
140
- | .error error => .error error
141
- | .ok value => evaluate (next value)
142
- | .thrown error => .error error
143
- | .handle attempt recovery =>
144
- match evaluate attempt with
145
- | .ok value => .ok value
146
- | .error _ => evaluate recovery
147
-
148
- -- Target denotation using the primitives and Except sequencing of the emitter.
149
- def lower : Expr ε o → Except ε (Value o)
150
- | .integer value => .ok value
151
- | .boolean value => .ok value
152
- | .unary op arg => (lower arg).bind fun value => .ok (op.apply value)
153
- | .binary op lhs rhs => (lower lhs).bind fun left => (lower rhs).bind fun right => op.lower left right
154
- | .choose test yes no => (lower test).bind fun value => if value then lower yes else lower no
155
- | .and lhs rhs => (lower lhs).bind fun value => if value then lower rhs else .ok false
156
- | .or lhs rhs => (lower lhs).bind fun value => if value then .ok true else lower rhs
157
- | .bind arg next => (lower arg).bind fun value => lower (next value)
158
- | .thrown error => .error error
159
- | .handle attempt recovery =>
160
- match lower attempt with
161
- | .ok value => .ok value
162
- | .error _ => lower recovery
163
-
164
- @[simp] theorem bind_ok {ε α β : Type} (value : α) (next : α → Except ε β) :
165
- (Except.ok value).bind next = next value := rfl
166
-
167
- @[simp] theorem bind_error {ε α β : Type} (error : ε) (next : α → Except ε β) :
168
- (Except.error error : Except ε α).bind next = .error error := rfl
169
-
170
- @[simp] theorem bind_return {ε α : Type} (value : Except ε α) :
171
- value.bind Except.ok = value := by cases value <;> rfl
172
-
173
- @[simp] theorem bind_if {ε α β : Type} (test : Prop) [Decidable test]
174
- (yes no : Except ε α) (next : α → Except ε β) :
175
- (if test then yes else no).bind next = if test then yes.bind next else no.bind next := by
176
- by_cases h : test <;> simp [h]
177
-
178
- theorem preservation (expression : Expr ε o) :
179
- evaluate expression = lower expression := by
180
- induction expression <;> simp [evaluate, lower, Except.bind, Unary.preservation, Binary.preservation, *]
181
- all_goals (repeat' (split <;> try simp_all))
182
-
183
- end Pud.Scalar
@@ -1,196 +0,0 @@
1
- /// <reference path="./lean-assets.d.ts" />
2
- import type { BlockStatement, Node, Statement, VariableDeclarator } from "@babel/types";
3
- import iterationModel from "./iteration.lean" with { type: "text" };
4
- import scalarModel from "./scalar.lean" with { type: "text" };
5
- import { errorKinds, type Sort } from "./syntax.ts";
6
-
7
- export const scalarSemantics = scalarModel.replace(/^import Std\s*/, "").trimEnd();
8
- export const iterationSemantics = iterationModel.replace(/^import Std\s*/, "").trimEnd();
9
-
10
- type Kind = "integer" | "boolean";
11
- type Scalar = { sort: Kind; code: string };
12
- type Scope = ReadonlyMap<string, Scalar>;
13
-
14
- interface ScalarFunction {
15
- code: string;
16
- result: Sort;
17
- sourceExpression?: string;
18
- }
19
-
20
- const integerOperators = { "+": "add", "-": "sub", "*": "mul",
21
- "<": "lt", "<=": "lte", ">": "gt", ">=": "gte" } as const;
22
-
23
- export function scalarValue(sort: Sort, value: string): Scalar | undefined {
24
- return sort === "integer" || sort === "boolean" ? { sort, code: `(.${sort} ${value})` } : undefined;
25
- }
26
-
27
- export function scalarCall(subject: ScalarFunction, args: readonly (Scalar | undefined)[], fresh: () => string): Scalar | undefined {
28
- if (!subject.sourceExpression || args.some(arg => arg === undefined)) return;
29
- const sort = subject.result;
30
- if (sort !== "integer" && sort !== "boolean") return;
31
- const names = args.map(fresh);
32
- const call = `(${[subject.code + "Source", ...names].join(" ")})`;
33
- return { sort, code: args.reduceRight((body, arg, index) =>
34
- `(.bind ${arg!.code} (fun ${names[index]} => ${body}))`, call) };
35
- }
36
-
37
- class OutsideScalarSemantics extends Error {}
38
- function outside(): never { throw new OutsideScalarSemantics(); }
39
-
40
- /** Reify the frozen AST independently of the ordinary Lean expression printer. */
41
- export function scalarSource(
42
- fn: Node, parameters: readonly { name: string; sort: Sort; code: string }[], result: Sort,
43
- callees: ReadonlyMap<string, ScalarFunction>,
44
- ): string | undefined {
45
- if (result !== "integer" && result !== "boolean") return;
46
- const scope = new Map<string, Scalar>();
47
- for (const param of parameters) {
48
- const value = scalarValue(param.sort, param.code);
49
- if (!value) return;
50
- scope.set(param.name, { sort: value.sort, code: param.code });
51
- }
52
-
53
- let next = 0;
54
- const fresh = () => `_js${next++}`;
55
- const unary = (op: string, value: Scalar, sort: Kind): Scalar => ({ sort, code: `(.unary .${op} ${value.code})` });
56
- const conditional = (test: Scalar, yes: string, no: string) =>
57
- `(.choose ${test.sort === "integer" ? unary("truthy", test, "boolean").code : test.code} ${yes} ${no})`;
58
- const extend = (env: Scope, name: string, value: Scalar): Scope => new Map([...env, [name, value]]);
59
-
60
- function expression(node: Node, env: Scope): Scalar {
61
- switch (node.type) {
62
- case "Identifier": {
63
- const value = env.get(node.name) ?? outside();
64
- return scalarValue(value.sort, value.code)!;
65
- }
66
- case "BigIntLiteral": return scalarValue("integer", `(${BigInt(node.value)} : Int)`)!;
67
- case "BooleanLiteral": return scalarValue("boolean", String(node.value))!;
68
- case "UnaryExpression": {
69
- const arg = expression(node.argument, env);
70
- if (node.operator === "-") return unary("neg", arg, "integer");
71
- if (node.operator === "!") return unary("not", arg, "boolean");
72
- return outside();
73
- }
74
- case "LogicalExpression": {
75
- if (node.operator !== "&&" && node.operator !== "||") return outside();
76
- const lhs = expression(node.left, env), rhs = expression(node.right, env);
77
- return { sort: "boolean", code: `(.${node.operator === "&&" ? "and" : "or"} ${lhs.code} ${rhs.code})` };
78
- }
79
- case "ConditionalExpression": {
80
- const yes = expression(node.consequent, env), no = expression(node.alternate, env);
81
- return { sort: yes.sort, code: conditional(expression(node.test, env), yes.code, no.code) };
82
- }
83
- case "BinaryExpression": {
84
- const lhs = expression(node.left, env), op = node.operator;
85
- if (op === "<<") {
86
- if (node.right.type !== "BigIntLiteral") return outside();
87
- return { sort: "integer", code: `(.unary (.shift ${BigInt(node.right.value)}) ${lhs.code})` };
88
- }
89
- if (op === "&") {
90
- if (node.right.type !== "BigIntLiteral") return outside();
91
- const mask = BigInt(node.right.value);
92
- if ((mask & (mask + 1n)) !== 0n) return outside();
93
- const bits = mask === 0n ? 0 : mask.toString(2).length;
94
- return { sort: "integer", code: `(.unary (.mask ${bits}) ${lhs.code})` };
95
- }
96
- const rhs = expression(node.right, env);
97
- if (op === "/" || op === "%") {
98
- const operator = op === "/" ? "divide" : "remainder";
99
- return { sort: "integer", code: `(.binary (.${operator} .rangeError) ${lhs.code} ${rhs.code})` };
100
- }
101
- if (op === "===" || op === "!==") {
102
- const equality = lhs.sort === "integer" ? "equalInt" : "equalBool";
103
- const equal: Scalar = { sort: "boolean", code: `(.binary .${equality} ${lhs.code} ${rhs.code})` };
104
- return op === "===" ? equal : unary("not", equal, "boolean");
105
- }
106
- if (!Object.hasOwn(integerOperators, op)) return outside();
107
- const operator = integerOperators[op as keyof typeof integerOperators];
108
- const sort = op === "+" || op === "-" || op === "*" ? "integer" : "boolean";
109
- return { sort, code: `(.binary .${operator} ${lhs.code} ${rhs.code})` };
110
- }
111
- case "CallExpression": {
112
- if (node.callee.type !== "Identifier") return outside();
113
- const callee = callees.get(node.callee.name) ?? outside();
114
- return scalarCall(callee, node.arguments.map(arg => expression(arg, env)), fresh) ?? outside();
115
- }
116
- default: return outside();
117
- }
118
- }
119
-
120
- const type = (value: Scalar) => value.sort === "integer" ? "Int" : "Bool";
121
-
122
- function bind(name: string, value: Scalar, env: Scope, resume: (scope: Scope) => string): string {
123
- const local = fresh();
124
- return `(.bind ${value.code} (fun ${local} => ${resume(extend(env, name, { sort: value.sort, code: local }))}))`;
125
- }
126
-
127
- function declarations(nodes: readonly VariableDeclarator[], env: Scope, resume: (scope: Scope) => string): string {
128
- const [node, ...rest] = nodes;
129
- if (!node) return resume(env);
130
- if (node.id.type !== "Identifier" || !node.init) return outside();
131
- return bind(node.id.name, expression(node.init, env), env, scope => declarations(rest, scope, resume));
132
- }
133
-
134
- function statements(nodes: readonly Statement[], env: Scope, resume: (scope: Scope) => string): string {
135
- const [node, ...rest] = nodes;
136
- if (!node) return resume(env);
137
- const continueWith = (scope: Scope) => statements(rest, scope, resume);
138
- switch (node.type) {
139
- case "ReturnStatement": return node.argument ? expression(node.argument, env).code : outside();
140
- case "EmptyStatement": return continueWith(env);
141
- case "VariableDeclaration": return declarations(node.declarations, env, continueWith);
142
- case "ExpressionStatement": {
143
- const assignment = node.expression;
144
- if (assignment.type !== "AssignmentExpression" || assignment.left.type !== "Identifier") return outside();
145
- const name = assignment.left.name;
146
- const rhs = expression(assignment.right, env);
147
- if (assignment.operator === "=") return bind(name, rhs, env, continueWith);
148
- if (assignment.operator !== "+=" && assignment.operator !== "-=") return outside();
149
- const lhs = expression(assignment.left, env);
150
- const op = assignment.operator === "+=" ? "add" : "sub";
151
- return bind(name, { sort: "integer", code: `(.binary .${op} ${lhs.code} ${rhs.code})` }, env, continueWith);
152
- }
153
- case "ThrowStatement": {
154
- const thrown = node.argument;
155
- if (thrown.type !== "NewExpression" || thrown.callee.type !== "Identifier" || !Object.hasOwn(errorKinds, thrown.callee.name)) return outside();
156
- return `(.thrown .${errorKinds[thrown.callee.name as keyof typeof errorKinds]})`;
157
- }
158
- case "IfStatement": {
159
- // Share the continuation so consecutive if statements don't duplicate the source witness.
160
- const captured = [...env].map(([name, value]) => [name, { sort: value.sort, code: fresh() }] as const);
161
- const continuation = fresh();
162
- let used = false;
163
- const resumeBranch = (scope: Scope) => {
164
- used = true;
165
- return `(${[continuation, ...captured.map(([name]) => scope.get(name)!.code)].join(" ")})`;
166
- };
167
- const yes = statements(branch(node.consequent), env, resumeBranch);
168
- const no = statements(branch(node.alternate), env, resumeBranch);
169
- const choice = conditional(expression(node.test, env), yes, no);
170
- if (!used) return choice;
171
- const args = captured.map(([, value]) => `(${value.code} : ${type(value)})`);
172
- const tail = continueWith(new Map(captured));
173
- return `(let ${continuation}${args.length ? " " + args.join(" ") : ""} := ${tail}; ${choice})`;
174
- }
175
- case "TryStatement": {
176
- const [attempt] = node.block.body;
177
- if (node.block.body.length !== 1 || attempt?.type !== "ReturnStatement" || !attempt.argument ||
178
- !node.handler || node.handler.param || node.finalizer) return outside();
179
- const recover = statements(node.handler.body.body, env, next => continueWith(new Map([...env].map(([name]) => [name, next.get(name)!]))));
180
- return `(.handle ${expression(attempt.argument, env).code} ${recover})`;
181
- }
182
- default: return outside();
183
- }
184
- }
185
-
186
- function branch(node: Statement | null | undefined): BlockStatement["body"] {
187
- return node?.type === "BlockStatement" ? node.body : node ? [node] : [];
188
- }
189
-
190
- try {
191
- if (fn.type === "BlockStatement") return statements(fn.body, scope, outside);
192
- return expression(fn, scope).code;
193
- } catch (error) {
194
- if (!(error instanceof OutsideScalarSemantics)) throw error;
195
- }
196
- }