leanfran 0.0.0-stage → 0.6.0-rc.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 +202 -0
- package/README.md +667 -2
- package/dist/arbitrary-B7Frjn9q.js +131 -0
- package/dist/block-CU7YIXdj.js +37 -0
- package/dist/check-DROT5twE.js +2931 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +134 -0
- package/dist/embed-BlX4FUDH.js +200 -0
- package/dist/index-DPF21ftq.d.ts +210 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.js +1 -0
- package/dist/io-CmMW8KGX.d.ts +66 -0
- package/dist/marshal-DhKsxhRw.js +2012 -0
- package/dist/node-B3DpEsaq.js +46 -0
- package/dist/object-G1zwZFrv.d.ts +93 -0
- package/dist/runtime/node.d.ts +2 -0
- package/dist/runtime/node.js +1 -0
- package/dist/runtime.d.ts +433 -0
- package/dist/runtime.js +1020 -0
- package/dist/schema-CvTyc8wa.js +308 -0
- package/dist/schema.d.ts +2 -0
- package/dist/schema.js +4 -0
- package/dist/verify.d.ts +27 -0
- package/dist/verify.js +215 -0
- package/package.json +69 -4
- package/src/lean/LeanTsLib/Ts.lean +78 -0
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
import { A as unitDesc, C as sintDesc, S as resolve, T as stringDesc, a as charDesc, d as intDesc, i as boolDesc, j as usizeDesc, k as uintDesc, l as float32Desc, m as jsonValue, n as LeanValidationError, o as checkValue, p as isizeDesc, u as floatDesc, v as natDesc } from "./marshal-DhKsxhRw.js";
|
|
2
|
+
import { t as blockRegistry } from "./block-CU7YIXdj.js";
|
|
3
|
+
import "./arbitrary-B7Frjn9q.js";
|
|
4
|
+
// src/schema/desc.ts
|
|
5
|
+
const TARGETS = [
|
|
6
|
+
"draft-2020-12",
|
|
7
|
+
"draft-07",
|
|
8
|
+
"openapi-3.0"
|
|
9
|
+
];
|
|
10
|
+
function isTarget(t) {
|
|
11
|
+
return TARGETS.includes(t);
|
|
12
|
+
}
|
|
13
|
+
function isRecord(v) {
|
|
14
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
15
|
+
}
|
|
16
|
+
function unreachable(d) {
|
|
17
|
+
throw new TypeError(`leanfran: unknown type descriptor ${JSON.stringify(d)}`);
|
|
18
|
+
}
|
|
19
|
+
function withBounds(s, bounds) {
|
|
20
|
+
if (Object.keys(bounds).length === 0) return s;
|
|
21
|
+
if ("$ref" in s || "anyOf" in s || "oneOf" in s || "allOf" in s) return { allOf: [s, { ...bounds }] };
|
|
22
|
+
return {
|
|
23
|
+
...s,
|
|
24
|
+
...bounds
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
function modelJsonSchema(key, name, target) {
|
|
28
|
+
const s = blockRegistry().models.get(key);
|
|
29
|
+
const std = isRecord(s) ? s["~standard"] : void 0;
|
|
30
|
+
const converter = isRecord(std) ? std["jsonSchema"] : void 0;
|
|
31
|
+
const input = isRecord(converter) ? converter["input"] : void 0;
|
|
32
|
+
if (typeof input !== "function") throw new TypeError(`leanfran: the model ${name} (${key}) is not registered as a Standard JSON Schema; the lean(...) block that declares it has not run`);
|
|
33
|
+
const out = Reflect.apply(input, converter, [{ target }]);
|
|
34
|
+
if (!isRecord(out)) throw new TypeError(`leanfran: the JSON Schema of the model ${name} is not an object`);
|
|
35
|
+
const { $schema: _, ...rest } = out;
|
|
36
|
+
return rest;
|
|
37
|
+
}
|
|
38
|
+
function openapiBounds(v) {
|
|
39
|
+
if (Array.isArray(v)) return v.map(openapiBounds);
|
|
40
|
+
if (!isRecord(v)) return v;
|
|
41
|
+
const out = {};
|
|
42
|
+
for (const [k, x] of Object.entries(v)) if (k === "exclusiveMinimum" && typeof x === "number") {
|
|
43
|
+
out["minimum"] = x;
|
|
44
|
+
out["exclusiveMinimum"] = true;
|
|
45
|
+
} else if (k === "exclusiveMaximum" && typeof x === "number") {
|
|
46
|
+
out["maximum"] = x;
|
|
47
|
+
out["exclusiveMaximum"] = true;
|
|
48
|
+
} else out[k] = openapiBounds(x);
|
|
49
|
+
return out;
|
|
50
|
+
}
|
|
51
|
+
function jsonSchemaOf(root, target) {
|
|
52
|
+
if (!isTarget(target)) throw new TypeError(`leanfran: unsupported JSON Schema target ${JSON.stringify(target)} (expected one of ${TARGETS.join(", ")})`);
|
|
53
|
+
const defsKey = target === "draft-2020-12" ? "$defs" : "definitions";
|
|
54
|
+
const defs = /* @__PURE__ */ new Map();
|
|
55
|
+
const needed = /* @__PURE__ */ new Set();
|
|
56
|
+
const stack = [];
|
|
57
|
+
const ref = (name) => ({ $ref: `#/${defsKey}/${name}` });
|
|
58
|
+
const named = (name, make) => {
|
|
59
|
+
if (stack.includes(name)) {
|
|
60
|
+
needed.add(name);
|
|
61
|
+
return ref(name);
|
|
62
|
+
}
|
|
63
|
+
if (defs.has(name)) return ref(name);
|
|
64
|
+
stack.push(name);
|
|
65
|
+
const s = make();
|
|
66
|
+
stack.pop();
|
|
67
|
+
if (!needed.has(name)) return s;
|
|
68
|
+
defs.set(name, s);
|
|
69
|
+
return ref(name);
|
|
70
|
+
};
|
|
71
|
+
const constant = (v) => target === "openapi-3.0" ? {
|
|
72
|
+
type: "string",
|
|
73
|
+
enum: [v]
|
|
74
|
+
} : { const: v };
|
|
75
|
+
const tuple = (items) => target === "draft-2020-12" ? {
|
|
76
|
+
type: "array",
|
|
77
|
+
prefixItems: items,
|
|
78
|
+
minItems: items.length,
|
|
79
|
+
maxItems: items.length
|
|
80
|
+
} : {
|
|
81
|
+
type: "array",
|
|
82
|
+
items,
|
|
83
|
+
minItems: items.length,
|
|
84
|
+
maxItems: items.length
|
|
85
|
+
};
|
|
86
|
+
const fieldsSchema = (variant) => {
|
|
87
|
+
const properties = {};
|
|
88
|
+
const required = [];
|
|
89
|
+
for (const f of variant.fields) {
|
|
90
|
+
if (f.flat) {
|
|
91
|
+
const parent = fieldsSchema(structVariant(f.desc));
|
|
92
|
+
Object.assign(properties, parent["properties"]);
|
|
93
|
+
const req = parent["required"];
|
|
94
|
+
if (Array.isArray(req)) {
|
|
95
|
+
for (const r of req) if (typeof r === "string") required.push(r);
|
|
96
|
+
}
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
properties[f.key] = withBounds(gen(f.desc), f.bounds);
|
|
100
|
+
if (resolve(f.desc).kind !== "option") required.push(f.key);
|
|
101
|
+
}
|
|
102
|
+
return {
|
|
103
|
+
type: "object",
|
|
104
|
+
properties,
|
|
105
|
+
required,
|
|
106
|
+
additionalProperties: false
|
|
107
|
+
};
|
|
108
|
+
};
|
|
109
|
+
const gen = (d) => {
|
|
110
|
+
switch (d.kind) {
|
|
111
|
+
case "nat": return {
|
|
112
|
+
type: "integer",
|
|
113
|
+
minimum: 0
|
|
114
|
+
};
|
|
115
|
+
case "int": return { type: "integer" };
|
|
116
|
+
case "uint": return d.bits === 64 ? {
|
|
117
|
+
type: "string",
|
|
118
|
+
pattern: "^(0|[1-9][0-9]*)$"
|
|
119
|
+
} : {
|
|
120
|
+
type: "integer",
|
|
121
|
+
minimum: 0,
|
|
122
|
+
maximum: 2 ** d.bits - 1
|
|
123
|
+
};
|
|
124
|
+
case "sint": return d.bits === 64 ? {
|
|
125
|
+
type: "integer",
|
|
126
|
+
minimum: -(2 ** 63),
|
|
127
|
+
exclusiveMaximum: 2 ** 63
|
|
128
|
+
} : {
|
|
129
|
+
type: "integer",
|
|
130
|
+
minimum: -(2 ** (d.bits - 1)),
|
|
131
|
+
maximum: 2 ** (d.bits - 1) - 1
|
|
132
|
+
};
|
|
133
|
+
case "usize": return {
|
|
134
|
+
type: "string",
|
|
135
|
+
pattern: "^(0|[1-9][0-9]*)$"
|
|
136
|
+
};
|
|
137
|
+
case "isize": return {
|
|
138
|
+
type: "integer",
|
|
139
|
+
minimum: -(2 ** 63),
|
|
140
|
+
exclusiveMaximum: 2 ** 63
|
|
141
|
+
};
|
|
142
|
+
case "fin": return {
|
|
143
|
+
type: "integer",
|
|
144
|
+
minimum: 0,
|
|
145
|
+
exclusiveMaximum: Number(d.bound)
|
|
146
|
+
};
|
|
147
|
+
case "bool": return { type: "boolean" };
|
|
148
|
+
case "char": return {
|
|
149
|
+
type: "string",
|
|
150
|
+
minLength: 1,
|
|
151
|
+
maxLength: 1
|
|
152
|
+
};
|
|
153
|
+
case "string": return { type: "string" };
|
|
154
|
+
case "float":
|
|
155
|
+
case "float32": return { type: "number" };
|
|
156
|
+
case "unit": return {
|
|
157
|
+
type: "object",
|
|
158
|
+
additionalProperties: false
|
|
159
|
+
};
|
|
160
|
+
case "list":
|
|
161
|
+
case "array": return {
|
|
162
|
+
type: "array",
|
|
163
|
+
items: gen(d.item)
|
|
164
|
+
};
|
|
165
|
+
case "option": {
|
|
166
|
+
const item = gen(d.item);
|
|
167
|
+
if (target !== "openapi-3.0") return { anyOf: [item, { type: "null" }] };
|
|
168
|
+
if ("type" in item && !("$ref" in item)) return {
|
|
169
|
+
...item,
|
|
170
|
+
nullable: true
|
|
171
|
+
};
|
|
172
|
+
return {
|
|
173
|
+
allOf: [item],
|
|
174
|
+
nullable: true
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
case "prod": return tuple([gen(d.fst), gen(d.snd)]);
|
|
178
|
+
case "except": return { oneOf: [{
|
|
179
|
+
type: "object",
|
|
180
|
+
properties: { ok: gen(d.value) },
|
|
181
|
+
required: ["ok"],
|
|
182
|
+
additionalProperties: false
|
|
183
|
+
}, {
|
|
184
|
+
type: "object",
|
|
185
|
+
properties: { error: gen(d.error) },
|
|
186
|
+
required: ["error"],
|
|
187
|
+
additionalProperties: false
|
|
188
|
+
}] };
|
|
189
|
+
case "struct": return named(d.name, () => fieldsSchema(d.variant));
|
|
190
|
+
case "enum": return named(d.name, () => ({
|
|
191
|
+
type: "string",
|
|
192
|
+
enum: [...d.ctors]
|
|
193
|
+
}));
|
|
194
|
+
case "inductive": return named(d.name, () => ({ oneOf: d.variants.map((v) => {
|
|
195
|
+
if (v.fields.length === 0) return constant(v.name);
|
|
196
|
+
const payload = !v.positional ? fieldsSchema(v) : v.fields.length === 1 && v.fields[0] !== void 0 ? withBounds(gen(v.fields[0].desc), v.fields[0].bounds) : tuple(v.fields.map((f) => withBounds(gen(f.desc), f.bounds)));
|
|
197
|
+
return {
|
|
198
|
+
type: "object",
|
|
199
|
+
properties: { [v.name]: payload },
|
|
200
|
+
required: [v.name],
|
|
201
|
+
additionalProperties: false
|
|
202
|
+
};
|
|
203
|
+
}) }));
|
|
204
|
+
case "subtype": return named(d.name, () => withBounds(gen(d.base), d.bounds));
|
|
205
|
+
case "model": return named(d.name, () => modelJsonSchema(d.key, d.name, target));
|
|
206
|
+
case "ref": return gen(d.get());
|
|
207
|
+
}
|
|
208
|
+
return unreachable(d);
|
|
209
|
+
};
|
|
210
|
+
const top = gen(root);
|
|
211
|
+
const withDefs = defs.size === 0 ? top : target === "draft-2020-12" ? {
|
|
212
|
+
...top,
|
|
213
|
+
[defsKey]: Object.fromEntries(defs)
|
|
214
|
+
} : {
|
|
215
|
+
allOf: [top],
|
|
216
|
+
[defsKey]: Object.fromEntries(defs)
|
|
217
|
+
};
|
|
218
|
+
const out = target === "openapi-3.0" ? openapiBounds(withDefs) : withDefs;
|
|
219
|
+
const schemaUri = target === "draft-2020-12" ? "https://json-schema.org/draft/2020-12/schema" : target === "draft-07" ? "http://json-schema.org/draft-07/schema#" : void 0;
|
|
220
|
+
if (!isRecord(out)) throw new TypeError("leanfran: the generated JSON Schema is not an object");
|
|
221
|
+
return schemaUri === void 0 ? { ...out } : {
|
|
222
|
+
$schema: schemaUri,
|
|
223
|
+
...out
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
function structVariant(d) {
|
|
227
|
+
const r = resolve(d);
|
|
228
|
+
if (r.kind !== "struct") throw new TypeError(`leanfran: a flattened field is not a structure (${r.kind})`);
|
|
229
|
+
return r.variant;
|
|
230
|
+
}
|
|
231
|
+
// src/schema/index.ts
|
|
232
|
+
function schema(desc) {
|
|
233
|
+
const converter = (options) => jsonSchemaOf(desc, options.target);
|
|
234
|
+
return {
|
|
235
|
+
"~standard": {
|
|
236
|
+
version: 1,
|
|
237
|
+
vendor: "leanfran",
|
|
238
|
+
validate: (value) => checkValue(desc, value),
|
|
239
|
+
jsonSchema: {
|
|
240
|
+
input: converter,
|
|
241
|
+
output: converter
|
|
242
|
+
}
|
|
243
|
+
},
|
|
244
|
+
desc
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
function merge(target, members) {
|
|
248
|
+
return Object.assign(target, members);
|
|
249
|
+
}
|
|
250
|
+
function fromJSON(s, json) {
|
|
251
|
+
const r = checkValue(s.desc, json);
|
|
252
|
+
if ("issues" in r) throw new LeanValidationError(r.issues);
|
|
253
|
+
return r.value;
|
|
254
|
+
}
|
|
255
|
+
function toJSON(s, value) {
|
|
256
|
+
return jsonValue(s.desc, value, false);
|
|
257
|
+
}
|
|
258
|
+
function write(v) {
|
|
259
|
+
if (v === null) return "null";
|
|
260
|
+
if (typeof v === "bigint") return v.toString();
|
|
261
|
+
if (typeof v === "number") {
|
|
262
|
+
if (!Number.isFinite(v)) throw new TypeError(`leanfran: ${v} is not a JSON number`);
|
|
263
|
+
return JSON.stringify(v);
|
|
264
|
+
}
|
|
265
|
+
if (typeof v === "string" || typeof v === "boolean") return JSON.stringify(v);
|
|
266
|
+
if (Array.isArray(v)) return `[${v.map((x) => write(x)).join(",")}]`;
|
|
267
|
+
if (typeof v === "object") {
|
|
268
|
+
const parts = [];
|
|
269
|
+
for (const [k, x] of Object.entries(v)) if (x !== void 0) parts.push(`${JSON.stringify(k)}:${write(x)}`);
|
|
270
|
+
return `{${parts.join(",")}}`;
|
|
271
|
+
}
|
|
272
|
+
throw new TypeError(`leanfran: a ${typeof v} is not a JSON value`);
|
|
273
|
+
}
|
|
274
|
+
function stringify(s, value) {
|
|
275
|
+
return write(jsonValue(s.desc, value, true));
|
|
276
|
+
}
|
|
277
|
+
const INTEGER = /^-?(?:0|[1-9][0-9]*)$/u;
|
|
278
|
+
function reviver(_key, value, ...rest) {
|
|
279
|
+
if (typeof value !== "number" || Number.isSafeInteger(value)) return value;
|
|
280
|
+
const ctx = rest[0];
|
|
281
|
+
const source = typeof ctx === "object" && ctx !== null ? Reflect.get(ctx, "source") : void 0;
|
|
282
|
+
return typeof source === "string" && INTEGER.test(source) ? BigInt(source) : value;
|
|
283
|
+
}
|
|
284
|
+
function parse(s, text) {
|
|
285
|
+
return fromJSON(s, JSON.parse(text, reviver));
|
|
286
|
+
}
|
|
287
|
+
function scalar(desc) {
|
|
288
|
+
return schema(desc);
|
|
289
|
+
}
|
|
290
|
+
const Nat = scalar(natDesc);
|
|
291
|
+
const Int = scalar(intDesc);
|
|
292
|
+
const UInt8 = scalar(uintDesc(8));
|
|
293
|
+
const UInt16 = scalar(uintDesc(16));
|
|
294
|
+
const UInt32 = scalar(uintDesc(32));
|
|
295
|
+
const UInt64 = scalar(uintDesc(64));
|
|
296
|
+
const USize = scalar(usizeDesc);
|
|
297
|
+
const Int8 = scalar(sintDesc(8));
|
|
298
|
+
const Int16 = scalar(sintDesc(16));
|
|
299
|
+
const Int32 = scalar(sintDesc(32));
|
|
300
|
+
const Int64 = scalar(sintDesc(64));
|
|
301
|
+
const ISize = scalar(isizeDesc);
|
|
302
|
+
const Bool = scalar(boolDesc);
|
|
303
|
+
const Char = scalar(charDesc);
|
|
304
|
+
const StringSchema = scalar(stringDesc);
|
|
305
|
+
const Float = scalar(floatDesc);
|
|
306
|
+
const Float32 = scalar(float32Desc);
|
|
307
|
+
const Unit = scalar(unitDesc);
|
|
308
|
+
export { stringify as C, schema as S, jsonSchemaOf as T, USize as _, ISize as a, merge as b, Int32 as c, Nat as d, StringSchema as f, UInt8 as g, UInt64 as h, Float32 as i, Int64 as l, UInt32 as m, Char as n, Int as o, UInt16 as p, Float as r, Int16 as s, Bool as t, Int8 as u, Unit as v, toJSON as w, parse as x, fromJSON as y };
|
package/dist/schema.d.ts
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { A as FC, B as Issue, C as UnitInput, D as schema, E as parse, G as TypeDesc, H as LeanValidationError, I as DescNode, K as VariantDesc, M as JsonSchemaTarget, N as jsonSchemaOf, O as stringify, P as Absent, R as FieldDesc, S as Unit, T as merge, U as SchemaBounds, W as Slot, _ as UInt16, a as Float32, b as UInt8, c as InferOutput, d as Int32, f as Int64, ft as resolve, g as StringSchema, h as Nat, i as Float, j as arbitrary, k as toJSON, l as Int, m as LeanSchema, n as Char, o as ISize, p as Int8, r as ExceptInput, s as InferInput, t as Bool, u as Int16, v as UInt32, w as fromJSON, x as USize, y as UInt64, z as InvariantDesc } from "./index-DPF21ftq.js";
|
|
2
|
+
export { type Absent, Bool, Char, type DescNode, ExceptInput, type FC, type FieldDesc, Float, Float32, ISize, InferInput, InferOutput, Int, Int16, Int32, Int64, Int8, type InvariantDesc, type Issue, JsonSchemaTarget, LeanSchema, LeanValidationError, Nat, type SchemaBounds, type Slot, StringSchema as String, type TypeDesc, UInt16, UInt32, UInt64, UInt8, USize, Unit, UnitInput, type VariantDesc, arbitrary, fromJSON, jsonSchemaOf, merge, parse, resolve, schema, stringify, toJSON };
|
package/dist/schema.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { S as resolve, n as LeanValidationError } from "./marshal-DhKsxhRw.js";
|
|
2
|
+
import { C as stringify, S as schema, T as jsonSchemaOf, _ as USize, a as ISize, b as merge, c as Int32, d as Nat, f as StringSchema, g as UInt8, h as UInt64, i as Float32, l as Int64, m as UInt32, n as Char, o as Int, p as UInt16, r as Float, s as Int16, t as Bool, u as Int8, v as Unit, w as toJSON, x as parse, y as fromJSON } from "./schema-CvTyc8wa.js";
|
|
3
|
+
import { t as arbitrary } from "./arbitrary-B7Frjn9q.js";
|
|
4
|
+
export { Bool, Char, Float, Float32, ISize, Int, Int16, Int32, Int64, Int8, LeanValidationError, Nat, StringSchema as String, UInt16, UInt32, UInt64, UInt8, USize, Unit, arbitrary, fromJSON, jsonSchemaOf, merge, parse, resolve, schema, stringify, toJSON };
|
package/dist/verify.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export type Spec = (...args: never[]) => unknown;
|
|
2
|
+
export interface ModelOptions {
|
|
3
|
+
readonly refines?: Spec;
|
|
4
|
+
readonly requires?: Spec;
|
|
5
|
+
readonly ensures?: Readonly<Record<string, Spec>>;
|
|
6
|
+
}
|
|
7
|
+
export interface ModelEntry {
|
|
8
|
+
readonly fn: Spec;
|
|
9
|
+
readonly name: string;
|
|
10
|
+
readonly options: ModelOptions;
|
|
11
|
+
readonly file: string | undefined;
|
|
12
|
+
}
|
|
13
|
+
export declare function modelRegistry(): Map<Spec, ModelEntry>;
|
|
14
|
+
export declare function model<F extends Spec>(fn: F, options: ModelOptions): F;
|
|
15
|
+
export declare class PropertyFailure extends Error {
|
|
16
|
+
constructor(message: string, cause?: unknown);
|
|
17
|
+
}
|
|
18
|
+
export interface CheckOptions {
|
|
19
|
+
readonly numRuns?: number;
|
|
20
|
+
readonly seed?: number;
|
|
21
|
+
readonly range?: {
|
|
22
|
+
readonly min: bigint;
|
|
23
|
+
readonly max: bigint;
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
export declare function checkModel(fn: Spec, options?: CheckOptions): Promise<void>;
|
|
27
|
+
export declare function checkModule(module: Readonly<Record<string, unknown>>, options?: CheckOptions): Promise<void>;
|
package/dist/verify.js
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import { r as leanNameOf } from "./block-CU7YIXdj.js";
|
|
2
|
+
import { w as standardValidate } from "./marshal-DhKsxhRw.js";
|
|
3
|
+
import { s as modelSchema } from "./embed-BlX4FUDH.js";
|
|
4
|
+
import { t as arbitrary } from "./arbitrary-B7Frjn9q.js";
|
|
5
|
+
import { c as astHash, i as readSource, o as BIG, r as modelStruct, s as Fn } from "./check-DROT5twE.js";
|
|
6
|
+
import { dirname } from "node:path";
|
|
7
|
+
import { pathToFileURL } from "node:url";
|
|
8
|
+
// src/verify/index.ts
|
|
9
|
+
const KEY = Symbol.for("leanfran.models");
|
|
10
|
+
function isRegistry(x) {
|
|
11
|
+
return typeof x === "object" && x !== null && Reflect.get(x, "brand") === "leanfran.models";
|
|
12
|
+
}
|
|
13
|
+
function modelRegistry() {
|
|
14
|
+
const existing = Reflect.get(globalThis, KEY);
|
|
15
|
+
if (isRegistry(existing)) return existing.models;
|
|
16
|
+
const created = {
|
|
17
|
+
brand: "leanfran.models",
|
|
18
|
+
models: /* @__PURE__ */ new Map()
|
|
19
|
+
};
|
|
20
|
+
Reflect.set(globalThis, KEY, created);
|
|
21
|
+
return created.models;
|
|
22
|
+
}
|
|
23
|
+
function callerFile() {
|
|
24
|
+
const holder = {};
|
|
25
|
+
Error.captureStackTrace(holder, model);
|
|
26
|
+
for (const line of (holder.stack ?? "").split("\n").slice(1)) {
|
|
27
|
+
const f = /\(?((?:file:\/\/)?\/[^():]+\.[cm]?[tj]sx?)(?:\?[^:]*)?:\d+:\d+\)?\s*$/u.exec(line)?.[1];
|
|
28
|
+
if (f !== void 0) return f.startsWith("file://") ? decodeURIComponent(new URL(f).pathname) : f;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function checkSpec(fnName, label, s) {
|
|
32
|
+
if (typeof s !== "function" || leanNameOf(s) === void 0) throw new TypeError(`leanfran: the ${label} specification of ${fnName} is not a function of a lean(...) block`);
|
|
33
|
+
}
|
|
34
|
+
function model(fn, options) {
|
|
35
|
+
modelRegistry().set(fn, {
|
|
36
|
+
fn,
|
|
37
|
+
name: fn.name,
|
|
38
|
+
options,
|
|
39
|
+
file: callerFile()
|
|
40
|
+
});
|
|
41
|
+
return fn;
|
|
42
|
+
}
|
|
43
|
+
var PropertyFailure = class extends Error {
|
|
44
|
+
constructor(message, cause) {
|
|
45
|
+
super(message, cause === void 0 ? void 0 : { cause });
|
|
46
|
+
this.name = "PropertyFailure";
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
const SAFE = BigInt(Number.MAX_SAFE_INTEGER);
|
|
50
|
+
function show(v) {
|
|
51
|
+
if (typeof v === "bigint") return `${v}n`;
|
|
52
|
+
if (typeof v === "string") return JSON.stringify(v);
|
|
53
|
+
if (Array.isArray(v)) return `[${v.map(show).join(", ")}]`;
|
|
54
|
+
if (typeof v === "object" && v !== null) return `{ ${Object.entries(v).map(([k, x]) => `${k}: ${show(x)}`).join(", ")} }`;
|
|
55
|
+
return String(v);
|
|
56
|
+
}
|
|
57
|
+
function call(name, args) {
|
|
58
|
+
return `${name}(${args.map(show).join(", ")})`;
|
|
59
|
+
}
|
|
60
|
+
function normal(v) {
|
|
61
|
+
if (typeof v === "number" && Number.isInteger(v)) return BigInt(v);
|
|
62
|
+
if (v === void 0) return null;
|
|
63
|
+
if (Array.isArray(v)) return v.map(normal);
|
|
64
|
+
if (typeof v === "object" && v !== null) return Object.fromEntries(Object.entries(v).filter(([, x]) => x !== void 0).toSorted(([a], [b]) => a.localeCompare(b)).map(([k, x]) => [k, normal(x)]));
|
|
65
|
+
return v;
|
|
66
|
+
}
|
|
67
|
+
function unsafeNumber(v) {
|
|
68
|
+
if (typeof v === "number") return !Number.isSafeInteger(v);
|
|
69
|
+
if (Array.isArray(v)) return v.some(unsafeNumber);
|
|
70
|
+
if (typeof v === "object" && v !== null) return Object.values(v).some(unsafeNumber);
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
73
|
+
function isTypeDesc(d) {
|
|
74
|
+
return typeof d === "object" && d !== null && typeof Reflect.get(d, "kind") === "string";
|
|
75
|
+
}
|
|
76
|
+
async function loadFastCheck() {
|
|
77
|
+
try {
|
|
78
|
+
return await import("fast-check");
|
|
79
|
+
} catch (e) {
|
|
80
|
+
throw new TypeError("leanfran: checkModel needs the optional peer dependency fast-check", { cause: e });
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
async function paramTypes(entry) {
|
|
84
|
+
const file = entry.file;
|
|
85
|
+
if (file === void 0) throw new TypeError(`leanfran: the source file of the model call of ${entry.name} is unknown`);
|
|
86
|
+
const src = readSource(dirname(file), file);
|
|
87
|
+
const node = src.fns.get(entry.name);
|
|
88
|
+
if (node === void 0) throw new TypeError(`leanfran: ${entry.name} is not a function declaration of ${file}`);
|
|
89
|
+
const modules = /* @__PURE__ */ new Map();
|
|
90
|
+
for (const i of src.imports.values()) if (i.from.startsWith("/") && !modules.has(i.from)) modules.set(i.from, await import(pathToFileURL(i.from.endsWith(".ts") ? i.from : `${i.from}.ts`).href));
|
|
91
|
+
const descs = /* @__PURE__ */ new Map();
|
|
92
|
+
const models = /* @__PURE__ */ new Map();
|
|
93
|
+
const own = astHash(node.params).includes("TSTypeQuery") ? await import(pathToFileURL(file).href) : void 0;
|
|
94
|
+
return {
|
|
95
|
+
fn: new Fn(entry.name, node, src, {
|
|
96
|
+
reference(name, qualifier, at) {
|
|
97
|
+
const i = src.imports.get(qualifier ?? name);
|
|
98
|
+
if (i === void 0) return void 0;
|
|
99
|
+
const exportName = qualifier === void 0 ? i.exportName : i.exportName === null ? name : null;
|
|
100
|
+
if (exportName === null) return void 0;
|
|
101
|
+
if (i.from === "leanfran/schema" && (exportName === "Nat" || exportName === "Int")) return BIG;
|
|
102
|
+
const m = modules.get(i.from);
|
|
103
|
+
const v = typeof m === "object" && m !== null ? Reflect.get(m, exportName) : void 0;
|
|
104
|
+
const d = typeof v === "object" && v !== null || typeof v === "function" ? Reflect.get(v, "desc") : void 0;
|
|
105
|
+
if (!isTypeDesc(d)) throw new TypeError(`leanfran: ${src.where(at)}: ${exportName} is not a leanfran schema`);
|
|
106
|
+
const key = `${i.from}#${exportName}`;
|
|
107
|
+
descs.set(key, d);
|
|
108
|
+
return {
|
|
109
|
+
k: "struct",
|
|
110
|
+
lean: key,
|
|
111
|
+
ts: exportName,
|
|
112
|
+
fields: []
|
|
113
|
+
};
|
|
114
|
+
},
|
|
115
|
+
model(name, at) {
|
|
116
|
+
const i = src.imports.get(name);
|
|
117
|
+
const exportName = i === void 0 ? name : i.exportName;
|
|
118
|
+
if (exportName === null) return void 0;
|
|
119
|
+
const m = i === void 0 ? own : modules.get(i.from);
|
|
120
|
+
const v = typeof m === "object" && m !== null ? Reflect.get(m, exportName) : void 0;
|
|
121
|
+
if (typeof v !== "object" || v === null || !("~standard" in v)) return void 0;
|
|
122
|
+
const key = `${i?.from ?? file}#${exportName}`;
|
|
123
|
+
models.set(key, v);
|
|
124
|
+
return modelStruct(modelSchema(exportName, v), key, exportName, src.where(at));
|
|
125
|
+
}
|
|
126
|
+
}),
|
|
127
|
+
tables: {
|
|
128
|
+
descs,
|
|
129
|
+
models
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
function arbOf(fc, t, nat, tables, options) {
|
|
134
|
+
const lo = options.range?.min;
|
|
135
|
+
const hi = options.range?.max;
|
|
136
|
+
switch (t.k) {
|
|
137
|
+
case "num": {
|
|
138
|
+
const min = lo === void 0 ? -SAFE : lo < -SAFE ? -SAFE : lo;
|
|
139
|
+
const max = hi === void 0 ? SAFE : hi > SAFE ? SAFE : hi;
|
|
140
|
+
return fc.bigInt({
|
|
141
|
+
min: nat && min < 0n ? 0n : min,
|
|
142
|
+
max
|
|
143
|
+
}).map(Number);
|
|
144
|
+
}
|
|
145
|
+
case "big": return fc.bigInt({
|
|
146
|
+
min: nat && (lo === void 0 || lo < 0n) ? 0n : lo ?? -(2n ** 64n),
|
|
147
|
+
max: hi ?? 2n ** 64n
|
|
148
|
+
});
|
|
149
|
+
case "bool": return fc.boolean();
|
|
150
|
+
case "str": return fc.string({
|
|
151
|
+
unit: "grapheme",
|
|
152
|
+
maxLength: 12
|
|
153
|
+
});
|
|
154
|
+
case "list": return fc.array(arbOf(fc, t.item, false, tables, options), { maxLength: 10 });
|
|
155
|
+
case "tuple": return fc.tuple(...t.items.map((x) => arbOf(fc, x, false, tables, options)));
|
|
156
|
+
case "opt": return fc.option(arbOf(fc, t.item, false, tables, options), { nil: t.absent === "null" ? null : void 0 });
|
|
157
|
+
default: {
|
|
158
|
+
const schema = tables.models.get(t.lean);
|
|
159
|
+
if (schema !== void 0 && t.k === "struct") {
|
|
160
|
+
const parts = t.fields.map((f) => arbOf(fc, f.type, f.nat, tables, options).map((v) => [f.key, v]));
|
|
161
|
+
return fc.tuple(...parts).map((kv) => Object.fromEntries(kv.filter(([, v]) => v !== void 0))).filter((v) => standardValidate(schema, v).issues === null);
|
|
162
|
+
}
|
|
163
|
+
const d = tables.descs.get(t.lean);
|
|
164
|
+
if (d === void 0) throw new TypeError(`leanfran: no descriptor for ${t.ts}`);
|
|
165
|
+
return arbitrary(d, fc);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
async function checkModel(fn, options = {}) {
|
|
170
|
+
const entry = modelRegistry().get(fn);
|
|
171
|
+
if (entry === void 0) throw new TypeError(`leanfran: ${fn.name} has no model(...) call`);
|
|
172
|
+
const fc = await loadFastCheck();
|
|
173
|
+
const { fn: sig, tables } = await paramTypes(entry);
|
|
174
|
+
const arbs = sig.params.map((p) => arbOf(fc, p.type, p.nat, tables, options));
|
|
175
|
+
const { refines, requires, ensures } = entry.options;
|
|
176
|
+
const name = entry.name;
|
|
177
|
+
if (refines !== void 0) checkSpec(name, "refines", refines);
|
|
178
|
+
if (requires !== void 0) checkSpec(name, "requires", requires);
|
|
179
|
+
for (const [label, s] of Object.entries(ensures ?? {})) checkSpec(name, label, s);
|
|
180
|
+
const property = fc.property(fc.tuple(...arbs), (args) => {
|
|
181
|
+
if (requires !== void 0) fc.pre(Reflect.apply(requires, void 0, args) === true);
|
|
182
|
+
let result;
|
|
183
|
+
try {
|
|
184
|
+
result = Reflect.apply(fn, void 0, args);
|
|
185
|
+
} catch (e) {
|
|
186
|
+
throw new PropertyFailure(`${call(name, args)} raised ${e instanceof Error ? `${e.name}: ${e.message}` : String(e)}`);
|
|
187
|
+
}
|
|
188
|
+
fc.pre(!unsafeNumber(result));
|
|
189
|
+
if (refines !== void 0) {
|
|
190
|
+
const expected = Reflect.apply(refines, void 0, args);
|
|
191
|
+
if (show(normal(result)) !== show(normal(expected))) throw new PropertyFailure(`${call(name, args)} = ${show(result)}, the spec gives ${show(expected)}`);
|
|
192
|
+
}
|
|
193
|
+
for (const [label, e] of Object.entries(ensures ?? {})) if (Reflect.apply(e, void 0, [...args, result]) !== true) throw new PropertyFailure(`${call(name, args)} = ${show(result)} breaks ${label}`);
|
|
194
|
+
return true;
|
|
195
|
+
});
|
|
196
|
+
try {
|
|
197
|
+
fc.assert(property, {
|
|
198
|
+
numRuns: options.numRuns ?? 200,
|
|
199
|
+
...options.seed === void 0 ? {} : { seed: options.seed }
|
|
200
|
+
});
|
|
201
|
+
} catch (e) {
|
|
202
|
+
if (e instanceof Error) {
|
|
203
|
+
const c = e.cause;
|
|
204
|
+
throw new PropertyFailure(c instanceof PropertyFailure ? c.message : e.message, e);
|
|
205
|
+
}
|
|
206
|
+
throw e;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
async function checkModule(module, options = {}) {
|
|
210
|
+
const values = new Set(Object.values(module));
|
|
211
|
+
const entries = [...modelRegistry().values()].filter((e) => values.has(e.fn));
|
|
212
|
+
if (entries.length === 0) throw new TypeError("leanfran: the module has no model(...) functions");
|
|
213
|
+
for (const entry of entries) await checkModel(entry.fn, options);
|
|
214
|
+
}
|
|
215
|
+
export { PropertyFailure, checkModel, checkModule, model, modelRegistry };
|
package/package.json
CHANGED
|
@@ -1,6 +1,71 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "leanfran",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.6.0-rc.0",
|
|
4
|
+
"description": "Write and prove functions in Lean 4, run them as TypeScript: Lean blocks in TypeScript modules, Standard Schema for Lean types, TypeScript functions verified in Lean",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"homepage": "https://github.com/conao3/lean-leanfran/tree/master/TypeScript#readme",
|
|
7
|
+
"bugs": "https://github.com/conao3/lean-leanfran/issues",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/conao3/lean-leanfran.git",
|
|
11
|
+
"directory": "TypeScript"
|
|
12
|
+
},
|
|
13
|
+
"keywords": [
|
|
14
|
+
"lean4",
|
|
15
|
+
"typescript",
|
|
16
|
+
"compiler"
|
|
17
|
+
],
|
|
18
|
+
"type": "module",
|
|
19
|
+
"packageManager": "pnpm@12.9.0",
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=22.18.0"
|
|
22
|
+
},
|
|
23
|
+
"bin": {
|
|
24
|
+
"leanfran": "./dist/cli.js"
|
|
25
|
+
},
|
|
26
|
+
"exports": {
|
|
27
|
+
".": {
|
|
28
|
+
"types": "./dist/index.d.ts",
|
|
29
|
+
"import": "./dist/index.js"
|
|
30
|
+
},
|
|
31
|
+
"./runtime": {
|
|
32
|
+
"types": "./dist/runtime.d.ts",
|
|
33
|
+
"import": "./dist/runtime.js"
|
|
34
|
+
},
|
|
35
|
+
"./runtime/node": {
|
|
36
|
+
"types": "./dist/runtime/node.d.ts",
|
|
37
|
+
"import": "./dist/runtime/node.js"
|
|
38
|
+
},
|
|
39
|
+
"./schema": {
|
|
40
|
+
"types": "./dist/schema.d.ts",
|
|
41
|
+
"import": "./dist/schema.js"
|
|
42
|
+
},
|
|
43
|
+
"./verify": {
|
|
44
|
+
"types": "./dist/verify.d.ts",
|
|
45
|
+
"import": "./dist/verify.js"
|
|
46
|
+
}
|
|
47
|
+
},
|
|
48
|
+
"files": [
|
|
49
|
+
"dist",
|
|
50
|
+
"src/lean"
|
|
51
|
+
],
|
|
52
|
+
"devDependencies": {
|
|
53
|
+
"@hono/standard-validator": "0.4.1",
|
|
54
|
+
"@types/node": "^26.6.6",
|
|
55
|
+
"hono": "4.13.14",
|
|
56
|
+
"vite-plus": "1.5.0",
|
|
57
|
+
"zod": "4.6.7"
|
|
58
|
+
},
|
|
59
|
+
"peerDependencies": {
|
|
60
|
+
"fast-check": "^4.10.2"
|
|
61
|
+
},
|
|
62
|
+
"peerDependenciesMeta": {
|
|
63
|
+
"fast-check": {
|
|
64
|
+
"optional": true
|
|
65
|
+
}
|
|
66
|
+
},
|
|
67
|
+
"dependencies": {
|
|
68
|
+
"@standard-schema/spec": "1.1.0",
|
|
69
|
+
"oxc-parser": "0.158.0"
|
|
70
|
+
}
|
|
71
|
+
}
|