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,287 +0,0 @@
1
- import type { CallExpression, Node } from "@babel/types";
2
- import { readExpression, ref, type Expr } from "../expressions.ts";
3
- import { invalid } from "../source.ts";
4
- import { numberBinary, numberLiteral } from "./number.ts";
5
-
6
- export const leanTypes = {
7
- integer: "Int",
8
- number: "JSNumber",
9
- boolean: "Bool",
10
- integers: "List Int",
11
- items: "List Item",
12
- textOrItems: "Option (List Item)",
13
- };
14
- export type Sort = keyof typeof leanTypes;
15
- export type Value = { sort: Sort; code: string; fallible?: boolean };
16
-
17
- export const errorKinds = { Error: "error", RangeError: "rangeError", TypeError: "typeError" } as const;
18
-
19
- export function isScalar(sort: Sort): sort is "integer" | "number" | "boolean" {
20
- return sort === "integer" || sort === "number" || sort === "boolean";
21
- }
22
-
23
- export function truthy(value: Value, code: string) {
24
- if (value.sort === "number") return `(JSNumber.truthy ${code})`;
25
- return value.sort === "integer" ? `(decide (${code} ≠ (0 : Int)))` : code;
26
- }
27
-
28
- export function nameOf(file: string, node: Node | null | undefined): string {
29
- if (node?.type !== "Identifier" || node.name === "this" || node.optional || node.decorators?.length) {
30
- return invalid(file, node ?? undefined, "Expected a named binding.");
31
- }
32
- return node.name;
33
- }
34
-
35
- function arrayElement(type: Node) {
36
- if (type.type === "TSTypeOperator" && type.operator === "readonly" && type.typeAnnotation.type === "TSArrayType") {
37
- return type.typeAnnotation.elementType;
38
- }
39
- }
40
-
41
- export function tsSort(
42
- file: string,
43
- annotation: Node | null | undefined,
44
- at: Node,
45
- registerItem?: (name: string, node: Node) => void,
46
- ): Sort {
47
- function isOpaqueItem(element: Node | undefined) {
48
- if (!registerItem || element?.type !== "TSTypeReference" || element.typeName.type !== "Identifier" || element.typeArguments) return false;
49
- registerItem(element.typeName.name, element);
50
- return true;
51
- }
52
-
53
- if (annotation?.type === "TSTypeAnnotation") {
54
- const type = annotation.typeAnnotation;
55
- if (type.type === "TSBigIntKeyword") return "integer";
56
- if (type.type === "TSNumberKeyword") return "number";
57
- if (type.type === "TSBooleanKeyword") return "boolean";
58
- const element = arrayElement(type);
59
- if (element?.type === "TSBigIntKeyword") return "integers";
60
- if (isOpaqueItem(element)) return "items";
61
- if (type.type === "TSUnionType" && type.types.length === 2 && type.types.some(branch => branch.type === "TSStringKeyword")) {
62
- const array = type.types.find(branch => branch.type !== "TSStringKeyword");
63
- if (array && isOpaqueItem(arrayElement(array))) return "textOrItems";
64
- }
65
- }
66
- return invalid(file, at, "Expected bigint, number, boolean, a supported readonly array, or a string-or-record-array union.");
67
- }
68
-
69
- const comparisons = { "<": "<", "<=": "≤", ">": ">", ">=": "≥", "===": "=", "!==": "≠" } as const;
70
-
71
- function emit(expr: Expr): string {
72
- switch (expr.kind) {
73
- case "integer": return `(${expr.value} : Int)`;
74
- case "boolean": return String(expr.value);
75
- case "reference": return expr.path[0]!;
76
- case "unary": return `(${expr.op}${emit(expr.arg)})`;
77
- case "choose": return `(if ${emit(expr.test)} then ${emit(expr.yes)} else ${emit(expr.no)})`;
78
- case "binary": {
79
- const lhs = emit(expr.left), rhs = emit(expr.right);
80
- if (expr.op in comparisons) {
81
- return `(decide (${lhs} ${comparisons[expr.op as keyof typeof comparisons]} ${rhs}))`;
82
- }
83
- return `(${lhs} ${expr.op} ${rhs})`;
84
- }
85
- default: throw new Error(`Unexpected expression in Lean lowering: ${expr.kind}`);
86
- }
87
- }
88
-
89
- function readSpecCall(file: string, node: Node, helpers: ReadonlySet<string> | undefined, read: (node: Node) => Value): Value | undefined {
90
- if (node.type !== "CallExpression" || node.typeArguments || node.callee.type !== "MemberExpression" || node.callee.computed ||
91
- node.callee.object.type !== "Identifier" || !helpers?.has(node.callee.object.name) || node.callee.property.type !== "Identifier") return;
92
- const name = node.callee.property.name;
93
- if (name === "sum" || name === "length") {
94
- const [input] = node.arguments;
95
- if (node.arguments.length !== 1 || !input) invalid(file, node, `Pass one array to pud.${name}().`);
96
- const value = read(input);
97
- if (name === "sum") {
98
- return { sort: "integer", code: `(List.sum ${ofSort(file, input, value, "integers")})` };
99
- }
100
- if (value.sort !== "integers" && value.sort !== "items") invalid(file, input, "Pass a supported array to pud.length().");
101
- return { sort: "integer", code: `(Int.ofNat (List.length ${value.code}))` };
102
- }
103
- if (name === "modulo") {
104
- const [input, divisor] = node.arguments;
105
- if (node.arguments.length !== 2 || !input || divisor?.type !== "BigIntLiteral" || BigInt(divisor.value) <= 0n) {
106
- invalid(file, node, "Pass a bigint and a positive literal divisor to pud.modulo().");
107
- }
108
- return { sort: "integer", code: `(${ofSort(file, input, read(input), "integer")} % (${BigInt(divisor.value)} : Int))` };
109
- }
110
- if (name === "quotient") {
111
- const [input, divisor] = node.arguments;
112
- if (node.arguments.length !== 2 || !input || !divisor) invalid(file, node, "Pass two bigints to pud.quotient().");
113
- const lhs = ofSort(file, input, read(input), "integer"), rhs = ofSort(file, divisor, read(divisor), "integer");
114
- return { sort: "integer", code: `(Int.tdiv ${lhs} ${rhs})` };
115
- }
116
- }
117
-
118
- export function asOutcome(value: Value): string {
119
- return value.fallible ? value.code : `(Except.ok (${value.code}))`;
120
- }
121
-
122
- /** Sequence exactly the potentially throwing operands in JavaScript evaluation order. */
123
- export function sequence(values: readonly Value[], fresh: () => string, finish: (codes: string[]) => Value): Value {
124
- const steps: string[] = [];
125
- const operands = values.map(value => {
126
- if (!value.fallible) return value.code;
127
- const name = fresh();
128
- steps.push(`let ${name} ← ${value.code};`);
129
- return name;
130
- });
131
- const result = finish(operands);
132
- if (!steps.length) return result;
133
- return { sort: result.sort, fallible: true, code: `(do ${steps.join(" ")} ${asOutcome(result)})` };
134
- }
135
-
136
- export function invoke(callee: { code: string; result: Sort; fallible: boolean }, args: readonly Value[], fresh: () => string): Value {
137
- return sequence(args, fresh, values => ({
138
- sort: callee.result,
139
- fallible: callee.fallible,
140
- code: values.length ? `(${callee.code} ${values.join(" ")})` : callee.code,
141
- }));
142
- }
143
-
144
- export interface ExecutableExpressions {
145
- fresh(): string;
146
- call(node: CallExpression, read: (value: Node) => Value): Value;
147
- recursive: boolean;
148
- numberGlobal: boolean;
149
- }
150
-
151
- export function bigintLiteral(node: Node): bigint | undefined {
152
- if (node.type === "BigIntLiteral") return BigInt(node.value);
153
- if (node.type === "UnaryExpression" && node.operator === "-" && node.argument.type === "BigIntLiteral") {
154
- return -BigInt(node.argument.value);
155
- }
156
- }
157
-
158
- export function readValue(
159
- file: string, node: Node, scope: ReadonlyMap<string, Value>, helpers?: ReadonlySet<string>, executable?: ExecutableExpressions, numberGlobal = executable?.numberGlobal,
160
- ): Value {
161
- if (node.type === "Identifier") return scope.get(node.name) ?? invalid(file, node, `Unknown binding '${node.name}'.`);
162
- if (node.type === "NumericLiteral") return numberLiteral(node.value);
163
- const read = (child: Node) => readValue(file, child, scope, helpers, executable, numberGlobal);
164
- const fresh = () => executable?.fresh() ?? invalid(file, node, "A specification expression must be total.");
165
- if (node.type === "CallExpression" && node.callee.type === "MemberExpression" && !node.callee.computed &&
166
- node.callee.object.type === "Identifier" && node.callee.object.name === "Number" && node.callee.property.type === "Identifier" &&
167
- (node.callee.property.name === "isInteger" || node.callee.property.name === "isNaN")) {
168
- const method = node.callee.property.name;
169
- if (!numberGlobal || scope.has("Number")) invalid(file, node, `Number.${method} requires the unshadowed Number built-in.`);
170
- const [arg] = node.arguments;
171
- if (node.typeArguments || node.arguments.length !== 1 || !arg) invalid(file, node, `Pass one number to Number.${method}.`);
172
- const value = read(arg);
173
- ofSort(file, arg, value, "number");
174
- return sequence([value], fresh, ([x]) => ({ sort: "boolean", code: `(JSNumber.${method} ${x})` }));
175
- }
176
- const spec = readSpecCall(file, node, helpers, read);
177
- if (spec) return spec;
178
- if (node.type === "CallExpression" && executable) return executable.call(node, read);
179
-
180
- const operands: Node[] = node.type === "BinaryExpression" ? [node.left, node.right] : node.type === "UnaryExpression" ? [node.argument] : [];
181
- const values = operands.map(read);
182
- if (node.type === "BinaryExpression") {
183
- const op = node.operator;
184
- const left = values[0]!, right = values[1]!;
185
- if (left.sort === "number" || right.sort === "number") {
186
- ofSort(file, node.left, left, "number");
187
- ofSort(file, node.right, right, "number");
188
- return sequence(values, fresh, ([a, b]) => numberBinary(op, a!, b!) ?? invalid(file, node, `Unsupported number operator '${op}'.`));
189
- }
190
- if (op === "/" || op === "%") {
191
- const divisor = bigintLiteral(node.right);
192
- if (!executable && (divisor === undefined || divisor === 0n)) {
193
- invalid(file, node.right, "A specification division or remainder needs a nonzero bigint literal divisor.");
194
- }
195
- ofSort(file, node.left, left, "integer");
196
- ofSort(file, node.right, right, "integer");
197
- const operation = op === "%" ? "Int.tmod" : "Int.tdiv";
198
- return sequence([left, right], fresh, ([lhs, rhs]) => divisor !== undefined && divisor !== 0n
199
- ? { sort: "integer", code: `(${operation} ${lhs} ${rhs})` }
200
- : { sort: "integer", fallible: true, code: `(if ${rhs} = 0 then Except.error .rangeError else Except.ok (${operation} ${lhs} ${rhs}))` });
201
- }
202
- if (op === "<<" || op === "&") {
203
- const literal = node.right.type === "BigIntLiteral" ? BigInt(node.right.value) : undefined;
204
- if (literal === undefined || (op === "&" && (literal & (literal + 1n)) !== 0n)) {
205
- invalid(file, node.right, op === "<<" ? "Bigint left shift needs a nonnegative literal count."
206
- : "Bigint bitwise AND needs a literal mask with only consecutive low bits set.");
207
- }
208
- ofSort(file, node.left, left, "integer");
209
- return sequence([left], fresh, ([lhs]) => ({ sort: "integer",
210
- code: op === "<<" ? `(${lhs} * (2 : Int) ^ (${literal} : Nat))` : `(${lhs} % (${literal + 1n} : Int))` }));
211
- }
212
- }
213
-
214
- if (node.type === "UnaryExpression" && values[0]?.sort === "number") {
215
- return sequence(values, fresh, ([x]) => {
216
- if (node.operator === "-") return { sort: "number", code: `(JSNumber.neg ${x})` };
217
- if (node.operator === "+") return { sort: "number", code: x! };
218
- if (node.operator === "!") return { sort: "boolean", code: `(!(JSNumber.truthy ${x}))` };
219
- return invalid(file, node, `Unsupported number operator '${node.operator}'.`);
220
- });
221
- }
222
- const conditional = (test: Value, yes: Value, no: Value): Value => {
223
- if (test.sort !== "number") ofSort(file, node, test, "boolean");
224
- if (yes.sort !== no.sort) invalid(file, node, "A conditional needs two branches of the same type.");
225
- const branchesThrow = yes.fallible || no.fallible;
226
- const premise = executable?.recursive ? `_${fresh()} : ` : "";
227
- return sequence([test], fresh, ([code]) => ({
228
- sort: yes.sort, fallible: branchesThrow,
229
- code: `(if ${premise}${truthy(test, code!)} then ${branchesThrow ? asOutcome(yes) : yes.code} else ${branchesThrow ? asOutcome(no) : no.code})`,
230
- }));
231
- };
232
- if (node.type === "ConditionalExpression") return conditional(read(node.test), read(node.consequent), read(node.alternate));
233
- if (node.type === "LogicalExpression" && (node.operator === "&&" || node.operator === "||")) {
234
- const left = read(node.left), right = read(node.right);
235
- ofSort(file, node.left, left, "boolean");
236
- ofSort(file, node.right, right, "boolean");
237
- if (left.fallible || right.fallible || executable?.recursive) {
238
- const short = { sort: "boolean" as const, code: node.operator === "&&" ? "false" : "true" };
239
- return node.operator === "&&" ? conditional(left, right, short) : conditional(left, short, right);
240
- }
241
- return { sort: "boolean", code: `(${left.code} ${node.operator} ${right.code})` };
242
- }
243
-
244
- return sequence(values, fresh, codes => {
245
- const expr = readExpression(file, node, child => {
246
- const i = operands.indexOf(child);
247
- if (i === -1) return;
248
- // The shared reader checks scalar operand types and chooses the result sort.
249
- const value = values[i]!;
250
- if (value.sort !== "integer" && value.sort !== "boolean") invalid(file, child, "Use arrays and unions as whole values.");
251
- return ref(value.sort, codes[i]!);
252
- });
253
- if (expr.sort === "string") return invalid(file, node, "Use bigint or boolean for scalar values in the Lean adapter.");
254
- return { sort: expr.sort, code: emit(expr) };
255
- });
256
- }
257
-
258
- export function ofSort<T extends Sort>(file: string, at: Node, value: Value, expected: T): string {
259
- if (value.sort !== expected) invalid(file, at, `Expected ${leanTypes[expected]}, got ${leanTypes[value.sort]}.`);
260
- return value.code;
261
- }
262
-
263
- export function readProposition(file: string, node: Node, scope: ReadonlyMap<string, Value>, helpers?: ReadonlySet<string>, numberGlobal?: boolean): string {
264
- const read = (child: Node) => readValue(file, child, scope, helpers, undefined, numberGlobal);
265
- const predicate = (child: Node) => readProposition(file, child, scope, helpers, numberGlobal);
266
- if (node.type === "LogicalExpression" && (node.operator === "&&" || node.operator === "||")) {
267
- return `(${predicate(node.left)} ${node.operator === "&&" ? "∧" : "∨"} ${predicate(node.right)})`;
268
- }
269
- if (node.type === "UnaryExpression" && node.operator === "!") {
270
- const value = read(node.argument);
271
- if (value.sort === "number") return `(JSNumber.truthy ${value.code} = false)`;
272
- return `(¬ ${predicate(node.argument)})`;
273
- }
274
- if (node.type === "BinaryExpression" && Object.hasOwn(comparisons, node.operator)) {
275
- const left = read(node.left);
276
- if (left.sort === "number") {
277
- const right = ofSort(file, node.right, read(node.right), "number");
278
- return `(${numberBinary(node.operator, left.code, right)!.code} = true)`;
279
- }
280
- const sort = node.operator === "===" || node.operator === "!==" ? left.sort : "integer";
281
- if (!isScalar(sort)) invalid(file, node, "Use equality on bigint or boolean values.");
282
- const lhs = ofSort(file, node.left, left, sort);
283
- const rhs = ofSort(file, node.right, read(node.right), sort);
284
- return `(${lhs} ${comparisons[node.operator as keyof typeof comparisons]} ${rhs})`;
285
- }
286
- return `(${ofSort(file, node, read(node), "boolean")} = true)`;
287
- }
package/src/module.ts DELETED
@@ -1,110 +0,0 @@
1
- import { traverseFast, type ArrowFunctionExpression, type FunctionDeclaration, type Node, type Program } from "@babel/types";
2
- import { invalid } from "./source.ts";
3
-
4
- type SubjectFunction = FunctionDeclaration | ArrowFunctionExpression;
5
-
6
- function literalInitializer(node: Node | null | undefined): boolean {
7
- if (!node) return false;
8
- switch (node.type) {
9
- case "StringLiteral":
10
- case "NumericLiteral":
11
- case "BooleanLiteral":
12
- case "BigIntLiteral":
13
- case "NullLiteral":
14
- return true;
15
- case "TemplateLiteral":
16
- return node.expressions.length === 0;
17
- case "UnaryExpression":
18
- return node.operator === "-" && (node.argument.type === "BigIntLiteral" || node.argument.type === "NumericLiteral");
19
- case "TSAsExpression":
20
- case "TSSatisfiesExpression":
21
- case "TSTypeAssertion":
22
- return literalInitializer(node.expression);
23
- default:
24
- return false;
25
- }
26
- }
27
-
28
- function writesBinding(target: Node, name: string): boolean {
29
- switch (target.type) {
30
- case "Identifier":
31
- return target.name === name;
32
- case "MemberExpression":
33
- case "OptionalMemberExpression":
34
- case "VariableDeclaration": // A declaration in a sibling's for-in/of creates a local binding.
35
- return false;
36
- case "ObjectPattern":
37
- return target.properties.some(p => writesBinding(p.type === "RestElement" ? p.argument : p.value, name));
38
- case "ArrayPattern":
39
- return target.elements.some(item => item !== null && writesBinding(item, name));
40
- case "RestElement":
41
- return writesBinding(target.argument, name);
42
- case "AssignmentPattern":
43
- return writesBinding(target.left, name);
44
- case "ParenthesizedExpression":
45
- case "TSAsExpression":
46
- case "TSInstantiationExpression":
47
- case "TSNonNullExpression":
48
- case "TSSatisfiesExpression":
49
- case "TSTypeAssertion":
50
- return writesBinding(target.expression, name);
51
- default:
52
- return true; // An unfamiliar write target needs review before we can admit it.
53
- }
54
- }
55
-
56
- // A callable sibling must not be able to replace the exported binding after verification.
57
- function checkSibling(file: string, fn: SubjectFunction, subject: string) {
58
- const hasLocalParameter = fn.params.some(p => p.type === "Identifier" && p.name === subject);
59
- traverseFast(fn, node => {
60
- if (node.type === "Identifier" && node.name === "eval") {
61
- invalid(file, node, "Cannot verify a function alongside code that may evaluate dynamic JavaScript.");
62
- }
63
- const target = node.type === "UpdateExpression" ? node.argument
64
- : node.type === "AssignmentExpression" || node.type === "ForOfStatement" || node.type === "ForInStatement" ? node.left
65
- : undefined;
66
- if (target && !hasLocalParameter && writesBinding(target, subject)) {
67
- invalid(file, target, `Another function may reassign the verified binding '${subject}'.`);
68
- }
69
- });
70
- }
71
-
72
- type FunctionOptions = { allowArrowFunctions: true; allowLocalFunctions?: boolean };
73
-
74
- export function selectSubject(program: Program, file: string, name: string): FunctionDeclaration;
75
- export function selectSubject(program: Program, file: string, name: string, options: FunctionOptions): SubjectFunction;
76
- export function selectSubject(program: Program, file: string, name: string, options?: FunctionOptions): SubjectFunction {
77
- let fn: SubjectFunction | undefined;
78
- for (const stmt of program.body) {
79
- if (stmt.type === "ImportDeclaration" && stmt.importKind === "type") continue;
80
- if ((stmt.type === "ExportNamedDeclaration" || stmt.type === "ExportAllDeclaration") && stmt.exportKind === "type") continue;
81
- const exported = stmt.type === "ExportNamedDeclaration";
82
- const selectable = exported || options?.allowLocalFunctions;
83
- const decl = exported ? stmt.declaration : stmt;
84
- if (decl?.type === "FunctionDeclaration") {
85
- if (selectable && decl.id?.name === name) fn = decl;
86
- else checkSibling(file, decl, name);
87
- continue;
88
- }
89
- if (decl?.type === "TSInterfaceDeclaration" || decl?.type === "TSTypeAliasDeclaration") continue;
90
- if (decl?.type === "VariableDeclaration" && decl.kind === "const" && !decl.declare) {
91
- for (const d of decl.declarations) {
92
- if (d.id.type === "Identifier" && literalInitializer(d.init)) continue;
93
- if (d.id.type !== "Identifier" || !options?.allowArrowFunctions || d.init?.type !== "ArrowFunctionExpression") {
94
- invalid(file, d, "Subject modules may contain only named functions, type-only declarations, or constants with supported initializers.");
95
- }
96
- if (selectable && d.id.name === name) {
97
- if (d.id.typeAnnotation) invalid(file, d.id, "Declare parameter and return types on the arrow function itself.");
98
- fn = d.init;
99
- } else checkSibling(file, d.init, name);
100
- }
101
- continue;
102
- }
103
- invalid(file, stmt, "Subject modules may contain only named functions, type-only declarations, or constants with supported initializers.");
104
- }
105
- if (!fn) {
106
- if (options?.allowLocalFunctions) return invalid(file, undefined, `Expected a directly declared function named '${name}'.`);
107
- throw new Error(`${file}: No named function export '${name}'.`);
108
- }
109
- return fn;
110
- }
@@ -1,26 +0,0 @@
1
- import { once } from "node:events";
2
- import { Unsupported } from "./assistant.ts";
3
- import { checkFiles, emit, type CheckProgress } from "./check.ts";
4
- import type { ProjectReply, ProjectRequest } from "./run.ts";
5
-
6
- const send = (reply: ProjectReply) => process.send!(reply);
7
- function progress(event: CheckProgress) {
8
- // Apply synchronous progress callbacks in the caller before rechecking the files.
9
- const acknowledged = event.kind === "validating" ? once(process, "message") : undefined;
10
- send({ kind: "progress", event });
11
- return acknowledged;
12
- }
13
-
14
- process.once("disconnect", () => process.exit());
15
- process.once("message", async (request: ProjectRequest) => {
16
- try {
17
- const value = request.kind === "check"
18
- ? await checkFiles(request.files, { onProgress: request.progress ? progress : undefined })
19
- : await emit(request.file, { property: request.property });
20
- send({ kind: "result", value });
21
- } catch (cause) {
22
- const error = cause instanceof Error ? cause : new Error(String(cause));
23
- const code = "code" in error && typeof error.code === "string" ? error.code : undefined;
24
- send({ kind: "error", error, unsupported: error instanceof Unsupported, code });
25
- }
26
- });
@@ -1,16 +0,0 @@
1
- import { execFile, type ExecFileOptions } from "node:child_process";
2
- import { promisify } from "node:util";
3
-
4
- const exec = promisify(execFile);
5
-
6
- /** A normal prover rejection is evidence. Startup, timeout and signal failures are tool errors. */
7
- export async function runProver(binary: string, args: string[], options: ExecFileOptions) {
8
- try {
9
- const { stdout, stderr } = await exec(binary, args, { ...options, encoding: "utf8" });
10
- return { status: 0, stdout, stderr };
11
- } catch (error) {
12
- const failure = error as { code?: number | string; killed?: boolean; signal?: string; stdout?: string; stderr?: string };
13
- if (typeof failure.code !== "number" || failure.killed || failure.signal) throw error;
14
- return { status: failure.code, stdout: failure.stdout ?? "", stderr: failure.stderr ?? "" };
15
- }
16
- }
package/src/reporter.ts DELETED
@@ -1,173 +0,0 @@
1
- import { dirname, relative, resolve } from "node:path";
2
- import type { CheckProgress, CheckReport, CheckResult } from "./check.ts";
3
- import { terminalProgress } from "./terminal-progress.ts";
4
- import { pudBanner, terminalInk, verdictColor, verdictMark } from "./terminal.ts";
5
-
6
- const badges = { proved: "PASS", disproved: "FAIL", unproved: "UNPROVED", unsupported: "UNSUPPORTED", error: "ERROR", todo: "TODO" } as const;
7
- const summaryLabels = { proved: "passed", disproved: "failed", unproved: "unproved", unsupported: "unsupported", error: "errors", todo: "todo" };
8
- type Counts = Record<CheckResult["status"], number>;
9
-
10
- function target(result: CheckResult) {
11
- const title = result.name ?? result.subject;
12
- if (!title) return;
13
- const scope = result.concreteScope === "no-inputs" ? " [no inputs]" : result.concreteScope ? " [literal inputs]" : "";
14
- return title + (result.exactResult ? " [exact result]" : "") + scope;
15
- }
16
-
17
- function detail(result: CheckResult, verbose: boolean, ink: ReturnType<typeof terminalInk>) {
18
- if (result.counterexample?.difference) {
19
- const { summary, input, difference } = result.counterexample;
20
- return [
21
- summary,
22
- Object.entries(input).map(([key, value]) => `${key}=${value}`).join(" "),
23
- difference.subject,
24
- ` ${ink.green("Expected")} ${difference.expected}`,
25
- ` ${ink.red("Received")} ${difference.received}`,
26
- ].join("\n");
27
- }
28
- if (result.counterexample) {
29
- const { summary, input } = result.counterexample;
30
- return [summary, Object.entries(input).map(([key, value]) => `${key}=${value}`).join(" ")].filter(Boolean).join("\n");
31
- }
32
- return verbose ? result.diagnostic ?? result.detail : result.detail;
33
- }
34
-
35
- function location(file: string, result: CheckResult) {
36
- return result.line ? `${file}:${result.line}` : file;
37
- }
38
-
39
- export function display(file: string, result: CheckResult, verbose: boolean, out: NodeJS.WriteStream) {
40
- const ink = terminalInk(out);
41
- const verdict = badges[result.status];
42
- const badge = verdictColor(ink, verdict).bold(verdict.padEnd(9));
43
- const name = target(result);
44
- out.write(`${badge} ${name ? name + " " : ""}${ink.dim(location(file, result))}\n`);
45
- const message = detail(result, verbose, ink);
46
- if (message) out.write(` ${message.replaceAll("\n", "\n ")}\n`);
47
- }
48
-
49
- function reportRows(results: readonly CheckResult[]) {
50
- const rows: { result: CheckResult; affected?: CheckResult[] }[] = [];
51
- const printed = new Set<CheckResult>();
52
- for (const result of results) {
53
- if (printed.has(result)) continue;
54
- if (result.subject && (result.status === "unsupported" || result.status === "error")) {
55
- const affected = results.filter(other => other.subject === result.subject && other.status === result.status && other.detail === result.detail);
56
- if (affected.length > 1) {
57
- rows.push({ result: { ...result, name: `${result.subject} (${affected.length} properties)`, line: undefined }, affected });
58
- for (const item of affected) printed.add(item);
59
- continue;
60
- }
61
- }
62
- rows.push({ result });
63
- }
64
- return rows;
65
- }
66
-
67
- function affectedLocation(file: string, result: CheckResult) {
68
- return `${target(result)} ${location(file, result)}`;
69
- }
70
-
71
- function displayReport({ file, results }: CheckReport, verbose: boolean, out: NodeJS.WriteStream) {
72
- for (const { result, affected } of reportRows(results)) {
73
- display(file, result, verbose, out);
74
- if (verbose && affected) for (const item of affected) out.write(` ${affectedLocation(file, item)}\n`);
75
- }
76
- }
77
-
78
- function width(out: NodeJS.WriteStream) {
79
- return Math.min(out.columns || 80, 96);
80
- }
81
-
82
- function writeLine(out: NodeJS.WriteStream, prefix: string, text: string, continuation?: string) {
83
- const indent = Bun.stringWidth(prefix);
84
- const wrapped = Bun.wrapAnsi(text, Math.max(1, width(out) - indent - 1), { hard: true, trim: false });
85
- out.write(`${prefix}${wrapped.replaceAll("\n", `\n${continuation ?? " ".repeat(indent)}`)}\n`);
86
- }
87
-
88
- function duration(ms: number) {
89
- return ms < 1000 ? `${Math.round(ms)}ms` : `${(ms / 1000).toFixed(2)}s`;
90
- }
91
-
92
- function displayTerminalReport({ file, results }: CheckReport, verbose: boolean, out: NodeJS.WriteStream, root: string, elapsedMs: number) {
93
- const ink = terminalInk(out);
94
- const priority = ["error", "unsupported", "disproved", "unproved", "proved", "todo"] as const;
95
- const status = priority.find(status => results.some(result => result.status === status)) ?? "todo";
96
- const lead = ` ${verdictMark(ink, badges[status])} `;
97
- const label = ink.bold(relative(root, file));
98
- const time = ink.dim(duration(elapsedMs));
99
- const gap = Math.max(2, width(out) - 2 - Bun.stringWidth(lead + label + time));
100
- writeLine(out, lead, label + " ".repeat(gap) + time);
101
-
102
- const rows = reportRows(results);
103
- const margin = " ";
104
- const edge = ink.dim(`${margin}│ `);
105
- const source = relative(process.cwd(), file);
106
- for (const [index, { result, affected }] of rows.entries()) {
107
- const branch = ink.dim(index === rows.length - 1 ? " └─ " : " ├─ ");
108
- const verdict = badges[result.status];
109
- const badge = verdictColor(ink, verdict).bold(verdict.padEnd(4));
110
- const line = result.line ? ink.dim(` :${result.line}`) : "";
111
- writeLine(out, `${branch}${badge} `, (target(result) ?? "") + line);
112
- const message = detail(result, verbose, ink);
113
- if (message) {
114
- const assistant = result.assistant;
115
- const diagnostic = assistant ? `${assistant[0]!.toUpperCase()}${assistant.slice(1)} diagnostic` : "Diagnostic";
116
- const heading = result.counterexample ? "Counterexample" : diagnostic;
117
- writeLine(out, margin, ink.bold(heading));
118
- out.write(`${margin}${ink.dim(location(source, result))}\n`);
119
- writeLine(out, edge, message, edge);
120
- }
121
- if (verbose && affected) for (const item of affected) writeLine(out, margin, affectedLocation(source, item));
122
- }
123
- }
124
-
125
- function displaySummary(counts: Counts, elapsedMs: number, out: NodeJS.WriteStream, fileCount?: string) {
126
- const statuses = (Object.keys(counts) as (keyof Counts)[]).filter(status => counts[status]);
127
- const label = (status: keyof Counts) => `${counts[status]} ${status === "error" && counts.error === 1 ? "error" : summaryLabels[status]}`;
128
- if (!fileCount) {
129
- out.write(`\n${statuses.map(label).join(" · ")} ${(elapsedMs / 1000).toFixed(1)}s\n`);
130
- return;
131
- }
132
- const ink = terminalInk(out);
133
- const tally = statuses.map(status => verdictColor(ink, badges[status]).bold(label(status)));
134
- out.write(`\n ${ink.dim("─".repeat(width(out) - 4))}\n`);
135
- writeLine(out, " ", [...tally, ink.dim(fileCount), ink.dim(duration(elapsedMs))].join(ink.dim(" · ")));
136
- }
137
-
138
- export function proofReporter(files: readonly string[], started: number, verbose: boolean) {
139
- const progress = files.length ? terminalProgress(process.stderr, started) : undefined;
140
- const cwd = process.cwd();
141
- const directories = new Set(files.map(file => dirname(resolve(file))));
142
- const root = directories.size === 1 ? directories.values().next().value! : cwd;
143
- const fileCount = `${files.length} proof file${files.length === 1 ? "" : "s"}`;
144
- if (progress) {
145
- const out = process.stderr;
146
- const scope = relative(cwd, root);
147
- out.write(`\n${pudBanner(out, "Proof check")}\n`);
148
- writeLine(out, " ", terminalInk(out).dim(scope ? `${fileCount} · ${scope}` : fileCount));
149
- out.write("\n");
150
- }
151
- const times = new Map<string, number>();
152
- let active: { file: string; started: number } | undefined;
153
- return {
154
- update: progress && ((event: CheckProgress) => {
155
- if (event.kind === "suite" || event.kind === "validating") {
156
- const now = performance.now();
157
- if (active) times.set(active.file, now - active.started);
158
- active = event.kind === "suite" ? { file: event.file, started: now } : undefined;
159
- }
160
- progress.update(event);
161
- }),
162
- close: progress?.close,
163
- report(reports: readonly CheckReport[], counts: Counts, errors: readonly string[], out: NodeJS.WriteStream) {
164
- const rich = progress && (!out.columns || out.columns >= 28);
165
- for (const report of reports) {
166
- if (rich) displayTerminalReport(report, verbose, out, root, times.get(report.file) ?? 0);
167
- else displayReport(report, verbose, out);
168
- }
169
- for (const error of errors) out.write(error + "\n");
170
- if (reports.length) displaySummary(counts, performance.now() - started, out, rich ? fileCount : undefined);
171
- },
172
- };
173
- }