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
package/src/suite.ts DELETED
@@ -1,515 +0,0 @@
1
- import type { CallExpression, Node, Program, StringLiteral } from "@babel/types";
2
- import manifest from "../package.json";
3
- import type { NativeProofTerm, PreparedProofAssistant, ProofCall, ProofClaim, ProofComparison, ProofConstraint, ProofErrorKind, ProofExpression, ProofPredicate, ProofTarget, ProofType } from "./assistant.ts";
4
- import { invalid, resolveTypeScriptImport } from "./source.ts";
5
- import { dirname, resolve } from "node:path";
6
-
7
- const authoringPackage = manifest.name;
8
- const portableHelpers = new Set(["describe", "expect", "given", "it", "native", "pud"]);
9
- const configuredHelpers = new Set(["expect", "given", "it", "pud", "use"]);
10
- const comparisons = new Set<string>(["eq", "gt", "gte", "lt", "lte"] satisfies ProofComparison[]);
11
- const assistantId = /^[a-z][a-z0-9_-]*$/;
12
- const qualifiedName = /^[A-Za-z_][A-Za-z0-9_']*(\.[A-Za-z_][A-Za-z0-9_']*)*$/;
13
- const emptyBindings = new Map<string, string>();
14
-
15
- type SuiteProperty = { name: string; line: number } & (
16
- | { kind: "todo" }
17
- | { kind: "claim"; call: CallExpression; proof?: Node }
18
- );
19
-
20
- export interface Suite {
21
- file: string;
22
- source: string;
23
- subject: { file: string; name: string };
24
- subjects: ReadonlyMap<string, { file: string; name: string }>;
25
- binding: string;
26
- properties: SuiteProperty[];
27
- modules: { assistant: string; file: string }[];
28
- helpers: ReadonlyMap<string, string>;
29
- schemaBindings: ReadonlySet<string>;
30
- native: ReadonlyMap<string, string>;
31
- configured: boolean;
32
- numberGlobal: boolean;
33
- imports: { path: string; resolveAgain: () => string }[];
34
- }
35
-
36
- function named(node: Node | null | undefined, name: string | undefined): boolean {
37
- return name !== undefined && node?.type === "Identifier" && node.name === name;
38
- }
39
-
40
- function identifier(file: string, node: Node | null | undefined): string {
41
- if (node?.type !== "Identifier" || node.name === "this" || node.optional || node.decorators?.length) {
42
- return invalid(file, node ?? undefined, "Expected a named binding.");
43
- }
44
- return node.name;
45
- }
46
-
47
- function directCall(node: Node | null | undefined, name: string | undefined): CallExpression | undefined {
48
- if (node?.type === "CallExpression" && !node.typeArguments && named(node.callee, name)) return node;
49
- }
50
-
51
- function memberCall(node: Node | undefined, typeArguments = false) {
52
- if (node?.type !== "CallExpression" || (!typeArguments && node.typeArguments) || node.callee.type !== "MemberExpression" ||
53
- node.callee.computed || node.callee.property.type !== "Identifier") return;
54
- return { call: node, receiver: node.callee.object, name: node.callee.property.name };
55
- }
56
-
57
- function arity(file: string, call: CallExpression, count: number) {
58
- if (call.arguments.length !== count) invalid(file, call, `Expected ${count} argument(s).`);
59
- return call.arguments;
60
- }
61
-
62
- function staticString(file: string, node: Node | undefined): string {
63
- if (node?.type === "StringLiteral") return node.value;
64
- if (node?.type === "TemplateLiteral" && !node.expressions.length && node.quasis[0]?.value.cooked != null) {
65
- return node.quasis[0].value.cooked;
66
- }
67
- return invalid(file, node, "Expected a static string.");
68
- }
69
-
70
- function blockArrow(file: string, node: Node | undefined, count: number) {
71
- if (node?.type !== "ArrowFunctionExpression" || node.async || node.typeParameters ||
72
- node.body.type !== "BlockStatement" || node.params.length !== count) {
73
- return invalid(file, node, `Expected a synchronous block callback with ${count} parameter(s).`);
74
- }
75
- return { params: node.params, statements: node.body.body };
76
- }
77
-
78
- function fields(file: string, node: Node | undefined, kind: "ObjectExpression" | "ObjectPattern") {
79
- if (node?.type !== kind) invalid(file, node, "Expected an object of named fields.");
80
- const keys = new Set<string>();
81
- return node.properties.map(field => {
82
- if (field.type !== "ObjectProperty" || field.computed || field.key.type !== "Identifier") {
83
- return invalid(file, field, "Expected a plain named field.");
84
- }
85
- const key = field.key.name;
86
- if (keys.has(key)) invalid(file, field, `Duplicate field '${key}'.`);
87
- keys.add(key);
88
- return { key, value: field.value };
89
- });
90
- }
91
-
92
- const relativeConfig = /^\.\.?\/(?:.*\/)?pud\.config(?:\.ts)?$/;
93
-
94
- export function readSuite(file: string, origin: string, source: string, program: Program, config?: string): Suite {
95
- const manifest = program.body.find(node => node.type === "ExportDefaultDeclaration");
96
- if (manifest) invalid(file, manifest, `Declare a suite with describe() from '${authoringPackage}' or pud.describe() from the project config.`);
97
-
98
- const base = dirname(origin);
99
- const helpers = new Map<string, string>();
100
- const native = new Map<string, string>();
101
- const subjects = new Map<string, Suite["subject"]>();
102
- const imports: Suite["imports"] = [];
103
- const paths = new Map<string, string>();
104
- function resolveImport(specifier: StringLiteral) {
105
- const cached = paths.get(specifier.value);
106
- if (cached) return cached;
107
- const resolveAgain = () => resolveTypeScriptImport(file, specifier, base);
108
- const path = resolveAgain();
109
- if (!specifier.value.endsWith(".ts")) imports.push({ path, resolveAgain });
110
- paths.set(specifier.value, path);
111
- return path;
112
- }
113
- let configBinding: string | undefined;
114
- let describe: CallExpression | undefined;
115
- let configured = false;
116
- for (const statement of program.body) {
117
- if (describe) invalid(file, statement, "Expected one describe() suite after the imports.");
118
- if (statement.type === "ImportDeclaration") {
119
- if (statement.importKind === "type") continue;
120
- if (statement.attributes?.length || statement.phase || !statement.specifiers.length) {
121
- invalid(file, statement, "Import proof helpers and the subject by name.");
122
- }
123
- const path = statement.source.value;
124
- if (relativeConfig.test(path)) {
125
- const [spec] = statement.specifiers;
126
- if (configBinding || statement.specifiers.length !== 1 || spec?.type !== "ImportDefaultSpecifier" ||
127
- resolveImport(statement.source) !== config) {
128
- invalid(file, statement, "Import the default export of this project's pud.config.ts.");
129
- }
130
- configBinding = spec.local.name;
131
- continue;
132
- }
133
- for (const spec of statement.specifiers) {
134
- if (spec.type !== "ImportSpecifier" || spec.imported.type !== "Identifier") invalid(file, spec, "Use named imports.");
135
- if (spec.importKind === "type") continue;
136
- const { imported, local } = spec;
137
- if (path === authoringPackage && portableHelpers.has(imported.name)) {
138
- if (helpers.has(imported.name)) invalid(file, spec, "Import each proof helper once.");
139
- helpers.set(imported.name, local.name);
140
- } else if (path === `${authoringPackage}/lean` && imported.name === "lean") {
141
- native.set(local.name, "lean");
142
- } else {
143
- subjects.set(local.name, { file: resolveImport(statement.source), name: imported.name });
144
- }
145
- }
146
- continue;
147
- }
148
- if (statement.type === "VariableDeclaration" && statement.kind === "const" && statement.declarations.length === 1) {
149
- const declaration = statement.declarations[0]!;
150
- const call = directCall(declaration.init, helpers.get("native"));
151
- if (call) {
152
- const [argument] = arity(file, call, 1);
153
- const id = staticString(file, argument);
154
- if (!assistantId.test(id)) invalid(file, argument, "Use a literal proof assistant identifier.");
155
- native.set(identifier(file, declaration.id), id);
156
- continue;
157
- }
158
- }
159
- if (statement.type !== "ExpressionStatement") invalid(file, statement, "Expected imports and describe().");
160
- const call = memberCall(statement.expression);
161
- if (call?.name === "describe" && named(call.receiver, configBinding)) {
162
- describe = call.call;
163
- configured = true;
164
- } else {
165
- describe = directCall(statement.expression, helpers.get("describe"));
166
- if (!describe) invalid(file, statement, "Use describe(subject, callback) or pud.describe(subject, callback).");
167
- }
168
- }
169
-
170
- if (!describe) invalid(file, undefined, "Expected a describe() suite.");
171
- const [target, callback] = arity(file, describe, 2);
172
- const binding = identifier(file, target);
173
- const subject = subjects.get(binding) ?? invalid(file, target, "The subject must be a named TypeScript import.");
174
- const { params, statements } = blockArrow(file, callback, configured ? 1 : 0);
175
- const numberImported = configBinding === "Number" || subjects.has("Number") || native.has("Number") || [...helpers.values()].includes("Number");
176
- if (configured) {
177
- helpers.clear();
178
- for (const { key, value } of fields(file, params[0], "ObjectPattern")) {
179
- if (!configuredHelpers.has(key)) invalid(file, value, `Unknown proof helper '${key}'.`);
180
- const name = identifier(file, value);
181
- if (subjects.has(name) || native.has(name)) invalid(file, value, "Proof helpers cannot shadow an imported function or a native tag.");
182
- helpers.set(key, name);
183
- }
184
- }
185
- const schemaBindings = new Set<string>();
186
- const schemaHelper = helpers.get("pud");
187
- if (schemaHelper) schemaBindings.add(schemaHelper);
188
- if (configured && configBinding && ![...helpers.values()].includes(configBinding)) schemaBindings.add(configBinding);
189
-
190
- const properties: SuiteProperty[] = [];
191
- const modules: Suite["modules"] = [];
192
- const names = new Set<string>();
193
- for (const statement of statements) {
194
- if (statement.type !== "ExpressionStatement") invalid(file, statement, "Use it(), it.todo(), or use() in the suite.");
195
- const use = directCall(statement.expression, helpers.get("use"));
196
- if (use) {
197
- if (properties.length) invalid(file, statement, "Declare native modules before properties.");
198
- const [argument] = arity(file, use, 1);
199
- const module = memberCall(argument);
200
- const assistant = module?.receiver.type === "Identifier" && native.get(module.receiver.name);
201
- if (module?.name !== "module" || !assistant) invalid(file, argument, "Use an assistant's module() helper.");
202
- const [path] = arity(file, module.call, 1);
203
- const specifier = staticString(file, path);
204
- if (!/^\.\.?\//.test(specifier)) invalid(file, path, "Use a relative path to the proof module.");
205
- modules.push({ assistant, file: resolve(base, specifier) });
206
- continue;
207
- }
208
- const member = memberCall(statement.expression);
209
- const todo = member?.name === "todo" && named(member.receiver, helpers.get("it"));
210
- const by = member?.name === "by" ? member : undefined;
211
- const call = todo ? member.call : directCall(by ? by.receiver : statement.expression, helpers.get("it"));
212
- if (!call) invalid(file, statement, "Use it() or it.todo() for each property.");
213
- const name = staticString(file, call.arguments[0]);
214
- if (!name.trim() || names.has(name)) invalid(file, call, "Use a unique, non-empty property title.");
215
- names.add(name);
216
- const line = call.loc!.start.line;
217
- if (todo) {
218
- arity(file, call, 1);
219
- properties.push({ kind: "todo", name, line });
220
- } else {
221
- const proof = by && arity(file, by.call, 1)[0];
222
- properties.push({ kind: "claim", name, line, call, proof });
223
- }
224
- }
225
- if (!properties.length) invalid(file, describe, "Add at least one property or an it.todo().");
226
- const numberGlobal = !numberImported && ![...helpers.values()].includes("Number");
227
- return { file, source, subject, subjects, binding, properties, modules, helpers, schemaBindings, native, configured, imports, numberGlobal };
228
- }
229
-
230
- function expression(suite: Suite, node: Node | undefined, bindings: ReadonlyMap<string, string>): ProofExpression {
231
- if (!node || node.type === "SpreadElement" || node.type === "ArgumentPlaceholder") {
232
- return invalid(suite.file, node, "Expected a TypeScript expression.");
233
- }
234
- const at = node.loc!.start;
235
- return { file: suite.file, source: suite.source.slice(node.start!, node.end!), line: at.line,
236
- column: at.column, offset: node.start!, bindings, schemaBindings: suite.schemaBindings, numberGlobal: suite.numberGlobal };
237
- }
238
-
239
- function nativeTerm(suite: Suite, node: Node | undefined, bindings: ReadonlyMap<string, string>): NativeProofTerm {
240
- const { file, native } = suite;
241
- if (!suite.configured) invalid(file, node, "Import pud from pud.config.ts and use pud.describe() for native proof terms.");
242
- if (node?.type === "TaggedTemplateExpression" && !node.typeArguments && node.tag.type === "Identifier") {
243
- const assistant = native.get(node.tag.name);
244
- if (assistant) {
245
- const parts = node.quasi.quasis.map(part => part.value.cooked ?? invalid(file, part, "Invalid escape in the native proof template."));
246
- return { kind: "template", assistant, parts, args: node.quasi.expressions.map(arg => expression(suite, arg, bindings)) };
247
- }
248
- }
249
- const reference = memberCall(node);
250
- const assistant = reference?.receiver.type === "Identifier" && native.get(reference.receiver.name);
251
- if (!assistant || reference?.name !== "ref") return invalid(file, node, "Use a native proof template or a named reference.");
252
- const [head, ...args] = reference.call.arguments;
253
- const name = staticString(file, head);
254
- if (!qualifiedName.test(name)) invalid(file, head, "Expected a qualified theorem or predicate name.");
255
- return { kind: "reference", assistant, name, args: args.map(arg => expression(suite, arg, bindings)) };
256
- }
257
-
258
- function isSchemaBuilder(suite: Suite, node: Node): boolean {
259
- return node.type === "Identifier" && suite.schemaBindings.has(node.name);
260
- }
261
-
262
- function isSchema(suite: Suite, node: Node | undefined, type: ProofType): boolean {
263
- const schema = memberCall(node, true);
264
- if (!schema || !isSchemaBuilder(suite, schema.receiver)) return false;
265
- const { name, call } = schema;
266
- if (type.kind === "opaque") {
267
- const args = call.typeArguments;
268
- const item = args?.type === "TSTypeParameterInstantiation" && args.params[0];
269
- return name === "opaque" && !call.arguments.length && !!item && args.params.length === 1 &&
270
- item.type === "TSTypeReference" && !item.typeArguments && named(item.typeName, type.name);
271
- }
272
- if (call.typeArguments) return false;
273
- switch (type.kind) {
274
- case "integer": return (name === "bigint" || name === "int") && !call.arguments.length;
275
- case "number": return name === "number" && !call.arguments.length;
276
- case "boolean": return (name === "boolean" || name === "bool") && !call.arguments.length;
277
- case "array":
278
- case "textOrArray": return name === type.kind && call.arguments.length === 1 && isSchema(suite, call.arguments[0], type.item);
279
- }
280
- }
281
-
282
- function schemaHint(type: ProofType): string {
283
- switch (type.kind) {
284
- case "integer": return "pud.bigint()";
285
- case "number": return "pud.number()";
286
- case "boolean": return "pud.boolean()";
287
- case "opaque": return `pud.opaque<${type.name}>()`;
288
- case "array":
289
- case "textOrArray": return `pud.${type.kind}(${schemaHint(type.item)})`;
290
- }
291
- }
292
-
293
- function predicateCallback(suite: Suite, node: Node | undefined, bindings: ReadonlyMap<string, string>) {
294
- const { file, schemaBindings } = suite;
295
- if (node?.type !== "ArrowFunctionExpression" || node.async || node.typeParameters || node.params.length !== 1) {
296
- return invalid(file, node, "Use a synchronous predicate with one parameter.");
297
- }
298
- const variable = identifier(file, node.params[0]);
299
- if (schemaBindings.has(variable) || suite.native.has(variable)) {
300
- invalid(file, node.params[0], "The predicate parameter cannot shadow Pud's helpers or a native tag.");
301
- }
302
- if (node.body.type !== "BlockStatement") return { variable, predicate: proofPredicate(suite, node.body, bindings) };
303
- const [statement] = node.body.body;
304
- if (node.body.body.length !== 1 || statement?.type !== "ReturnStatement" || !statement.argument) {
305
- return invalid(file, node.body, "Return a single predicate expression.");
306
- }
307
- return { variable, predicate: proofPredicate(suite, statement.argument, bindings) };
308
- }
309
-
310
- function quantifiedType(suite: Suite, node: Node | undefined): "integer" | "number" | "boolean" | undefined {
311
- const chain = memberCall(node, true);
312
- if (!chain) return;
313
- if (!isSchemaBuilder(suite, chain.receiver)) return quantifiedType(suite, chain.receiver);
314
- if (chain.name === "bigint" || chain.name === "int") return "integer";
315
- if (chain.name === "number") return "number";
316
- if (chain.name === "boolean" || chain.name === "bool") return "boolean";
317
- }
318
-
319
- function proofPredicate(suite: Suite, node: Node | undefined, bindings: ReadonlyMap<string, string>): ProofPredicate {
320
- const call = memberCall(node, true);
321
- if (!call || !isSchemaBuilder(suite, call.receiver)) return { kind: "boolean", expression: expression(suite, node, bindings) };
322
- const read = (part: Node | undefined) => proofPredicate(suite, part, bindings);
323
- switch (call.name) {
324
- case "not": {
325
- const [operand] = arity(suite.file, call.call, 1);
326
- return { kind: "not", operand: read(operand) };
327
- }
328
- case "and":
329
- case "or":
330
- case "implies":
331
- case "iff": {
332
- const [left, right] = arity(suite.file, call.call, 2);
333
- return { kind: "binary", operator: call.name, left: read(left), right: read(right) };
334
- }
335
- case "forall":
336
- case "exists": {
337
- const [input, callback] = arity(suite.file, call.call, 2);
338
- const type = quantifiedType(suite, input);
339
- const domain = type ? { kind: "schema" as const, type,
340
- constraints: schemaConstraints(suite, input, { kind: type }, { kind: "quantified" }, bindings),
341
- } : { kind: "array" as const, expression: expression(suite, input, bindings) };
342
- return { kind: "quantifier", quantifier: call.name, domain, ...predicateCallback(suite, callback, bindings) };
343
- }
344
- default: return { kind: "boolean", expression: expression(suite, node, bindings) };
345
- }
346
- }
347
-
348
- function schemaConstraints(suite: Suite, node: Node | undefined, type: ProofType, target: ProofTarget, bindings: ReadonlyMap<string, string>): ProofConstraint[] {
349
- if (isSchema(suite, node, type)) return [];
350
- const chain = memberCall(node);
351
- if (!chain || isSchemaBuilder(suite, chain.receiver)) {
352
- const value = target.kind === "result" ? "the result"
353
- : target.kind === "quantified" ? "the quantified value" : `parameter '${target.name}'`;
354
- return invalid(suite.file, node, `Use ${schemaHint(type)} for ${value}.`);
355
- }
356
- const constraints = schemaConstraints(suite, chain.receiver, type, target, bindings);
357
- if (type.kind === "number" && chain.name === "nearestIntegerTo") {
358
- const [value, options] = arity(suite.file, chain.call, 2);
359
- const policy = fields(suite.file, options, "ObjectExpression");
360
- if (policy.length !== 1 || policy[0]!.key !== "ties") invalid(suite.file, options, 'Specify { ties: "up" } or { ties: "down" }.');
361
- const ties = staticString(suite.file, policy[0]!.value);
362
- if (ties !== "up" && ties !== "down") invalid(suite.file, options, 'Choose "up" or "down" for half-integer ties.');
363
- return [...constraints, { kind: "nearestInteger", target, value: expression(suite, value, bindings), ties }];
364
- }
365
- const [value] = arity(suite.file, chain.call, 1);
366
- if (chain.name === "refine") {
367
- constraints.push({ kind: "refinement", target, ...predicateCallback(suite, value, bindings) });
368
- } else if (type.kind === "number" && chain.name === "sameValue") {
369
- constraints.push({ kind: "sameValue", target, value: expression(suite, value, bindings) });
370
- } else if (chain.name === "satisfies" && type.kind !== "textOrArray" && type.kind !== "opaque") {
371
- constraints.push({ kind: "native", target, term: nativeTerm(suite, value, bindings) });
372
- } else if (((type.kind === "integer" || type.kind === "number") && comparisons.has(chain.name)) || (type.kind === "boolean" && chain.name === "eq")) {
373
- constraints.push({ kind: "comparison", target, operator: chain.name as ProofComparison, value: expression(suite, value, bindings) });
374
- } else invalid(suite.file, node, `Unknown ${type.kind} matcher '${chain.name}'.`);
375
- return constraints;
376
- }
377
-
378
- export function bindClaim(suite: Suite, property: Extract<SuiteProperty, { kind: "claim" }>, subject: PreparedProofAssistant): ProofClaim {
379
- const { file, helpers } = suite;
380
- const [, schemas, callback] = arity(file, property.call, 3);
381
- const { params, statements } = blockArrow(file, callback, 1);
382
- const parameters = new Map(subject.parameters.map(p => [p.name, p.type]));
383
- const domain = fields(file, schemas, "ObjectExpression");
384
- if (domain.length !== parameters.size) invalid(file, schemas, "Declare one input schema per subject parameter.");
385
- // A result binding shadows the global throughout its callback, including before initialization.
386
- const callbackSuite = statements.some(step => step.type === "VariableDeclaration" &&
387
- step.declarations.some(declaration => named(declaration.id, "Number"))) ? { ...suite, numberGlobal: false } : suite;
388
- const premises = domain.flatMap(({ key, value }) => {
389
- const type = parameters.get(key) ?? invalid(file, value, `No subject parameter named '${key}'.`);
390
- return schemaConstraints(suite, value, type, { kind: "parameter", name: key }, emptyBindings);
391
- });
392
- suite = callbackSuite;
393
- const bindings = new Map<string, string>();
394
- const reserved = new Set([...helpers.values(), ...suite.schemaBindings, ...suite.native.keys(), ...suite.subjects.keys()]);
395
- const inputs = fields(file, params[0], "ObjectPattern");
396
- if (inputs.length !== parameters.size) invalid(file, params[0], "Destructure every input in the property callback.");
397
- for (const { key, value } of inputs) {
398
- if (!parameters.has(key)) invalid(file, value, `No subject parameter named '${key}'.`);
399
- const alias = identifier(file, value);
400
- if (bindings.has(alias) || reserved.has(alias)) invalid(file, value, "Input bindings cannot shadow the subject or proof helpers.");
401
- bindings.set(alias, key);
402
- }
403
- const results = new Map<string, ProofCall>();
404
- const assertions: ProofConstraint[] = [];
405
- let claim: ProofClaim | undefined;
406
- let observation: ProofCall | undefined;
407
- let observationKey: string | undefined;
408
- let resultType = subject.result;
409
-
410
- function readCall(node: Node | null | undefined): ProofCall {
411
- const callee = node?.type === "CallExpression" && !node.typeArguments && node.callee.type === "Identifier"
412
- ? node.callee.name : undefined;
413
- const linked = callee && suite.subjects.get(callee);
414
- if (!linked || node?.type !== "CallExpression") {
415
- return invalid(file, node ?? undefined, "Call a named TypeScript import directly.");
416
- }
417
- return {
418
- kind: "call", callee: callee === suite.binding ? "subject" : linked,
419
- args: node.arguments.map(arg => {
420
- const parameter = arg.type === "Identifier" && bindings.get(arg.name);
421
- return parameter ? { kind: "parameter", name: parameter } : readCall(arg);
422
- }),
423
- };
424
- }
425
-
426
- const includesSubject = (call: ProofCall): boolean => call.callee === "subject" ||
427
- call.args.some(arg => arg.kind === "call" && includesSubject(arg));
428
- function observe(call: ProofCall, at: Node) {
429
- const key = JSON.stringify(call);
430
- if (observationKey !== undefined && observationKey !== key) {
431
- invalid(file, at, "Use one observed call expression per property.");
432
- }
433
- if (observationKey !== undefined) return;
434
- observationKey = key;
435
- const direct = call.callee === "subject" && call.args.every(arg => arg.kind === "parameter");
436
- if (direct) {
437
- if (call.args.length !== parameters.size || call.args.some((arg, index) =>
438
- arg.kind !== "parameter" || arg.name !== subject.parameters[index]!.name)) {
439
- invalid(file, at, "Pass the declared inputs to the subject in parameter order.");
440
- }
441
- return;
442
- }
443
- if (!includesSubject(call)) invalid(file, at, "The observed expression must call the subject of the suite.");
444
- if (!subject.inspectCall) invalid(file, at, "The selected assistant does not support composed calls.");
445
- resultType = subject.inspectCall(call);
446
- observation = call;
447
- }
448
-
449
- for (const step of statements) {
450
- if (step.type === "VariableDeclaration" && step.kind === "const" && step.declarations.length === 1) {
451
- const local = step.declarations[0]!;
452
- const name = identifier(file, local.id);
453
- if (reserved.has(name) || bindings.has(name) || results.has(name)) invalid(file, local.id, "Use a fresh binding for the subject result.");
454
- if (claim?.kind === "throw") invalid(file, local, "Keep the throwing call inside expect's callback.");
455
- const call = readCall(local.init);
456
- observe(call, local);
457
- results.set(name, call);
458
- continue;
459
- }
460
- if (step.type !== "ExpressionStatement") invalid(file, step, "Use given(), a subject call, or an expect() assertion.");
461
- const given = directCall(step.expression, helpers.get("given"));
462
- if (given) {
463
- if (claim) invalid(file, step, "Put given() before the assertions.");
464
- const [condition] = arity(file, given, 1);
465
- const predicate = proofPredicate(suite, condition, bindings);
466
- premises.push(predicate.kind === "boolean"
467
- ? { kind: "condition", expression: predicate.expression }
468
- : { kind: "proposition", predicate });
469
- continue;
470
- }
471
- const to = memberCall(step.expression);
472
- const expect = to && ["to", "toExactly", "toEqual", "toThrow"].includes(to.name) && directCall(to.receiver, helpers.get("expect"));
473
- if (!to || !expect) invalid(file, step, "Use expect() with to(), toExactly(), toEqual(), or toThrow().");
474
- const [result] = arity(file, expect, 1);
475
- const [matcher] = arity(file, to.call, 1);
476
- if (to.name === "toThrow") {
477
- if (claim || results.size) invalid(file, step, "Use one throw assertion with its call inside expect.");
478
- if (result?.type !== "ArrowFunctionExpression" || result.async || result.typeParameters || result.params.length || result.body.type === "BlockStatement") {
479
- invalid(file, result, "Use a parameterless arrow expression for a throwing call.");
480
- }
481
- const error = staticString(file, matcher);
482
- if (!subject.errors?.some(kind => kind === error)) invalid(file, matcher, "Select an exception supported by the configured assistant.");
483
- observe(readCall(result.body), result);
484
- claim = { kind: "throw", premises, assertions: [], expectedError: error as ProofErrorKind };
485
- continue;
486
- }
487
- if (claim && (claim.kind !== "return" || claim.exactResult)) invalid(file, step, "Use one outcome per property.");
488
- const local = result?.type === "Identifier" && results.get(result.name);
489
- observe(local || readCall(result), result!);
490
- if (to.name === "toEqual") {
491
- if (claim) invalid(file, step, "Use toEqual() as the only assertion in its property.");
492
- if (!subject.callEquality || !subject.inspectCall) invalid(file, step, "The selected assistant does not support equality between calls.");
493
- const reference = readCall(matcher);
494
- const expected = subject.inspectCall(reference);
495
- if ((resultType.kind !== "integer" && resultType.kind !== "number" && resultType.kind !== "boolean") || resultType.kind !== expected.kind) {
496
- invalid(file, matcher, "Use toEqual() with calls returning the same scalar type.");
497
- }
498
- claim = { kind: "equal", premises, assertions: [], reference };
499
- continue;
500
- }
501
- const exact = to.name === "toExactly";
502
- if (exact) {
503
- if (claim) invalid(file, step, "Combine the result conditions in one toExactly() schema.");
504
- if (!subject.exactResults) invalid(file, step, "The selected assistant does not support exact result schemas.");
505
- if (!["integer", "number", "boolean"].includes(resultType.kind)) invalid(file, matcher, "Use toExactly() with a scalar result.");
506
- }
507
- const clauses = schemaConstraints(suite, matcher, resultType, { kind: "result" }, bindings);
508
- if (!clauses.length && !exact) invalid(file, matcher, "Add a constraint to the result schema.");
509
- assertions.push(...clauses);
510
- claim ??= { kind: "return", premises, assertions, ...(exact && { exactResult: true }) };
511
- }
512
- if (!claim) invalid(file, property.call, "Add an assertion or use it.todo().");
513
- const proof = property.proof && nativeTerm(suite, property.proof, emptyBindings);
514
- return { ...claim, proof, ...(observation && { observation }) };
515
- }
@@ -1,145 +0,0 @@
1
- import type { ChalkInstance } from "chalk";
2
- import { basename } from "node:path";
3
- import type { CheckProgress } from "./check.ts";
4
- import { isInteractiveTerminal, terminalInk, verdictColor } from "./terminal.ts";
5
-
6
- const frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
7
- const erase = (lines: number) => lines ? `\x1b[${lines}F\x1b[J` : "";
8
- const width = (text: string) => Bun.stringWidth(text);
9
- const seconds = (ms: number) => `${(ms / 1000).toFixed(1)}s`;
10
-
11
- function clip(text: string, columns: number) {
12
- if (columns < 1) return "";
13
- return width(text) <= columns ? text : Bun.sliceAnsi(text, 0, columns - 1) + "…";
14
- }
15
-
16
- function safeText(text: string) {
17
- return text.replace(/\p{Cc}/gu, " ").trim();
18
- }
19
-
20
- type Completion = { proved: number; failed: number };
21
-
22
- function alignRight(label: string, detail: string, columns: number) {
23
- if (!detail) return clip(label, columns);
24
- const available = columns - width(detail);
25
- const left = clip(label, available - 2);
26
- return left + " ".repeat(available - width(left)) + detail;
27
- }
28
-
29
- function proofTrail(ink: ChalkInstance, completed: readonly Completion[], total: number, active: boolean, columns: number) {
30
- if (!total) return "";
31
- const done = completed.length;
32
- const countWidth = width(`${total}/${total}`);
33
- const slots = Math.min(total, Math.max(1, Math.floor((columns - countWidth - 1) / 2)));
34
- const queued = ink.hex("#a1a1aa")(ink.level ? "•" : "·");
35
- const proved = verdictColor(ink, "PASS")("•");
36
- const failed = verdictColor(ink, "FAIL")(ink.level ? "•" : "×");
37
- const unknown = ink.dim(ink.level ? "•" : "○");
38
- const cursor = ink.cyan.bold("◆");
39
-
40
- const markers = Array.from({ length: slots }, (_, slot) => {
41
- const start = Math.floor(slot * total / slots);
42
- const end = Math.floor((slot + 1) * total / slots);
43
- if (end > done) return active && start <= done ? cursor : queued;
44
- const last = completed[end - 1]!;
45
- const previous = completed[start - 1];
46
- if (last.failed > (previous?.failed ?? 0)) return failed;
47
- return last.proved - (previous?.proved ?? 0) === end - start ? proved : unknown;
48
- });
49
-
50
- return `${markers.join(" ")} ${ink.dim(`${done}/${total}`)}`;
51
- }
52
-
53
- /** The live trail shows provisional outcomes. The final report validates the snapshots. */
54
- export function terminalProgress(out = process.stderr, runStarted = performance.now()) {
55
- if (!isInteractiveTerminal(process.stdout) || !isInteractiveTerminal(out) || (out.columns && out.columns < 28)) return;
56
-
57
- const ink = terminalInk(out);
58
- let suite: Extract<CheckProgress, { kind: "suite" }> | undefined;
59
- let written = 0, frame = 0, remaining = 0;
60
- let validating = false;
61
- const running = new Map<number, number>();
62
- const completed: Completion[] = [];
63
-
64
- function draw() {
65
- if (!suite) return;
66
- const now = performance.now();
67
- const columns = (out.columns || 80) - 1;
68
- if (columns < 27) {
69
- if (written) out.write(erase(written));
70
- written = 0;
71
- return;
72
- }
73
- const spinner = frames[frame % frames.length]!;
74
- const active = validating ? undefined : running.entries().next().value;
75
- const item = active && suite.items[active[0]];
76
- const title = validating ? "Validating input snapshots" : item ? safeText(item.name)
77
- : remaining ? "Preparing proofs" : "Finishing suite";
78
- const totalTime = ink.dim(`total ${seconds(now - runStarted)}`);
79
- const proofTime = active ? ink.dim(`proof ${seconds(now - active[1])}`) : "";
80
- const file = safeText(basename(suite.file));
81
- const batch = active && running.size > 1 ? ` · +${running.size - 1} running` : "";
82
- const lines = [
83
- alignRight(` ${ink.cyan(spinner)} ${ink.bold(title)}`, totalTime, columns),
84
- alignRight(` ${ink.dim(file + batch)}`, proofTime, columns),
85
- ];
86
- const trail = proofTrail(ink, completed, suite.totalItems, !!item, columns - 2);
87
- if (trail) lines.push("", ` ${trail}`);
88
- out.write(erase(written) + lines.map(line => clip(line, columns)).join("\n") + "\n");
89
- written = lines.length;
90
- }
91
-
92
- const timer = setInterval(() => { frame++; draw(); }, 90);
93
- timer.unref();
94
- function clear() {
95
- if (written) out.write(erase(written));
96
- written = 0;
97
- suite = undefined;
98
- }
99
- function close() {
100
- clearInterval(timer);
101
- clear();
102
- process.off("SIGINT", interrupt);
103
- process.off("SIGTERM", interrupt);
104
- }
105
- function interrupt(signal: NodeJS.Signals) {
106
- close();
107
- process.kill(process.pid, signal);
108
- }
109
- process.once("SIGINT", interrupt);
110
- process.once("SIGTERM", interrupt);
111
- return {
112
- update(event: CheckProgress) {
113
- if (event.kind === "suite") {
114
- suite = event;
115
- remaining = event.items.reduce((count, item) => count + Number(!item.todo), 0);
116
- running.clear();
117
- validating = false;
118
- } else if (event.kind === "validating") {
119
- validating = true;
120
- } else if (event.file === suite?.file) {
121
- if (event.kind === "running") {
122
- const active = running.entries().next().value;
123
- running.clear();
124
- const now = performance.now();
125
- for (const index of event.indices) {
126
- running.set(index, index === active?.[0] ? active[1] : now);
127
- }
128
- } else {
129
- remaining -= event.indices.length;
130
- for (const [offset, index] of event.indices.entries()) {
131
- running.delete(index);
132
- const status = event.statuses[offset]!;
133
- const previous = completed.at(-1);
134
- completed.push({
135
- proved: (previous?.proved ?? 0) + Number(status === "proved"),
136
- failed: (previous?.failed ?? 0) + Number(status !== "proved" && status !== "todo"),
137
- });
138
- }
139
- }
140
- }
141
- if (!written || event.kind === "validating") draw();
142
- },
143
- close,
144
- };
145
- }