@bytewaveco/pudding 0.0.0-stage → 0.1.0-beta.0
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/LICENSE +21 -0
- package/README.md +363 -2
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +143 -0
- package/dist/crosscheck.d.ts +63 -0
- package/dist/crosscheck.js +164 -0
- package/dist/index.d.ts +76 -0
- package/dist/index.js +72 -0
- package/dist/install.d.ts +25 -0
- package/dist/install.js +192 -0
- package/dist/ir.d.ts +93 -0
- package/dist/ir.js +331 -0
- package/dist/lean.d.ts +56 -0
- package/dist/lean.js +438 -0
- package/dist/report.d.ts +7 -0
- package/dist/report.js +74 -0
- package/dist/runner.d.ts +79 -0
- package/dist/runner.js +672 -0
- package/dist/search.d.ts +24 -0
- package/dist/search.js +137 -0
- package/dist/translate.d.ts +247 -0
- package/dist/translate.js +1938 -0
- package/dist/vitest.d.ts +8 -0
- package/dist/vitest.js +96 -0
- package/package.json +77 -4
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
// Runs in a worker thread. Executes each law against the real code and
|
|
2
|
+
// compares the outcome with the model the proofs are about.
|
|
3
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
4
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
5
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
6
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
7
|
+
});
|
|
8
|
+
}
|
|
9
|
+
return path;
|
|
10
|
+
};
|
|
11
|
+
import { realpathSync } from "node:fs";
|
|
12
|
+
import { registerHooks } from "node:module";
|
|
13
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
14
|
+
import { parentPort, workerData } from "node:worker_threads";
|
|
15
|
+
import * as ir from "./ir.js";
|
|
16
|
+
import { assignments, showInputs, valuePool } from "./search.js";
|
|
17
|
+
const pathOf = (url) => fileURLToPath(url.split("?")[0]);
|
|
18
|
+
function buildArgument(shape, env, numbers) {
|
|
19
|
+
switch (shape.k) {
|
|
20
|
+
case "binder": return numbers.has(shape.name) ? Number(env.get(shape.name)) : env.get(shape.name);
|
|
21
|
+
case "const": return shape.num ? Number(shape.value) : shape.value;
|
|
22
|
+
case "array": return shape.items.map(item => buildArgument(item, env, numbers));
|
|
23
|
+
case "record": return Object.fromEntries(shape.fields.map(([key, field]) => [key, buildArgument(field, env, numbers)]));
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* What the model says about an input: whether the law holds, or that the
|
|
28
|
+
* model does not describe this input. The latter is when a number leaves the
|
|
29
|
+
* range of exact whole numbers; the real code then computes something the
|
|
30
|
+
* model has no counterpart for, and that is already reported on its own.
|
|
31
|
+
*/
|
|
32
|
+
function modelHolds(instance, env) {
|
|
33
|
+
try {
|
|
34
|
+
let holds = true;
|
|
35
|
+
for (const obligation of instance.obligations) {
|
|
36
|
+
if (ir.evaluate(obligation.guard, env) !== true || ir.evaluate(obligation.claim, env) === true)
|
|
37
|
+
continue;
|
|
38
|
+
if (obligation.inexact)
|
|
39
|
+
return "outside";
|
|
40
|
+
holds = false;
|
|
41
|
+
}
|
|
42
|
+
return holds;
|
|
43
|
+
}
|
|
44
|
+
catch (error) {
|
|
45
|
+
if (error instanceof ir.EvaluationError)
|
|
46
|
+
return false;
|
|
47
|
+
throw error;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
function runtimeHolds(callback, argument) {
|
|
51
|
+
try {
|
|
52
|
+
const result = callback(argument);
|
|
53
|
+
// A law that hands back a promise has not finished, so it has not passed.
|
|
54
|
+
if (typeof result?.then === "function")
|
|
55
|
+
return false;
|
|
56
|
+
return true;
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
async function register(file) {
|
|
63
|
+
const key = Symbol.for("pudding.registry");
|
|
64
|
+
const registry = [];
|
|
65
|
+
const globals = globalThis;
|
|
66
|
+
globals[key] = registry;
|
|
67
|
+
try {
|
|
68
|
+
await import(__rewriteRelativeImportExtension(pathToFileURL(file).href));
|
|
69
|
+
return registry;
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
// Node failing to load or link the files raises its error from inside
|
|
73
|
+
// Node. An error raised while the project's own code was running has a
|
|
74
|
+
// frame in a project file, and means the module really does not load.
|
|
75
|
+
const stack = error instanceof Error ? error.stack ?? "" : "";
|
|
76
|
+
const throws = !(error instanceof Error) || /\n\s+at [^\n]*file:\/\/(?![^\n]*\/node_modules\/)/.test(stack);
|
|
77
|
+
const text = error instanceof Error ? `${error.name}: ${error.message.split("\n")[0]}` : String(error);
|
|
78
|
+
return { message: text, throws };
|
|
79
|
+
}
|
|
80
|
+
finally {
|
|
81
|
+
delete globals[key];
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
async function execute(job, report) {
|
|
85
|
+
const rerouted = new Set();
|
|
86
|
+
registerHooks({
|
|
87
|
+
resolve(specifier, context, nextResolve) {
|
|
88
|
+
const target = context.parentURL?.startsWith("file:") ? job.map.resolutions.get(pathOf(context.parentURL))?.get(specifier) : undefined;
|
|
89
|
+
if (!target)
|
|
90
|
+
return nextResolve(specifier, context);
|
|
91
|
+
// The proofs are about the file TypeScript read, so that is the file to
|
|
92
|
+
// run. Where Node alone would have picked another, say so.
|
|
93
|
+
try {
|
|
94
|
+
const native = nextResolve(specifier, context).url;
|
|
95
|
+
if (native.startsWith("file:") && realpathSync(pathOf(native)) !== realpathSync(target)) {
|
|
96
|
+
rerouted.add(`\`${specifier}\` in ${pathOf(context.parentURL)}: Node resolves it to ${pathOf(native)}, TypeScript read ${target}`);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
// Node cannot resolve it at all, which is the usual reason the map exists.
|
|
101
|
+
}
|
|
102
|
+
return { url: pathToFileURL(target).href, shortCircuit: true };
|
|
103
|
+
},
|
|
104
|
+
load(url, context, nextLoad) {
|
|
105
|
+
const result = nextLoad(url, context);
|
|
106
|
+
const ranges = url.startsWith("file:") ? job.map.elided.get(pathOf(url)) : undefined;
|
|
107
|
+
if (!ranges || result.source === undefined || result.source === null)
|
|
108
|
+
return result;
|
|
109
|
+
// Blank the names rather than cut them, so positions in error messages stay true.
|
|
110
|
+
let text = typeof result.source === "string" ? result.source : Buffer.from(result.source).toString("utf8");
|
|
111
|
+
for (const [start, end] of ranges)
|
|
112
|
+
text = text.slice(0, start) + text.slice(start, end).replace(/[^\n]/g, " ") + text.slice(end);
|
|
113
|
+
return { ...result, source: text };
|
|
114
|
+
},
|
|
115
|
+
});
|
|
116
|
+
for (const { file, registered, laws } of job.files) {
|
|
117
|
+
const outcome = { file, laws: [] };
|
|
118
|
+
const runtime = await register(file);
|
|
119
|
+
if (!Array.isArray(runtime)) {
|
|
120
|
+
outcome.error = runtime.throws ? runtime.message : `it could not be executed (${runtime.message})`;
|
|
121
|
+
outcome.throws = runtime.throws;
|
|
122
|
+
}
|
|
123
|
+
else if (runtime.length !== registered)
|
|
124
|
+
outcome.miscounted = { ran: runtime.length, read: registered };
|
|
125
|
+
else {
|
|
126
|
+
for (const law of laws) {
|
|
127
|
+
const callback = runtime[law.index]?.callback;
|
|
128
|
+
if (!callback)
|
|
129
|
+
continue;
|
|
130
|
+
const result = { index: law.index, executed: 0, exhaustive: true };
|
|
131
|
+
for (const instance of law.instances) {
|
|
132
|
+
const numbers = new Set(instance.binders.filter(b => b.num).map(b => b.name));
|
|
133
|
+
const space = assignments(instance.binders, valuePool([...instance.obligations.flatMap(o => [o.guard, o.claim]), ...law.mentioned]), job.budget);
|
|
134
|
+
result.exhaustive &&= space.exhaustive;
|
|
135
|
+
space.each(env => {
|
|
136
|
+
const expected = law.unproved ? true : modelHolds(instance, env);
|
|
137
|
+
if (expected === "outside")
|
|
138
|
+
return false;
|
|
139
|
+
if (expected === false)
|
|
140
|
+
result.modelFails ??= showInputs(instance.binders, env);
|
|
141
|
+
result.executed++;
|
|
142
|
+
const actual = runtimeHolds(callback, instance.arg ? buildArgument(instance.arg, env, numbers) : undefined);
|
|
143
|
+
if (actual === expected)
|
|
144
|
+
return false;
|
|
145
|
+
result.failure = { kind: law.unproved ? "counterexample" : "mismatch", inputs: showInputs(instance.binders, env), actual, expected };
|
|
146
|
+
return true;
|
|
147
|
+
});
|
|
148
|
+
if (result.failure)
|
|
149
|
+
break;
|
|
150
|
+
}
|
|
151
|
+
outcome.laws.push(result);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
if (rerouted.size)
|
|
155
|
+
outcome.rerouted = [...rerouted];
|
|
156
|
+
rerouted.clear();
|
|
157
|
+
report(outcome);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
if (parentPort) {
|
|
161
|
+
const port = parentPort;
|
|
162
|
+
await execute(workerData, outcome => port.postMessage(outcome));
|
|
163
|
+
port.postMessage("done");
|
|
164
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
export interface Config {
|
|
2
|
+
/** Globs of law files, relative to the project. Default: every `*.law.ts`. */
|
|
3
|
+
include?: string[];
|
|
4
|
+
/** Globs to leave out. `node_modules` is always left out. */
|
|
5
|
+
exclude?: string[];
|
|
6
|
+
/**
|
|
7
|
+
* The tsconfig whose compiler options (paths, module resolution, strictness)
|
|
8
|
+
* the law files are read with. Default: `tsconfig.json` when it exists. The
|
|
9
|
+
* law files do not have to be included by it.
|
|
10
|
+
*/
|
|
11
|
+
tsconfig?: string;
|
|
12
|
+
/** Fail when a law is checked by execution only, without a proof. */
|
|
13
|
+
strict?: boolean;
|
|
14
|
+
/** Execute each law against the real code and compare it with the proved model. Default: true. */
|
|
15
|
+
crossCheck?: boolean;
|
|
16
|
+
/** Reuse results from earlier runs. Default: true. */
|
|
17
|
+
cache?: boolean;
|
|
18
|
+
/** Path of the Lean binary. */
|
|
19
|
+
lean?: string;
|
|
20
|
+
/** How results are printed. Default: `default`, or `github` inside GitHub Actions. */
|
|
21
|
+
reporter?: "default" | "verbose" | "json" | "github";
|
|
22
|
+
}
|
|
23
|
+
export declare function defineConfig(config: Config): Config;
|
|
24
|
+
/**
|
|
25
|
+
* A whole number. As a law input it means every integer from `Min` to `Max`,
|
|
26
|
+
* or every integer a `number` holds exactly when no bounds are given. A plain
|
|
27
|
+
* `number` cannot be an input, because it also covers fractions, NaN and
|
|
28
|
+
* infinities, which are not modeled.
|
|
29
|
+
*/
|
|
30
|
+
export type Integer<Min extends number = number, Max extends number = number> = number & {
|
|
31
|
+
readonly __puddingInteger?: [Min, Max];
|
|
32
|
+
};
|
|
33
|
+
export interface Domain<T> {
|
|
34
|
+
readonly value: T;
|
|
35
|
+
}
|
|
36
|
+
export interface LawOptions {
|
|
37
|
+
/**
|
|
38
|
+
* A Lean tactic script used in place of the default automation for the
|
|
39
|
+
* obligations of this law that range over unbounded inputs.
|
|
40
|
+
*/
|
|
41
|
+
proof?: string;
|
|
42
|
+
}
|
|
43
|
+
export interface Matchers<T> {
|
|
44
|
+
/** Structural equality. */
|
|
45
|
+
toEqual(expected: NoInfer<T>): void;
|
|
46
|
+
/** Equality of booleans, bigints and strings. */
|
|
47
|
+
toBe(expected: NoInfer<T>): void;
|
|
48
|
+
readonly not: Matchers<T>;
|
|
49
|
+
}
|
|
50
|
+
/** Describe every value of `T`. The type argument is read by the prover. */
|
|
51
|
+
export declare function domain<T>(): Domain<T>;
|
|
52
|
+
export interface LawFunction {
|
|
53
|
+
/** State a law that must hold for every value of the domain. */
|
|
54
|
+
<T>(name: string, inputs: Domain<T>, check: (input: T) => void, options?: LawOptions): void;
|
|
55
|
+
/** State a law about fixed values. */
|
|
56
|
+
(name: string, check: () => void, options?: LawOptions): void;
|
|
57
|
+
}
|
|
58
|
+
export interface Law extends LawFunction {
|
|
59
|
+
/** List the law without checking it. */
|
|
60
|
+
skip: LawFunction;
|
|
61
|
+
/** Check only the laws of this file that are marked `only`. */
|
|
62
|
+
only: LawFunction;
|
|
63
|
+
/** Record a law that is still to be written. */
|
|
64
|
+
todo(name: string): void;
|
|
65
|
+
}
|
|
66
|
+
export declare const law: Law;
|
|
67
|
+
export interface Describe {
|
|
68
|
+
/** Group laws under a shared name. */
|
|
69
|
+
(name: string, body: () => void): void;
|
|
70
|
+
skip(name: string, body: () => void): void;
|
|
71
|
+
only(name: string, body: () => void): void;
|
|
72
|
+
}
|
|
73
|
+
export declare const describe: Describe;
|
|
74
|
+
export declare class ExpectationFailed extends Error {
|
|
75
|
+
}
|
|
76
|
+
export declare function expect<T>(actual: T): Matchers<T>;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// The API that law files import.
|
|
2
|
+
//
|
|
3
|
+
// Pudding proves laws by reading them, not by running them. These functions
|
|
4
|
+
// still work at run time so the runner can execute a law against the real
|
|
5
|
+
// code and compare the result with the model it proved things about.
|
|
6
|
+
export function defineConfig(config) {
|
|
7
|
+
return config;
|
|
8
|
+
}
|
|
9
|
+
const REGISTRY = Symbol.for("pudding.registry");
|
|
10
|
+
/** Describe every value of `T`. The type argument is read by the prover. */
|
|
11
|
+
export function domain() {
|
|
12
|
+
return {};
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* A law file can be loaded in three ways. Pudding's own runner loads it with a
|
|
16
|
+
* registry in place, to execute the laws against the real code. Vitest loads
|
|
17
|
+
* it as a test file, and each law becomes a test that reports its proof.
|
|
18
|
+
* Anything else, such as importing it by accident, does nothing.
|
|
19
|
+
*/
|
|
20
|
+
const registry = () => globalThis[REGISTRY];
|
|
21
|
+
const bridge = typeof process !== "undefined" && process.env["VITEST"] !== undefined && !registry() ? await import("./vitest.js").catch(() => undefined) : undefined;
|
|
22
|
+
const vitest = bridge?.collecting() ? bridge : undefined;
|
|
23
|
+
const register = (modifier) => (name, second, third) => {
|
|
24
|
+
const collected = registry();
|
|
25
|
+
const callback = (typeof second === "function" ? second : typeof third === "function" ? third : undefined);
|
|
26
|
+
if (collected)
|
|
27
|
+
collected.push({ name, callback });
|
|
28
|
+
else
|
|
29
|
+
vitest?.defineLaw(modifier, name);
|
|
30
|
+
};
|
|
31
|
+
export const law = Object.assign(register("run"), {
|
|
32
|
+
skip: register("skip"), only: register("only"), todo: register("todo"),
|
|
33
|
+
});
|
|
34
|
+
const group = (modifier) => (name, body) => {
|
|
35
|
+
if (vitest && !registry())
|
|
36
|
+
vitest.defineGroup(modifier, name, body);
|
|
37
|
+
else
|
|
38
|
+
body();
|
|
39
|
+
};
|
|
40
|
+
export const describe = Object.assign(group("run"), { skip: group("skip"), only: group("only") });
|
|
41
|
+
export class ExpectationFailed extends Error {
|
|
42
|
+
}
|
|
43
|
+
// Zero and negative zero are treated as equal, as `===` treats them: whole
|
|
44
|
+
// numbers are modeled as integers, which have a single zero.
|
|
45
|
+
function equal(a, b) {
|
|
46
|
+
if (a === b || Object.is(a, b))
|
|
47
|
+
return true;
|
|
48
|
+
if (typeof a !== "object" || typeof b !== "object" || a === null || b === null)
|
|
49
|
+
return false;
|
|
50
|
+
if (Array.isArray(a) !== Array.isArray(b))
|
|
51
|
+
return false;
|
|
52
|
+
const keys = Object.keys(a);
|
|
53
|
+
if (keys.length !== Object.keys(b).length)
|
|
54
|
+
return false;
|
|
55
|
+
return keys.every(key => Object.hasOwn(b, key) && equal(a[key], b[key]));
|
|
56
|
+
}
|
|
57
|
+
function matchers(actual, negated) {
|
|
58
|
+
const check = (pass) => {
|
|
59
|
+
if (pass === negated)
|
|
60
|
+
throw new ExpectationFailed("expectation failed");
|
|
61
|
+
};
|
|
62
|
+
return {
|
|
63
|
+
toEqual: expected => check(equal(actual, expected)),
|
|
64
|
+
toBe: expected => check(actual === expected || Object.is(actual, expected)),
|
|
65
|
+
get not() {
|
|
66
|
+
return matchers(actual, !negated);
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
export function expect(actual) {
|
|
71
|
+
return matchers(actual, false);
|
|
72
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export declare const LEAN_VERSION = "4.36.0";
|
|
2
|
+
/** Where downloads shared by every project on this machine are kept. */
|
|
3
|
+
export declare function cacheDirectory(): string;
|
|
4
|
+
/** The directory name of the Lean release for this machine, or undefined when there is no prebuilt one. */
|
|
5
|
+
export declare function toolchainName(): string | undefined;
|
|
6
|
+
/**
|
|
7
|
+
* Install Lean into the machine-wide cache, or into `<cwd>/.toolchain` when
|
|
8
|
+
* `local` is set. By default everything Pudding does not use is removed after
|
|
9
|
+
* unpacking; `full` keeps the whole toolchain, which a proof you write
|
|
10
|
+
* yourself may need.
|
|
11
|
+
*/
|
|
12
|
+
export declare function installLean(cwd: string, options: {
|
|
13
|
+
full: boolean;
|
|
14
|
+
local: boolean;
|
|
15
|
+
log: (line: string) => void;
|
|
16
|
+
}): Promise<string>;
|
|
17
|
+
/** Every module the given ones import, directly or not, read from the sources a toolchain ships. */
|
|
18
|
+
export declare function importClosure(toolchain: string, roots: readonly string[]): string[];
|
|
19
|
+
/**
|
|
20
|
+
* Remove everything from an unpacked toolchain except what running `lean` on
|
|
21
|
+
* Pudding's theorems needs: the binary, its shared libraries, and the compiled
|
|
22
|
+
* form of the modules those theorems import. That is about an eighth of the
|
|
23
|
+
* download. `scripts/pack-runtime.mjs` goes further and strips the libraries.
|
|
24
|
+
*/
|
|
25
|
+
export declare function prune(target: string): void;
|
package/dist/install.js
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
// Download the Lean release Pudding was built against, and keep the part of it Pudding uses.
|
|
2
|
+
import { execFileSync, spawn } from "node:child_process";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { createReadStream, createWriteStream, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync } from "node:fs";
|
|
5
|
+
import { homedir } from "node:os";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { Readable, Transform } from "node:stream";
|
|
8
|
+
import { pipeline } from "node:stream/promises";
|
|
9
|
+
import { createZstdDecompress } from "node:zlib";
|
|
10
|
+
import { FALLBACK_IMPORTS } from "./lean.js";
|
|
11
|
+
export const LEAN_VERSION = "4.36.0";
|
|
12
|
+
/** SHA-256 of each release archive, so that what gets installed is the Lean that Pudding was tested with. */
|
|
13
|
+
const CHECKSUMS = {
|
|
14
|
+
"lean-4.36.0-darwin_aarch64": "49acada8749ad1343eff1224a3d2510ac61ed53363d37b5e738e8c587e7deabd",
|
|
15
|
+
"lean-4.36.0-darwin": "476f9dcf7bee6a070e39a6b15cab7ada48b0086bd91d6e61aa1a454d3da409ce",
|
|
16
|
+
"lean-4.36.0-linux": "2b7ab1ed8b92d2e6abfaf41344823b510064dbc9c0260cac73eb496ab2dea6eb",
|
|
17
|
+
"lean-4.36.0-linux_aarch64": "35471998152191ef809418ce5bf61f8fc5f209e5e3be05b48bdc4949fdb3e726",
|
|
18
|
+
};
|
|
19
|
+
/** Where downloads shared by every project on this machine are kept. */
|
|
20
|
+
export function cacheDirectory() {
|
|
21
|
+
if (process.env["PUDDING_CACHE_DIR"])
|
|
22
|
+
return process.env["PUDDING_CACHE_DIR"];
|
|
23
|
+
if (process.platform === "darwin")
|
|
24
|
+
return join(homedir(), "Library", "Caches", "pudding");
|
|
25
|
+
if (process.platform === "win32")
|
|
26
|
+
return join(process.env["LOCALAPPDATA"] ?? join(homedir(), "AppData", "Local"), "pudding", "Cache");
|
|
27
|
+
return join(process.env["XDG_CACHE_HOME"] ?? join(homedir(), ".cache"), "pudding");
|
|
28
|
+
}
|
|
29
|
+
/** The directory name of the Lean release for this machine, or undefined when there is no prebuilt one. */
|
|
30
|
+
export function toolchainName() {
|
|
31
|
+
const names = {
|
|
32
|
+
"darwin-arm64": "darwin_aarch64", "darwin-x64": "darwin", "linux-x64": "linux", "linux-arm64": "linux_aarch64",
|
|
33
|
+
};
|
|
34
|
+
const name = names[`${process.platform}-${process.arch}`];
|
|
35
|
+
return name && `lean-${LEAN_VERSION}-${name}`;
|
|
36
|
+
}
|
|
37
|
+
/** Download a file, showing how far along it is when someone is watching, and return its SHA-256. */
|
|
38
|
+
async function download(url, file) {
|
|
39
|
+
const response = await fetch(url);
|
|
40
|
+
if (!response.ok || !response.body)
|
|
41
|
+
throw new Error(`could not download ${url}: ${response.status} ${response.statusText}`);
|
|
42
|
+
const total = Number(response.headers.get("content-length")) || 0;
|
|
43
|
+
const hash = createHash("sha256");
|
|
44
|
+
const live = process.stderr.isTTY && total > 0;
|
|
45
|
+
let received = 0;
|
|
46
|
+
let shown = -1;
|
|
47
|
+
const meter = new Transform({
|
|
48
|
+
transform(chunk, _encoding, done) {
|
|
49
|
+
hash.update(chunk);
|
|
50
|
+
received += chunk.length;
|
|
51
|
+
const percent = Math.floor((received / total) * 100);
|
|
52
|
+
if (live && percent !== shown)
|
|
53
|
+
process.stderr.write(`\r ${(shown = percent)}% of ${Math.round(total / 1e6)} MB`);
|
|
54
|
+
done(null, chunk);
|
|
55
|
+
},
|
|
56
|
+
});
|
|
57
|
+
try {
|
|
58
|
+
await pipeline(Readable.fromWeb(response.body), meter, createWriteStream(file));
|
|
59
|
+
}
|
|
60
|
+
finally {
|
|
61
|
+
if (live)
|
|
62
|
+
process.stderr.write("\r\x1b[K");
|
|
63
|
+
}
|
|
64
|
+
return hash.digest("hex");
|
|
65
|
+
}
|
|
66
|
+
/** Unpack a `.tar.zst`. Node does the decompression, so the machine's `tar` does not have to know zstd. */
|
|
67
|
+
async function unpack(archive, into) {
|
|
68
|
+
const tar = spawn("tar", ["-xf", "-", "-C", into], { stdio: ["pipe", "inherit", "inherit"] });
|
|
69
|
+
const exit = new Promise((done, fail) => tar.on("close", done).on("error", fail));
|
|
70
|
+
await pipeline(createReadStream(archive), createZstdDecompress(), tar.stdin);
|
|
71
|
+
if ((await exit) !== 0)
|
|
72
|
+
throw new Error("could not unpack the archive");
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Install Lean into the machine-wide cache, or into `<cwd>/.toolchain` when
|
|
76
|
+
* `local` is set. By default everything Pudding does not use is removed after
|
|
77
|
+
* unpacking; `full` keeps the whole toolchain, which a proof you write
|
|
78
|
+
* yourself may need.
|
|
79
|
+
*/
|
|
80
|
+
export async function installLean(cwd, options) {
|
|
81
|
+
const name = toolchainName();
|
|
82
|
+
if (!name)
|
|
83
|
+
throw new Error(`there is no prebuilt Lean for ${process.platform}-${process.arch}; install Lean ${LEAN_VERSION} yourself and set PUDDING_LEAN`);
|
|
84
|
+
const root = options.local ? join(cwd, ".toolchain") : cacheDirectory();
|
|
85
|
+
const target = join(root, name);
|
|
86
|
+
const binary = join(target, "bin", "lean");
|
|
87
|
+
// The compiler's own library is the first thing trimming removes, so it tells a whole toolchain from a trimmed one.
|
|
88
|
+
const whole = existsSync(join(target, "lib", "lean", "Lean.olean"));
|
|
89
|
+
if (existsSync(binary) && (whole || !options.full)) {
|
|
90
|
+
options.log(`Lean ${LEAN_VERSION} is already installed at ${target}`);
|
|
91
|
+
return binary;
|
|
92
|
+
}
|
|
93
|
+
const url = `https://github.com/leanprover/lean4/releases/download/v${LEAN_VERSION}/${name}.tar.zst`;
|
|
94
|
+
options.log(`Downloading ${url}`);
|
|
95
|
+
// Everything happens in a directory of its own and is moved into place at
|
|
96
|
+
// the end, so an interrupted install never looks like a finished one.
|
|
97
|
+
const staging = join(root, `.installing-${process.pid}`);
|
|
98
|
+
rmSync(staging, { recursive: true, force: true });
|
|
99
|
+
mkdirSync(staging, { recursive: true });
|
|
100
|
+
try {
|
|
101
|
+
const archive = join(staging, `${name}.tar.zst`);
|
|
102
|
+
const found = await download(url, archive);
|
|
103
|
+
if (found !== CHECKSUMS[name]) {
|
|
104
|
+
throw new Error(`the download does not match the Lean ${LEAN_VERSION} release: expected SHA-256 ${CHECKSUMS[name]}, found ${found}`);
|
|
105
|
+
}
|
|
106
|
+
options.log("Unpacking");
|
|
107
|
+
await unpack(archive, staging);
|
|
108
|
+
if (!options.full)
|
|
109
|
+
prune(join(staging, name));
|
|
110
|
+
rmSync(target, { recursive: true, force: true });
|
|
111
|
+
renameSync(join(staging, name), target);
|
|
112
|
+
}
|
|
113
|
+
finally {
|
|
114
|
+
rmSync(staging, { recursive: true, force: true });
|
|
115
|
+
}
|
|
116
|
+
options.log(`Installed ${execFileSync(binary, ["--version"], { encoding: "utf8" }).trim()}`);
|
|
117
|
+
return binary;
|
|
118
|
+
}
|
|
119
|
+
/** The modules a Lean source file imports, in any of the forms the module system allows. */
|
|
120
|
+
function headerImports(text) {
|
|
121
|
+
const imports = [];
|
|
122
|
+
for (const raw of text.replace(/\/-[\s\S]*?-\//g, "").replace(/--.*$/gm, "").split("\n")) {
|
|
123
|
+
const line = raw.trim();
|
|
124
|
+
if (!line || line === "module" || line === "prelude")
|
|
125
|
+
continue;
|
|
126
|
+
const match = /^(?:public\s+)?(?:private\s+)?(?:meta\s+)?import\s+(?:all\s+)?(.+)$/.exec(line);
|
|
127
|
+
if (!match)
|
|
128
|
+
break;
|
|
129
|
+
imports.push(...match[1].trim().split(/\s+/));
|
|
130
|
+
}
|
|
131
|
+
return imports;
|
|
132
|
+
}
|
|
133
|
+
/** Every module the given ones import, directly or not, read from the sources a toolchain ships. */
|
|
134
|
+
export function importClosure(toolchain, roots) {
|
|
135
|
+
const seen = new Set();
|
|
136
|
+
const stack = [...roots];
|
|
137
|
+
while (stack.length) {
|
|
138
|
+
const name = stack.pop();
|
|
139
|
+
if (seen.has(name))
|
|
140
|
+
continue;
|
|
141
|
+
seen.add(name);
|
|
142
|
+
stack.push(...headerImports(readFileSync(join(toolchain, "src", "lean", ...name.split(".")) + ".lean", "utf8")));
|
|
143
|
+
}
|
|
144
|
+
return [...seen].sort();
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Remove everything from an unpacked toolchain except what running `lean` on
|
|
148
|
+
* Pudding's theorems needs: the binary, its shared libraries, and the compiled
|
|
149
|
+
* form of the modules those theorems import. That is about an eighth of the
|
|
150
|
+
* download. `scripts/pack-runtime.mjs` goes further and strips the libraries.
|
|
151
|
+
*/
|
|
152
|
+
export function prune(target) {
|
|
153
|
+
const library = join(target, "lib", "lean");
|
|
154
|
+
const keep = new Set();
|
|
155
|
+
for (const name of importClosure(target, FALLBACK_IMPORTS)) {
|
|
156
|
+
// A file that is not itself a `module` makes Lean open all three of these for each import.
|
|
157
|
+
for (const variant of [".olean", ".olean.server", ".olean.private"])
|
|
158
|
+
keep.add(join(library, ...name.split(".")) + variant);
|
|
159
|
+
}
|
|
160
|
+
const visit = (directory) => {
|
|
161
|
+
for (const entry of readdirSync(directory, { withFileTypes: true })) {
|
|
162
|
+
const path = join(directory, entry.name);
|
|
163
|
+
if (entry.isDirectory()) {
|
|
164
|
+
visit(path);
|
|
165
|
+
if (!readdirSync(path).length)
|
|
166
|
+
rmSync(path, { recursive: true });
|
|
167
|
+
}
|
|
168
|
+
else if (!keep.has(path))
|
|
169
|
+
rmSync(path);
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
for (const entry of readdirSync(target)) {
|
|
173
|
+
if (entry !== "bin" && entry !== "lib" && !entry.startsWith("LICENSE"))
|
|
174
|
+
rmSync(join(target, entry), { recursive: true });
|
|
175
|
+
}
|
|
176
|
+
for (const entry of readdirSync(join(target, "bin")))
|
|
177
|
+
if (entry !== "lean")
|
|
178
|
+
rmSync(join(target, "bin", entry), { recursive: true });
|
|
179
|
+
for (const entry of readdirSync(join(target, "lib")))
|
|
180
|
+
if (entry !== "lean")
|
|
181
|
+
rmSync(join(target, "lib", entry), { recursive: true });
|
|
182
|
+
for (const entry of readdirSync(library, { withFileTypes: true })) {
|
|
183
|
+
const path = join(library, entry.name);
|
|
184
|
+
if (entry.isDirectory()) {
|
|
185
|
+
visit(path);
|
|
186
|
+
if (!readdirSync(path).length)
|
|
187
|
+
rmSync(path, { recursive: true });
|
|
188
|
+
}
|
|
189
|
+
else if (!keep.has(path) && !/^lib(leanshared|Init_shared).*\.(dylib|so)$/.test(entry.name))
|
|
190
|
+
rmSync(path);
|
|
191
|
+
}
|
|
192
|
+
}
|
package/dist/ir.d.ts
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
export type Ty = "bool" | "int" | "str";
|
|
2
|
+
export type Scalar = boolean | bigint | string;
|
|
3
|
+
export type Op = "not" | "and" | "or" | "eq" | "lt" | "le" | "add" | "sub" | "mul" | "neg" | "div" | "mod" | "fdiv" | "concat" | "str" | "ite";
|
|
4
|
+
export type Expr = {
|
|
5
|
+
readonly t: "var";
|
|
6
|
+
readonly ty: Ty;
|
|
7
|
+
readonly name: string;
|
|
8
|
+
} | {
|
|
9
|
+
readonly t: "lit";
|
|
10
|
+
readonly ty: Ty;
|
|
11
|
+
readonly value: Scalar;
|
|
12
|
+
} | {
|
|
13
|
+
readonly t: "op";
|
|
14
|
+
readonly ty: Ty;
|
|
15
|
+
readonly op: Op;
|
|
16
|
+
readonly args: readonly Expr[];
|
|
17
|
+
};
|
|
18
|
+
export interface Binder {
|
|
19
|
+
/** Name of the variable in the IR and in Lean. */
|
|
20
|
+
name: string;
|
|
21
|
+
/** How the input is written in the law, such as `from` or `entry.amount`. */
|
|
22
|
+
label: string;
|
|
23
|
+
ty: Ty;
|
|
24
|
+
/** Present when the input ranges over a finite set of values. */
|
|
25
|
+
domain?: Scalar[];
|
|
26
|
+
/** True when the input is a JavaScript `number` holding a whole number, modeled as an integer. */
|
|
27
|
+
num?: boolean;
|
|
28
|
+
/** Inclusive bounds of an integer input that is not enumerated. */
|
|
29
|
+
range?: [bigint, bigint];
|
|
30
|
+
}
|
|
31
|
+
export type ObligationKind = "expect" | "unreachable" | "falloff" | "missing" | "nothrow" | "overflow" | "nan";
|
|
32
|
+
export interface Obligation {
|
|
33
|
+
kind: ObligationKind;
|
|
34
|
+
/** The condition under which the claim must hold. */
|
|
35
|
+
guard: Expr;
|
|
36
|
+
claim: Expr;
|
|
37
|
+
file: string;
|
|
38
|
+
line: number;
|
|
39
|
+
column: number;
|
|
40
|
+
/** Source text of the statement that produced the obligation. */
|
|
41
|
+
text: string;
|
|
42
|
+
/** Both sides of an equality assertion, kept for reporting. */
|
|
43
|
+
sides?: {
|
|
44
|
+
actual: Expr;
|
|
45
|
+
expected: Expr;
|
|
46
|
+
negated: boolean;
|
|
47
|
+
num: boolean;
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
export declare const TRUE: Expr;
|
|
51
|
+
export declare const FALSE: Expr;
|
|
52
|
+
export declare function lit(value: Scalar): Expr;
|
|
53
|
+
export declare function variable(name: string, ty: Ty): Expr;
|
|
54
|
+
export declare function same(a: Expr, b: Expr): boolean;
|
|
55
|
+
export declare function not(a: Expr): Expr;
|
|
56
|
+
export declare function and(a: Expr, b: Expr): Expr;
|
|
57
|
+
export declare function or(a: Expr, b: Expr): Expr;
|
|
58
|
+
export declare function all(parts: readonly Expr[]): Expr;
|
|
59
|
+
export declare function eq(a: Expr, b: Expr): Expr;
|
|
60
|
+
export declare function lt(a: Expr, b: Expr): Expr;
|
|
61
|
+
export declare function le(a: Expr, b: Expr): Expr;
|
|
62
|
+
export declare function add(a: Expr, b: Expr): Expr;
|
|
63
|
+
export declare function sub(a: Expr, b: Expr): Expr;
|
|
64
|
+
export declare function mul(a: Expr, b: Expr): Expr;
|
|
65
|
+
export declare function neg(a: Expr): Expr;
|
|
66
|
+
/** BigInt division, which truncates toward zero. The divisor must not be zero. */
|
|
67
|
+
export declare function div(a: Expr, b: Expr): Expr;
|
|
68
|
+
/** Division rounded toward minus infinity, as `Math.floor(a / b)` computes it for whole numbers. The divisor must not be zero. */
|
|
69
|
+
export declare function fdiv(a: Expr, b: Expr): Expr;
|
|
70
|
+
/** BigInt remainder, which takes the sign of the dividend. */
|
|
71
|
+
export declare function mod(a: Expr, b: Expr): Expr;
|
|
72
|
+
/** String concatenation, kept flat and left-nested with adjacent literals merged so equal strings look equal. */
|
|
73
|
+
export declare function concat(a: Expr, b: Expr): Expr;
|
|
74
|
+
/** The decimal text of a bigint, as `String(n)` gives it. */
|
|
75
|
+
export declare function toStr(a: Expr): Expr;
|
|
76
|
+
export declare function ite(c: Expr, a: Expr, b: Expr): Expr;
|
|
77
|
+
/** Replace variables by expressions, folding constants on the way back up. */
|
|
78
|
+
export declare function substitute(e: Expr, values: ReadonlyMap<string, Expr>, memo?: Map<Expr, Expr>): Expr;
|
|
79
|
+
export declare function freeVariables(e: Expr, into?: Set<string>, seen?: Set<Expr>): Set<string>;
|
|
80
|
+
/** Size of the expression when printed as a tree. */
|
|
81
|
+
export declare function treeSize(e: Expr, memo?: Map<Expr, number>): number;
|
|
82
|
+
export declare function stringLiterals(e: Expr, into?: Set<string>, seen?: Set<Expr>): Set<string>;
|
|
83
|
+
export declare function integerLiterals(e: Expr, into?: Set<bigint>, seen?: Set<Expr>): Set<bigint>;
|
|
84
|
+
export declare class EvaluationError extends Error {
|
|
85
|
+
}
|
|
86
|
+
/** Evaluate with JavaScript semantics. Only used for diagnostics, never to accept a law. */
|
|
87
|
+
export declare function evaluate(e: Expr, env: ReadonlyMap<string, Scalar>): Scalar;
|
|
88
|
+
/** A value as it is written in TypeScript. `num` marks an integer that stands for a `number`. */
|
|
89
|
+
export declare function showScalar(value: Scalar, num?: boolean): string;
|
|
90
|
+
/** The largest whole number a JavaScript `number` holds exactly. */
|
|
91
|
+
export declare const MAX_SAFE: bigint;
|
|
92
|
+
/** Whether an integer is one a `number` holds exactly. */
|
|
93
|
+
export declare function isSafe(e: Expr): Expr;
|