pud.dev 0.0.0-stage → 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CLAUDE.md +106 -0
- package/README.md +117 -2
- package/package.json +24 -4
- package/scripts/pack.ts +67 -0
- package/scripts/setup-lean.ts +88 -0
- package/src/assistant.ts +131 -0
- package/src/check.ts +173 -0
- package/src/cli.ts +70 -0
- package/src/expressions.ts +65 -0
- package/src/index.ts +4 -0
- package/src/input-scope.ts +71 -0
- package/src/lean/command.ts +40 -0
- package/src/lean/index.ts +437 -0
- package/src/lean/iteration.lean +145 -0
- package/src/lean/lean-assets.d.ts +4 -0
- package/src/lean/number.lean +427 -0
- package/src/lean/number.ts +25 -0
- package/src/lean/program.ts +110 -0
- package/src/lean/replay-predicate.ts +95 -0
- package/src/lean/replay.ts +136 -0
- package/src/lean/scalar.lean +183 -0
- package/src/lean/scalar.ts +196 -0
- package/src/lean/subject.ts +443 -0
- package/src/lean/syntax.ts +287 -0
- package/src/module.ts +110 -0
- package/src/project-runner.ts +26 -0
- package/src/prover-process.ts +16 -0
- package/src/reporter.ts +173 -0
- package/src/run.ts +60 -0
- package/src/source.ts +54 -0
- package/src/suite-authoring.ts +135 -0
- package/src/suite-check.ts +157 -0
- package/src/suite.ts +515 -0
- package/src/terminal-progress.ts +145 -0
- package/src/terminal.ts +41 -0
- package/test/authoring.test.ts +151 -0
- package/test/lean.test.ts +394 -0
- package/test/module.test.ts +55 -0
- package/test/number.test.ts +318 -0
- package/test/package.test.ts +170 -0
- package/test/suite.test.ts +257 -0
- package/tsconfig.json +7 -0
- package/tsconfig.pack.json +12 -0
package/CLAUDE.md
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
|
|
2
|
+
Default to using Bun instead of Node.js.
|
|
3
|
+
|
|
4
|
+
- Use `bun <file>` instead of `node <file>` or `ts-node <file>`
|
|
5
|
+
- Use `bun test` instead of `jest` or `vitest`
|
|
6
|
+
- Use `bun build <file.html|file.ts|file.css>` instead of `webpack` or `esbuild`
|
|
7
|
+
- Use `bun install` instead of `npm install` or `yarn install` or `pnpm install`
|
|
8
|
+
- Use `bun run <script>` instead of `npm run <script>` or `yarn run <script>` or `pnpm run <script>`
|
|
9
|
+
- Use `bunx <package> <command>` instead of `npx <package> <command>`
|
|
10
|
+
- Bun automatically loads .env, so don't use dotenv.
|
|
11
|
+
|
|
12
|
+
## APIs
|
|
13
|
+
|
|
14
|
+
- `Bun.serve()` supports WebSockets, HTTPS, and routes. Don't use `express`.
|
|
15
|
+
- `bun:sqlite` for SQLite. Don't use `better-sqlite3`.
|
|
16
|
+
- `Bun.redis` for Redis. Don't use `ioredis`.
|
|
17
|
+
- `Bun.sql` for Postgres. Don't use `pg` or `postgres.js`.
|
|
18
|
+
- `WebSocket` is built-in. Don't use `ws`.
|
|
19
|
+
- Prefer `Bun.file` over `node:fs`'s readFile/writeFile
|
|
20
|
+
- Bun.$`ls` instead of execa.
|
|
21
|
+
|
|
22
|
+
## Testing
|
|
23
|
+
|
|
24
|
+
Use `bun test` to run tests.
|
|
25
|
+
|
|
26
|
+
```ts#index.test.ts
|
|
27
|
+
import { test, expect } from "bun:test";
|
|
28
|
+
|
|
29
|
+
test("hello world", () => {
|
|
30
|
+
expect(1).toBe(1);
|
|
31
|
+
});
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Frontend
|
|
35
|
+
|
|
36
|
+
Use HTML imports with `Bun.serve()`. Don't use `vite`. HTML imports fully support React, CSS, Tailwind.
|
|
37
|
+
|
|
38
|
+
Server:
|
|
39
|
+
|
|
40
|
+
```ts#index.ts
|
|
41
|
+
import index from "./index.html"
|
|
42
|
+
|
|
43
|
+
Bun.serve({
|
|
44
|
+
routes: {
|
|
45
|
+
"/": index,
|
|
46
|
+
"/api/users/:id": {
|
|
47
|
+
GET: (req) => {
|
|
48
|
+
return new Response(JSON.stringify({ id: req.params.id }));
|
|
49
|
+
},
|
|
50
|
+
},
|
|
51
|
+
},
|
|
52
|
+
// optional websocket support
|
|
53
|
+
websocket: {
|
|
54
|
+
open: (ws) => {
|
|
55
|
+
ws.send("Hello, world!");
|
|
56
|
+
},
|
|
57
|
+
message: (ws, message) => {
|
|
58
|
+
ws.send(message);
|
|
59
|
+
},
|
|
60
|
+
close: (ws) => {
|
|
61
|
+
// handle close
|
|
62
|
+
}
|
|
63
|
+
},
|
|
64
|
+
development: {
|
|
65
|
+
hmr: true,
|
|
66
|
+
console: true,
|
|
67
|
+
}
|
|
68
|
+
})
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
HTML files can import .tsx, .jsx or .js files directly and Bun's bundler will transpile & bundle automatically. `<link>` tags can point to stylesheets and Bun's CSS bundler will bundle.
|
|
72
|
+
|
|
73
|
+
```html#index.html
|
|
74
|
+
<html>
|
|
75
|
+
<body>
|
|
76
|
+
<h1>Hello, world!</h1>
|
|
77
|
+
<script type="module" src="./frontend.tsx"></script>
|
|
78
|
+
</body>
|
|
79
|
+
</html>
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
With the following `frontend.tsx`:
|
|
83
|
+
|
|
84
|
+
```tsx#frontend.tsx
|
|
85
|
+
import React from "react";
|
|
86
|
+
import { createRoot } from "react-dom/client";
|
|
87
|
+
|
|
88
|
+
// import .css files directly and it works
|
|
89
|
+
import './index.css';
|
|
90
|
+
|
|
91
|
+
const root = createRoot(document.body);
|
|
92
|
+
|
|
93
|
+
export default function Frontend() {
|
|
94
|
+
return <h1>Hello, world!</h1>;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
root.render(<Frontend />);
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Then, run index.ts
|
|
101
|
+
|
|
102
|
+
```sh
|
|
103
|
+
bun --hot ./index.ts
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
For more information, read the Bun API docs in `node_modules/bun-types/docs/**.mdx`.
|
package/README.md
CHANGED
|
@@ -1,3 +1,118 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Pud
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The `@pud.dev/lib` package provides the command, the TypeScript suite API, and the proof-assistant adapter contract. A project selects its driver in `pud.config.ts`. Lean is the first bundled driver, available from `@pud.dev/lib/lean`. [Quick start](../../README.md#try-it-locally)
|
|
4
|
+
|
|
5
|
+
## Configure a proof assistant
|
|
6
|
+
|
|
7
|
+
Create `pud.config.ts` beside your sidecars or in a parent directory. Pud uses the nearest config for each suite.
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { defineConfig } from "@pud.dev/lib";
|
|
11
|
+
import { leanAdapter } from "@pud.dev/lib/lean";
|
|
12
|
+
|
|
13
|
+
const pud = defineConfig({ adapter: leanAdapter() });
|
|
14
|
+
|
|
15
|
+
export default pud;
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
The Lean adapter locates Lean on the path or through Elan and reads the nearest `lean-toolchain` file. Pass `executable` or `toolchain` to `leanAdapter` to select them explicitly. Pud loads `pud.config.ts` as project code and reads proof sidecars as source.
|
|
19
|
+
|
|
20
|
+
### Write a portable suite
|
|
21
|
+
|
|
22
|
+
Import `pud` and the suite helpers from `@pud.dev/lib`. Declare the inputs in `it()`. When the caller expects one particular answer, describe it with an exact result schema.
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
import { describe, expect, it, pud } from "@pud.dev/lib";
|
|
26
|
+
import { toCents } from "./cents.ts";
|
|
27
|
+
|
|
28
|
+
describe(toCents, () => {
|
|
29
|
+
it("returns the nearest whole cent, with half cents rounded toward positive infinity", {
|
|
30
|
+
amount: pud.number(),
|
|
31
|
+
}, ({ amount }) => {
|
|
32
|
+
expect(toCents(amount)).toExactly(pud.number().nearestIntegerTo(amount * 100, { ties: "up" }));
|
|
33
|
+
});
|
|
34
|
+
});
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Lean checks two things for every admitted input. The function returns an answer accepted by the schema, and every other answer is excluded. At 12.5 cents, this rule requires 13. Change the rule to `.refine(cents => Number.isInteger(cents))` and enable replay. At an amount of zero, Pud shows that both 0 and 1 cent satisfy the weaker rule. The CLI labels exact result claims `[exact result]`.
|
|
38
|
+
|
|
39
|
+
Start with the inputs the caller may actually supply. Each `given()` narrows that promise. Here, requiring an already-integral scaled amount would exclude precisely the fractions that need rounding. Choose the rounding policy independently of the implementation. This example rounds the JavaScript product `amount * 100`, so `0.29` returns 29 and `1.005` returns 100. A policy defined on decimal input text has a different contract.
|
|
40
|
+
|
|
41
|
+
Use `pud.number()` for ordinary TypeScript numbers. The Lean adapter models binary64 arithmetic, including fractions, overflow and signed zero. Numeric `.eq()` and `toEqual()` use JavaScript strict equality, so the two zeros compare equal and NaN compares unequal to itself. Use `.sameValue(value)` to express `Object.is` equality, including the sign of zero. Exact result schemas use that same distinction when checking uniqueness, and also support bigint and boolean returns. [Motion time conversions](.examples/motion/seconds.proof.ts) · [Currency rounding](.examples/cents.proof.ts)
|
|
42
|
+
|
|
43
|
+
Use `.to()` for an invariant. For example, `expect(clamp(value, lower, upper)).to(pud.bigint().gte(lower).lte(upper))` guarantees bounds when `lower <= upper`. A clamp that always returns the lower bound also satisfies this property. [Clamp sidecar](.examples/clamp.proof.ts)
|
|
44
|
+
|
|
45
|
+
Use `pud.bigint()`, `pud.boolean()`, and `pud.array(item)` for the other supported inputs. Chain bounds such as `.gte()` and `.lte()`, or add a predicate with `.refine(value => …)`. Refinements work on input and result schemas. Use `given()` to relate inputs.
|
|
46
|
+
|
|
47
|
+
```ts
|
|
48
|
+
expect(arrayContains(values, target)).to(pud.boolean().refine(found =>
|
|
49
|
+
pud.iff(found, pud.exists(values, value => value === target)),
|
|
50
|
+
));
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
`pud.exists` and `pud.forall` quantify over the elements of an array or the values admitted by a scalar schema. Compose symbolic predicates with `pud.and`, `pud.or`, `pud.not`, `pud.implies`, and `pud.iff`. Pud translates the callbacks from source. [Supported domains and operators](.examples/README.md#sidecar-syntax)
|
|
54
|
+
|
|
55
|
+
Run `pud check cents.proof.ts` to certify the claim or `pud --emit cents.proof.ts` to see the quantified theorem. `pud check --deny-cases` makes CI reject recognized example cases. It flags a parameterless check or literal equalities on every parameter, including simple `given()` and refinement equalities or matching inclusive bounds. A fixed policy threshold, a fixed result or one fixed argument in a larger domain can all belong in a law. The guard recognizes explicit syntax. More complex preconditions can still describe a singleton or an empty domain. `it.todo(title)` records a pending property.
|
|
56
|
+
|
|
57
|
+
The terminal highlights the active property, its elapsed time, and the time for the whole run. A trail marks queued and completed checks. After validating the input snapshots, Pud groups verdicts, timings, and diagnostics by sidecar. Redirected output uses plain rows, and `--json` returns the machine-readable report.
|
|
58
|
+
|
|
59
|
+
### Check calls and exceptions
|
|
60
|
+
|
|
61
|
+
With the Lean adapter, `describe(encode, …)` supplies the input signature and the observation can compose imported functions.
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
expect(decode(encode(value))).to(pud.bigint().eq(value));
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Use `expect(call()).toEqual(reference())` to compare two linked, nonthrowing calls that return the same scalar type. The sidecar can supply input constraints with `given()` before the check. The generated claim links and compares both implementations. [Availability example](.examples/availability/README.md)
|
|
68
|
+
|
|
69
|
+
With `leanAdapter({ replay: true })`, an open scalar result predicate or call equality can produce a concrete counterexample. Pud filters candidate inputs through the supported schema and `given()` conditions, runs the frozen TypeScript in Bun, and reports the input and observed result on a violation. Native predicates and quantified assertions are outside replay. Only the proof assistant can establish a pass. Enable replay for source you trust to execute.
|
|
70
|
+
|
|
71
|
+
A property can also assert the exact class of a modeled exception. The callback keeps the throwing call inside the observation.
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
expect(() => divide(numerator, divisor)).toThrow("RangeError");
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
`.to()` requires a successful return. `.toThrow()` accepts `"Error"`, `"RangeError"`, or `"TypeError"` in Lean suites. [Supported calls, outcomes, and termination](.examples/README.md#what-a-pass-establishes)
|
|
78
|
+
|
|
79
|
+
### Use native proof code
|
|
80
|
+
|
|
81
|
+
Import `pud` from your config when a property needs native code. Both `pud.describe()` and the schema builders carry the selected assistant's type.
|
|
82
|
+
|
|
83
|
+
```ts
|
|
84
|
+
import pud from "./pud.config";
|
|
85
|
+
import { lean } from "@pud.dev/lib/lean";
|
|
86
|
+
import { increment } from "./increment";
|
|
87
|
+
|
|
88
|
+
pud.describe(increment, ({ it, expect }) => {
|
|
89
|
+
it("returns a greater integer", { value: pud.bigint() }, ({ value }) => {
|
|
90
|
+
expect(increment(value)).to(pud.bigint().satisfies(
|
|
91
|
+
lean`fun (result : Int) => ${value} < result`,
|
|
92
|
+
));
|
|
93
|
+
});
|
|
94
|
+
});
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
Use `.satisfies()` to add a native predicate to a schema and `.by()` to supply a proof of the whole property. A `lean` template can interpolate TypeScript expressions in scope, and `lean.ref("Namespace.name", ...args)` can name a predicate or theorem. Register a local helper file with `use(lean.module("./helper.lean"))`. [Lean examples and supported types](.examples/README.md)
|
|
98
|
+
|
|
99
|
+
### Use the library
|
|
100
|
+
|
|
101
|
+
```ts
|
|
102
|
+
import { check, emit } from "@pud.dev/lib";
|
|
103
|
+
import { leanAdapter } from "@pud.dev/lib/lean";
|
|
104
|
+
|
|
105
|
+
const adapter = leanAdapter();
|
|
106
|
+
const report = await check("clamp.proof.ts", { adapter });
|
|
107
|
+
const unit = await emit("clamp.proof.ts", { adapter, property: "keeps the result within ordered bounds" });
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
`checkFiles(files, { adapter })` applies the same override to a batch and runs the supplied adapter in the caller’s process. When Pud loads the project config, each `check`, `checkFiles`, or `emit` call starts a fresh Bun process. Suites in one batch share its loaded modules. The next call picks up edits to the config and its imports. Project logs go to stderr so the CLI can pipe a JSON report or an emitted unit through stdout.
|
|
111
|
+
|
|
112
|
+
An adapter implements `ProofAssistant` from `@pud.dev/lib` and supplies a stable assistant ID. Its `prepare` method reads the named TypeScript export from the supplied snapshot and returns its signature, an emitter, and a verifier. Pud binds one `ProofClaim` per active property and checks its native term IDs against the adapter. Switch on `claim.kind` to handle a return rule (`"return"`), equality with a reference call (`"equal"`), or an expected exception (`"throw"`). Exact return rules carry `exactResult: true`. For a custom native tag, import `native` from `@pud.dev/lib` and declare `const term = native("assistant-id")` at file scope before `pud.describe`. [Adapter contract](src/assistant.ts)
|
|
113
|
+
|
|
114
|
+
Use `checkFiles(files, { onProgress })` for a live view. Suite events declare the queue and total item count. Each active property index appears in exactly one `finished` event during a completed run. Its status is at the same position in `statuses`. Pending properties stay out of the count. The `validating` event precedes the input snapshot check. The returned reports carry the final verdicts.
|
|
115
|
+
|
|
116
|
+
## Development
|
|
117
|
+
|
|
118
|
+
Follow the [workspace setup](../../README.md#workspace) and run `bun run test` from the root. Run `bun run pack:cli` to write the self-contained archive to `dist/`. The archive contains the executable, both public entry points, and their TypeScript declarations.
|
package/package.json
CHANGED
|
@@ -1,6 +1,26 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pud.dev",
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"type": "module",
|
|
4
|
+
"version": "0.0.1",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": "./src/index.ts",
|
|
8
|
+
"./lean": "./src/lean/index.ts"
|
|
9
|
+
},
|
|
10
|
+
"bin": {
|
|
11
|
+
"pud": "./src/cli.ts"
|
|
12
|
+
},
|
|
13
|
+
"dependencies": {
|
|
14
|
+
"@babel/parser": "catalog:",
|
|
15
|
+
"@babel/types": "catalog:",
|
|
16
|
+
"chalk": "catalog:"
|
|
17
|
+
},
|
|
18
|
+
"devDependencies": {
|
|
19
|
+
"@types/node": "catalog:"
|
|
20
|
+
},
|
|
21
|
+
"scripts": {
|
|
22
|
+
"pack": "\"$npm_execpath\" ./scripts/pack.ts",
|
|
23
|
+
"test": "\"$npm_execpath\" test",
|
|
24
|
+
"typecheck": "tsc --noEmit"
|
|
25
|
+
}
|
|
26
|
+
}
|
package/scripts/pack.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { chmod, copyFile, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join, resolve, sep } from "node:path";
|
|
5
|
+
import manifest from "../package.json";
|
|
6
|
+
|
|
7
|
+
const pud = resolve(import.meta.dir, "..");
|
|
8
|
+
const root = resolve(pud, "../..");
|
|
9
|
+
|
|
10
|
+
/** Ship the notices of every third-party package actually present in the Bun bundle. */
|
|
11
|
+
async function writeNotices(files: string[], target: string) {
|
|
12
|
+
const packages = new Set<string>();
|
|
13
|
+
for (const file of files) {
|
|
14
|
+
const parts = resolve(file).split(sep);
|
|
15
|
+
const index = parts.lastIndexOf("node_modules");
|
|
16
|
+
if (index < 0) continue;
|
|
17
|
+
const scoped = parts[index + 1]!.startsWith("@");
|
|
18
|
+
packages.add(parts.slice(0, index + (scoped ? 3 : 2)).join(sep));
|
|
19
|
+
}
|
|
20
|
+
const notices: string[] = [];
|
|
21
|
+
for (const dir of [...packages].sort()) {
|
|
22
|
+
const { name, version } = await Bun.file(join(dir, "package.json")).json();
|
|
23
|
+
const licenses = (await readdir(dir)).filter(n => /^(licen[cs]e|copying|notice)(?:$|[.-])/i.test(n)).sort();
|
|
24
|
+
if (!licenses.length) throw new Error(`Missing license for ${name}@${version}`);
|
|
25
|
+
notices.push(`${name}@${version}`, ...await Promise.all(licenses.map(n => readFile(join(dir, n), "utf8"))));
|
|
26
|
+
}
|
|
27
|
+
await writeFile(target, notices.join("\n\n"));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export async function pack(destination = join(root, "dist")) {
|
|
31
|
+
destination = resolve(destination);
|
|
32
|
+
const stage = await mkdtemp(join(tmpdir(), "pud-pack-"));
|
|
33
|
+
try {
|
|
34
|
+
const build = await Bun.build({
|
|
35
|
+
entrypoints: ["cli.ts", "index.ts", "lean/index.ts", "project-runner.ts"].map(file => join(pud, "src", file)),
|
|
36
|
+
root: join(pud, "src"),
|
|
37
|
+
outdir: stage,
|
|
38
|
+
target: "bun",
|
|
39
|
+
splitting: true,
|
|
40
|
+
metafile: true,
|
|
41
|
+
minify: { whitespace: true },
|
|
42
|
+
});
|
|
43
|
+
if (!build.success) throw new AggregateError(build.logs, "Could not bundle Pud");
|
|
44
|
+
execFileSync(process.execPath, [
|
|
45
|
+
join(root, "node_modules/typescript/bin/tsc"), "-p", join(pud, "tsconfig.pack.json"), "--outDir", join(stage, "types"),
|
|
46
|
+
], { stdio: "inherit" });
|
|
47
|
+
await writeNotices(Object.keys(build.metafile!.inputs), join(stage, "THIRD-PARTY-NOTICES"));
|
|
48
|
+
await copyFile(join(root, "LICENSE"), join(stage, "LICENSE"));
|
|
49
|
+
await chmod(join(stage, "cli.js"), 0o755);
|
|
50
|
+
const types = "./types/index.d.ts";
|
|
51
|
+
await writeFile(join(stage, "package.json"), JSON.stringify({
|
|
52
|
+
name: manifest.name, version: manifest.version, type: "module", license: manifest.license,
|
|
53
|
+
exports: {
|
|
54
|
+
".": { types, default: "./index.js" },
|
|
55
|
+
"./lean": { types: "./types/lean/index.d.ts", default: "./lean/index.js" },
|
|
56
|
+
}, types,
|
|
57
|
+
bin: { pud: "./cli.js" },
|
|
58
|
+
}, null, 2));
|
|
59
|
+
await mkdir(destination, { recursive: true });
|
|
60
|
+
const archive = execFileSync(process.execPath, ["pm", "pack", "--destination", destination, "--quiet"], { cwd: stage, encoding: "utf8" }).trim();
|
|
61
|
+
return resolve(destination, archive);
|
|
62
|
+
} finally {
|
|
63
|
+
await rm(stage, { recursive: true, force: true });
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
if (import.meta.main) console.log(await pack(process.argv[2]));
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import { mkdir, mkdtemp, rename, rm, writeFile } from "node:fs/promises";
|
|
4
|
+
import { basename, dirname, join } from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
|
|
7
|
+
const toolchain = readFileSync(new URL("../.examples/lean-toolchain", import.meta.url), "utf8").trim();
|
|
8
|
+
const checkoutElan = fileURLToPath(new URL("../../../.cache/elan", import.meta.url));
|
|
9
|
+
const extension = process.platform === "win32" ? ".exe" : "";
|
|
10
|
+
const elanVersion = "v4.4.0";
|
|
11
|
+
|
|
12
|
+
// https://github.com/leanprover/elan/releases/tag/v4.4.0
|
|
13
|
+
const releases: Record<string, { archive: string; sha256: string }> = {
|
|
14
|
+
"darwin-arm64": { archive: "aarch64-apple-darwin.tar.gz", sha256: "27af24edeace839730e8c9119783f12d5f694327d4771605021ca09db1ab0a87" },
|
|
15
|
+
"darwin-x64": { archive: "x86_64-apple-darwin.tar.gz", sha256: "a5123096d662216ceaf69d68d6bbabb118c024d20d270bf0d639a830dd4ff97e" },
|
|
16
|
+
"linux-arm64": { archive: "aarch64-unknown-linux-gnu.tar.gz", sha256: "45cde3006f82f98804c94cf2ca4949d117060a5f3cc8afa62f523759947ee21f" },
|
|
17
|
+
"linux-x64": { archive: "x86_64-unknown-linux-gnu.tar.gz", sha256: "0e8250aa2be86c7af929ade68db617af9edc8b9ccf6eaf5ece228250d0d032e2" },
|
|
18
|
+
"win32-x64": { archive: "x86_64-pc-windows-msvc.zip", sha256: "63f50605424284927799702347e2bdbd99d017b9d80ae083c65ee2189c4caf75" },
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
function shim(home: string, name: "lean" | "elan") {
|
|
22
|
+
return join(home, "bin", name + extension);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function elanEnv(home: string) {
|
|
26
|
+
return { ...process.env, ELAN_HOME: home, ELAN_TOOLCHAIN: toolchain };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async function run(binary: string, args: string[], env = process.env) {
|
|
30
|
+
const child = Bun.spawn([binary, ...args], { env, stdout: "inherit", stderr: "inherit" });
|
|
31
|
+
const exit = await child.exited;
|
|
32
|
+
if (exit !== 0) throw new Error(`${basename(binary)} exited with status ${exit}.`);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async function selectToolchain(home: string) {
|
|
36
|
+
await run(shim(home, "elan"), ["default", toolchain], elanEnv(home));
|
|
37
|
+
await run(shim(home, "lean"), ["--version"], elanEnv(home));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function hasElan(home: string) {
|
|
41
|
+
return Boolean(Bun.which(shim(home, "elan")) && Bun.which(shim(home, "lean")));
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function setupLean() {
|
|
45
|
+
if (hasElan(checkoutElan)) {
|
|
46
|
+
await selectToolchain(checkoutElan);
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const platform = `${process.platform}-${process.arch}`;
|
|
51
|
+
const release = releases[platform];
|
|
52
|
+
if (!release) throw new Error(`Elan has no bundled installer for ${platform}. Set PUD_LEAN to a working Lean executable.`);
|
|
53
|
+
|
|
54
|
+
const cache = dirname(checkoutElan);
|
|
55
|
+
await mkdir(cache, { recursive: true });
|
|
56
|
+
const stage = await mkdtemp(join(cache, ".elan-install-"));
|
|
57
|
+
try {
|
|
58
|
+
const archive = join(stage, `elan-${release.archive}`);
|
|
59
|
+
const stagedHome = join(stage, "elan-home");
|
|
60
|
+
console.log(`Installing Elan ${elanVersion} and ${toolchain} in .cache/elan`);
|
|
61
|
+
const response = await fetch(`https://github.com/leanprover/elan/releases/download/${elanVersion}/${basename(archive)}`, {
|
|
62
|
+
signal: AbortSignal.timeout(60_000),
|
|
63
|
+
});
|
|
64
|
+
if (!response.ok) throw new Error(`Elan download returned HTTP ${response.status}.`);
|
|
65
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
66
|
+
if (createHash("sha256").update(bytes).digest("hex") !== release.sha256) throw new Error("Elan release checksum mismatch.");
|
|
67
|
+
await writeFile(archive, bytes);
|
|
68
|
+
await run("tar", ["-xf", archive, "-C", stage]);
|
|
69
|
+
await run(join(stage, `elan-init${extension}`), ["-y", "--no-modify-path", "--default-toolchain", "none"], elanEnv(stagedHome));
|
|
70
|
+
await selectToolchain(stagedHome);
|
|
71
|
+
try {
|
|
72
|
+
await rename(stagedHome, checkoutElan);
|
|
73
|
+
} catch (error) {
|
|
74
|
+
if (!hasElan(checkoutElan)) throw error;
|
|
75
|
+
await selectToolchain(checkoutElan);
|
|
76
|
+
}
|
|
77
|
+
} finally {
|
|
78
|
+
await rm(stage, { recursive: true, force: true });
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (import.meta.main) {
|
|
83
|
+
try { await setupLean(); }
|
|
84
|
+
catch (error) {
|
|
85
|
+
console.error(`Lean setup failed. ${(error as Error).message}`);
|
|
86
|
+
process.exitCode = 1;
|
|
87
|
+
}
|
|
88
|
+
}
|
package/src/assistant.ts
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
/** A construct for which the selected frontend or adapter has no semantics. */
|
|
2
|
+
export class Unsupported extends Error {}
|
|
3
|
+
|
|
4
|
+
export function failure(error: unknown): { status: "unsupported" | "error"; detail: string } {
|
|
5
|
+
return { status: error instanceof Unsupported ? "unsupported" : "error", detail: error instanceof Error ? error.message : String(error) };
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface SubjectSource {
|
|
9
|
+
name: string;
|
|
10
|
+
file: string;
|
|
11
|
+
source: string;
|
|
12
|
+
/** Read and track a UTF-8 input relative to the subject's directory or by absolute path. */
|
|
13
|
+
readDependency?(path: string): string;
|
|
14
|
+
/** Read a linked source and track any import resolution that selected it. */
|
|
15
|
+
readModule?(path: string, resolveAgain?: () => string): { canonical: string; source: string };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface Counterexample {
|
|
19
|
+
summary: string;
|
|
20
|
+
input: Record<string, string>;
|
|
21
|
+
result: string;
|
|
22
|
+
/** A distinct value accepted by an exact result rule for the same input. */
|
|
23
|
+
alternative?: string;
|
|
24
|
+
difference?: { subject: string; expected: string; received: string };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export type ProofType =
|
|
28
|
+
| { kind: "integer" | "number" | "boolean" }
|
|
29
|
+
| { kind: "opaque"; name: string }
|
|
30
|
+
| { kind: "array" | "textOrArray"; item: ProofType };
|
|
31
|
+
|
|
32
|
+
/** A TypeScript expression and its mapping from callback bindings to subject parameters. */
|
|
33
|
+
export interface ProofExpression {
|
|
34
|
+
file: string;
|
|
35
|
+
source: string;
|
|
36
|
+
line: number;
|
|
37
|
+
column: number;
|
|
38
|
+
offset: number;
|
|
39
|
+
bindings: ReadonlyMap<string, string>;
|
|
40
|
+
/** In-scope references to Pud's specification helpers. */
|
|
41
|
+
schemaBindings?: ReadonlySet<string>;
|
|
42
|
+
/** The JavaScript Number constructor is in scope in this expression. */
|
|
43
|
+
numberGlobal?: boolean;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export type NativeProofTerm = { assistant: string; args: readonly ProofExpression[] } & (
|
|
47
|
+
| { kind: "reference"; name: string }
|
|
48
|
+
| { kind: "template"; parts: readonly string[] }
|
|
49
|
+
);
|
|
50
|
+
|
|
51
|
+
export type ProofTarget = { kind: "parameter"; name: string } | { kind: "result" } | { kind: "quantified" };
|
|
52
|
+
export type ProofComparison = "eq" | "gt" | "gte" | "lt" | "lte";
|
|
53
|
+
|
|
54
|
+
export type ProofPredicate =
|
|
55
|
+
| { kind: "boolean"; expression: ProofExpression }
|
|
56
|
+
| { kind: "not"; operand: ProofPredicate }
|
|
57
|
+
| { kind: "binary"; operator: "and" | "or" | "implies" | "iff"; left: ProofPredicate; right: ProofPredicate }
|
|
58
|
+
| {
|
|
59
|
+
kind: "quantifier";
|
|
60
|
+
quantifier: "forall" | "exists";
|
|
61
|
+
variable: string;
|
|
62
|
+
domain: { kind: "array"; expression: ProofExpression }
|
|
63
|
+
| { kind: "schema"; type: "integer" | "number" | "boolean"; constraints: readonly ProofConstraint[] };
|
|
64
|
+
predicate: ProofPredicate;
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
export type ProofConstraint =
|
|
68
|
+
| { kind: "condition"; expression: ProofExpression }
|
|
69
|
+
| { kind: "proposition"; predicate: ProofPredicate }
|
|
70
|
+
| { kind: "comparison"; target: ProofTarget; operator: ProofComparison; value: ProofExpression }
|
|
71
|
+
| { kind: "nearestInteger"; target: ProofTarget; value: ProofExpression; ties: "up" | "down" }
|
|
72
|
+
| { kind: "sameValue"; target: ProofTarget; value: ProofExpression }
|
|
73
|
+
| { kind: "refinement"; target: ProofTarget; variable: string; predicate: ProofPredicate }
|
|
74
|
+
| { kind: "native"; target: ProofTarget; term: NativeProofTerm };
|
|
75
|
+
|
|
76
|
+
export type ProofClaim = {
|
|
77
|
+
premises: readonly ProofConstraint[];
|
|
78
|
+
proof?: NativeProofTerm;
|
|
79
|
+
observation?: ProofCall;
|
|
80
|
+
} & (
|
|
81
|
+
| {
|
|
82
|
+
kind: "return";
|
|
83
|
+
assertions: readonly ProofConstraint[];
|
|
84
|
+
/** The assertions must characterize the observed result uniquely. */
|
|
85
|
+
exactResult?: true;
|
|
86
|
+
reference?: never;
|
|
87
|
+
expectedError?: never;
|
|
88
|
+
}
|
|
89
|
+
| { kind: "equal"; assertions: readonly []; reference: ProofCall; expectedError?: never; exactResult?: never }
|
|
90
|
+
| { kind: "throw"; assertions: readonly []; expectedError: ProofErrorKind; reference?: never; exactResult?: never }
|
|
91
|
+
);
|
|
92
|
+
|
|
93
|
+
export type ProofErrorKind = "Error" | "RangeError" | "TypeError";
|
|
94
|
+
|
|
95
|
+
export interface ProofCall {
|
|
96
|
+
kind: "call";
|
|
97
|
+
callee: "subject" | { file: string; name: string };
|
|
98
|
+
args: readonly (ProofCall | { kind: "parameter"; name: string })[];
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export interface ProofModule {
|
|
102
|
+
file: string;
|
|
103
|
+
source: string;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export type ProofOutcome =
|
|
107
|
+
| { status: "proved" }
|
|
108
|
+
/** A concrete input witnesses a violated assertion or an ambiguous exact result. */
|
|
109
|
+
| { status: "disproved"; counterexample: Counterexample }
|
|
110
|
+
| { status: "unproved" | "unsupported" | "error"; detail: string; diagnostic?: string };
|
|
111
|
+
|
|
112
|
+
export type ClaimProgress = (index: number, state: "running" | "finished", status?: ProofOutcome["status"]) => void;
|
|
113
|
+
|
|
114
|
+
/** The adapter has parsed the exact implementation snapshot and can certify claims about it. */
|
|
115
|
+
export interface PreparedProofAssistant {
|
|
116
|
+
parameters: readonly { name: string; type: ProofType }[];
|
|
117
|
+
result: ProofType;
|
|
118
|
+
inspectCall?(call: ProofCall): ProofType;
|
|
119
|
+
/** The assistant can compare the observation with a reference call. */
|
|
120
|
+
callEquality?: true;
|
|
121
|
+
/** The assistant proves both satisfaction and uniqueness for scalar return schemas. */
|
|
122
|
+
exactResults?: true;
|
|
123
|
+
errors?: readonly ProofErrorKind[];
|
|
124
|
+
emit(claim: ProofClaim, modules: readonly ProofModule[]): string | Promise<string>;
|
|
125
|
+
verify(claims: readonly ProofClaim[], modules: readonly ProofModule[], onClaim?: ClaimProgress): Promise<readonly ProofOutcome[]>;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export interface ProofAssistant<Id extends string = string> {
|
|
129
|
+
readonly id: Id;
|
|
130
|
+
prepare(subject: SubjectSource): PreparedProofAssistant | Promise<PreparedProofAssistant>;
|
|
131
|
+
}
|