eutaxy 0.9.0 → 0.9.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/README.md +7 -6
- package/dist/aws.mjs +2 -2
- package/dist/bin.mjs +2 -2
- package/dist/cli-CVdHb_gU.mjs +2 -0
- package/dist/cli.mjs +2 -2
- package/dist/cloudflare.mjs +2 -2
- package/dist/{delivery-invariants-hmhwh_qD.mjs → delivery-invariants-Cg3eVKSw.mjs} +2 -2
- package/dist/{delivery-invariants-hmhwh_qD.mjs.map → delivery-invariants-Cg3eVKSw.mjs.map} +1 -1
- package/dist/explore-Rwe1PPqX.d.mts.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/{src-BO7I3f-1.mjs → src-BRjmbzMV.mjs} +116 -30
- package/dist/src-BRjmbzMV.mjs.map +1 -0
- package/dist/{src-BzZU6eGF.mjs → src-BnTcWa-4.mjs} +2354 -1532
- package/dist/src-BnTcWa-4.mjs.map +1 -0
- package/dist/{src-BZtuuu_j.mjs → src-Db2r3ZDr.mjs} +2 -2
- package/dist/{src-BZtuuu_j.mjs.map → src-Db2r3ZDr.mjs.map} +1 -1
- package/package.json +1 -1
- package/dist/cli-DpeAhtU5.mjs +0 -2
- package/dist/src-BO7I3f-1.mjs.map +0 -1
- package/dist/src-BzZU6eGF.mjs.map +0 -1
|
@@ -1,18 +1,17 @@
|
|
|
1
|
-
import { E as canonicalJson, T as getPath, _ as defaultBounds, a as explore, c as CrashSignal, d as withoutNetwork, f as patchGlobals, g as toJson, i as proxiedSide, l as InjectedEffectError, m as settleOn, n as DifferentialStuck, r as compareSides, t as observeCore, u as installScriptedFetch, v as validateScenario } from "./src-
|
|
2
|
-
import { n as atLeastOncePerMessage$1 } from "./delivery-invariants-
|
|
3
|
-
import { _ as endpointNumber, a as renderText, b as describeVerdict, c as aggregate, f as shrinkRefutation, g as endpointBigInt, h as conforms, i as renderSpecs, l as checkSpecModule, m as evaluate, n as renderSpecReport, r as renderSpecReportJson, s as emitRegressionTest, t as renderJson, v as render, y as describeType } from "./src-
|
|
1
|
+
import { E as canonicalJson, T as getPath, _ as defaultBounds, a as explore, c as CrashSignal, d as withoutNetwork, f as patchGlobals, g as toJson, i as proxiedSide, l as InjectedEffectError, m as settleOn, n as DifferentialStuck, r as compareSides, t as observeCore, u as installScriptedFetch, v as validateScenario } from "./src-BRjmbzMV.mjs";
|
|
2
|
+
import { n as atLeastOncePerMessage$1 } from "./delivery-invariants-Cg3eVKSw.mjs";
|
|
3
|
+
import { _ as endpointNumber, a as renderText, b as describeVerdict, c as aggregate, f as shrinkRefutation, g as endpointBigInt, h as conforms, i as renderSpecs, l as checkSpecModule, m as evaluate, n as renderSpecReport, r as renderSpecReportJson, s as emitRegressionTest, t as renderJson, v as render, y as describeType } from "./src-Db2r3ZDr.mjs";
|
|
4
4
|
import { n as isSpec } from "./combinators-CVjxodAJ.mjs";
|
|
5
5
|
import { createRequire, registerHooks } from "node:module";
|
|
6
|
-
import { spawn } from "node:child_process";
|
|
6
|
+
import { fork, spawn } from "node:child_process";
|
|
7
7
|
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
|
8
8
|
import { basename, dirname, join, relative, resolve } from "node:path";
|
|
9
|
-
import { InternalSymbolName, ModifierFlags, NodeFlags, SyntaxKind } from "typescript/ast";
|
|
9
|
+
import { InternalSymbolName, ModifierFlags, NodeFlags, SyntaxKind, forEachLeadingCommentRange, forEachTrailingCommentRange } from "typescript/ast";
|
|
10
10
|
import { createFileSystemLayer } from "typescript/fs";
|
|
11
|
-
import { API, SymbolFlags, TypeFlags, TypeFormatFlags } from "typescript/sync";
|
|
11
|
+
import { API, DiagnosticCategory, SymbolFlags, TypeFlags, TypeFormatFlags } from "typescript/sync";
|
|
12
12
|
import * as is from "typescript/ast/is";
|
|
13
13
|
import { homedir, tmpdir } from "node:os";
|
|
14
|
-
import { pathToFileURL } from "node:url";
|
|
15
|
-
import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads";
|
|
14
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
16
15
|
// packages/cli/src/args.ts
|
|
17
16
|
function parseArgs(argv, booleans = []) {
|
|
18
17
|
const positionals = [];
|
|
@@ -100,11 +99,43 @@ function withProgram(files, fn) {
|
|
|
100
99
|
message: first.text
|
|
101
100
|
} : void 0;
|
|
102
101
|
};
|
|
102
|
+
const errors = /* @__PURE__ */ new Map();
|
|
103
|
+
const typeErrors = (path) => {
|
|
104
|
+
let found = errors.get(path);
|
|
105
|
+
if (!found) {
|
|
106
|
+
found = program.getSemanticDiagnostics(path).filter((d) => d.category === DiagnosticCategory.Error).map((d) => ({
|
|
107
|
+
pos: d.pos,
|
|
108
|
+
end: d.end,
|
|
109
|
+
message: d.text,
|
|
110
|
+
line: (d.startPosition?.line ?? 0) + 1
|
|
111
|
+
}));
|
|
112
|
+
errors.set(path, found);
|
|
113
|
+
}
|
|
114
|
+
return found;
|
|
115
|
+
};
|
|
116
|
+
const standard = /* @__PURE__ */ new Map();
|
|
117
|
+
const typeOnly = /* @__PURE__ */ new Set([SyntaxKind.InterfaceDeclaration, SyntaxKind.TypeAliasDeclaration]);
|
|
118
|
+
const standardGlobal = (id) => {
|
|
119
|
+
const symbol = checker.getSymbolAtLocation(id);
|
|
120
|
+
if (!symbol) return false;
|
|
121
|
+
let known = standard.get(symbol.id);
|
|
122
|
+
if (known === void 0) {
|
|
123
|
+
const values = symbol.declarations.filter((d) => !typeOnly.has(d.kind));
|
|
124
|
+
known = values.length > 0 && values.every((d) => {
|
|
125
|
+
const sf = d.resolve()?.getSourceFile();
|
|
126
|
+
return sf !== void 0 && program.isSourceFileDefaultLibrary(sf);
|
|
127
|
+
});
|
|
128
|
+
standard.set(symbol.id, known);
|
|
129
|
+
}
|
|
130
|
+
return known;
|
|
131
|
+
};
|
|
103
132
|
return fn({
|
|
104
133
|
program,
|
|
105
134
|
checker,
|
|
106
135
|
file,
|
|
107
|
-
parseError
|
|
136
|
+
parseError,
|
|
137
|
+
typeErrors,
|
|
138
|
+
standardGlobal
|
|
108
139
|
});
|
|
109
140
|
} finally {
|
|
110
141
|
snapshot.dispose();
|
|
@@ -149,1348 +180,903 @@ function openParen(sf, fn) {
|
|
|
149
180
|
function kindName(kind) {
|
|
150
181
|
return SyntaxKind[kind] ?? String(kind);
|
|
151
182
|
}
|
|
152
|
-
// packages/prover/src/reader/
|
|
153
|
-
/** Levels of records and lists inside one another a type may hold before it is cut (a generic instantiating itself anew at each level never repeats). */
|
|
154
|
-
const maxDepth = 16;
|
|
183
|
+
// packages/prover/src/reader/expressions.ts
|
|
155
184
|
/**
|
|
156
|
-
*
|
|
157
|
-
*
|
|
158
|
-
*
|
|
159
|
-
*
|
|
185
|
+
* Function bodies and spec arrows read from the compiler's syntax tree
|
|
186
|
+
* into the subset's `Expr`: `const` bindings, `if` with early returns,
|
|
187
|
+
* `return`, and expressions from arithmetic, comparisons, `&& || !`, the
|
|
188
|
+
* conditional operator, record and array literals, field reads, list
|
|
189
|
+
* methods and calls to the module's own functions. What a name stands
|
|
190
|
+
* for comes from the scope (parameters and consts) and from `Names`: the
|
|
191
|
+
* module's own functions when the text is the module, the spec file's
|
|
192
|
+
* imports when it is an arrow. Anything else is `OutsideSubset` with the
|
|
193
|
+
* construct named and its line.
|
|
160
194
|
*/
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
195
|
+
const binaryOps = {
|
|
196
|
+
[SyntaxKind.PlusToken]: "+",
|
|
197
|
+
[SyntaxKind.MinusToken]: "-",
|
|
198
|
+
[SyntaxKind.AsteriskToken]: "*",
|
|
199
|
+
[SyntaxKind.SlashToken]: "/",
|
|
200
|
+
[SyntaxKind.LessThanToken]: "<",
|
|
201
|
+
[SyntaxKind.LessThanEqualsToken]: "<=",
|
|
202
|
+
[SyntaxKind.GreaterThanToken]: ">",
|
|
203
|
+
[SyntaxKind.GreaterThanEqualsToken]: ">=",
|
|
204
|
+
[SyntaxKind.EqualsEqualsEqualsToken]: "===",
|
|
205
|
+
[SyntaxKind.ExclamationEqualsEqualsToken]: "!==",
|
|
206
|
+
[SyntaxKind.AmpersandAmpersandToken]: "&&",
|
|
207
|
+
[SyntaxKind.BarBarToken]: "||"
|
|
208
|
+
};
|
|
209
|
+
const methods = /* @__PURE__ */ new Set([
|
|
210
|
+
"slice",
|
|
211
|
+
"map",
|
|
212
|
+
"flatMap",
|
|
213
|
+
"every",
|
|
214
|
+
"some",
|
|
215
|
+
"reduce"
|
|
216
|
+
]);
|
|
217
|
+
/** The reader of one text: a function body, or an arrow of the spec file. */
|
|
218
|
+
var ExprReader = class {
|
|
219
|
+
sf;
|
|
220
|
+
names;
|
|
221
|
+
types;
|
|
222
|
+
ctx;
|
|
223
|
+
/** The line a refusal reports for a node: the file's, or none for text whose position the caller knows. */
|
|
224
|
+
lineOf;
|
|
225
|
+
inline;
|
|
226
|
+
constant;
|
|
227
|
+
/** Record literals typed by the call they are passed to, in place of the compiler's contextual type. */
|
|
228
|
+
typedAs = /* @__PURE__ */ new Map();
|
|
229
|
+
constructor(sf, names, types, ctx, lineOf = (node) => lineAt(sf, node), inline, constant) {
|
|
230
|
+
this.sf = sf;
|
|
231
|
+
this.names = names;
|
|
232
|
+
this.types = types;
|
|
233
|
+
this.ctx = ctx;
|
|
234
|
+
this.lineOf = lineOf;
|
|
235
|
+
this.inline = inline;
|
|
236
|
+
this.constant = constant;
|
|
177
237
|
}
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
return checker.typeToString(type, void 0, TypeFormatFlags.NoTruncation);
|
|
182
|
-
}
|
|
183
|
-
/**
|
|
184
|
-
* The name a record or union goes by: its alias or interface name when
|
|
185
|
-
* declared without type arguments, otherwise the type as the compiler
|
|
186
|
-
* prints it (`Result<true, Locked>`, `{ readonly ok: boolean; }`).
|
|
187
|
-
*/
|
|
188
|
-
function nameOfType(checker, type) {
|
|
189
|
-
const alias = type.getAliasSymbol();
|
|
190
|
-
if (alias) return type.getAliasTypeArguments().length === 0 ? alias.name : printType(checker, type);
|
|
191
|
-
const symbol = type.getSymbol();
|
|
192
|
-
if (symbol && (symbol.flags & (SymbolFlags.Interface | SymbolFlags.Class)) !== 0 && !(type.isTypeReference() && checker.getTypeArguments(type).length > 0)) return symbol.name;
|
|
193
|
-
return printType(checker, type);
|
|
194
|
-
}
|
|
195
|
-
/** A union's members with `true | false` folded back into `boolean`, which the compiler keeps apart. */
|
|
196
|
-
function foldBooleans(members) {
|
|
197
|
-
const isTrue = (t) => t.isBooleanLiteralType() && t.value === true;
|
|
198
|
-
const isFalse = (t) => t.isBooleanLiteralType() && t.value === false;
|
|
199
|
-
if (!members.some(isTrue) || !members.some(isFalse)) return [...members];
|
|
200
|
-
const out = [];
|
|
201
|
-
let folded = false;
|
|
202
|
-
for (const m of members) if (isTrue(m) || isFalse(m)) {
|
|
203
|
-
if (!folded) out.push("boolean");
|
|
204
|
-
folded = true;
|
|
205
|
-
} else out.push(m);
|
|
206
|
-
return out;
|
|
207
|
-
}
|
|
208
|
-
/** The members of a union as one type: flattened, deduplicated, one member alone. */
|
|
209
|
-
function unionOf$1(members) {
|
|
210
|
-
const flat = members.flatMap((m) => m.kind === "union" ? m.members : [m]);
|
|
211
|
-
const seen = /* @__PURE__ */ new Set();
|
|
212
|
-
const unique = flat.filter((m) => {
|
|
213
|
-
const key = JSON.stringify(m);
|
|
214
|
-
if (seen.has(key)) return false;
|
|
215
|
-
seen.add(key);
|
|
216
|
-
return true;
|
|
217
|
-
});
|
|
218
|
-
return unique.length === 1 ? unique[0] : {
|
|
219
|
-
kind: "union",
|
|
220
|
-
members: unique
|
|
221
|
-
};
|
|
222
|
-
}
|
|
223
|
-
/** A type into `SpecType`; what the spec surface does not describe is `unknown` with the type's text. */
|
|
224
|
-
function specTypeOf(checker, type, seen = /* @__PURE__ */ new Set()) {
|
|
225
|
-
const unknown = () => ({
|
|
226
|
-
kind: "unknown",
|
|
227
|
-
text: printType(checker, type)
|
|
228
|
-
});
|
|
229
|
-
const flags = type.flags;
|
|
230
|
-
if (type.isErrorType()) return unknown();
|
|
231
|
-
if (flags & TypeFlags.Number) return { kind: "number" };
|
|
232
|
-
if (flags & TypeFlags.String) return { kind: "string" };
|
|
233
|
-
if (flags & TypeFlags.Boolean) return { kind: "boolean" };
|
|
234
|
-
if (flags & TypeFlags.BigInt) return { kind: "bigint" };
|
|
235
|
-
if (type.isStringLiteralType() || type.isNumberLiteralType() || type.isBooleanLiteralType()) return {
|
|
236
|
-
kind: "literal",
|
|
237
|
-
value: type.value
|
|
238
|
-
};
|
|
239
|
-
if (flags & TypeFlags.Null) return { kind: "null" };
|
|
240
|
-
if (flags & (TypeFlags.Undefined | TypeFlags.Void)) return { kind: "undefined" };
|
|
241
|
-
if (type.isUnionType()) return unionOf$1(foldBooleans(type.getTypes()).map((m) => m === "boolean" ? { kind: "boolean" } : specTypeOf(checker, m, seen)));
|
|
242
|
-
if (!type.isObjectType()) return unknown();
|
|
243
|
-
if (seen.has(type.id) || seen.size >= maxDepth) return unknown();
|
|
244
|
-
const inner = new Set(seen).add(type.id);
|
|
245
|
-
if (checker.isArrayType(type)) {
|
|
246
|
-
const element = checker.getTypeArguments(type)[0];
|
|
247
|
-
return element ? {
|
|
248
|
-
kind: "array",
|
|
249
|
-
element: specTypeOf(checker, element, inner)
|
|
250
|
-
} : unknown();
|
|
238
|
+
/** Whether an identifier is the global of its name here: no scope or function shadows it, and the names confirm it. */
|
|
239
|
+
global(id, scope) {
|
|
240
|
+
return !scope.has(id.text) && !this.names.declared(id.text) && this.names.global(id);
|
|
251
241
|
}
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
const properties = type.getProperties();
|
|
255
|
-
const computed = SymbolFlags.Method | SymbolFlags.GetAccessor | SymbolFlags.SetAccessor;
|
|
256
|
-
if (properties.some((p) => (p.flags & computed) !== 0 || isSymbolKey(p.name))) return unknown();
|
|
257
|
-
const fields = properties.map((p) => ({
|
|
258
|
-
name: p.name,
|
|
259
|
-
type: specTypeOf(checker, checker.getTypeOfSymbol(p), inner)
|
|
260
|
-
}));
|
|
261
|
-
return {
|
|
262
|
-
kind: "record",
|
|
263
|
-
name: nameOfType(checker, type),
|
|
264
|
-
fields
|
|
265
|
-
};
|
|
266
|
-
}
|
|
267
|
-
/** Whether a property's name is the compiler's spelling of a symbol key, which no string names. */
|
|
268
|
-
const isSymbolKey = (name) => name.startsWith("__@");
|
|
269
|
-
/** Names a Lean structure declaration generates itself, which a field cannot take. */
|
|
270
|
-
const structureNames = /* @__PURE__ */ new Set([
|
|
271
|
-
"mk",
|
|
272
|
-
"rec",
|
|
273
|
-
"recOn",
|
|
274
|
-
"casesOn",
|
|
275
|
-
"noConfusion",
|
|
276
|
-
"noConfusionType",
|
|
277
|
-
"injEq"
|
|
278
|
-
]);
|
|
279
|
-
/**
|
|
280
|
-
* The subset's types read from the compiler's, with every record and
|
|
281
|
-
* union met along the way kept by name, in the order met, for the engines
|
|
282
|
-
* to declare. One type is read once: a second meeting gives the same
|
|
283
|
-
* record, and so does another compiler type of the same name and the
|
|
284
|
-
* same fields (an inline type written twice). A type the subset does not
|
|
285
|
-
* take is refused with the construct named, and a read that is refused
|
|
286
|
-
* leaves nothing behind: whatever it registered on the way is taken back,
|
|
287
|
-
* so no record belongs to a union that was never declared.
|
|
288
|
-
*/
|
|
289
|
-
var SubsetTypes = class {
|
|
290
|
-
records = /* @__PURE__ */ new Map();
|
|
291
|
-
unions = [];
|
|
292
|
-
checker;
|
|
293
|
-
/** By the compiler's type id. */
|
|
294
|
-
byId = /* @__PURE__ */ new Map();
|
|
295
|
-
idOfName = /* @__PURE__ */ new Map();
|
|
296
|
-
/** Types being read now, to refuse a type that holds itself. */
|
|
297
|
-
reading = /* @__PURE__ */ new Set();
|
|
298
|
-
constructor(checker) {
|
|
299
|
-
this.checker = checker;
|
|
242
|
+
fail(what, at) {
|
|
243
|
+
throw new OutsideSubset(what, this.lineOf(at));
|
|
300
244
|
}
|
|
301
|
-
/**
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
if (cached) return cached;
|
|
305
|
-
if (this.reading.size > 0) return this.enter(type, refuse);
|
|
306
|
-
const saved = {
|
|
307
|
-
records: new Map(this.records),
|
|
308
|
-
idOfName: new Map(this.idOfName),
|
|
309
|
-
byId: new Map(this.byId),
|
|
310
|
-
unions: this.unions.length
|
|
311
|
-
};
|
|
312
|
-
try {
|
|
313
|
-
return this.enter(type, refuse);
|
|
314
|
-
} catch (err) {
|
|
315
|
-
this.records.clear();
|
|
316
|
-
for (const [k, v] of saved.records) this.records.set(k, v);
|
|
317
|
-
this.idOfName.clear();
|
|
318
|
-
for (const [k, v] of saved.idOfName) this.idOfName.set(k, v);
|
|
319
|
-
this.byId.clear();
|
|
320
|
-
for (const [k, v] of saved.byId) this.byId.set(k, v);
|
|
321
|
-
this.unions.length = saved.unions;
|
|
322
|
-
throw err;
|
|
323
|
-
}
|
|
245
|
+
/** `OutsideSubset` at a node, for a type read there. */
|
|
246
|
+
refuseAt(at) {
|
|
247
|
+
return (what) => this.fail(what, at);
|
|
324
248
|
}
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
if (this.reading.has(type.id)) return refuse(`${nameOfType(this.checker, type)} holds itself (a recursive type)`);
|
|
328
|
-
if (this.reading.size >= maxDepth) return refuse(`${nameOfType(this.checker, type)} is nested too deep (more than ${maxDepth} levels)`);
|
|
329
|
-
this.reading.add(type.id);
|
|
330
|
-
try {
|
|
331
|
-
const out = this.read(type, refuse);
|
|
332
|
-
this.byId.set(type.id, out);
|
|
333
|
-
return out;
|
|
334
|
-
} finally {
|
|
335
|
-
this.reading.delete(type.id);
|
|
336
|
-
}
|
|
249
|
+
text(node) {
|
|
250
|
+
return textOf(this.sf, node);
|
|
337
251
|
}
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
const flags = type.flags;
|
|
342
|
-
if (type.isErrorType()) return refuse(`type ${text()}, which does not resolve`);
|
|
343
|
-
if (flags & TypeFlags.Number) return { kind: "int" };
|
|
344
|
-
if (flags & (TypeFlags.String | TypeFlags.StringLiteral)) return { kind: "string" };
|
|
345
|
-
if (flags & (TypeFlags.Boolean | TypeFlags.BooleanLiteral)) return { kind: "bool" };
|
|
346
|
-
if (flags & TypeFlags.Null) return refuse("null alone is not a type the subset takes");
|
|
347
|
-
if (flags & (TypeFlags.Undefined | TypeFlags.Void)) return refuse("undefined in a type (the subset has null)");
|
|
348
|
-
if (flags & TypeFlags.NumberLiteral) return refuse(`the numeric literal type ${text()} (the subset has number)`);
|
|
349
|
-
if (flags & TypeFlags.BigInt) return refuse("bigint (the subset has number)");
|
|
350
|
-
if (flags & TypeFlags.TypeParameter) return refuse("type parameters");
|
|
351
|
-
if (type.isUnionType()) return this.union(type, refuse);
|
|
352
|
-
if (type.isIntersectionType()) return refuse("an intersection type");
|
|
353
|
-
if (!type.isObjectType()) return refuse(`type ${text()} (the subset has number, boolean, string, null, and record types, unions and arrays of them)`);
|
|
354
|
-
if (checker.isArrayType(type)) {
|
|
355
|
-
const element = checker.getTypeArguments(type)[0];
|
|
356
|
-
if (!element) return refuse(`type ${text()}`);
|
|
357
|
-
return {
|
|
358
|
-
kind: "list",
|
|
359
|
-
element: this.of(element, refuse)
|
|
360
|
-
};
|
|
361
|
-
}
|
|
362
|
-
if (type.isTupleType()) return refuse("a tuple type");
|
|
363
|
-
if (type.getCallSignatures().length > 0 || type.getConstructSignatures().length > 0) return refuse("a function type");
|
|
364
|
-
if (type.getIndexInfos().length > 0) return refuse("an index signature");
|
|
365
|
-
const why = notPlain(checker, type);
|
|
366
|
-
if (why !== void 0) return refuse(`type ${text()} is outside the subset: ${why}`);
|
|
367
|
-
return {
|
|
368
|
-
kind: "record",
|
|
369
|
-
name: this.record(type, nameOfType(checker, type), refuse).name
|
|
370
|
-
};
|
|
252
|
+
/** The expression with `narrow` nodes inserted where a null check guards a nullable name. */
|
|
253
|
+
narrowed(e, scope, at) {
|
|
254
|
+
return insertNarrows(e, scope, this.ctx, (m) => this.fail(m, at));
|
|
371
255
|
}
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
const members = type.isUnionType() ? type.getTypes() : [type];
|
|
375
|
-
if (members.some((m) => (m.flags & (TypeFlags.Undefined | TypeFlags.Void)) !== 0)) return refuse("undefined in a type (the subset has null)");
|
|
376
|
-
const nulls = members.filter((m) => (m.flags & TypeFlags.Null) !== 0);
|
|
377
|
-
const rest = members.filter((m) => (m.flags & TypeFlags.Null) === 0);
|
|
378
|
-
const bare = nulls.length === 0 ? type : type.getNonNullableType();
|
|
379
|
-
let base;
|
|
380
|
-
if (rest.length === 0) return refuse("null alone is not a type the subset takes");
|
|
381
|
-
else if (rest.every((m) => (m.flags & (TypeFlags.String | TypeFlags.StringLiteral)) !== 0)) base = { kind: "string" };
|
|
382
|
-
else if (rest.every((m) => (m.flags & (TypeFlags.Boolean | TypeFlags.BooleanLiteral)) !== 0)) base = { kind: "bool" };
|
|
383
|
-
else if (rest.length === 1) base = this.of(rest[0], refuse);
|
|
384
|
-
else if (rest.every((m) => m.isObjectType() && !this.checker.isArrayType(m))) base = this.taggedUnion(bare, rest, refuse);
|
|
385
|
-
else if (rest.some((m) => m.isObjectType())) return refuse("a union mixing records with other types");
|
|
386
|
-
else if (rest.every((m) => (m.flags & TypeFlags.NumberLiteral) !== 0)) return refuse(`the numeric literal type ${printType(this.checker, type)} (the subset has number)`);
|
|
387
|
-
else return refuse(`a union of several types (${printType(this.checker, type)}): the subset has a union of literals of one kind, a tagged union of records, and either with null`);
|
|
388
|
-
if (nulls.length === 0) return base;
|
|
389
|
-
if (base.kind === "nullable") return base;
|
|
390
|
-
return {
|
|
391
|
-
kind: "nullable",
|
|
392
|
-
inner: base
|
|
393
|
-
};
|
|
256
|
+
typeOfExpr(e, scope, at, expected) {
|
|
257
|
+
return typeOf(e, scope, this.ctx, (m) => this.fail(m, at), expected);
|
|
394
258
|
}
|
|
395
259
|
/**
|
|
396
|
-
* A
|
|
397
|
-
*
|
|
398
|
-
*
|
|
399
|
-
* record declared on its own keeps its name and belongs to one union.
|
|
260
|
+
* A block's statements as one expression: `const` becomes `let`, `if (c)
|
|
261
|
+
* return a; rest` a conditional, and the last statement must return:
|
|
262
|
+
* every path ends in a `return`.
|
|
400
263
|
*/
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
if (cached) return cached;
|
|
404
|
-
const checker = this.checker;
|
|
405
|
-
const name = nameOfType(checker, type);
|
|
406
|
-
const taken = this.idOfName.get(name);
|
|
407
|
-
if (taken !== void 0 && taken !== type.id) return refuse(`two types named ${name}`);
|
|
408
|
-
if (taken === void 0 && (this.records.has(name) || this.unions.some((u) => u.name === name))) return refuse(`two types named ${name}`);
|
|
409
|
-
const literalFields = (m) => {
|
|
410
|
-
const out = /* @__PURE__ */ new Map();
|
|
411
|
-
for (const p of m.getProperties()) {
|
|
412
|
-
const t = checker.getTypeOfSymbol(p);
|
|
413
|
-
if (t.isStringLiteralType() || t.isBooleanLiteralType()) out.set(p.name, t.value);
|
|
414
|
-
}
|
|
415
|
-
return out;
|
|
416
|
-
};
|
|
417
|
-
const literals = members.map(literalFields);
|
|
418
|
-
const tag = [...literals[0].keys()].find((field) => literals.every((l) => l.has(field)) && new Set(literals.map((l) => JSON.stringify(l.get(field)))).size === literals.length);
|
|
419
|
-
if (tag === void 0) return refuse(`${name}: a union of records without a tag (a literal-typed field every member has, different in each)`);
|
|
420
|
-
const isAnonymous = (m) => !m.getAliasSymbol() && ((m.getSymbol()?.flags ?? 0) & (SymbolFlags.Interface | SymbolFlags.Class)) === 0;
|
|
421
|
-
const union = {
|
|
422
|
-
name,
|
|
423
|
-
tag,
|
|
424
|
-
members: members.map((m, i) => {
|
|
425
|
-
const value = literals[i].get(tag);
|
|
426
|
-
const memberName = isAnonymous(m) ? `${name}.${String(value)}` : nameOfType(checker, m);
|
|
427
|
-
return {
|
|
428
|
-
tag: value,
|
|
429
|
-
record: this.record(m, memberName, refuse, name).name
|
|
430
|
-
};
|
|
431
|
-
})
|
|
432
|
-
};
|
|
433
|
-
this.unions.push(union);
|
|
434
|
-
this.idOfName.set(name, type.id);
|
|
435
|
-
const out = {
|
|
436
|
-
kind: "union",
|
|
437
|
-
name
|
|
438
|
-
};
|
|
439
|
-
this.byId.set(type.id, out);
|
|
440
|
-
return out;
|
|
264
|
+
block(statements, scope, end) {
|
|
265
|
+
return this.statements(statements, 0, scope, end);
|
|
441
266
|
}
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
if (
|
|
446
|
-
if (
|
|
447
|
-
const
|
|
448
|
-
if (
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
267
|
+
statements(statements, i, scope, end) {
|
|
268
|
+
const s = statements[i];
|
|
269
|
+
if (!s) this.fail("a path that does not return", end);
|
|
270
|
+
if (is.isEmptyStatement(s)) return this.statements(statements, i + 1, scope, end);
|
|
271
|
+
if (is.isVariableStatement(s)) {
|
|
272
|
+
const list = s.declarationList;
|
|
273
|
+
if (!isConst(list)) this.fail("a mutable binding (use const)", s);
|
|
274
|
+
const [decl, second] = list.declarations;
|
|
275
|
+
if (!decl || second) this.fail("several bindings in one const", s);
|
|
276
|
+
if (!is.isIdentifier(decl.name)) this.fail("a destructured const", decl.name);
|
|
277
|
+
const name = decl.name.text;
|
|
278
|
+
if (this.names.declared(name)) this.fail(`const ${name} shadows the module's function ${name} in its block`, decl.name);
|
|
279
|
+
if (scope.has(name)) this.fail(`const ${name} redeclares a name already bound here`, decl.name);
|
|
280
|
+
const annotated = decl.type ? this.types.annotation(decl.type, this.refuseAt(decl.type)) : void 0;
|
|
281
|
+
if (!decl.initializer) this.fail(`const ${name} without a value`, decl);
|
|
282
|
+
const value = this.expression(decl.initializer, scope);
|
|
283
|
+
const inner = new Map(scope);
|
|
284
|
+
inner.set(name, annotated ?? { kind: "null" });
|
|
285
|
+
return {
|
|
286
|
+
kind: "let",
|
|
287
|
+
name,
|
|
288
|
+
value,
|
|
289
|
+
body: this.statements(statements, i + 1, inner, end),
|
|
290
|
+
...annotated ? { type: annotated } : {}
|
|
291
|
+
};
|
|
453
292
|
}
|
|
454
|
-
if (
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
293
|
+
if (is.isIfStatement(s)) {
|
|
294
|
+
const test = this.expression(s.expression, scope);
|
|
295
|
+
const then = this.branch(s.thenStatement, scope);
|
|
296
|
+
if (s.elseStatement) {
|
|
297
|
+
const otherwise = this.branch(s.elseStatement, scope);
|
|
298
|
+
const after = statements[i + 1];
|
|
299
|
+
if (after) this.fail("statements after an if/else that both return", after);
|
|
300
|
+
return {
|
|
301
|
+
kind: "cond",
|
|
302
|
+
test,
|
|
303
|
+
ifTrue: then,
|
|
304
|
+
ifFalse: otherwise
|
|
460
305
|
};
|
|
461
|
-
this.records.set(name, known);
|
|
462
306
|
}
|
|
463
|
-
return
|
|
307
|
+
return {
|
|
308
|
+
kind: "cond",
|
|
309
|
+
test,
|
|
310
|
+
ifTrue: then,
|
|
311
|
+
ifFalse: this.statements(statements, i + 1, scope, end)
|
|
312
|
+
};
|
|
464
313
|
}
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
this.records.set(name, record);
|
|
471
|
-
this.idOfName.set(name, type.id);
|
|
472
|
-
this.byId.set(type.id, {
|
|
473
|
-
kind: "record",
|
|
474
|
-
name
|
|
475
|
-
});
|
|
476
|
-
return record;
|
|
477
|
-
}
|
|
478
|
-
/** The fields of a record type, each a stored value the subset takes. */
|
|
479
|
-
fieldsOf(type, name, refuse) {
|
|
480
|
-
const guard = !this.reading.has(type.id);
|
|
481
|
-
if (guard) this.reading.add(type.id);
|
|
482
|
-
try {
|
|
483
|
-
const checker = this.checker;
|
|
484
|
-
const fields = [];
|
|
485
|
-
const outside = (what) => refuse(`type ${name} is outside the subset: ${what}`);
|
|
486
|
-
for (const p of type.getProperties()) {
|
|
487
|
-
if (isSymbolKey(p.name)) return outside("a field keyed by a symbol");
|
|
488
|
-
if ((p.flags & SymbolFlags.Optional) !== 0) return outside(`optional field ${p.name}`);
|
|
489
|
-
if ((p.flags & SymbolFlags.Method) !== 0) return outside(`a method ${p.name}`);
|
|
490
|
-
if ((p.flags & (SymbolFlags.GetAccessor | SymbolFlags.SetAccessor)) !== 0) return outside(`an accessor ${p.name}`);
|
|
491
|
-
if (structureNames.has(p.name)) return outside(`field ${p.name} takes a name Lean's structures reserve`);
|
|
492
|
-
if (p.name === "__proto__") return outside("a field named __proto__, which JavaScript treats specially");
|
|
493
|
-
const fieldType = checker.getTypeOfSymbol(p);
|
|
494
|
-
const read = this.of(fieldType, (what) => outside(`field ${p.name}: ${what}`));
|
|
495
|
-
const literal = fieldType.isStringLiteralType() ? fieldType.value : fieldType.isBooleanLiteralType() ? fieldType.value : void 0;
|
|
496
|
-
fields.push({
|
|
497
|
-
name: p.name,
|
|
498
|
-
type: read,
|
|
499
|
-
...literal === void 0 ? {} : { literal }
|
|
500
|
-
});
|
|
314
|
+
if (is.isReturnStatement(s)) {
|
|
315
|
+
const after = statements[i + 1];
|
|
316
|
+
if (!s.expression && after) {
|
|
317
|
+
const gap = this.sf.text.slice(s.getStart(this.sf) + 6, after.getStart(this.sf));
|
|
318
|
+
if (/[\n\r\u2028\u2029]/.test(gap)) this.fail("a line break after return (JavaScript inserts a semicolon and returns undefined)", s);
|
|
501
319
|
}
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
320
|
+
const value = this.returned(s, scope);
|
|
321
|
+
if (after) this.fail("statements after a return", after);
|
|
322
|
+
return value;
|
|
505
323
|
}
|
|
324
|
+
if (is.isForStatement(s) || is.isForOfStatement(s) || is.isForInStatement(s) || is.isWhileStatement(s) || is.isDoStatement(s)) this.fail("a loop", s);
|
|
325
|
+
if (is.isThrowStatement(s)) this.fail("throw", s);
|
|
326
|
+
if (is.isSwitchStatement(s)) this.fail("switch", s);
|
|
327
|
+
if (is.isTryStatement(s)) this.fail("try", s);
|
|
328
|
+
if (is.isFunctionDeclaration(s)) this.fail("a nested function", s);
|
|
329
|
+
this.fail(`statement starting with ${this.text(s).split(/\s/)[0] ?? kindName(s.kind)}`, s);
|
|
506
330
|
}
|
|
507
|
-
}
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
if (
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
331
|
+
/** An `if` branch: `return e;` or `{ ...statements ending in return }`. */
|
|
332
|
+
branch(s, scope) {
|
|
333
|
+
if (is.isBlock(s)) return this.block(s.statements, scope, s);
|
|
334
|
+
if (is.isReturnStatement(s)) return this.returned(s, scope);
|
|
335
|
+
this.fail("an if branch that does not return", s);
|
|
336
|
+
}
|
|
337
|
+
/** `return e;`. A line break after `return` makes JavaScript return undefined: no value, refused. */
|
|
338
|
+
returned(s, scope) {
|
|
339
|
+
if (!s.expression) this.fail("a return without a value", s);
|
|
340
|
+
return this.expression(s.expression, scope);
|
|
341
|
+
}
|
|
342
|
+
expression(node, scope) {
|
|
343
|
+
if (is.isParenthesizedExpression(node)) return this.expression(node.expression, scope);
|
|
344
|
+
if (is.isIdentifier(node)) return this.identifier(node, scope);
|
|
345
|
+
if (is.isNumericLiteral(node)) {
|
|
346
|
+
const raw = this.text(node);
|
|
347
|
+
if (!/^[0-9](_?[0-9])*$/.test(raw)) this.fail(`the numeric literal ${raw} (integers in decimal only)`, node);
|
|
348
|
+
return {
|
|
349
|
+
kind: "int",
|
|
350
|
+
value: raw.replace(/_/g, "")
|
|
351
|
+
};
|
|
524
352
|
}
|
|
525
|
-
|
|
526
|
-
if (
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
353
|
+
if (is.isBigIntLiteral(node)) this.fail(`the bigint literal ${this.text(node)}`, node);
|
|
354
|
+
if (is.isStringLiteral(node)) {
|
|
355
|
+
if (hasLoneSurrogate(node.text)) this.fail("a string literal with a lone surrogate, which Lean's strings cannot hold", node);
|
|
356
|
+
return {
|
|
357
|
+
kind: "string",
|
|
358
|
+
value: node.text
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
if (is.isNoSubstitutionTemplateLiteral(node) || is.isTemplateExpression(node)) this.fail("a template literal", node);
|
|
362
|
+
if (is.isRegularExpressionLiteral(node)) this.fail("a regular expression", node);
|
|
363
|
+
if (node.kind === SyntaxKind.TrueKeyword) return {
|
|
364
|
+
kind: "bool",
|
|
365
|
+
value: true
|
|
531
366
|
};
|
|
532
|
-
if (
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
}
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
inModule: true
|
|
552
|
-
});
|
|
553
|
-
return;
|
|
554
|
-
}
|
|
555
|
-
declarations.set(name, {
|
|
556
|
-
name,
|
|
557
|
-
params: readParams(checker, fn),
|
|
558
|
-
line: lineAt(sf, at),
|
|
559
|
-
offset
|
|
560
|
-
});
|
|
561
|
-
};
|
|
562
|
-
for (const st of sf.statements) {
|
|
563
|
-
if (is.isFunctionDeclaration(st)) {
|
|
564
|
-
if (!st.name) continue;
|
|
565
|
-
declare(st.name.text, st, st);
|
|
566
|
-
if (isExported(st)) exports.set(st.name.text, st.name.text);
|
|
567
|
-
continue;
|
|
568
|
-
}
|
|
569
|
-
if (is.isVariableStatement(st)) {
|
|
570
|
-
for (const d of st.declarationList.declarations) {
|
|
571
|
-
if (!is.isIdentifier(d.name) || !d.initializer) continue;
|
|
572
|
-
let init = d.initializer;
|
|
573
|
-
while (is.isParenthesizedExpression(init)) init = init.expression;
|
|
574
|
-
if (!is.isArrowFunction(init) && !is.isFunctionExpression(init)) continue;
|
|
575
|
-
declare(d.name.text, init, st);
|
|
576
|
-
if (isExported(st)) exports.set(d.name.text, d.name.text);
|
|
367
|
+
if (node.kind === SyntaxKind.FalseKeyword) return {
|
|
368
|
+
kind: "bool",
|
|
369
|
+
value: false
|
|
370
|
+
};
|
|
371
|
+
if (node.kind === SyntaxKind.NullKeyword) return { kind: "null" };
|
|
372
|
+
if (is.isPrefixUnaryExpression(node)) {
|
|
373
|
+
if (node.operator === SyntaxKind.ExclamationToken) return {
|
|
374
|
+
kind: "not",
|
|
375
|
+
operand: this.expression(node.operand, scope)
|
|
376
|
+
};
|
|
377
|
+
if (node.operator === SyntaxKind.MinusToken) {
|
|
378
|
+
const operand = this.expression(node.operand, scope);
|
|
379
|
+
return operand.kind === "int" ? {
|
|
380
|
+
kind: "int",
|
|
381
|
+
value: operand.value.startsWith("-") ? operand.value.slice(1) : `-${operand.value}`
|
|
382
|
+
} : {
|
|
383
|
+
kind: "neg",
|
|
384
|
+
operand
|
|
385
|
+
};
|
|
577
386
|
}
|
|
578
|
-
|
|
387
|
+
if (node.operator === SyntaxKind.PlusToken) this.fail("unary plus", node);
|
|
388
|
+
this.fail(`the ${this.text(node).slice(0, 2)} operator`, node);
|
|
579
389
|
}
|
|
580
|
-
if (is.
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
390
|
+
if (is.isPostfixUnaryExpression(node)) this.fail(`the ${this.text(node).slice(-2)} operator`, node);
|
|
391
|
+
if (is.isTypeOfExpression(node)) this.fail("the typeof operator", node);
|
|
392
|
+
if (is.isVoidExpression(node)) this.fail("the void operator", node);
|
|
393
|
+
if (is.isAwaitExpression(node)) this.fail("the await operator", node);
|
|
394
|
+
if (is.isNewExpression(node)) this.fail("the new operator", node);
|
|
395
|
+
if (is.isDeleteExpression(node)) this.fail("the delete operator", node);
|
|
396
|
+
if (is.isBinaryExpression(node)) return this.binary(node, scope);
|
|
397
|
+
if (is.isConditionalExpression(node)) return {
|
|
398
|
+
kind: "cond",
|
|
399
|
+
test: this.expression(node.condition, scope),
|
|
400
|
+
ifTrue: this.expression(node.whenTrue, scope),
|
|
401
|
+
ifFalse: this.expression(node.whenFalse, scope)
|
|
402
|
+
};
|
|
403
|
+
if (is.isCallExpression(node)) return this.call(node, scope);
|
|
404
|
+
if (is.isPropertyAccessExpression(node)) {
|
|
405
|
+
if (node.questionDotToken) this.fail("optional chaining", node);
|
|
406
|
+
if (!is.isIdentifier(node.name)) this.fail("a private field", node.name);
|
|
407
|
+
return {
|
|
408
|
+
kind: "field",
|
|
409
|
+
object: this.expression(node.expression, scope),
|
|
410
|
+
field: node.name.text
|
|
411
|
+
};
|
|
587
412
|
}
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
exports,
|
|
592
|
-
errors
|
|
593
|
-
};
|
|
594
|
-
}
|
|
595
|
-
/** `import { a, b as c } from "x"`, `import * as ns from "x"`, `import d from "x"`; type-only imports skipped. */
|
|
596
|
-
function imports(sf) {
|
|
597
|
-
const out = /* @__PURE__ */ new Map();
|
|
598
|
-
for (const st of sf.statements) {
|
|
599
|
-
if (!is.isImportDeclaration(st) || !st.importClause) continue;
|
|
600
|
-
const clause = st.importClause;
|
|
601
|
-
if (clause.phaseModifier === SyntaxKind.TypeKeyword) continue;
|
|
602
|
-
if (!is.isStringLiteral(st.moduleSpecifier)) continue;
|
|
603
|
-
const from = st.moduleSpecifier.text;
|
|
604
|
-
if (clause.name) out.set(clause.name.text, {
|
|
605
|
-
from,
|
|
606
|
-
name: "default",
|
|
607
|
-
declaration: st
|
|
608
|
-
});
|
|
609
|
-
const bindings = clause.namedBindings;
|
|
610
|
-
if (!bindings) continue;
|
|
611
|
-
if (is.isNamespaceImport(bindings)) out.set(bindings.name.text, {
|
|
612
|
-
from,
|
|
613
|
-
name: "*",
|
|
614
|
-
declaration: st
|
|
615
|
-
});
|
|
616
|
-
else for (const e of bindings.elements) {
|
|
617
|
-
if (e.isTypeOnly) continue;
|
|
618
|
-
const imported = e.propertyName ?? e.name;
|
|
619
|
-
const name = is.isIdentifier(imported) ? imported.text : imported.text;
|
|
620
|
-
out.set(e.name.text, {
|
|
621
|
-
from,
|
|
622
|
-
name,
|
|
623
|
-
declaration: st
|
|
624
|
-
});
|
|
413
|
+
if (is.isElementAccessExpression(node)) {
|
|
414
|
+
if (this.isHead(node)) this.fail("xs[0] without ?? fallback (it is undefined on an empty list)", node);
|
|
415
|
+
this.fail("index access other than xs[0] ?? fallback", node);
|
|
625
416
|
}
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
function conjuncts(node, out = []) {
|
|
636
|
-
let e = node;
|
|
637
|
-
while (is.isParenthesizedExpression(e)) e = e.expression;
|
|
638
|
-
if (is.isBinaryExpression(e) && e.operatorToken.kind === SyntaxKind.AmpersandAmpersandToken) {
|
|
639
|
-
conjuncts(e.left, out);
|
|
640
|
-
conjuncts(e.right, out);
|
|
641
|
-
} else out.push(e);
|
|
642
|
-
return out;
|
|
643
|
-
}
|
|
644
|
-
const comparisons = {
|
|
645
|
-
[SyntaxKind.LessThanToken]: "<",
|
|
646
|
-
[SyntaxKind.LessThanEqualsToken]: "<=",
|
|
647
|
-
[SyntaxKind.GreaterThanToken]: ">",
|
|
648
|
-
[SyntaxKind.GreaterThanEqualsToken]: ">="
|
|
649
|
-
};
|
|
650
|
-
/**
|
|
651
|
-
* What an expression says about each of the named parameters on its own:
|
|
652
|
-
* its top-level conjuncts of the forms `Number.isInteger(x)`, `x < n`,
|
|
653
|
-
* `n <= x` (and the other comparisons) and `/re/.test(x)`, by parameter
|
|
654
|
-
* index.
|
|
655
|
-
*/
|
|
656
|
-
function hintsIn(sf, body, params) {
|
|
657
|
-
const out = /* @__PURE__ */ new Map();
|
|
658
|
-
const position = /* @__PURE__ */ new Map();
|
|
659
|
-
params.forEach((p, i) => {
|
|
660
|
-
if (p !== null) position.set(p, i);
|
|
661
|
-
});
|
|
662
|
-
const merge = (i, h) => {
|
|
663
|
-
const old = out.get(i) ?? {};
|
|
664
|
-
out.set(i, {
|
|
665
|
-
...old,
|
|
666
|
-
...h
|
|
667
|
-
});
|
|
668
|
-
};
|
|
669
|
-
for (const conjunct of conjuncts(body)) {
|
|
670
|
-
if (is.isCallExpression(conjunct)) {
|
|
671
|
-
const callee = conjunct.expression;
|
|
672
|
-
const [arg, extra] = conjunct.arguments;
|
|
673
|
-
if (!is.isPropertyAccessExpression(callee) || !is.isIdentifier(callee.name) || !arg || extra) continue;
|
|
674
|
-
if (!is.isIdentifier(arg)) continue;
|
|
675
|
-
const at = position.get(arg.text);
|
|
676
|
-
if (at === void 0) continue;
|
|
677
|
-
if (is.isIdentifier(callee.expression) && callee.expression.text === "Number" && callee.name.text === "isInteger") merge(at, { integer: true });
|
|
678
|
-
else if (is.isRegularExpressionLiteral(callee.expression) && callee.name.text === "test") {
|
|
679
|
-
const m = /^\/([\s\S]*)\/([a-z]*)$/.exec(textOf(sf, callee.expression));
|
|
680
|
-
if (m) merge(at, { regex: {
|
|
681
|
-
pattern: m[1],
|
|
682
|
-
flags: m[2]
|
|
683
|
-
} });
|
|
417
|
+
if (is.isObjectLiteralExpression(node)) return this.record(node, scope);
|
|
418
|
+
if (is.isArrayLiteralExpression(node)) {
|
|
419
|
+
const items = [];
|
|
420
|
+
let rest;
|
|
421
|
+
for (const item of node.elements) {
|
|
422
|
+
if (rest) this.fail("a spread that is not last in an array literal", item);
|
|
423
|
+
if (is.isSpreadElement(item)) rest = this.expression(item.expression, scope);
|
|
424
|
+
else if (is.isOmittedExpression(item)) this.fail("a hole in an array literal", item);
|
|
425
|
+
else items.push(this.expression(item, scope));
|
|
684
426
|
}
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
if (op === void 0) continue;
|
|
690
|
-
const bound = (variable, literal, variableOnLeft) => {
|
|
691
|
-
if (!is.isIdentifier(variable)) return;
|
|
692
|
-
const value = numberText(sf, literal);
|
|
693
|
-
if (value === void 0) return;
|
|
694
|
-
const at = position.get(variable.text);
|
|
695
|
-
if (at === void 0) return;
|
|
696
|
-
const above = variableOnLeft ? op.startsWith("<") : op.startsWith(">");
|
|
697
|
-
const endpoint = {
|
|
698
|
-
value,
|
|
699
|
-
inclusive: op.endsWith("=")
|
|
427
|
+
return {
|
|
428
|
+
kind: "list",
|
|
429
|
+
items,
|
|
430
|
+
...rest ? { rest } : {}
|
|
700
431
|
};
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
if (is.
|
|
704
|
-
|
|
432
|
+
}
|
|
433
|
+
if (is.isArrowFunction(node) || is.isFunctionExpression(node)) this.fail("a function expression (the subset has callbacks of list methods only)", node);
|
|
434
|
+
if (is.isAsExpression(node)) this.fail("the as operator", node);
|
|
435
|
+
if (is.isSatisfiesExpression(node)) this.fail("the satisfies operator", node);
|
|
436
|
+
if (is.isNonNullExpression(node)) this.fail("the ! assertion", node);
|
|
437
|
+
if (is.isTypeAssertion(node)) this.fail("a type assertion", node);
|
|
438
|
+
if (node.kind === SyntaxKind.ThisKeyword) this.fail("this", node);
|
|
439
|
+
this.fail(`unexpected ${this.text(node) || kindName(node.kind)}`, node);
|
|
705
440
|
}
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
441
|
+
identifier(node, scope) {
|
|
442
|
+
const name = node.text;
|
|
443
|
+
if (name === "undefined") this.fail("undefined (the subset has null)", node);
|
|
444
|
+
if (scope.has(name) || this.names.declared(name)) return {
|
|
445
|
+
kind: "var",
|
|
446
|
+
name
|
|
447
|
+
};
|
|
448
|
+
const constant = this.constant?.(node, (what) => this.fail(what, node));
|
|
449
|
+
if (constant) return constant;
|
|
450
|
+
if ((name === "Math" || name === "Number") && !this.names.global(node)) this.fail(`${name}, which is not the standard ${name} here: a declaration of it other than the compiler's is in scope`, node);
|
|
451
|
+
this.fail(this.names.spec ? `${name}, which is neither a parameter, a const nor a function imported from the module beside the spec file` : `${name}, which is neither a parameter, a const nor a function of this module`, node);
|
|
713
452
|
}
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
const errors = [];
|
|
718
|
-
const bound = imports(sf);
|
|
719
|
-
const specs = [];
|
|
720
|
-
function fail(message, at) {
|
|
721
|
-
throw new SpecFail(message, lineAt(sf, at));
|
|
453
|
+
/** Whether an element access is `xs[0]`. */
|
|
454
|
+
isHead(node) {
|
|
455
|
+
return is.isElementAccessExpression(node) && is.isNumericLiteral(node.argumentExpression) && this.text(node.argumentExpression) === "0";
|
|
722
456
|
}
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
const
|
|
726
|
-
if (
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
457
|
+
binary(node, scope) {
|
|
458
|
+
const kind = node.operatorToken.kind;
|
|
459
|
+
const op = binaryOps[kind];
|
|
460
|
+
if (op) return {
|
|
461
|
+
kind: "binary",
|
|
462
|
+
op,
|
|
463
|
+
left: this.expression(node.left, scope),
|
|
464
|
+
right: this.expression(node.right, scope)
|
|
465
|
+
};
|
|
466
|
+
if (kind === SyntaxKind.QuestionQuestionToken) {
|
|
467
|
+
if (is.isBinaryExpression(node.left) && node.left.operatorToken.kind === kind) this.fail("a chain of ??", node);
|
|
468
|
+
if (is.isElementAccessExpression(node.left) && !this.isHead(node.left)) this.fail("index access other than xs[0] ?? fallback", node.left);
|
|
469
|
+
if (!is.isElementAccessExpression(node.left)) this.fail("?? after anything but xs[0] (write xs[0] ?? fallback, parenthesized where it meets other operators)", node);
|
|
470
|
+
if (node.left.questionDotToken) this.fail("optional chaining", node.left);
|
|
471
|
+
return {
|
|
472
|
+
kind: "headOr",
|
|
473
|
+
list: this.expression(node.left.expression, scope),
|
|
474
|
+
fallback: this.expression(node.right, scope)
|
|
475
|
+
};
|
|
476
|
+
}
|
|
477
|
+
if (kind >= SyntaxKind.FirstAssignment && kind <= SyntaxKind.LastAssignment) this.fail("an assignment", node);
|
|
478
|
+
if (kind === SyntaxKind.CommaToken) this.fail("the comma operator", node);
|
|
479
|
+
if (kind === SyntaxKind.InKeyword || kind === SyntaxKind.InstanceOfKeyword) this.fail(`the ${this.text(node.operatorToken)} operator`, node);
|
|
480
|
+
this.fail(`the ${this.text(node.operatorToken)} operator`, node);
|
|
481
|
+
}
|
|
482
|
+
call(node, scope) {
|
|
483
|
+
if (node.questionDotToken) this.fail("optional chaining", node);
|
|
484
|
+
let callee = node.expression;
|
|
485
|
+
while (is.isParenthesizedExpression(callee)) callee = callee.expression;
|
|
735
486
|
if (is.isPropertyAccessExpression(callee)) {
|
|
736
|
-
if (
|
|
737
|
-
|
|
738
|
-
const
|
|
739
|
-
|
|
740
|
-
|
|
487
|
+
if (callee.questionDotToken) this.fail("optional chaining", callee);
|
|
488
|
+
if (!is.isIdentifier(callee.name)) this.fail("a private method", callee.name);
|
|
489
|
+
const method = callee.name.text;
|
|
490
|
+
const receiver = callee.expression;
|
|
491
|
+
if (is.isIdentifier(receiver) && receiver.text === "Number" && method === "isInteger" && this.global(receiver, scope)) {
|
|
492
|
+
const [arg, extra] = node.arguments;
|
|
493
|
+
if (!arg || extra) this.fail("Number.isInteger takes one argument", node);
|
|
494
|
+
return {
|
|
495
|
+
kind: "isInteger",
|
|
496
|
+
operand: this.expression(arg, scope)
|
|
497
|
+
};
|
|
498
|
+
}
|
|
499
|
+
if (is.isIdentifier(receiver) && receiver.text === "Math" && method === "floor" && this.global(receiver, scope)) {
|
|
500
|
+
const [arg, extra] = node.arguments;
|
|
501
|
+
if (!arg || extra) this.fail("Math.floor takes one argument", node);
|
|
502
|
+
return {
|
|
503
|
+
kind: "floor",
|
|
504
|
+
operand: this.expression(arg, scope)
|
|
505
|
+
};
|
|
506
|
+
}
|
|
507
|
+
const list = this.expression(receiver, scope);
|
|
508
|
+
if (!methods.has(method)) this.fail(`the method ${method} (the subset has slice(1), map, flatMap, every, some and reduce)`, callee.name);
|
|
509
|
+
return this.method(node, list, method, scope);
|
|
741
510
|
}
|
|
742
|
-
if (!is.isIdentifier(callee))
|
|
743
|
-
const
|
|
744
|
-
if (
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
511
|
+
if (!is.isIdentifier(callee)) this.fail("a call to a computed callee", callee);
|
|
512
|
+
const name = callee.text;
|
|
513
|
+
if (scope.has(name)) this.fail(`a call to ${name}, which names a value here, not the module's function`, callee);
|
|
514
|
+
if (!this.names.callable(name) && this.inline) {
|
|
515
|
+
const readArgs = (types) => node.arguments.map((a, i) => {
|
|
516
|
+
if (is.isSpreadElement(a)) this.fail("a spread argument", a);
|
|
517
|
+
const type = types[i];
|
|
518
|
+
if (!type) return this.expression(a, scope);
|
|
519
|
+
const literals = [];
|
|
520
|
+
const collect = (e) => {
|
|
521
|
+
if (is.isParenthesizedExpression(e)) collect(e.expression);
|
|
522
|
+
else if (is.isConditionalExpression(e)) {
|
|
523
|
+
collect(e.whenTrue);
|
|
524
|
+
collect(e.whenFalse);
|
|
525
|
+
} else if (is.isObjectLiteralExpression(e)) literals.push(e);
|
|
526
|
+
};
|
|
527
|
+
collect(a);
|
|
528
|
+
for (const l of literals) this.typedAs.set(l, type);
|
|
529
|
+
try {
|
|
530
|
+
return this.expression(a, scope);
|
|
531
|
+
} finally {
|
|
532
|
+
for (const l of literals) this.typedAs.delete(l);
|
|
533
|
+
}
|
|
534
|
+
});
|
|
535
|
+
const inlined = this.inline(node, callee, scope, readArgs, (what) => this.fail(what, node));
|
|
536
|
+
if (inlined) return inlined;
|
|
753
537
|
}
|
|
754
|
-
if (!
|
|
755
|
-
|
|
756
|
-
if (!imp) return fail(`${arg.text} is not imported from the module (import it from ./${modulePath.split("/").pop()})`, arg);
|
|
757
|
-
if (!fromModule(imp)) return fail(`${arg.text} is imported from ${JSON.stringify(imp.from)}, not from the module beside this spec file`, arg);
|
|
758
|
-
if (imp.name === "*" || imp.name === "default") return fail(`${arg.text} must be a named import of the module's function`, arg);
|
|
759
|
-
return imp.name;
|
|
760
|
-
};
|
|
761
|
-
/** An arrow function: its params, body text and whether the body is a block. */
|
|
762
|
-
const arrow = (node, what) => {
|
|
763
|
-
if (!is.isArrowFunction(node)) return fail(`${what} must be an arrow function, found ${textOf(sf, node).split(/\s/)[0] ?? ""}`, node);
|
|
764
|
-
if (isAsync(node)) fail(`${what} is an async arrow; it must be synchronous`, node);
|
|
765
|
-
const params = node.parameters.map((p) => !p.dotDotDotToken && is.isIdentifier(p.name) ? p.name.text : null);
|
|
766
|
-
const body = node.body;
|
|
767
|
-
const line = lineAt(sf, node);
|
|
768
|
-
if (is.isBlock(body)) return {
|
|
769
|
-
arrow: {
|
|
770
|
-
params,
|
|
771
|
-
body: sf.text.slice(body.getStart(sf) + 1, body.end - 1),
|
|
772
|
-
block: true,
|
|
773
|
-
line
|
|
774
|
-
},
|
|
775
|
-
node
|
|
776
|
-
};
|
|
538
|
+
if (!this.names.declared(name)) this.identifier(callee, scope);
|
|
539
|
+
if (!this.names.callable(name)) this.fail(`a call to ${name}, which is outside the subset`, callee);
|
|
777
540
|
return {
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
}
|
|
784
|
-
node
|
|
541
|
+
kind: "call",
|
|
542
|
+
callee: this.names.target(name),
|
|
543
|
+
args: node.arguments.map((a) => {
|
|
544
|
+
if (is.isSpreadElement(a)) this.fail("a spread argument", a);
|
|
545
|
+
return this.expression(a, scope);
|
|
546
|
+
})
|
|
785
547
|
};
|
|
786
|
-
};
|
|
787
|
-
for (const st of sf.statements) {
|
|
788
|
-
if (!is.isVariableStatement(st)) continue;
|
|
789
|
-
const exported = isExported(st);
|
|
790
|
-
const constant = isConst(st.declarationList);
|
|
791
|
-
for (const d of st.declarationList.declarations) {
|
|
792
|
-
if (!is.isIdentifier(d.name) || !d.initializer) continue;
|
|
793
|
-
const name = d.name.text;
|
|
794
|
-
let init = d.initializer;
|
|
795
|
-
while (is.isParenthesizedExpression(init) || is.isSatisfiesExpression(init) || is.isAsExpression(init) || is.isNonNullExpression(init)) init = init.expression;
|
|
796
|
-
if (!is.isCallExpression(init)) continue;
|
|
797
|
-
const kind = combinator(init.expression);
|
|
798
|
-
if (!kind) continue;
|
|
799
|
-
const line = lineAt(sf, st);
|
|
800
|
-
try {
|
|
801
|
-
if (!exported) fail(`${name} is a spec but not exported, so nothing would check it`, st);
|
|
802
|
-
if (!constant) fail(`a spec must be a const export, not ${textOf(sf, st).split(/\s/)[exported ? 1 : 0] ?? "let"}`, st);
|
|
803
|
-
const [first, second, third] = init.arguments;
|
|
804
|
-
const fn = functionArg(first, init);
|
|
805
|
-
if (kind === "total") {
|
|
806
|
-
if (second) fail("total takes the function alone", second);
|
|
807
|
-
specs.push({
|
|
808
|
-
name,
|
|
809
|
-
kind: "total",
|
|
810
|
-
fn,
|
|
811
|
-
text: `total(${fn})`,
|
|
812
|
-
line,
|
|
813
|
-
hints: /* @__PURE__ */ new Map()
|
|
814
|
-
});
|
|
815
|
-
continue;
|
|
816
|
-
}
|
|
817
|
-
if (!second) return fail("forall takes the function, then { when, ensures }", init);
|
|
818
|
-
if (third) return fail(`unexpected ${textOf(sf, third)} after forall's arguments`, third);
|
|
819
|
-
if (!is.isObjectLiteralExpression(second)) return fail("forall's second argument must be an object literal { when, ensures }", second);
|
|
820
|
-
let sample;
|
|
821
|
-
let when;
|
|
822
|
-
let ensures;
|
|
823
|
-
for (const prop of second.properties) {
|
|
824
|
-
const key = is.isPropertyAssignment(prop) || is.isShorthandPropertyAssignment(prop) || is.isMethodDeclaration(prop) ? prop.name : void 0;
|
|
825
|
-
const keyName = key && is.isIdentifier(key) ? key.text : key ? textOf(sf, key) : textOf(sf, prop);
|
|
826
|
-
if (keyName !== "sample" && keyName !== "when" && keyName !== "ensures") fail(`forall's properties are sample, when and ensures, found ${keyName}`, prop);
|
|
827
|
-
if (!is.isPropertyAssignment(prop)) fail(`${keyName} must be written as ${keyName}: (…) => …`, prop);
|
|
828
|
-
const read = arrow(prop.initializer, keyName);
|
|
829
|
-
if (keyName === "sample") {
|
|
830
|
-
if (sample) fail("sample is given twice", prop);
|
|
831
|
-
sample = read;
|
|
832
|
-
} else if (keyName === "when") {
|
|
833
|
-
if (when) fail("when is given twice", prop);
|
|
834
|
-
when = read;
|
|
835
|
-
} else {
|
|
836
|
-
if (ensures) fail("ensures is given twice", prop);
|
|
837
|
-
ensures = read;
|
|
838
|
-
}
|
|
839
|
-
}
|
|
840
|
-
if (!ensures) return fail("forall needs an ensures", second);
|
|
841
|
-
const hintsOfArrow = (a) => a && !is.isBlock(a.node.body) ? hintsIn(sf, a.node.body, a.arrow.params) : /* @__PURE__ */ new Map();
|
|
842
|
-
const fromSample = hintsOfArrow(sample);
|
|
843
|
-
const fromWhen = hintsOfArrow(when);
|
|
844
|
-
const hints = /* @__PURE__ */ new Map();
|
|
845
|
-
for (const i of /* @__PURE__ */ new Set([...fromSample.keys(), ...fromWhen.keys()])) {
|
|
846
|
-
const h = combineHints(fromWhen.get(i), fromSample.get(i));
|
|
847
|
-
if (h) hints.set(i, h);
|
|
848
|
-
}
|
|
849
|
-
specs.push({
|
|
850
|
-
name,
|
|
851
|
-
kind: "forall",
|
|
852
|
-
fn,
|
|
853
|
-
...sample ? { sample: sample.arrow } : {},
|
|
854
|
-
...when ? { when: when.arrow } : {},
|
|
855
|
-
ensures: ensures.arrow,
|
|
856
|
-
text: ensures.arrow.body.replace(/\s+/g, " ").trim(),
|
|
857
|
-
line,
|
|
858
|
-
hints
|
|
859
|
-
});
|
|
860
|
-
} catch (err) {
|
|
861
|
-
if (!(err instanceof SpecFail)) throw err;
|
|
862
|
-
errors.push({
|
|
863
|
-
line: err.line,
|
|
864
|
-
message: `${name}: ${err.message}`
|
|
865
|
-
});
|
|
866
|
-
}
|
|
867
|
-
}
|
|
868
548
|
}
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
}
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
if (!second) return first;
|
|
882
|
-
const integral = (e) => !/[.eE]/.test(e.value);
|
|
883
|
-
let order;
|
|
884
|
-
try {
|
|
885
|
-
if (integral(first) && integral(second)) {
|
|
886
|
-
const a = endpointBigInt(first.value);
|
|
887
|
-
const b = endpointBigInt(second.value);
|
|
888
|
-
order = a === b ? 0 : a > b ? 1 : -1;
|
|
889
|
-
} else {
|
|
890
|
-
const a = endpointNumber(first.value);
|
|
891
|
-
const b = endpointNumber(second.value);
|
|
892
|
-
if (Number.isNaN(a) || Number.isNaN(b)) return first;
|
|
893
|
-
order = a === b ? 0 : a > b ? 1 : -1;
|
|
549
|
+
/** `(a, b) => body` or `a => body`, an expression body only; the names it binds go into scope. */
|
|
550
|
+
callback(node, scope, arity, what) {
|
|
551
|
+
if (!is.isArrowFunction(node)) this.fail(`${what} takes an arrow function`, node);
|
|
552
|
+
const arrow = node;
|
|
553
|
+
if (isAsync(arrow)) this.fail(`an async callback in ${what}`, arrow);
|
|
554
|
+
const names = [];
|
|
555
|
+
for (const p of arrow.parameters) {
|
|
556
|
+
if (!is.isIdentifier(p.name)) this.fail(`a destructured parameter of ${what}'s callback`, p);
|
|
557
|
+
if (p.type) this.fail(`a type annotation on ${what}'s parameter`, p.type);
|
|
558
|
+
if (p.initializer) this.fail(`a default value on ${what}'s parameter`, p);
|
|
559
|
+
if (p.dotDotDotToken) this.fail(`a rest parameter on ${what}'s callback`, p);
|
|
560
|
+
names.push(p.name.text);
|
|
894
561
|
}
|
|
895
|
-
|
|
896
|
-
|
|
562
|
+
if (names.length === 0 || names.length > arity) this.fail(`${what} takes a callback of 1 to ${arity} parameter(s), given ${names.length}`, arrow);
|
|
563
|
+
for (const n of names) if (scope.has(n) || this.names.declared(n)) this.fail(`${what}'s parameter ${n} shadows a name already bound here`, arrow);
|
|
564
|
+
if (new Set(names).size !== names.length) this.fail(`${what}'s parameters repeat a name`, arrow);
|
|
565
|
+
if (is.isBlock(arrow.body)) this.fail(`a block body in ${what}'s callback (write an expression)`, arrow.body);
|
|
566
|
+
const inner = new Map(scope);
|
|
567
|
+
for (const n of names) inner.set(n, { kind: "null" });
|
|
568
|
+
return {
|
|
569
|
+
names,
|
|
570
|
+
body: this.expression(arrow.body, inner)
|
|
571
|
+
};
|
|
897
572
|
}
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
if (!first) return second;
|
|
908
|
-
if (!second) return first;
|
|
909
|
-
const lower = tighter(first.lower, second.lower, "lower");
|
|
910
|
-
const upper = tighter(first.upper, second.upper, "upper");
|
|
911
|
-
const regex = first.regex ?? second.regex;
|
|
912
|
-
return {
|
|
913
|
-
...first.integer || second.integer ? { integer: true } : {},
|
|
914
|
-
...lower ? { lower } : {},
|
|
915
|
-
...upper ? { upper } : {},
|
|
916
|
-
...regex ? { regex } : {}
|
|
917
|
-
};
|
|
918
|
-
}
|
|
919
|
-
/** Read a module and its spec file. */
|
|
920
|
-
function readSpecs(input) {
|
|
921
|
-
const modulePath = input.modulePath;
|
|
922
|
-
const specPath = input.specPath ?? modulePath.replace(/\.ts$/, ".props.ts");
|
|
923
|
-
return withProgram([{
|
|
924
|
-
path: modulePath,
|
|
925
|
-
text: input.module
|
|
926
|
-
}, {
|
|
927
|
-
path: specPath,
|
|
928
|
-
text: input.spec
|
|
929
|
-
}], ({ program, checker, file, parseError }) => {
|
|
930
|
-
const moduleError = parseError(modulePath);
|
|
931
|
-
const specError = parseError(specPath);
|
|
932
|
-
const errors = [];
|
|
933
|
-
if (moduleError) errors.push({
|
|
934
|
-
line: moduleError.line,
|
|
935
|
-
message: `the module could not be parsed: ${moduleError.message}`,
|
|
936
|
-
inModule: true
|
|
937
|
-
});
|
|
938
|
-
if (specError) errors.push({
|
|
939
|
-
line: specError.line,
|
|
940
|
-
message: `the spec file could not be parsed: ${specError.message}`
|
|
941
|
-
});
|
|
942
|
-
if (moduleError || specError) return {
|
|
943
|
-
functions: [],
|
|
944
|
-
errors
|
|
945
|
-
};
|
|
946
|
-
const moduleFile = file(modulePath);
|
|
947
|
-
const moduleSide = readModuleSide(moduleFile, checker);
|
|
948
|
-
const specSide = readSpecSide(file(specPath), program, modulePath, moduleFile.path, new Set(input.specSpecifiers ?? ["eutaxy/spec", "@eutaxy/spec"]));
|
|
949
|
-
errors.push(...moduleSide.errors, ...specSide.errors);
|
|
950
|
-
const imports = specSide.imports.flatMap((i) => {
|
|
951
|
-
const fn = moduleSide.exports.get(i.name);
|
|
952
|
-
return fn === void 0 ? [] : [{
|
|
953
|
-
local: i.local,
|
|
954
|
-
fn
|
|
955
|
-
}];
|
|
956
|
-
});
|
|
957
|
-
const byFunction = /* @__PURE__ */ new Map();
|
|
958
|
-
for (const s of specSide.specs) {
|
|
959
|
-
const local = moduleSide.exports.get(s.fn);
|
|
960
|
-
const decl = local === void 0 ? void 0 : moduleSide.declarations.get(local);
|
|
961
|
-
if (!decl) {
|
|
962
|
-
errors.push({
|
|
963
|
-
line: s.line,
|
|
964
|
-
message: `${s.name}: the module exports no function ${s.fn} whose parameters the reader can read (a function declaration or a const arrow)`
|
|
965
|
-
});
|
|
966
|
-
continue;
|
|
967
|
-
}
|
|
968
|
-
const entry = byFunction.get(s.fn) ?? {
|
|
969
|
-
decl,
|
|
970
|
-
properties: []
|
|
573
|
+
/** A method call on a list: slice(1), map, flatMap, every, some, reduce. */
|
|
574
|
+
method(node, list, name, scope) {
|
|
575
|
+
const args = node.arguments;
|
|
576
|
+
if (name === "slice") {
|
|
577
|
+
const [one, extra] = args;
|
|
578
|
+
if (!one || extra || !is.isNumericLiteral(one) || this.text(one) !== "1") this.fail("slice with an argument other than 1", one ?? node);
|
|
579
|
+
return {
|
|
580
|
+
kind: "tail",
|
|
581
|
+
list
|
|
971
582
|
};
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
583
|
+
}
|
|
584
|
+
if (name === "reduce") {
|
|
585
|
+
const [cb, init, extra] = args;
|
|
586
|
+
if (!cb || !init || extra) this.fail("reduce takes a callback and an initial value", node);
|
|
587
|
+
const { names, body } = this.callback(cb, scope, 2, "reduce");
|
|
588
|
+
if (names.length !== 2) this.fail("reduce takes a callback of (accumulator, item)", cb);
|
|
589
|
+
return {
|
|
590
|
+
kind: "fold",
|
|
591
|
+
list,
|
|
592
|
+
acc: names[0],
|
|
593
|
+
item: names[1],
|
|
594
|
+
body,
|
|
595
|
+
init: this.expression(init, scope)
|
|
596
|
+
};
|
|
597
|
+
}
|
|
598
|
+
const [cb, extra] = args;
|
|
599
|
+
if (!cb || extra) this.fail(`${name} takes one callback`, node);
|
|
600
|
+
const { names, body } = this.callback(cb, scope, 2, name);
|
|
601
|
+
return {
|
|
602
|
+
kind: "iterate",
|
|
603
|
+
op: name,
|
|
604
|
+
list,
|
|
605
|
+
item: names[0],
|
|
606
|
+
...names[1] === void 0 ? {} : { index: names[1] },
|
|
607
|
+
body
|
|
608
|
+
};
|
|
609
|
+
}
|
|
610
|
+
record(node, scope) {
|
|
611
|
+
const fields = [];
|
|
612
|
+
for (const p of node.properties) {
|
|
613
|
+
if (is.isSpreadAssignment(p)) this.fail("spread in a record literal", p);
|
|
614
|
+
if (is.isShorthandPropertyAssignment(p)) {
|
|
615
|
+
if (!is.isIdentifier(p.name)) this.fail(`a key that is not a name: ${this.text(p.name)}`, p.name);
|
|
616
|
+
const name = p.name.text;
|
|
617
|
+
if (name === "__proto__") this.fail("a __proto__ key, which sets the prototype, not a field", p);
|
|
618
|
+
if (!scope.has(name)) this.fail(`shorthand ${name} names nothing in scope`, p);
|
|
619
|
+
fields.push({
|
|
620
|
+
name,
|
|
621
|
+
value: {
|
|
622
|
+
kind: "var",
|
|
623
|
+
name
|
|
624
|
+
}
|
|
976
625
|
});
|
|
977
626
|
continue;
|
|
978
627
|
}
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
};
|
|
987
|
-
});
|
|
988
|
-
entry.properties.push({
|
|
989
|
-
name: s.name,
|
|
990
|
-
kind: s.kind,
|
|
991
|
-
binders,
|
|
992
|
-
...s.sample ? { sample: s.sample } : {},
|
|
993
|
-
...s.when ? { when: s.when } : {},
|
|
994
|
-
...s.ensures ? { ensures: s.ensures } : {},
|
|
995
|
-
imports,
|
|
996
|
-
text: s.text,
|
|
997
|
-
line: s.line
|
|
628
|
+
if (!is.isPropertyAssignment(p)) this.fail(`a method ${this.text(p).split("(")[0] ?? ""}`, p);
|
|
629
|
+
if (is.isComputedPropertyName(p.name)) this.fail("a computed key", p.name);
|
|
630
|
+
if (!is.isIdentifier(p.name)) this.fail(`a key that is not a name: ${this.text(p.name)}`, p.name);
|
|
631
|
+
if (p.name.text === "__proto__") this.fail("a __proto__ key, which sets the prototype, not a field", p.name);
|
|
632
|
+
fields.push({
|
|
633
|
+
name: p.name.text,
|
|
634
|
+
value: this.expression(p.initializer, scope)
|
|
998
635
|
});
|
|
999
|
-
byFunction.set(s.fn, entry);
|
|
1000
636
|
}
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
637
|
+
const type = this.typedAs.get(node) ?? this.types.contextual(node);
|
|
638
|
+
const literal = (fs) => ({
|
|
639
|
+
kind: "record",
|
|
640
|
+
fields: fs,
|
|
641
|
+
...type ? { type } : {}
|
|
642
|
+
});
|
|
643
|
+
const tag = type?.kind === "union" ? tagOf(type.name, this.ctx) : void 0;
|
|
644
|
+
const chosen = tag === void 0 ? void 0 : fields.find((f) => f.name === tag);
|
|
645
|
+
if (chosen?.value.kind === "cond") {
|
|
646
|
+
const split = (value) => value.kind === "cond" ? {
|
|
647
|
+
kind: "cond",
|
|
648
|
+
test: value.test,
|
|
649
|
+
ifTrue: split(value.ifTrue),
|
|
650
|
+
ifFalse: split(value.ifFalse)
|
|
651
|
+
} : literal(fields.map((f) => f === chosen ? {
|
|
652
|
+
name: f.name,
|
|
653
|
+
value
|
|
654
|
+
} : f));
|
|
655
|
+
return split(chosen.value);
|
|
656
|
+
}
|
|
657
|
+
return literal(fields);
|
|
658
|
+
}
|
|
659
|
+
};
|
|
1014
660
|
/**
|
|
1015
|
-
*
|
|
1016
|
-
*
|
|
1017
|
-
*
|
|
1018
|
-
*
|
|
1019
|
-
* methods and calls to the module's own functions. What a name stands
|
|
1020
|
-
* for comes from the scope (parameters and consts) and from `Names`: the
|
|
1021
|
-
* module's own functions when the text is the module, the spec file's
|
|
1022
|
-
* imports when it is an arrow. Anything else is `OutsideSubset` with the
|
|
1023
|
-
* construct named and its line.
|
|
661
|
+
* A `const` annotation inside a spec arrow, read from its syntax against
|
|
662
|
+
* the module's declared types: no compiler stands behind an arrow's
|
|
663
|
+
* text, so a name must be a record or union the module reads, and the
|
|
664
|
+
* forms are the primitives, `null`, literals, unions of those and arrays.
|
|
1024
665
|
*/
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
[SyntaxKind.GreaterThanToken]: ">",
|
|
1032
|
-
[SyntaxKind.GreaterThanEqualsToken]: ">=",
|
|
1033
|
-
[SyntaxKind.EqualsEqualsEqualsToken]: "===",
|
|
1034
|
-
[SyntaxKind.ExclamationEqualsEqualsToken]: "!==",
|
|
1035
|
-
[SyntaxKind.AmpersandAmpersandToken]: "&&",
|
|
1036
|
-
[SyntaxKind.BarBarToken]: "||"
|
|
1037
|
-
};
|
|
1038
|
-
const methods = /* @__PURE__ */ new Set([
|
|
1039
|
-
"slice",
|
|
1040
|
-
"map",
|
|
1041
|
-
"flatMap",
|
|
1042
|
-
"every",
|
|
1043
|
-
"some",
|
|
1044
|
-
"reduce"
|
|
1045
|
-
]);
|
|
1046
|
-
/** The reader of one text: a function body, or an arrow of the spec file. */
|
|
1047
|
-
var ExprReader = class {
|
|
1048
|
-
sf;
|
|
1049
|
-
names;
|
|
1050
|
-
types;
|
|
1051
|
-
ctx;
|
|
1052
|
-
/** The line a refusal reports for a node: the file's, or none for text whose position the caller knows. */
|
|
1053
|
-
lineOf;
|
|
1054
|
-
constructor(sf, names, types, ctx, lineOf = (node) => lineAt(sf, node)) {
|
|
1055
|
-
this.sf = sf;
|
|
1056
|
-
this.names = names;
|
|
1057
|
-
this.types = types;
|
|
1058
|
-
this.ctx = ctx;
|
|
1059
|
-
this.lineOf = lineOf;
|
|
666
|
+
function syntacticType(sf, node, records, unions, refuse) {
|
|
667
|
+
const go = (n) => syntacticType(sf, n, records, unions, refuse);
|
|
668
|
+
if (is.isParenthesizedTypeNode(node)) return go(node.type);
|
|
669
|
+
if (is.isTypeOperatorNode(node) && node.operator === SyntaxKind.ReadonlyKeyword) {
|
|
670
|
+
if (!is.isArrayTypeNode(node.type)) return refuse("readonly before a type that is not an array");
|
|
671
|
+
return go(node.type);
|
|
1060
672
|
}
|
|
1061
|
-
|
|
1062
|
-
|
|
673
|
+
if (is.isArrayTypeNode(node)) return {
|
|
674
|
+
kind: "list",
|
|
675
|
+
element: go(node.elementType)
|
|
676
|
+
};
|
|
677
|
+
if (node.kind === SyntaxKind.NumberKeyword) return { kind: "int" };
|
|
678
|
+
if (node.kind === SyntaxKind.BooleanKeyword) return { kind: "bool" };
|
|
679
|
+
if (node.kind === SyntaxKind.StringKeyword) return { kind: "string" };
|
|
680
|
+
if (node.kind === SyntaxKind.UndefinedKeyword) return refuse("undefined in a type (the subset has null)");
|
|
681
|
+
if (is.isLiteralTypeNode(node)) {
|
|
682
|
+
const lit = node.literal;
|
|
683
|
+
if (lit.kind === SyntaxKind.NullKeyword) return { kind: "null" };
|
|
684
|
+
if (lit.kind === SyntaxKind.TrueKeyword || lit.kind === SyntaxKind.FalseKeyword) return { kind: "bool" };
|
|
685
|
+
if (is.isStringLiteral(lit)) return { kind: "string" };
|
|
686
|
+
return refuse(`the literal type ${textOf(sf, node)}`);
|
|
1063
687
|
}
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
688
|
+
if (is.isTypeReferenceNode(node)) {
|
|
689
|
+
if (node.typeArguments) return refuse(`type ${textOf(sf, node)} (a generic type in an arrow's const)`);
|
|
690
|
+
if (!is.isIdentifier(node.typeName)) return refuse(`type ${textOf(sf, node)}`);
|
|
691
|
+
const name = node.typeName.text;
|
|
692
|
+
if (records.has(name)) return {
|
|
693
|
+
kind: "record",
|
|
694
|
+
name
|
|
695
|
+
};
|
|
696
|
+
if (unions.has(name)) return {
|
|
697
|
+
kind: "union",
|
|
698
|
+
name
|
|
699
|
+
};
|
|
700
|
+
return refuse(`type ${name} (the subset has number, boolean, string, null, and the module's own record types and unions)`);
|
|
1067
701
|
}
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
return
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
return
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
* A block's statements as one expression: `const` becomes `let`, `if (c)
|
|
1080
|
-
* return a; rest` a conditional, and the last statement must return:
|
|
1081
|
-
* every path ends in a `return`.
|
|
1082
|
-
*/
|
|
1083
|
-
block(statements, scope, end) {
|
|
1084
|
-
return this.statements(statements, 0, scope, end);
|
|
1085
|
-
}
|
|
1086
|
-
statements(statements, i, scope, end) {
|
|
1087
|
-
const s = statements[i];
|
|
1088
|
-
if (!s) this.fail("a path that does not return", end);
|
|
1089
|
-
if (is.isEmptyStatement(s)) return this.statements(statements, i + 1, scope, end);
|
|
1090
|
-
if (is.isVariableStatement(s)) {
|
|
1091
|
-
const list = s.declarationList;
|
|
1092
|
-
if (!isConst(list)) this.fail("a mutable binding (use const)", s);
|
|
1093
|
-
const [decl, second] = list.declarations;
|
|
1094
|
-
if (!decl || second) this.fail("several bindings in one const", s);
|
|
1095
|
-
if (!is.isIdentifier(decl.name)) this.fail("a destructured const", decl.name);
|
|
1096
|
-
const name = decl.name.text;
|
|
1097
|
-
if (this.names.declared(name)) this.fail(`const ${name} shadows the module's function ${name} in its block`, decl.name);
|
|
1098
|
-
if (scope.has(name)) this.fail(`const ${name} redeclares a name already bound here`, decl.name);
|
|
1099
|
-
const annotated = decl.type ? this.types.annotation(decl.type, this.refuseAt(decl.type)) : void 0;
|
|
1100
|
-
if (!decl.initializer) this.fail(`const ${name} without a value`, decl);
|
|
1101
|
-
const value = this.expression(decl.initializer, scope);
|
|
1102
|
-
const inner = new Map(scope);
|
|
1103
|
-
inner.set(name, annotated ?? { kind: "null" });
|
|
1104
|
-
return {
|
|
1105
|
-
kind: "let",
|
|
1106
|
-
name,
|
|
1107
|
-
value,
|
|
1108
|
-
body: this.statements(statements, i + 1, inner, end),
|
|
1109
|
-
...annotated ? { type: annotated } : {}
|
|
1110
|
-
};
|
|
1111
|
-
}
|
|
1112
|
-
if (is.isIfStatement(s)) {
|
|
1113
|
-
const test = this.expression(s.expression, scope);
|
|
1114
|
-
const then = this.branch(s.thenStatement, scope);
|
|
1115
|
-
if (s.elseStatement) {
|
|
1116
|
-
const otherwise = this.branch(s.elseStatement, scope);
|
|
1117
|
-
const after = statements[i + 1];
|
|
1118
|
-
if (after) this.fail("statements after an if/else that both return", after);
|
|
1119
|
-
return {
|
|
1120
|
-
kind: "cond",
|
|
1121
|
-
test,
|
|
1122
|
-
ifTrue: then,
|
|
1123
|
-
ifFalse: otherwise
|
|
1124
|
-
};
|
|
1125
|
-
}
|
|
1126
|
-
return {
|
|
1127
|
-
kind: "cond",
|
|
1128
|
-
test,
|
|
1129
|
-
ifTrue: then,
|
|
1130
|
-
ifFalse: this.statements(statements, i + 1, scope, end)
|
|
1131
|
-
};
|
|
1132
|
-
}
|
|
1133
|
-
if (is.isReturnStatement(s)) {
|
|
1134
|
-
const after = statements[i + 1];
|
|
1135
|
-
if (!s.expression && after) {
|
|
1136
|
-
const gap = this.sf.text.slice(s.getStart(this.sf) + 6, after.getStart(this.sf));
|
|
1137
|
-
if (/[\n\r\u2028\u2029]/.test(gap)) this.fail("a line break after return (JavaScript inserts a semicolon and returns undefined)", s);
|
|
1138
|
-
}
|
|
1139
|
-
const value = this.returned(s, scope);
|
|
1140
|
-
if (after) this.fail("statements after a return", after);
|
|
1141
|
-
return value;
|
|
1142
|
-
}
|
|
1143
|
-
if (is.isForStatement(s) || is.isForOfStatement(s) || is.isForInStatement(s) || is.isWhileStatement(s) || is.isDoStatement(s)) this.fail("a loop", s);
|
|
1144
|
-
if (is.isThrowStatement(s)) this.fail("throw", s);
|
|
1145
|
-
if (is.isSwitchStatement(s)) this.fail("switch", s);
|
|
1146
|
-
if (is.isTryStatement(s)) this.fail("try", s);
|
|
1147
|
-
if (is.isFunctionDeclaration(s)) this.fail("a nested function", s);
|
|
1148
|
-
this.fail(`statement starting with ${this.text(s).split(/\s/)[0] ?? kindName(s.kind)}`, s);
|
|
1149
|
-
}
|
|
1150
|
-
/** An `if` branch: `return e;` or `{ ...statements ending in return }`. */
|
|
1151
|
-
branch(s, scope) {
|
|
1152
|
-
if (is.isBlock(s)) return this.block(s.statements, scope, s);
|
|
1153
|
-
if (is.isReturnStatement(s)) return this.returned(s, scope);
|
|
1154
|
-
this.fail("an if branch that does not return", s);
|
|
1155
|
-
}
|
|
1156
|
-
/** `return e;`. A line break after `return` makes JavaScript return undefined: no value, refused. */
|
|
1157
|
-
returned(s, scope) {
|
|
1158
|
-
if (!s.expression) this.fail("a return without a value", s);
|
|
1159
|
-
return this.expression(s.expression, scope);
|
|
1160
|
-
}
|
|
1161
|
-
expression(node, scope) {
|
|
1162
|
-
if (is.isParenthesizedExpression(node)) return this.expression(node.expression, scope);
|
|
1163
|
-
if (is.isIdentifier(node)) return this.identifier(node, scope);
|
|
1164
|
-
if (is.isNumericLiteral(node)) {
|
|
1165
|
-
const raw = this.text(node);
|
|
1166
|
-
if (!/^[0-9](_?[0-9])*$/.test(raw)) this.fail(`the numeric literal ${raw} (integers in decimal only)`, node);
|
|
1167
|
-
return {
|
|
1168
|
-
kind: "int",
|
|
1169
|
-
value: raw.replace(/_/g, "")
|
|
1170
|
-
};
|
|
1171
|
-
}
|
|
1172
|
-
if (is.isBigIntLiteral(node)) this.fail(`the bigint literal ${this.text(node)}`, node);
|
|
1173
|
-
if (is.isStringLiteral(node)) {
|
|
1174
|
-
if (hasLoneSurrogate(node.text)) this.fail("a string literal with a lone surrogate, which Lean's strings cannot hold", node);
|
|
1175
|
-
return {
|
|
1176
|
-
kind: "string",
|
|
1177
|
-
value: node.text
|
|
1178
|
-
};
|
|
1179
|
-
}
|
|
1180
|
-
if (is.isNoSubstitutionTemplateLiteral(node) || is.isTemplateExpression(node)) this.fail("a template literal", node);
|
|
1181
|
-
if (is.isRegularExpressionLiteral(node)) this.fail("a regular expression", node);
|
|
1182
|
-
if (node.kind === SyntaxKind.TrueKeyword) return {
|
|
1183
|
-
kind: "bool",
|
|
1184
|
-
value: true
|
|
1185
|
-
};
|
|
1186
|
-
if (node.kind === SyntaxKind.FalseKeyword) return {
|
|
1187
|
-
kind: "bool",
|
|
1188
|
-
value: false
|
|
1189
|
-
};
|
|
1190
|
-
if (node.kind === SyntaxKind.NullKeyword) return { kind: "null" };
|
|
1191
|
-
if (is.isPrefixUnaryExpression(node)) {
|
|
1192
|
-
if (node.operator === SyntaxKind.ExclamationToken) return {
|
|
1193
|
-
kind: "not",
|
|
1194
|
-
operand: this.expression(node.operand, scope)
|
|
1195
|
-
};
|
|
1196
|
-
if (node.operator === SyntaxKind.MinusToken) {
|
|
1197
|
-
const operand = this.expression(node.operand, scope);
|
|
1198
|
-
return operand.kind === "int" ? {
|
|
1199
|
-
kind: "int",
|
|
1200
|
-
value: operand.value.startsWith("-") ? operand.value.slice(1) : `-${operand.value}`
|
|
1201
|
-
} : {
|
|
1202
|
-
kind: "neg",
|
|
1203
|
-
operand
|
|
1204
|
-
};
|
|
1205
|
-
}
|
|
1206
|
-
if (node.operator === SyntaxKind.PlusToken) this.fail("unary plus", node);
|
|
1207
|
-
this.fail(`the ${this.text(node).slice(0, 2)} operator`, node);
|
|
1208
|
-
}
|
|
1209
|
-
if (is.isPostfixUnaryExpression(node)) this.fail(`the ${this.text(node).slice(-2)} operator`, node);
|
|
1210
|
-
if (is.isTypeOfExpression(node)) this.fail("the typeof operator", node);
|
|
1211
|
-
if (is.isVoidExpression(node)) this.fail("the void operator", node);
|
|
1212
|
-
if (is.isAwaitExpression(node)) this.fail("the await operator", node);
|
|
1213
|
-
if (is.isNewExpression(node)) this.fail("the new operator", node);
|
|
1214
|
-
if (is.isDeleteExpression(node)) this.fail("the delete operator", node);
|
|
1215
|
-
if (is.isBinaryExpression(node)) return this.binary(node, scope);
|
|
1216
|
-
if (is.isConditionalExpression(node)) return {
|
|
1217
|
-
kind: "cond",
|
|
1218
|
-
test: this.expression(node.condition, scope),
|
|
1219
|
-
ifTrue: this.expression(node.whenTrue, scope),
|
|
1220
|
-
ifFalse: this.expression(node.whenFalse, scope)
|
|
702
|
+
if (is.isUnionTypeNode(node)) {
|
|
703
|
+
const members = node.types.map(go);
|
|
704
|
+
const nulls = members.filter((m) => m.kind === "null");
|
|
705
|
+
const rest = members.filter((m) => m.kind !== "null");
|
|
706
|
+
const first = rest[0];
|
|
707
|
+
if (!first) return refuse("null alone is not a type the subset takes");
|
|
708
|
+
if (!rest.every((m) => JSON.stringify(m) === JSON.stringify(first))) return refuse("a union of several types (declare it as a type alias in the module)");
|
|
709
|
+
if (nulls.length === 0) return first;
|
|
710
|
+
return first.kind === "nullable" ? first : {
|
|
711
|
+
kind: "nullable",
|
|
712
|
+
inner: first
|
|
1221
713
|
};
|
|
1222
|
-
if (is.isCallExpression(node)) return this.call(node, scope);
|
|
1223
|
-
if (is.isPropertyAccessExpression(node)) {
|
|
1224
|
-
if (node.questionDotToken) this.fail("optional chaining", node);
|
|
1225
|
-
if (!is.isIdentifier(node.name)) this.fail("a private field", node.name);
|
|
1226
|
-
return {
|
|
1227
|
-
kind: "field",
|
|
1228
|
-
object: this.expression(node.expression, scope),
|
|
1229
|
-
field: node.name.text
|
|
1230
|
-
};
|
|
1231
|
-
}
|
|
1232
|
-
if (is.isElementAccessExpression(node)) {
|
|
1233
|
-
if (this.isHead(node)) this.fail("xs[0] without ?? fallback (it is undefined on an empty list)", node);
|
|
1234
|
-
this.fail("index access other than xs[0] ?? fallback", node);
|
|
1235
|
-
}
|
|
1236
|
-
if (is.isObjectLiteralExpression(node)) return this.record(node, scope);
|
|
1237
|
-
if (is.isArrayLiteralExpression(node)) {
|
|
1238
|
-
const items = [];
|
|
1239
|
-
let rest;
|
|
1240
|
-
for (const item of node.elements) {
|
|
1241
|
-
if (rest) this.fail("a spread that is not last in an array literal", item);
|
|
1242
|
-
if (is.isSpreadElement(item)) rest = this.expression(item.expression, scope);
|
|
1243
|
-
else if (is.isOmittedExpression(item)) this.fail("a hole in an array literal", item);
|
|
1244
|
-
else items.push(this.expression(item, scope));
|
|
1245
|
-
}
|
|
1246
|
-
return {
|
|
1247
|
-
kind: "list",
|
|
1248
|
-
items,
|
|
1249
|
-
...rest ? { rest } : {}
|
|
1250
|
-
};
|
|
1251
|
-
}
|
|
1252
|
-
if (is.isArrowFunction(node) || is.isFunctionExpression(node)) this.fail("a function expression (the subset has callbacks of list methods only)", node);
|
|
1253
|
-
if (is.isAsExpression(node)) this.fail("the as operator", node);
|
|
1254
|
-
if (is.isSatisfiesExpression(node)) this.fail("the satisfies operator", node);
|
|
1255
|
-
if (is.isNonNullExpression(node)) this.fail("the ! assertion", node);
|
|
1256
|
-
if (is.isTypeAssertion(node)) this.fail("a type assertion", node);
|
|
1257
|
-
if (node.kind === SyntaxKind.ThisKeyword) this.fail("this", node);
|
|
1258
|
-
this.fail(`unexpected ${this.text(node) || kindName(node.kind)}`, node);
|
|
1259
714
|
}
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
715
|
+
return refuse(`type ${textOf(sf, node)}`);
|
|
716
|
+
}
|
|
717
|
+
/**
|
|
718
|
+
* The block body of an arrow read from a parsed fragment: the statements
|
|
719
|
+
* between the braces, every path returning.
|
|
720
|
+
*/
|
|
721
|
+
function blockOf(sf) {
|
|
722
|
+
const [first, second] = sf.statements;
|
|
723
|
+
return first && !second && is.isBlock(first) ? first : void 0;
|
|
724
|
+
}
|
|
725
|
+
// packages/prover/src/reader/types.ts
|
|
726
|
+
/** Levels of records and lists inside one another a type may hold before it is cut (a generic instantiating itself anew at each level never repeats). */
|
|
727
|
+
const maxDepth = 16;
|
|
728
|
+
/**
|
|
729
|
+
* Why an object type is not plain data, or undefined when it is: a class
|
|
730
|
+
* (an instance is more than its fields: nominal, with private ones), or an
|
|
731
|
+
* interface over a base the compiler could not resolve (it then shows the
|
|
732
|
+
* interface's own fields alone) or over a class.
|
|
733
|
+
*/
|
|
734
|
+
function notPlain(checker, type, seen = /* @__PURE__ */ new Set()) {
|
|
735
|
+
const symbol = type.getSymbol();
|
|
736
|
+
if (!symbol || seen.has(type.id)) return void 0;
|
|
737
|
+
seen.add(type.id);
|
|
738
|
+
if ((symbol.flags & SymbolFlags.Class) !== 0) return "a class (an instance is more than a record of its fields)";
|
|
739
|
+
if ((symbol.flags & SymbolFlags.Interface) === 0) return void 0;
|
|
740
|
+
for (const handle of symbol.declarations) {
|
|
741
|
+
if (handle.kind !== SyntaxKind.InterfaceDeclaration) continue;
|
|
742
|
+
const decl = handle.resolve();
|
|
743
|
+
if (!decl || !is.isInterfaceDeclaration(decl)) continue;
|
|
744
|
+
for (const clause of decl.heritageClauses ?? []) for (const base of clause.types) {
|
|
745
|
+
const baseType = checker.getTypeAtLocation(base);
|
|
746
|
+
if (baseType.isErrorType()) return `extends ${base.getText()}, which does not resolve`;
|
|
747
|
+
const why = notPlain(checker, baseType, seen);
|
|
748
|
+
if (why !== void 0) return `extends ${base.getText()}: ${why}`;
|
|
749
|
+
}
|
|
1268
750
|
}
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
751
|
+
}
|
|
752
|
+
/** A type as the compiler prints it, in full. */
|
|
753
|
+
function printType(checker, type) {
|
|
754
|
+
return checker.typeToString(type, void 0, TypeFormatFlags.NoTruncation);
|
|
755
|
+
}
|
|
756
|
+
/**
|
|
757
|
+
* The name a record or union goes by: its alias or interface name when
|
|
758
|
+
* declared without type arguments, otherwise the type as the compiler
|
|
759
|
+
* prints it (`Result<true, Locked>`, `{ readonly ok: boolean; }`).
|
|
760
|
+
*/
|
|
761
|
+
function nameOfType(checker, type) {
|
|
762
|
+
const alias = type.getAliasSymbol();
|
|
763
|
+
if (alias) return type.getAliasTypeArguments().length === 0 ? alias.name : printType(checker, type);
|
|
764
|
+
const symbol = type.getSymbol();
|
|
765
|
+
if (symbol && (symbol.flags & (SymbolFlags.Interface | SymbolFlags.Class)) !== 0 && !(type.isTypeReference() && checker.getTypeArguments(type).length > 0)) return symbol.name;
|
|
766
|
+
return printType(checker, type);
|
|
767
|
+
}
|
|
768
|
+
/** A union's members with `true | false` folded back into `boolean`, which the compiler keeps apart. */
|
|
769
|
+
function foldBooleans(members) {
|
|
770
|
+
const isTrue = (t) => t.isBooleanLiteralType() && t.value === true;
|
|
771
|
+
const isFalse = (t) => t.isBooleanLiteralType() && t.value === false;
|
|
772
|
+
if (!members.some(isTrue) || !members.some(isFalse)) return [...members];
|
|
773
|
+
const out = [];
|
|
774
|
+
let folded = false;
|
|
775
|
+
for (const m of members) if (isTrue(m) || isFalse(m)) {
|
|
776
|
+
if (!folded) out.push("boolean");
|
|
777
|
+
folded = true;
|
|
778
|
+
} else out.push(m);
|
|
779
|
+
return out;
|
|
780
|
+
}
|
|
781
|
+
/** The members of a union as one type: flattened, deduplicated, one member alone. */
|
|
782
|
+
function unionOf(members) {
|
|
783
|
+
const flat = members.flatMap((m) => m.kind === "union" ? m.members : [m]);
|
|
784
|
+
const seen = /* @__PURE__ */ new Set();
|
|
785
|
+
const unique = flat.filter((m) => {
|
|
786
|
+
const key = JSON.stringify(m);
|
|
787
|
+
if (seen.has(key)) return false;
|
|
788
|
+
seen.add(key);
|
|
789
|
+
return true;
|
|
790
|
+
});
|
|
791
|
+
return unique.length === 1 ? unique[0] : {
|
|
792
|
+
kind: "union",
|
|
793
|
+
members: unique
|
|
794
|
+
};
|
|
795
|
+
}
|
|
796
|
+
/** A type into `SpecType`; what the spec surface does not describe is `unknown` with the type's text. */
|
|
797
|
+
function specTypeOf(checker, type, seen = /* @__PURE__ */ new Set()) {
|
|
798
|
+
const unknown = () => ({
|
|
799
|
+
kind: "unknown",
|
|
800
|
+
text: printType(checker, type)
|
|
801
|
+
});
|
|
802
|
+
const flags = type.flags;
|
|
803
|
+
if (type.isErrorType()) return unknown();
|
|
804
|
+
if (flags & TypeFlags.Number) return { kind: "number" };
|
|
805
|
+
if (flags & TypeFlags.String) return { kind: "string" };
|
|
806
|
+
if (flags & TypeFlags.Boolean) return { kind: "boolean" };
|
|
807
|
+
if (flags & TypeFlags.BigInt) return { kind: "bigint" };
|
|
808
|
+
if (type.isStringLiteralType() || type.isNumberLiteralType() || type.isBooleanLiteralType()) return {
|
|
809
|
+
kind: "literal",
|
|
810
|
+
value: type.value
|
|
811
|
+
};
|
|
812
|
+
if (flags & TypeFlags.Null) return { kind: "null" };
|
|
813
|
+
if (flags & (TypeFlags.Undefined | TypeFlags.Void)) return { kind: "undefined" };
|
|
814
|
+
if (type.isUnionType()) return unionOf(foldBooleans(type.getTypes()).map((m) => m === "boolean" ? { kind: "boolean" } : specTypeOf(checker, m, seen)));
|
|
815
|
+
if (!type.isObjectType()) return unknown();
|
|
816
|
+
if (seen.has(type.id) || seen.size >= maxDepth) return unknown();
|
|
817
|
+
const inner = new Set(seen).add(type.id);
|
|
818
|
+
if (checker.isArrayType(type)) {
|
|
819
|
+
const element = checker.getTypeArguments(type)[0];
|
|
820
|
+
return element ? {
|
|
821
|
+
kind: "array",
|
|
822
|
+
element: specTypeOf(checker, element, inner)
|
|
823
|
+
} : unknown();
|
|
1272
824
|
}
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
825
|
+
if (type.isTupleType() || type.getCallSignatures().length > 0 || type.getConstructSignatures().length > 0 || type.getIndexInfos().length > 0) return unknown();
|
|
826
|
+
if (notPlain(checker, type) !== void 0) return unknown();
|
|
827
|
+
const properties = type.getProperties();
|
|
828
|
+
const computed = SymbolFlags.Method | SymbolFlags.GetAccessor | SymbolFlags.SetAccessor;
|
|
829
|
+
if (properties.some((p) => (p.flags & computed) !== 0 || isSymbolKey(p.name))) return unknown();
|
|
830
|
+
const fields = properties.map((p) => ({
|
|
831
|
+
name: p.name,
|
|
832
|
+
type: specTypeOf(checker, checker.getTypeOfSymbol(p), inner)
|
|
833
|
+
}));
|
|
834
|
+
return {
|
|
835
|
+
kind: "record",
|
|
836
|
+
name: nameOfType(checker, type),
|
|
837
|
+
fields
|
|
838
|
+
};
|
|
839
|
+
}
|
|
840
|
+
/** Whether a property's name is the compiler's spelling of a symbol key, which no string names. */
|
|
841
|
+
const isSymbolKey = (name) => name.startsWith("__@");
|
|
842
|
+
/** Names a Lean structure declaration generates itself, which a field cannot take. */
|
|
843
|
+
const structureNames = /* @__PURE__ */ new Set([
|
|
844
|
+
"mk",
|
|
845
|
+
"rec",
|
|
846
|
+
"recOn",
|
|
847
|
+
"casesOn",
|
|
848
|
+
"noConfusion",
|
|
849
|
+
"noConfusionType",
|
|
850
|
+
"injEq"
|
|
851
|
+
]);
|
|
852
|
+
/**
|
|
853
|
+
* The subset's types read from the compiler's, with every record and
|
|
854
|
+
* union met along the way kept by name, in the order met, for the engines
|
|
855
|
+
* to declare. One type is read once: a second meeting gives the same
|
|
856
|
+
* record, and so does another compiler type of the same name and the
|
|
857
|
+
* same fields (an inline type written twice). A type the subset does not
|
|
858
|
+
* take is refused with the construct named, and a read that is refused
|
|
859
|
+
* leaves nothing behind: whatever it registered on the way is taken back,
|
|
860
|
+
* so no record belongs to a union that was never declared.
|
|
861
|
+
*/
|
|
862
|
+
var SubsetTypes = class {
|
|
863
|
+
records = /* @__PURE__ */ new Map();
|
|
864
|
+
unions = [];
|
|
865
|
+
checker;
|
|
866
|
+
/** By the compiler's type id. */
|
|
867
|
+
byId = /* @__PURE__ */ new Map();
|
|
868
|
+
idOfName = /* @__PURE__ */ new Map();
|
|
869
|
+
/** Types being read now, to refuse a type that holds itself. */
|
|
870
|
+
reading = /* @__PURE__ */ new Set();
|
|
871
|
+
constructor(checker) {
|
|
872
|
+
this.checker = checker;
|
|
1297
873
|
}
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
if (
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
const [arg, extra] = node.arguments;
|
|
1309
|
-
if (!arg || extra) this.fail("Number.isInteger takes one argument", node);
|
|
1310
|
-
return {
|
|
1311
|
-
kind: "isInteger",
|
|
1312
|
-
operand: this.expression(arg, scope)
|
|
1313
|
-
};
|
|
1314
|
-
}
|
|
1315
|
-
const list = this.expression(receiver, scope);
|
|
1316
|
-
if (!methods.has(method)) this.fail(`the method ${method} (the subset has slice(1), map, flatMap, every, some and reduce)`, callee.name);
|
|
1317
|
-
return this.method(node, list, method, scope);
|
|
1318
|
-
}
|
|
1319
|
-
if (!is.isIdentifier(callee)) this.fail("a call to a computed callee", callee);
|
|
1320
|
-
const name = callee.text;
|
|
1321
|
-
if (scope.has(name)) this.fail(`a call to ${name}, which names a value here, not the module's function`, callee);
|
|
1322
|
-
if (!this.names.declared(name)) this.identifier(callee, scope);
|
|
1323
|
-
if (!this.names.callable(name)) this.fail(`a call to ${name}, which is outside the subset`, callee);
|
|
1324
|
-
return {
|
|
1325
|
-
kind: "call",
|
|
1326
|
-
callee: this.names.target(name),
|
|
1327
|
-
args: node.arguments.map((a) => {
|
|
1328
|
-
if (is.isSpreadElement(a)) this.fail("a spread argument", a);
|
|
1329
|
-
return this.expression(a, scope);
|
|
1330
|
-
})
|
|
874
|
+
/** The subset type of a compiler type, or a refusal, after which nothing of the read remains. */
|
|
875
|
+
of(type, refuse) {
|
|
876
|
+
const cached = this.byId.get(type.id);
|
|
877
|
+
if (cached) return cached;
|
|
878
|
+
if (this.reading.size > 0) return this.enter(type, refuse);
|
|
879
|
+
const saved = {
|
|
880
|
+
records: new Map(this.records),
|
|
881
|
+
idOfName: new Map(this.idOfName),
|
|
882
|
+
byId: new Map(this.byId),
|
|
883
|
+
unions: this.unions.length
|
|
1331
884
|
};
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
if (p.dotDotDotToken) this.fail(`a rest parameter on ${what}'s callback`, p);
|
|
1344
|
-
names.push(p.name.text);
|
|
885
|
+
try {
|
|
886
|
+
return this.enter(type, refuse);
|
|
887
|
+
} catch (err) {
|
|
888
|
+
this.records.clear();
|
|
889
|
+
for (const [k, v] of saved.records) this.records.set(k, v);
|
|
890
|
+
this.idOfName.clear();
|
|
891
|
+
for (const [k, v] of saved.idOfName) this.idOfName.set(k, v);
|
|
892
|
+
this.byId.clear();
|
|
893
|
+
for (const [k, v] of saved.byId) this.byId.set(k, v);
|
|
894
|
+
this.unions.length = saved.unions;
|
|
895
|
+
throw err;
|
|
1345
896
|
}
|
|
1346
|
-
if (names.length === 0 || names.length > arity) this.fail(`${what} takes a callback of 1 to ${arity} parameter(s), given ${names.length}`, arrow);
|
|
1347
|
-
for (const n of names) if (scope.has(n) || this.names.declared(n)) this.fail(`${what}'s parameter ${n} shadows a name already bound here`, arrow);
|
|
1348
|
-
if (new Set(names).size !== names.length) this.fail(`${what}'s parameters repeat a name`, arrow);
|
|
1349
|
-
if (is.isBlock(arrow.body)) this.fail(`a block body in ${what}'s callback (write an expression)`, arrow.body);
|
|
1350
|
-
const inner = new Map(scope);
|
|
1351
|
-
for (const n of names) inner.set(n, { kind: "null" });
|
|
1352
|
-
return {
|
|
1353
|
-
names,
|
|
1354
|
-
body: this.expression(arrow.body, inner)
|
|
1355
|
-
};
|
|
1356
897
|
}
|
|
1357
|
-
/** A
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
if (
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
898
|
+
/** A type read under the recursion guard. */
|
|
899
|
+
enter(type, refuse) {
|
|
900
|
+
if (this.reading.has(type.id)) return refuse(`${nameOfType(this.checker, type)} holds itself (a recursive type)`);
|
|
901
|
+
if (this.reading.size >= maxDepth) return refuse(`${nameOfType(this.checker, type)} is nested too deep (more than ${maxDepth} levels)`);
|
|
902
|
+
this.reading.add(type.id);
|
|
903
|
+
try {
|
|
904
|
+
const out = this.read(type, refuse);
|
|
905
|
+
this.byId.set(type.id, out);
|
|
906
|
+
return out;
|
|
907
|
+
} finally {
|
|
908
|
+
this.reading.delete(type.id);
|
|
1367
909
|
}
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
910
|
+
}
|
|
911
|
+
read(type, refuse) {
|
|
912
|
+
const checker = this.checker;
|
|
913
|
+
const text = () => printType(checker, type);
|
|
914
|
+
const flags = type.flags;
|
|
915
|
+
if (type.isErrorType()) return refuse(`type ${text()}, which does not resolve`);
|
|
916
|
+
if (flags & TypeFlags.Number) return { kind: "int" };
|
|
917
|
+
if (flags & (TypeFlags.String | TypeFlags.StringLiteral)) return { kind: "string" };
|
|
918
|
+
if (flags & (TypeFlags.Boolean | TypeFlags.BooleanLiteral)) return { kind: "bool" };
|
|
919
|
+
if (flags & TypeFlags.Null) return refuse("null alone is not a type the subset takes");
|
|
920
|
+
if (flags & (TypeFlags.Undefined | TypeFlags.Void)) return refuse("undefined in a type (the subset has null)");
|
|
921
|
+
if (flags & TypeFlags.NumberLiteral) return refuse(`the numeric literal type ${text()} (the subset has number)`);
|
|
922
|
+
if (flags & TypeFlags.BigInt) return refuse("bigint (the subset has number)");
|
|
923
|
+
if (flags & TypeFlags.TypeParameter) return refuse("type parameters");
|
|
924
|
+
if (type.isUnionType()) return this.union(type, refuse);
|
|
925
|
+
if (type.isIntersectionType()) return refuse("an intersection type");
|
|
926
|
+
if (!type.isObjectType()) return refuse(`type ${text()} (the subset has number, boolean, string, null, and record types, unions and arrays of them)`);
|
|
927
|
+
if (checker.isArrayType(type)) {
|
|
928
|
+
const element = checker.getTypeArguments(type)[0];
|
|
929
|
+
if (!element) return refuse(`type ${text()}`);
|
|
1373
930
|
return {
|
|
1374
|
-
kind: "
|
|
1375
|
-
|
|
1376
|
-
acc: names[0],
|
|
1377
|
-
item: names[1],
|
|
1378
|
-
body,
|
|
1379
|
-
init: this.expression(init, scope)
|
|
931
|
+
kind: "list",
|
|
932
|
+
element: this.of(element, refuse)
|
|
1380
933
|
};
|
|
1381
934
|
}
|
|
1382
|
-
|
|
1383
|
-
if (
|
|
1384
|
-
|
|
935
|
+
if (type.isTupleType()) return refuse("a tuple type");
|
|
936
|
+
if (type.getCallSignatures().length > 0 || type.getConstructSignatures().length > 0) return refuse("a function type");
|
|
937
|
+
if (type.getIndexInfos().length > 0) return refuse("an index signature");
|
|
938
|
+
const why = notPlain(checker, type);
|
|
939
|
+
if (why !== void 0) return refuse(`type ${text()} is outside the subset: ${why}`);
|
|
1385
940
|
return {
|
|
1386
|
-
kind: "
|
|
1387
|
-
|
|
1388
|
-
list,
|
|
1389
|
-
item: names[0],
|
|
1390
|
-
...names[1] === void 0 ? {} : { index: names[1] },
|
|
1391
|
-
body
|
|
941
|
+
kind: "record",
|
|
942
|
+
name: this.record(type, nameOfType(checker, type), refuse).name
|
|
1392
943
|
};
|
|
1393
944
|
}
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
if (!is.isPropertyAssignment(p)) this.fail(`a method ${this.text(p).split("(")[0] ?? ""}`, p);
|
|
1413
|
-
if (is.isComputedPropertyName(p.name)) this.fail("a computed key", p.name);
|
|
1414
|
-
if (!is.isIdentifier(p.name)) this.fail(`a key that is not a name: ${this.text(p.name)}`, p.name);
|
|
1415
|
-
if (p.name.text === "__proto__") this.fail("a __proto__ key, which sets the prototype, not a field", p.name);
|
|
1416
|
-
fields.push({
|
|
1417
|
-
name: p.name.text,
|
|
1418
|
-
value: this.expression(p.initializer, scope)
|
|
1419
|
-
});
|
|
1420
|
-
}
|
|
1421
|
-
const type = this.types.contextual(node);
|
|
945
|
+
/** A union: `T | null` a nullable, literals their base type, several records a tagged union. */
|
|
946
|
+
union(type, refuse) {
|
|
947
|
+
const members = type.isUnionType() ? type.getTypes() : [type];
|
|
948
|
+
if (members.some((m) => (m.flags & (TypeFlags.Undefined | TypeFlags.Void)) !== 0)) return refuse("undefined in a type (the subset has null)");
|
|
949
|
+
const nulls = members.filter((m) => (m.flags & TypeFlags.Null) !== 0);
|
|
950
|
+
const rest = members.filter((m) => (m.flags & TypeFlags.Null) === 0);
|
|
951
|
+
const bare = nulls.length === 0 ? type : type.getNonNullableType();
|
|
952
|
+
let base;
|
|
953
|
+
if (rest.length === 0) return refuse("null alone is not a type the subset takes");
|
|
954
|
+
else if (rest.every((m) => (m.flags & (TypeFlags.String | TypeFlags.StringLiteral)) !== 0)) base = { kind: "string" };
|
|
955
|
+
else if (rest.every((m) => (m.flags & (TypeFlags.Boolean | TypeFlags.BooleanLiteral)) !== 0)) base = { kind: "bool" };
|
|
956
|
+
else if (rest.length === 1) base = this.of(rest[0], refuse);
|
|
957
|
+
else if (rest.every((m) => m.isObjectType() && !this.checker.isArrayType(m))) base = this.taggedUnion(bare, rest, refuse);
|
|
958
|
+
else if (rest.some((m) => m.isObjectType())) return refuse("a union mixing records with other types");
|
|
959
|
+
else if (rest.every((m) => (m.flags & TypeFlags.NumberLiteral) !== 0)) return refuse(`the numeric literal type ${printType(this.checker, type)} (the subset has number)`);
|
|
960
|
+
else return refuse(`a union of several types (${printType(this.checker, type)}): the subset has a union of literals of one kind, a tagged union of records, and either with null`);
|
|
961
|
+
if (nulls.length === 0) return base;
|
|
962
|
+
if (base.kind === "nullable") return base;
|
|
1422
963
|
return {
|
|
1423
|
-
kind: "
|
|
1424
|
-
|
|
1425
|
-
...type ? { type } : {}
|
|
964
|
+
kind: "nullable",
|
|
965
|
+
inner: base
|
|
1426
966
|
};
|
|
1427
967
|
}
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
*
|
|
1431
|
-
*
|
|
1432
|
-
*
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
if (node.kind === SyntaxKind.UndefinedKeyword) return refuse("undefined in a type (the subset has null)");
|
|
1450
|
-
if (is.isLiteralTypeNode(node)) {
|
|
1451
|
-
const lit = node.literal;
|
|
1452
|
-
if (lit.kind === SyntaxKind.NullKeyword) return { kind: "null" };
|
|
1453
|
-
if (lit.kind === SyntaxKind.TrueKeyword || lit.kind === SyntaxKind.FalseKeyword) return { kind: "bool" };
|
|
1454
|
-
if (is.isStringLiteral(lit)) return { kind: "string" };
|
|
1455
|
-
return refuse(`the literal type ${textOf(sf, node)}`);
|
|
1456
|
-
}
|
|
1457
|
-
if (is.isTypeReferenceNode(node)) {
|
|
1458
|
-
if (node.typeArguments) return refuse(`type ${textOf(sf, node)} (a generic type in an arrow's const)`);
|
|
1459
|
-
if (!is.isIdentifier(node.typeName)) return refuse(`type ${textOf(sf, node)}`);
|
|
1460
|
-
const name = node.typeName.text;
|
|
1461
|
-
if (records.has(name)) return {
|
|
1462
|
-
kind: "record",
|
|
1463
|
-
name
|
|
968
|
+
/**
|
|
969
|
+
* A union of records, told apart by a tag: a literal-typed field every
|
|
970
|
+
* member has, holding a different literal in each. Members declared
|
|
971
|
+
* inline are named by the union and their tag (`Outcome.true`); a
|
|
972
|
+
* record declared on its own keeps its name, and may be a member of several unions.
|
|
973
|
+
*/
|
|
974
|
+
taggedUnion(type, members, refuse) {
|
|
975
|
+
const cached = this.byId.get(type.id);
|
|
976
|
+
if (cached) return cached;
|
|
977
|
+
const checker = this.checker;
|
|
978
|
+
const name = nameOfType(checker, type);
|
|
979
|
+
const taken = this.idOfName.get(name);
|
|
980
|
+
if (taken !== void 0 && taken !== type.id) return refuse(`two types named ${name}`);
|
|
981
|
+
if (taken === void 0 && (this.records.has(name) || this.unions.some((u) => u.name === name))) return refuse(`two types named ${name}`);
|
|
982
|
+
const literalFields = (m) => {
|
|
983
|
+
const out = /* @__PURE__ */ new Map();
|
|
984
|
+
for (const p of m.getProperties()) {
|
|
985
|
+
const t = checker.getTypeOfSymbol(p);
|
|
986
|
+
if (t.isStringLiteralType() || t.isBooleanLiteralType()) out.set(p.name, t.value);
|
|
987
|
+
}
|
|
988
|
+
return out;
|
|
1464
989
|
};
|
|
1465
|
-
|
|
990
|
+
const literals = members.map(literalFields);
|
|
991
|
+
const tag = [...literals[0].keys()].find((field) => literals.every((l) => l.has(field)) && new Set(literals.map((l) => JSON.stringify(l.get(field)))).size === literals.length);
|
|
992
|
+
if (tag === void 0) return refuse(`${name}: a union of records without a tag (a literal-typed field every member has, different in each)`);
|
|
993
|
+
const isAnonymous = (m) => !m.getAliasSymbol() && ((m.getSymbol()?.flags ?? 0) & (SymbolFlags.Interface | SymbolFlags.Class)) === 0;
|
|
994
|
+
const union = {
|
|
995
|
+
name,
|
|
996
|
+
tag,
|
|
997
|
+
members: members.map((m, i) => {
|
|
998
|
+
const value = literals[i].get(tag);
|
|
999
|
+
const memberName = isAnonymous(m) ? `${name}.${String(value)}` : nameOfType(checker, m);
|
|
1000
|
+
return {
|
|
1001
|
+
tag: value,
|
|
1002
|
+
record: this.record(m, memberName, refuse, name).name
|
|
1003
|
+
};
|
|
1004
|
+
})
|
|
1005
|
+
};
|
|
1006
|
+
this.unions.push(union);
|
|
1007
|
+
this.idOfName.set(name, type.id);
|
|
1008
|
+
const out = {
|
|
1466
1009
|
kind: "union",
|
|
1467
1010
|
name
|
|
1468
1011
|
};
|
|
1469
|
-
|
|
1012
|
+
this.byId.set(type.id, out);
|
|
1013
|
+
return out;
|
|
1470
1014
|
}
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1015
|
+
/** A record under `name`: its fields read, the record kept; a member of `union` when given. */
|
|
1016
|
+
record(type, name, refuse, union) {
|
|
1017
|
+
let known = this.records.get(name);
|
|
1018
|
+
if (!known && this.unions.some((u) => u.name === name)) return refuse(`two types named ${name}`);
|
|
1019
|
+
if (known && this.idOfName.get(name) !== type.id) {
|
|
1020
|
+
const fields = this.fieldsOf(type, name, refuse);
|
|
1021
|
+
if (JSON.stringify(fields) !== JSON.stringify(known.fields)) return refuse(`two types named ${name}`);
|
|
1022
|
+
this.byId.set(type.id, {
|
|
1023
|
+
kind: "record",
|
|
1024
|
+
name
|
|
1025
|
+
});
|
|
1026
|
+
}
|
|
1027
|
+
if (known) {
|
|
1028
|
+
if (union !== void 0 && !known.unions?.includes(union)) {
|
|
1029
|
+
known = {
|
|
1030
|
+
...known,
|
|
1031
|
+
unions: [...known.unions ?? [], union]
|
|
1032
|
+
};
|
|
1033
|
+
this.records.set(name, known);
|
|
1034
|
+
}
|
|
1035
|
+
return known;
|
|
1036
|
+
}
|
|
1037
|
+
const record = {
|
|
1038
|
+
name,
|
|
1039
|
+
fields: this.fieldsOf(type, name, refuse),
|
|
1040
|
+
...union === void 0 ? {} : { unions: [union] }
|
|
1482
1041
|
};
|
|
1042
|
+
this.records.set(name, record);
|
|
1043
|
+
this.idOfName.set(name, type.id);
|
|
1044
|
+
this.byId.set(type.id, {
|
|
1045
|
+
kind: "record",
|
|
1046
|
+
name
|
|
1047
|
+
});
|
|
1048
|
+
return record;
|
|
1483
1049
|
}
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1050
|
+
/** The fields of a record type, each a stored value the subset takes. */
|
|
1051
|
+
fieldsOf(type, name, refuse) {
|
|
1052
|
+
const guard = !this.reading.has(type.id);
|
|
1053
|
+
if (guard) this.reading.add(type.id);
|
|
1054
|
+
try {
|
|
1055
|
+
const checker = this.checker;
|
|
1056
|
+
const fields = [];
|
|
1057
|
+
const outside = (what) => refuse(`type ${name} is outside the subset: ${what}`);
|
|
1058
|
+
for (const p of type.getProperties()) {
|
|
1059
|
+
if (isSymbolKey(p.name)) return outside("a field keyed by a symbol");
|
|
1060
|
+
if ((p.flags & SymbolFlags.Optional) !== 0) return outside(`optional field ${p.name}`);
|
|
1061
|
+
if ((p.flags & SymbolFlags.Method) !== 0) return outside(`a method ${p.name}`);
|
|
1062
|
+
if ((p.flags & (SymbolFlags.GetAccessor | SymbolFlags.SetAccessor)) !== 0) return outside(`an accessor ${p.name}`);
|
|
1063
|
+
if (structureNames.has(p.name)) return outside(`field ${p.name} takes a name Lean's structures reserve`);
|
|
1064
|
+
if (p.name === "__proto__") return outside("a field named __proto__, which JavaScript treats specially");
|
|
1065
|
+
const fieldType = checker.getTypeOfSymbol(p);
|
|
1066
|
+
const read = this.of(fieldType, (what) => outside(`field ${p.name}: ${what}`));
|
|
1067
|
+
const literal = fieldType.isStringLiteralType() ? fieldType.value : fieldType.isBooleanLiteralType() ? fieldType.value : void 0;
|
|
1068
|
+
fields.push({
|
|
1069
|
+
name: p.name,
|
|
1070
|
+
type: read,
|
|
1071
|
+
...literal === void 0 ? {} : { literal }
|
|
1072
|
+
});
|
|
1073
|
+
}
|
|
1074
|
+
return fields;
|
|
1075
|
+
} finally {
|
|
1076
|
+
if (guard) this.reading.delete(type.id);
|
|
1077
|
+
}
|
|
1078
|
+
}
|
|
1079
|
+
};
|
|
1494
1080
|
// packages/prover/src/reader/subset.ts
|
|
1495
1081
|
var OutsideSubset = class extends Error {
|
|
1496
1082
|
line;
|
|
@@ -1499,6 +1085,14 @@ var OutsideSubset = class extends Error {
|
|
|
1499
1085
|
this.line = line;
|
|
1500
1086
|
}
|
|
1501
1087
|
};
|
|
1088
|
+
/** Whether a record is a member of a union. */
|
|
1089
|
+
function isMember(record, union) {
|
|
1090
|
+
return record?.unions?.includes(union) ?? false;
|
|
1091
|
+
}
|
|
1092
|
+
/** A union's members among the records known, in the order they were read. */
|
|
1093
|
+
function membersIn(union, ctx) {
|
|
1094
|
+
return [...ctx.records.values()].filter((rec) => isMember(rec, union));
|
|
1095
|
+
}
|
|
1502
1096
|
/** Whether a string holds a surrogate code unit without its pair: no Lean character corresponds to it. */
|
|
1503
1097
|
function hasLoneSurrogate(s) {
|
|
1504
1098
|
return /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/.test(s);
|
|
@@ -1523,7 +1117,7 @@ function fits(actual, expected, ctx) {
|
|
|
1523
1117
|
if (sameType(actual, expected)) return true;
|
|
1524
1118
|
if (actual.kind === "nothing") return true;
|
|
1525
1119
|
if (actual.kind === "list" && expected.kind === "list") return fits(actual.element, expected.element, ctx);
|
|
1526
|
-
if (expected.kind === "union") return actual.kind === "record" && ctx.records.get(actual.name)
|
|
1120
|
+
if (expected.kind === "union") return actual.kind === "record" && isMember(ctx.records.get(actual.name), expected.name);
|
|
1527
1121
|
if (expected.kind === "nullable") return actual.kind === "null" || (actual.kind === "nullable" ? fits(actual.inner, expected.inner, ctx) : fits(actual, expected.inner, ctx));
|
|
1528
1122
|
return false;
|
|
1529
1123
|
}
|
|
@@ -1539,10 +1133,11 @@ function join$1(a, b, ctx) {
|
|
|
1539
1133
|
};
|
|
1540
1134
|
}
|
|
1541
1135
|
if (a.kind === "record" && b.kind === "record") {
|
|
1542
|
-
const
|
|
1543
|
-
|
|
1136
|
+
const ub = ctx.records.get(b.name)?.unions ?? [];
|
|
1137
|
+
const common = (ctx.records.get(a.name)?.unions ?? []).filter((u) => ub.includes(u));
|
|
1138
|
+
if (common.length === 1) return {
|
|
1544
1139
|
kind: "union",
|
|
1545
|
-
name:
|
|
1140
|
+
name: common[0]
|
|
1546
1141
|
};
|
|
1547
1142
|
}
|
|
1548
1143
|
if (a.kind === "nullable" && b.kind === "nullable") {
|
|
@@ -1604,7 +1199,7 @@ function narrowsOf(test, holds) {
|
|
|
1604
1199
|
}
|
|
1605
1200
|
/** The field that tells a union's members apart: literal-typed in every member, with a different literal in each. */
|
|
1606
1201
|
function tagOf(union, ctx) {
|
|
1607
|
-
const members =
|
|
1202
|
+
const members = membersIn(union, ctx);
|
|
1608
1203
|
const first = members[0];
|
|
1609
1204
|
if (!first) return void 0;
|
|
1610
1205
|
return first.fields.filter((f) => f.literal !== void 0).map((f) => f.name).find((name) => {
|
|
@@ -1626,7 +1221,7 @@ function tagNarrowsOf(test, holds, scope, ctx) {
|
|
|
1626
1221
|
if (t?.kind !== "union" || tagOf(t.name, ctx) !== e.field) return void 0;
|
|
1627
1222
|
return {
|
|
1628
1223
|
name: e.object.name,
|
|
1629
|
-
members:
|
|
1224
|
+
members: membersIn(t.name, ctx)
|
|
1630
1225
|
};
|
|
1631
1226
|
};
|
|
1632
1227
|
const byTag = (read, tag, value, isIt) => {
|
|
@@ -1663,6 +1258,34 @@ function tagNarrowsOf(test, holds, scope, ctx) {
|
|
|
1663
1258
|
*/
|
|
1664
1259
|
function insertNarrows(e, scope, ctx, fail) {
|
|
1665
1260
|
const go = (x, sc) => insertNarrows(x, sc, ctx, fail);
|
|
1261
|
+
const probe = Symbol("untyped");
|
|
1262
|
+
const condition = (x, sc) => {
|
|
1263
|
+
if (x.kind === "binary" && (x.op === "&&" || x.op === "||")) return {
|
|
1264
|
+
...x,
|
|
1265
|
+
left: condition(x.left, sc),
|
|
1266
|
+
right: condition(x.right, sc)
|
|
1267
|
+
};
|
|
1268
|
+
if (x.kind === "not") return {
|
|
1269
|
+
kind: "not",
|
|
1270
|
+
operand: condition(x.operand, sc)
|
|
1271
|
+
};
|
|
1272
|
+
let t;
|
|
1273
|
+
try {
|
|
1274
|
+
t = typeOf(x, sc, ctx, () => {
|
|
1275
|
+
throw probe;
|
|
1276
|
+
});
|
|
1277
|
+
} catch (err) {
|
|
1278
|
+
if (err === probe) return x;
|
|
1279
|
+
throw err;
|
|
1280
|
+
}
|
|
1281
|
+
if (t.kind === "nullable" && (t.inner.kind === "record" || t.inner.kind === "union")) return {
|
|
1282
|
+
kind: "binary",
|
|
1283
|
+
op: "!==",
|
|
1284
|
+
left: x,
|
|
1285
|
+
right: { kind: "null" }
|
|
1286
|
+
};
|
|
1287
|
+
return x;
|
|
1288
|
+
};
|
|
1666
1289
|
const wrap = (body, test, holds, sc) => {
|
|
1667
1290
|
const inner = new Map(sc);
|
|
1668
1291
|
let out = body;
|
|
@@ -1696,9 +1319,13 @@ function insertNarrows(e, scope, ctx, fail) {
|
|
|
1696
1319
|
case "string":
|
|
1697
1320
|
case "null":
|
|
1698
1321
|
case "var": return e;
|
|
1322
|
+
case "not": return {
|
|
1323
|
+
kind: "not",
|
|
1324
|
+
operand: go(condition(e.operand, scope), scope)
|
|
1325
|
+
};
|
|
1699
1326
|
case "neg":
|
|
1700
|
-
case "
|
|
1701
|
-
case "
|
|
1327
|
+
case "isInteger":
|
|
1328
|
+
case "floor": return {
|
|
1702
1329
|
kind: e.kind,
|
|
1703
1330
|
operand: go(e.operand, scope)
|
|
1704
1331
|
};
|
|
@@ -1726,7 +1353,7 @@ function insertNarrows(e, scope, ctx, fail) {
|
|
|
1726
1353
|
};
|
|
1727
1354
|
}
|
|
1728
1355
|
case "cond": {
|
|
1729
|
-
const test = go(e.test, scope);
|
|
1356
|
+
const test = go(condition(e.test, scope), scope);
|
|
1730
1357
|
return {
|
|
1731
1358
|
kind: "cond",
|
|
1732
1359
|
test,
|
|
@@ -1850,7 +1477,7 @@ function foldScope(e, list, init, scope, ctx, fail) {
|
|
|
1850
1477
|
fail(`reduce's callback makes a ${describe(body)} from an accumulator of ${describe(start)}`);
|
|
1851
1478
|
}
|
|
1852
1479
|
/** The type of an expression in a scope; records are matched by their fields' names. */
|
|
1853
|
-
function typeOf(e, scope, ctx, fail) {
|
|
1480
|
+
function typeOf(e, scope, ctx, fail, expected) {
|
|
1854
1481
|
switch (e.kind) {
|
|
1855
1482
|
case "int": return { kind: "int" };
|
|
1856
1483
|
case "bool": return { kind: "bool" };
|
|
@@ -1865,17 +1492,17 @@ function typeOf(e, scope, ctx, fail) {
|
|
|
1865
1492
|
const t = scope.get(e.name);
|
|
1866
1493
|
if (!t) fail(`${e.name} is not in scope`);
|
|
1867
1494
|
if (t.kind !== "nullable") fail(`${e.name} is narrowed but is a ${describe(t)}, not a nullable`);
|
|
1868
|
-
return typeOf(e.body, new Map([...scope, [e.name, t.inner]]), ctx, fail);
|
|
1495
|
+
return typeOf(e.body, new Map([...scope, [e.name, t.inner]]), ctx, fail, expected);
|
|
1869
1496
|
}
|
|
1870
1497
|
case "narrowTag": {
|
|
1871
1498
|
const t = scope.get(e.name);
|
|
1872
1499
|
if (!t) fail(`${e.name} is not in scope`);
|
|
1873
1500
|
if (t.kind !== "union") fail(`${e.name} is narrowed by a tag but is a ${describe(t)}, not a union`);
|
|
1874
|
-
if (ctx.records.get(e.member)
|
|
1501
|
+
if (!isMember(ctx.records.get(e.member), t.name)) fail(`${e.member} is not a member of ${t.name}`);
|
|
1875
1502
|
return typeOf(e.body, new Map([...scope, [e.name, {
|
|
1876
1503
|
kind: "record",
|
|
1877
1504
|
name: e.member
|
|
1878
|
-
}]]), ctx, fail);
|
|
1505
|
+
}]]), ctx, fail, expected);
|
|
1879
1506
|
}
|
|
1880
1507
|
case "binary": {
|
|
1881
1508
|
const l = typeOf(e.left, scope, ctx, fail);
|
|
@@ -1885,6 +1512,7 @@ function typeOf(e, scope, ctx, fail) {
|
|
|
1885
1512
|
"+",
|
|
1886
1513
|
"-",
|
|
1887
1514
|
"*",
|
|
1515
|
+
"/",
|
|
1888
1516
|
"<",
|
|
1889
1517
|
"<=",
|
|
1890
1518
|
">",
|
|
@@ -1900,7 +1528,8 @@ function typeOf(e, scope, ctx, fail) {
|
|
|
1900
1528
|
return [
|
|
1901
1529
|
"+",
|
|
1902
1530
|
"-",
|
|
1903
|
-
"*"
|
|
1531
|
+
"*",
|
|
1532
|
+
"/"
|
|
1904
1533
|
].includes(e.op) ? { kind: "int" } : { kind: "bool" };
|
|
1905
1534
|
}
|
|
1906
1535
|
case "neg": {
|
|
@@ -1918,20 +1547,26 @@ function typeOf(e, scope, ctx, fail) {
|
|
|
1918
1547
|
if (t.kind !== "int") fail(`Number.isInteger on a ${t.kind}`);
|
|
1919
1548
|
return { kind: "bool" };
|
|
1920
1549
|
}
|
|
1550
|
+
case "floor": {
|
|
1551
|
+
const t = typeOf(e.operand, scope, ctx, fail);
|
|
1552
|
+
if (t.kind !== "int") fail(`Math.floor on a ${t.kind}`);
|
|
1553
|
+
return { kind: "int" };
|
|
1554
|
+
}
|
|
1921
1555
|
case "cond": {
|
|
1922
1556
|
const test = typeOf(e.test, scope, ctx, fail);
|
|
1923
1557
|
if (test.kind !== "bool") fail(`a condition that is a ${describe(test)} (truthiness is not in the subset; compare it)`);
|
|
1924
|
-
const a = typeOf(e.ifTrue, scope, ctx, fail);
|
|
1925
|
-
const b = typeOf(e.ifFalse, scope, ctx, fail);
|
|
1558
|
+
const a = typeOf(e.ifTrue, scope, ctx, fail, expected);
|
|
1559
|
+
const b = typeOf(e.ifFalse, scope, ctx, fail, expected);
|
|
1926
1560
|
const joined = join$1(a, b, ctx);
|
|
1927
|
-
if (
|
|
1928
|
-
return
|
|
1561
|
+
if (joined) return joined;
|
|
1562
|
+
if (expected && fits(a, expected, ctx) && fits(b, expected, ctx)) return expected;
|
|
1563
|
+
return fail(`the branches of a conditional have different types (${describe(a)} and ${describe(b)})`);
|
|
1929
1564
|
}
|
|
1930
1565
|
case "let": {
|
|
1931
|
-
const inferred = typeOf(e.value, scope, ctx, fail);
|
|
1566
|
+
const inferred = typeOf(e.value, scope, ctx, fail, e.type);
|
|
1932
1567
|
if (e.type && !fits(inferred, e.type, ctx)) fail(`const ${e.name} is annotated ${describe(e.type)} but holds a ${describe(inferred)}`);
|
|
1933
1568
|
if (!e.type && holdsNothing(inferred)) fail(`const ${e.name} holds an empty array of no declared type (annotate it: const ${e.name}: T[] = [])`);
|
|
1934
|
-
return typeOf(e.body, new Map([...scope, [e.name, e.type ?? inferred]]), ctx, fail);
|
|
1569
|
+
return typeOf(e.body, new Map([...scope, [e.name, e.type ?? inferred]]), ctx, fail, expected);
|
|
1935
1570
|
}
|
|
1936
1571
|
case "call": {
|
|
1937
1572
|
const sig = ctx.signatures.get(e.callee);
|
|
@@ -1939,7 +1574,7 @@ function typeOf(e, scope, ctx, fail) {
|
|
|
1939
1574
|
if (sig.params.length !== e.args.length) fail(`${e.callee} takes ${sig.params.length} argument(s), called with ${e.args.length}`);
|
|
1940
1575
|
e.args.forEach((a, i) => {
|
|
1941
1576
|
const want = sig.params[i]?.type;
|
|
1942
|
-
const got = typeOf(a, scope, ctx, fail);
|
|
1577
|
+
const got = typeOf(a, scope, ctx, fail, want);
|
|
1943
1578
|
if (!fits(got, want, ctx)) fail(`argument ${i + 1} of ${e.callee} is a ${describe(got)}, not the ${describe(want)} it takes`);
|
|
1944
1579
|
});
|
|
1945
1580
|
return sig.returns;
|
|
@@ -1953,7 +1588,7 @@ function typeOf(e, scope, ctx, fail) {
|
|
|
1953
1588
|
}
|
|
1954
1589
|
if (o.kind === "nullable") fail(`field ${e.field} read from a ${describe(o)}: compare it with null first, which narrows it`);
|
|
1955
1590
|
if (o.kind === "union") {
|
|
1956
|
-
const types =
|
|
1591
|
+
const types = membersIn(o.name, ctx).map((rec) => rec.fields.find((x) => x.name === e.field)?.type);
|
|
1957
1592
|
if (types.some((t) => t === void 0)) fail(`field ${e.field} is not on every member of ${o.name} (test the tag first, which narrows it)`);
|
|
1958
1593
|
const first = types[0];
|
|
1959
1594
|
if (!types.every((t) => sameType(t, first))) fail(`field ${e.field} has different types across the members of ${o.name}`);
|
|
@@ -1967,7 +1602,7 @@ function typeOf(e, scope, ctx, fail) {
|
|
|
1967
1602
|
case "record": {
|
|
1968
1603
|
const names = e.fields.map((f) => f.name).sort().join(",");
|
|
1969
1604
|
const context = e.type;
|
|
1970
|
-
const byNames = (context?.kind === "record" ? [...ctx.records.values()].filter((rec) => rec.name === context.name) : context?.kind === "union" ?
|
|
1605
|
+
const byNames = (context?.kind === "record" ? [...ctx.records.values()].filter((rec) => rec.name === context.name) : context?.kind === "union" ? membersIn(context.name, ctx) : [...ctx.records.values()]).filter((rec) => rec.fields.map((f) => f.name).sort().join(",") === names);
|
|
1971
1606
|
if (byNames.length === 0) fail(`a record literal with fields ${names} matches no declared record type`);
|
|
1972
1607
|
const types = new Map(e.fields.map((f) => [f.name, typeOf(f.value, scope, ctx, fail)]));
|
|
1973
1608
|
const fitting = byNames.filter((rec) => rec.fields.every((f) => fits(types.get(f.name), f.type, ctx)));
|
|
@@ -2047,7 +1682,8 @@ function boundNames(e, out = /* @__PURE__ */ new Set()) {
|
|
|
2047
1682
|
return boundNames(e.body, out);
|
|
2048
1683
|
case "neg":
|
|
2049
1684
|
case "not":
|
|
2050
|
-
case "isInteger":
|
|
1685
|
+
case "isInteger":
|
|
1686
|
+
case "floor": return boundNames(e.operand, out);
|
|
2051
1687
|
case "binary":
|
|
2052
1688
|
boundNames(e.left, out);
|
|
2053
1689
|
return boundNames(e.right, out);
|
|
@@ -2102,8 +1738,8 @@ function renameVars(e, names, taken = /* @__PURE__ */ new Set([
|
|
|
2102
1738
|
...names.keys(),
|
|
2103
1739
|
...names.values(),
|
|
2104
1740
|
...boundNames(e)
|
|
2105
|
-
])) {
|
|
2106
|
-
const go = (x) => renameVars(x, names, taken);
|
|
1741
|
+
]), avoid = /* @__PURE__ */ new Set()) {
|
|
1742
|
+
const go = (x) => renameVars(x, names, taken, avoid);
|
|
2107
1743
|
switch (e.kind) {
|
|
2108
1744
|
case "int":
|
|
2109
1745
|
case "bool":
|
|
@@ -2125,7 +1761,8 @@ function renameVars(e, names, taken = /* @__PURE__ */ new Set([
|
|
|
2125
1761
|
};
|
|
2126
1762
|
case "neg":
|
|
2127
1763
|
case "not":
|
|
2128
|
-
case "isInteger":
|
|
1764
|
+
case "isInteger":
|
|
1765
|
+
case "floor": return {
|
|
2129
1766
|
kind: e.kind,
|
|
2130
1767
|
operand: go(e.operand)
|
|
2131
1768
|
};
|
|
@@ -2162,7 +1799,7 @@ function renameVars(e, names, taken = /* @__PURE__ */ new Set([
|
|
|
2162
1799
|
const inner = new Map(names);
|
|
2163
1800
|
inner.delete(e.name);
|
|
2164
1801
|
let bound = e.name;
|
|
2165
|
-
if (new Set(names.values()).has(e.name)) {
|
|
1802
|
+
if ((/* @__PURE__ */ new Set([...names.values(), ...avoid])).has(e.name)) {
|
|
2166
1803
|
bound = fresh(e.name, taken);
|
|
2167
1804
|
inner.set(e.name, bound);
|
|
2168
1805
|
}
|
|
@@ -2170,7 +1807,7 @@ function renameVars(e, names, taken = /* @__PURE__ */ new Set([
|
|
|
2170
1807
|
...e,
|
|
2171
1808
|
name: bound,
|
|
2172
1809
|
value: go(e.value),
|
|
2173
|
-
body: renameVars(e.body, inner, /* @__PURE__ */ new Set([...taken, bound]))
|
|
1810
|
+
body: renameVars(e.body, inner, /* @__PURE__ */ new Set([...taken, bound]), avoid)
|
|
2174
1811
|
};
|
|
2175
1812
|
}
|
|
2176
1813
|
case "list": return {
|
|
@@ -2188,24 +1825,24 @@ function renameVars(e, names, taken = /* @__PURE__ */ new Set([
|
|
|
2188
1825
|
fallback: go(e.fallback)
|
|
2189
1826
|
};
|
|
2190
1827
|
case "iterate": {
|
|
2191
|
-
const { inner, bound, scoped } = bindAll([e.item, ...e.index === void 0 ? [] : [e.index]], names, taken);
|
|
1828
|
+
const { inner, bound, scoped } = bindAll([e.item, ...e.index === void 0 ? [] : [e.index]], names, taken, avoid);
|
|
2192
1829
|
return {
|
|
2193
1830
|
...e,
|
|
2194
1831
|
list: go(e.list),
|
|
2195
1832
|
item: bound[0],
|
|
2196
1833
|
...e.index === void 0 ? {} : { index: bound[1] },
|
|
2197
|
-
body: renameVars(e.body, inner, scoped)
|
|
1834
|
+
body: renameVars(e.body, inner, scoped, avoid)
|
|
2198
1835
|
};
|
|
2199
1836
|
}
|
|
2200
1837
|
case "fold": {
|
|
2201
|
-
const { inner, bound, scoped } = bindAll([e.acc, e.item], names, taken);
|
|
1838
|
+
const { inner, bound, scoped } = bindAll([e.acc, e.item], names, taken, avoid);
|
|
2202
1839
|
return {
|
|
2203
1840
|
...e,
|
|
2204
1841
|
list: go(e.list),
|
|
2205
1842
|
init: go(e.init),
|
|
2206
1843
|
acc: bound[0],
|
|
2207
1844
|
item: bound[1],
|
|
2208
|
-
body: renameVars(e.body, inner, scoped)
|
|
1845
|
+
body: renameVars(e.body, inner, scoped, avoid)
|
|
2209
1846
|
};
|
|
2210
1847
|
}
|
|
2211
1848
|
}
|
|
@@ -2215,9 +1852,9 @@ function renameVars(e, names, taken = /* @__PURE__ */ new Set([
|
|
|
2215
1852
|
* each shadows a rename of its own name, and one that is a rename's target
|
|
2216
1853
|
* moves to a fresh name so it captures nothing.
|
|
2217
1854
|
*/
|
|
2218
|
-
function bindAll(own, names, taken) {
|
|
1855
|
+
function bindAll(own, names, taken, avoid) {
|
|
2219
1856
|
const inner = new Map(names);
|
|
2220
|
-
const targets = new Set(names.values());
|
|
1857
|
+
const targets = /* @__PURE__ */ new Set([...names.values(), ...avoid]);
|
|
2221
1858
|
const scoped = new Set(taken);
|
|
2222
1859
|
return {
|
|
2223
1860
|
inner,
|
|
@@ -2244,7 +1881,8 @@ function callees(e, out = /* @__PURE__ */ new Set()) {
|
|
|
2244
1881
|
case "narrowTag": return callees(e.body, out);
|
|
2245
1882
|
case "neg":
|
|
2246
1883
|
case "not":
|
|
2247
|
-
case "isInteger":
|
|
1884
|
+
case "isInteger":
|
|
1885
|
+
case "floor": return callees(e.operand, out);
|
|
2248
1886
|
case "binary":
|
|
2249
1887
|
callees(e.left, out);
|
|
2250
1888
|
return callees(e.right, out);
|
|
@@ -2326,13 +1964,16 @@ function directEval(sf) {
|
|
|
2326
1964
|
visit(sf);
|
|
2327
1965
|
return line;
|
|
2328
1966
|
}
|
|
2329
|
-
|
|
1967
|
+
function isWrapper(n) {
|
|
1968
|
+
return is.isParenthesizedExpression(n) || is.isNonNullExpression(n) || is.isAsExpression(n) || is.isSatisfiesExpression(n) || is.isTypeAssertion(n);
|
|
1969
|
+
}
|
|
1970
|
+
/** Whether a node is written to: assigned, updated, or bound by a destructuring or a `for` head. */
|
|
2330
1971
|
function isWritten(node) {
|
|
2331
1972
|
let n = node;
|
|
2332
1973
|
for (;;) {
|
|
2333
1974
|
const p = n.parent;
|
|
2334
1975
|
if (!p) return false;
|
|
2335
|
-
if ((
|
|
1976
|
+
if (isWrapper(p) && p.expression === n) {
|
|
2336
1977
|
n = p;
|
|
2337
1978
|
continue;
|
|
2338
1979
|
}
|
|
@@ -2362,6 +2003,147 @@ function isWritten(node) {
|
|
|
2362
2003
|
return false;
|
|
2363
2004
|
}
|
|
2364
2005
|
}
|
|
2006
|
+
/** What every PROVEN rests on besides the engine's model: the reader's assumption about the built-ins. */
|
|
2007
|
+
const builtinsAssumption = "the built-ins the subset reads (Math, Number and the array methods) are the standard ones: a direct assignment to a global of the standard library or to a property of one, or through globalThis, self or window, in a read file is refused, but one made another way (Object.defineProperty, through an alias) or elsewhere (a polyfill, another module) is not seen";
|
|
2008
|
+
/** Names a file reaches the globals through that the library the reads compile against does not declare. */
|
|
2009
|
+
const globalObjects = /* @__PURE__ */ new Set([
|
|
2010
|
+
"globalThis",
|
|
2011
|
+
"self",
|
|
2012
|
+
"window",
|
|
2013
|
+
"global"
|
|
2014
|
+
]);
|
|
2015
|
+
/**
|
|
2016
|
+
* The first direct assignment (or `delete`) in a file whose target is a
|
|
2017
|
+
* global of the compiler's standard library or a property of one, at any
|
|
2018
|
+
* depth (`Math.floor = …`, `Number["isInteger"] = …`, `Array.prototype.map
|
|
2019
|
+
* = …`, `Math = …`), or anything under `globalThis`, `self`, `window` or
|
|
2020
|
+
* `global`, with its line; inside a function or not. The chain's root is
|
|
2021
|
+
* resolved by the compiler, so a local's `prototype` field is the local's.
|
|
2022
|
+
* What reaches a built-in another way (`Object.defineProperty`, an alias)
|
|
2023
|
+
* is not seen: `builtinsAssumption` says so.
|
|
2024
|
+
*/
|
|
2025
|
+
function rebound(sf, checker, standardGlobal) {
|
|
2026
|
+
let found;
|
|
2027
|
+
const globalObject = (r) => {
|
|
2028
|
+
if (!globalObjects.has(r.text)) return false;
|
|
2029
|
+
const decl = checker.getSymbolAtLocation(r)?.valueDeclaration?.resolve();
|
|
2030
|
+
if (!decl) return true;
|
|
2031
|
+
if (decl.kind === SyntaxKind.Parameter) return false;
|
|
2032
|
+
return !(is.isVariableDeclaration(decl) && decl.parent.parent.parent !== decl.getSourceFile());
|
|
2033
|
+
};
|
|
2034
|
+
const outermost = (node) => {
|
|
2035
|
+
let out = node;
|
|
2036
|
+
for (let p = out.parent; p && isWrapper(p) && p.expression === out; p = p.parent) out = p;
|
|
2037
|
+
return out;
|
|
2038
|
+
};
|
|
2039
|
+
const root = (node) => {
|
|
2040
|
+
let n = node;
|
|
2041
|
+
while (is.isPropertyAccessExpression(n) || is.isElementAccessExpression(n) || isWrapper(n)) n = n.expression;
|
|
2042
|
+
return n;
|
|
2043
|
+
};
|
|
2044
|
+
const builtin = (node) => {
|
|
2045
|
+
const r = root(node);
|
|
2046
|
+
return is.isIdentifier(r) && (globalObject(r) || standardGlobal(r));
|
|
2047
|
+
};
|
|
2048
|
+
const visit = (node) => {
|
|
2049
|
+
if (found) return;
|
|
2050
|
+
if ((is.isPropertyAccessExpression(node) || is.isElementAccessExpression(node) || is.isIdentifier(node)) && (isWritten(node) || is.isDeleteExpression(outermost(node).parent)) && builtin(node)) {
|
|
2051
|
+
found = {
|
|
2052
|
+
line: lineAt(sf, node),
|
|
2053
|
+
target: textOf(sf, node)
|
|
2054
|
+
};
|
|
2055
|
+
return;
|
|
2056
|
+
}
|
|
2057
|
+
node.forEachChild(visit);
|
|
2058
|
+
};
|
|
2059
|
+
visit(sf);
|
|
2060
|
+
return found;
|
|
2061
|
+
}
|
|
2062
|
+
/**
|
|
2063
|
+
* The first `@ts-ignore` or `@ts-expect-error` directive in a range of a
|
|
2064
|
+
* file, with its position: a comment shaped as the compiler reads one (the
|
|
2065
|
+
* directive opens a `//` comment, or the last line of a block comment),
|
|
2066
|
+
* found as the compiler finds comments, leading or trailing a node's
|
|
2067
|
+
* text, so the words in prose or in a string are not one. A comment
|
|
2068
|
+
* before a closing token alone (`/* … *\/ }`) is not seen; what it could
|
|
2069
|
+
* hide is on that token's line.
|
|
2070
|
+
*/
|
|
2071
|
+
function directiveIn(sf, start, end) {
|
|
2072
|
+
const text = sf.text;
|
|
2073
|
+
const singleLine = /^\/\/\/?\s*@ts-(ignore|expect-error)/;
|
|
2074
|
+
const lastLine = /^(?:\/|\*)*\s*@ts-(ignore|expect-error)/;
|
|
2075
|
+
let found;
|
|
2076
|
+
const check = (pos, commentEnd) => {
|
|
2077
|
+
if (found || pos < start || commentEnd > end) return;
|
|
2078
|
+
const comment = text.slice(pos, commentEnd);
|
|
2079
|
+
const m = comment.startsWith("//") ? singleLine.exec(comment) : lastLine.exec(comment.slice(comment.lastIndexOf("\n") + 1));
|
|
2080
|
+
if (m) found = {
|
|
2081
|
+
text: `@ts-${m[1]}`,
|
|
2082
|
+
pos
|
|
2083
|
+
};
|
|
2084
|
+
};
|
|
2085
|
+
const visit = (node) => {
|
|
2086
|
+
if (found || node.end < start || node.pos > end) return;
|
|
2087
|
+
forEachLeadingCommentRange(text, node.pos, check);
|
|
2088
|
+
forEachTrailingCommentRange(text, node.end, check);
|
|
2089
|
+
node.forEachChild(visit);
|
|
2090
|
+
};
|
|
2091
|
+
visit(sf);
|
|
2092
|
+
return found;
|
|
2093
|
+
}
|
|
2094
|
+
/**
|
|
2095
|
+
* The line of a `@ts-nocheck` directive at the top of a file, which turns
|
|
2096
|
+
* the compiler's checks off for all of it: as the compiler reads it, a
|
|
2097
|
+
* `//` comment opening with it, the last of it and `@ts-check` deciding.
|
|
2098
|
+
*/
|
|
2099
|
+
function noCheckDirective(sf) {
|
|
2100
|
+
const text = sf.text;
|
|
2101
|
+
const from = text.startsWith("#!") ? Math.max(0, text.indexOf("\n")) : 0;
|
|
2102
|
+
let line;
|
|
2103
|
+
forEachLeadingCommentRange(text, from, (pos, end) => {
|
|
2104
|
+
const m = /^\/\/\/?\s*@ts-(check|nocheck)\b/.exec(text.slice(pos, end));
|
|
2105
|
+
if (m) line = m[1] === "nocheck" ? sf.getLineAndCharacterOfPosition(pos).line + 1 : void 0;
|
|
2106
|
+
});
|
|
2107
|
+
return line;
|
|
2108
|
+
}
|
|
2109
|
+
/**
|
|
2110
|
+
* Why a range of a file is not read: the first error the compiler reports
|
|
2111
|
+
* inside it, or a `@ts-ignore` or `@ts-expect-error` directive in it or
|
|
2112
|
+
* in the leading comments (where a directive reaches the first line),
|
|
2113
|
+
* which hides one from the reader. Undefined when the range is clean.
|
|
2114
|
+
*/
|
|
2115
|
+
function notCompiled(sf, typeErrors, { start, end, lead }) {
|
|
2116
|
+
const error = typeErrors(sf.fileName).find((e) => e.pos < end && e.end > start);
|
|
2117
|
+
if (error) return {
|
|
2118
|
+
message: `the compiler reports an error: ${error.message}`,
|
|
2119
|
+
line: error.line
|
|
2120
|
+
};
|
|
2121
|
+
const silenced = (lead ? directiveIn(sf, lead.start, lead.end) : void 0) ?? directiveIn(sf, start, end);
|
|
2122
|
+
if (silenced) return {
|
|
2123
|
+
message: `a ${silenced.text} comment, which hides a compiler error from the reader`,
|
|
2124
|
+
line: sf.getLineAndCharacterOfPosition(silenced.pos).line + 1
|
|
2125
|
+
};
|
|
2126
|
+
}
|
|
2127
|
+
/**
|
|
2128
|
+
* Where a declared function's errors are looked for: its own declaration
|
|
2129
|
+
* (in a `const` list, a sibling's error, or a directive in a sibling's
|
|
2130
|
+
* body, is the sibling's), and for directives the statement's leading
|
|
2131
|
+
* comments too, since a directive above the statement reaches its first
|
|
2132
|
+
* line, siblings included.
|
|
2133
|
+
*/
|
|
2134
|
+
function rangeOf(d) {
|
|
2135
|
+
let declaration = d.node;
|
|
2136
|
+
while (!is.isFunctionDeclaration(declaration) && !is.isVariableDeclaration(declaration)) declaration = declaration.parent;
|
|
2137
|
+
const sf = d.statement.getSourceFile();
|
|
2138
|
+
return {
|
|
2139
|
+
start: declaration.pos,
|
|
2140
|
+
end: declaration.end,
|
|
2141
|
+
lead: {
|
|
2142
|
+
start: d.statement.pos,
|
|
2143
|
+
end: d.statement.getStart(sf)
|
|
2144
|
+
}
|
|
2145
|
+
};
|
|
2146
|
+
}
|
|
2365
2147
|
/**
|
|
2366
2148
|
* The declared functions the module assigns to anywhere, with the line
|
|
2367
2149
|
* of the first assignment: what runs under such a name may not be its
|
|
@@ -2374,7 +2156,7 @@ function assigned(sf, checker, declarations) {
|
|
|
2374
2156
|
const idOf = (name) => {
|
|
2375
2157
|
if (!symbolIds.has(name)) {
|
|
2376
2158
|
const decl = declarations.get(name);
|
|
2377
|
-
symbolIds.set(name, decl
|
|
2159
|
+
symbolIds.set(name, decl ? checker.getSymbolAtLocation(decl.name)?.id : void 0);
|
|
2378
2160
|
}
|
|
2379
2161
|
return symbolIds.get(name);
|
|
2380
2162
|
};
|
|
@@ -2390,27 +2172,35 @@ function assigned(sf, checker, declarations) {
|
|
|
2390
2172
|
visit(sf);
|
|
2391
2173
|
return out;
|
|
2392
2174
|
}
|
|
2393
|
-
/**
|
|
2394
|
-
function
|
|
2395
|
-
const sf = reader.sf;
|
|
2396
|
-
const name = decl.name.text;
|
|
2175
|
+
/** The parameter names of a function the subset can take at all: synchronous, no generator, plain parameters. */
|
|
2176
|
+
function shape(reader, decl) {
|
|
2397
2177
|
if (isAsync(decl)) reader.fail("an async function (core functions are synchronous)", decl);
|
|
2398
|
-
if (decl.asteriskToken) reader.fail("a generator function", decl);
|
|
2399
|
-
|
|
2400
|
-
const params = [];
|
|
2401
|
-
for (const p of decl.parameters) {
|
|
2178
|
+
if (!is.isArrowFunction(decl) && decl.asteriskToken) reader.fail("a generator function", decl);
|
|
2179
|
+
return decl.parameters.map((p) => {
|
|
2402
2180
|
if (!is.isIdentifier(p.name)) reader.fail("a destructured parameter", p);
|
|
2403
2181
|
const pname = p.name.text;
|
|
2404
2182
|
if (p.dotDotDotToken) reader.fail("a rest parameter", p);
|
|
2405
2183
|
if (pname === "this") reader.fail("a this parameter (the receiver is not modelled)", p);
|
|
2406
2184
|
if (p.questionToken) reader.fail(`optional parameter ${pname}`, p);
|
|
2407
|
-
if (!p.type) reader.fail(`parameter ${pname} without a type`, p);
|
|
2408
2185
|
if (p.initializer) reader.fail(`a default value for ${pname}`, p);
|
|
2409
|
-
|
|
2186
|
+
return pname;
|
|
2187
|
+
});
|
|
2188
|
+
}
|
|
2189
|
+
/** `export function name(params): Type {` or `export const name = (params): Type => …` read, the types through the compiler. */
|
|
2190
|
+
function head(reader, types, checker, d) {
|
|
2191
|
+
const sf = reader.sf;
|
|
2192
|
+
const decl = d.node;
|
|
2193
|
+
const name = d.name.text;
|
|
2194
|
+
const pnames = shape(reader, decl);
|
|
2195
|
+
if (decl.typeParameters) reader.fail("type parameters", decl.typeParameters[0] ?? decl);
|
|
2196
|
+
const params = decl.parameters.map((p, i) => {
|
|
2197
|
+
const pname = pnames[i];
|
|
2198
|
+
if (!p.type) reader.fail(`parameter ${pname} without a type`, p);
|
|
2199
|
+
return {
|
|
2410
2200
|
name: pname,
|
|
2411
2201
|
type: types.of(checker.getTypeAtLocation(p.type), reader.refuseAt(p.type))
|
|
2412
|
-
}
|
|
2413
|
-
}
|
|
2202
|
+
};
|
|
2203
|
+
});
|
|
2414
2204
|
if (!decl.type) reader.fail(`${name} without a return type (the subset needs it to name the record returned)`, decl);
|
|
2415
2205
|
const returns = types.of(checker.getTypeAtLocation(decl.type), reader.refuseAt(decl.type));
|
|
2416
2206
|
if (!decl.body) reader.fail("a function without a body", decl);
|
|
@@ -2421,7 +2211,7 @@ function head(reader, types, checker, decl) {
|
|
|
2421
2211
|
decl,
|
|
2422
2212
|
params,
|
|
2423
2213
|
returns,
|
|
2424
|
-
line: lineAt(sf,
|
|
2214
|
+
line: lineAt(sf, d.statement),
|
|
2425
2215
|
offset
|
|
2426
2216
|
};
|
|
2427
2217
|
}
|
|
@@ -2429,8 +2219,9 @@ function head(reader, types, checker, decl) {
|
|
|
2429
2219
|
function declaration(reader, h) {
|
|
2430
2220
|
const body = h.decl.body;
|
|
2431
2221
|
const scope = new Map(h.params.map((p) => [p.name, p.type]));
|
|
2432
|
-
const
|
|
2433
|
-
const
|
|
2222
|
+
const statements = is.isBlock(body) ? reader.block(body.statements, scope, body) : reader.expression(body, scope);
|
|
2223
|
+
const read = reader.narrowed(statements, scope, body);
|
|
2224
|
+
const actual = reader.typeOfExpr(read, scope, body, h.returns);
|
|
2434
2225
|
if (!fits(actual, h.returns, reader.ctx)) reader.fail(`${h.name} returns a ${describe(actual)} but declares ${describe(h.returns)}`, body);
|
|
2435
2226
|
return {
|
|
2436
2227
|
name: h.name,
|
|
@@ -2442,6 +2233,359 @@ function declaration(reader, h) {
|
|
|
2442
2233
|
};
|
|
2443
2234
|
}
|
|
2444
2235
|
/**
|
|
2236
|
+
* A file's top-level functions: declarations, and the arrows module-level
|
|
2237
|
+
* consts hold. A binding that may be reassigned (let, var) or holds a
|
|
2238
|
+
* function expression is listed, for its callers' typing, and untrusted;
|
|
2239
|
+
* so is every function of a file mentioning eval directly or assigning to
|
|
2240
|
+
* a built-in, and a function the file assigns to.
|
|
2241
|
+
*/
|
|
2242
|
+
function fileFunctions(sf, checker, standardGlobal) {
|
|
2243
|
+
const declarations = /* @__PURE__ */ new Map();
|
|
2244
|
+
const overloaded = /* @__PURE__ */ new Set();
|
|
2245
|
+
const untrusted = /* @__PURE__ */ new Map();
|
|
2246
|
+
const declare = (name, node, statement) => {
|
|
2247
|
+
if (declarations.has(name.text)) overloaded.add(name.text);
|
|
2248
|
+
else declarations.set(name.text, {
|
|
2249
|
+
name,
|
|
2250
|
+
node,
|
|
2251
|
+
statement
|
|
2252
|
+
});
|
|
2253
|
+
};
|
|
2254
|
+
for (const st of sf.statements) {
|
|
2255
|
+
if (is.isFunctionDeclaration(st)) {
|
|
2256
|
+
if (st.name) declare(st.name, st, st);
|
|
2257
|
+
continue;
|
|
2258
|
+
}
|
|
2259
|
+
if (!is.isVariableStatement(st)) continue;
|
|
2260
|
+
for (const d of st.declarationList.declarations) {
|
|
2261
|
+
if (!is.isIdentifier(d.name) || !d.initializer) continue;
|
|
2262
|
+
let init = d.initializer;
|
|
2263
|
+
while (is.isParenthesizedExpression(init)) init = init.expression;
|
|
2264
|
+
if (!is.isArrowFunction(init) && !is.isFunctionExpression(init)) continue;
|
|
2265
|
+
const name = d.name.text;
|
|
2266
|
+
declare(d.name, init, st);
|
|
2267
|
+
if (!isConst(st.declarationList)) untrusted.set(name, {
|
|
2268
|
+
name,
|
|
2269
|
+
line: lineAt(sf, st),
|
|
2270
|
+
message: `${name} is declared with let or var, so what runs under its name may be another function`
|
|
2271
|
+
});
|
|
2272
|
+
else if (is.isFunctionExpression(init)) untrusted.set(name, {
|
|
2273
|
+
name,
|
|
2274
|
+
line: lineAt(sf, st),
|
|
2275
|
+
message: `${name} holds a function expression (write a function declaration or an arrow)`
|
|
2276
|
+
});
|
|
2277
|
+
}
|
|
2278
|
+
}
|
|
2279
|
+
const evalLine = directEval(sf);
|
|
2280
|
+
const noCheck = noCheckDirective(sf);
|
|
2281
|
+
const patched = rebound(sf, checker, standardGlobal);
|
|
2282
|
+
const tainted = evalLine !== void 0 ? {
|
|
2283
|
+
line: evalLine,
|
|
2284
|
+
message: "the module mentions eval directly, which can rebind any of its declarations"
|
|
2285
|
+
} : noCheck !== void 0 ? {
|
|
2286
|
+
line: noCheck,
|
|
2287
|
+
message: "its file has a @ts-nocheck comment, which turns off the compiler's checks the reader relies on"
|
|
2288
|
+
} : patched !== void 0 ? {
|
|
2289
|
+
line: patched.line,
|
|
2290
|
+
message: `its file assigns to ${patched.target} (line ${patched.line}), so the built-ins its functions use may not be the standard ones`
|
|
2291
|
+
} : void 0;
|
|
2292
|
+
if (tainted) for (const name of declarations.keys()) untrusted.set(name, {
|
|
2293
|
+
name,
|
|
2294
|
+
...tainted
|
|
2295
|
+
});
|
|
2296
|
+
for (const [name, line] of assigned(sf, checker, declarations)) if (!untrusted.has(name)) untrusted.set(name, {
|
|
2297
|
+
name,
|
|
2298
|
+
line,
|
|
2299
|
+
message: `${name} is assigned in the module, so what runs under its name may not be its declaration`
|
|
2300
|
+
});
|
|
2301
|
+
return {
|
|
2302
|
+
declarations,
|
|
2303
|
+
overloaded,
|
|
2304
|
+
untrusted,
|
|
2305
|
+
...tainted ? { tainted } : {}
|
|
2306
|
+
};
|
|
2307
|
+
}
|
|
2308
|
+
/**
|
|
2309
|
+
* Bind the type parameters in `declared` so that it is `expected`, or a
|
|
2310
|
+
* member of `expected` when that is a union: a parameter binds to what it
|
|
2311
|
+
* meets, and two instantiations of one alias match argument by argument.
|
|
2312
|
+
* Returns the type matched (the union member, say), or undefined, with
|
|
2313
|
+
* `bound` unchanged by a member that did not match.
|
|
2314
|
+
*/
|
|
2315
|
+
function match(declared, expected, bound) {
|
|
2316
|
+
if (declared.isTypeParameter()) {
|
|
2317
|
+
const had = bound.get(declared.id);
|
|
2318
|
+
if (had && had.id !== expected.id) return void 0;
|
|
2319
|
+
bound.set(declared.id, expected);
|
|
2320
|
+
return expected;
|
|
2321
|
+
}
|
|
2322
|
+
const alias = declared.getAliasSymbol();
|
|
2323
|
+
const other = expected.getAliasSymbol();
|
|
2324
|
+
if (alias && other && alias.id === other.id) {
|
|
2325
|
+
const xs = declared.getAliasTypeArguments();
|
|
2326
|
+
const ys = expected.getAliasTypeArguments();
|
|
2327
|
+
if (xs.length !== ys.length) return void 0;
|
|
2328
|
+
const trial = new Map(bound);
|
|
2329
|
+
for (let i = 0; i < xs.length; i++) if (!match(xs[i], ys[i], trial)) return void 0;
|
|
2330
|
+
for (const [k, v] of trial) bound.set(k, v);
|
|
2331
|
+
return expected;
|
|
2332
|
+
}
|
|
2333
|
+
if (expected.isUnionType()) for (const member of expected.getTypes()) {
|
|
2334
|
+
const trial = new Map(bound);
|
|
2335
|
+
if (match(declared, member, trial)) {
|
|
2336
|
+
for (const [k, v] of trial) bound.set(k, v);
|
|
2337
|
+
return member;
|
|
2338
|
+
}
|
|
2339
|
+
}
|
|
2340
|
+
}
|
|
2341
|
+
/**
|
|
2342
|
+
* Calls to functions the module cannot name as its own, read inlined: a
|
|
2343
|
+
* generic function (of the module or not) at the call's instantiation,
|
|
2344
|
+
* and a function of another file, as the compiler resolves the import.
|
|
2345
|
+
* The callee's body is read in its own file under the parameter types the
|
|
2346
|
+
* call's resolved signature gives, its literals typed by the resolved
|
|
2347
|
+
* return type, its names moved away from the caller's, and bound by `let`
|
|
2348
|
+
* to the arguments in order: a pure function called by value computes
|
|
2349
|
+
* exactly that. The callee's own calls inline the same way, so the
|
|
2350
|
+
* helpers of its file come with it. A callee with no body here (a
|
|
2351
|
+
* declaration file), one its file may rebind, or one reached again while
|
|
2352
|
+
* it is being inlined (recursion) is outside the subset, with why.
|
|
2353
|
+
*/
|
|
2354
|
+
function inliner(c) {
|
|
2355
|
+
const files = /* @__PURE__ */ new Map([[c.module, c.own]]);
|
|
2356
|
+
const functionsOf = (file) => {
|
|
2357
|
+
let found = files.get(file);
|
|
2358
|
+
if (!found) {
|
|
2359
|
+
found = fileFunctions(file, c.checker, c.standardGlobal);
|
|
2360
|
+
files.set(file, found);
|
|
2361
|
+
}
|
|
2362
|
+
return found;
|
|
2363
|
+
};
|
|
2364
|
+
const vetted = /* @__PURE__ */ new Map();
|
|
2365
|
+
const vet = (file, key, range) => {
|
|
2366
|
+
if (!vetted.has(key)) vetted.set(key, notCompiled(file, c.typeErrors, range));
|
|
2367
|
+
return vetted.get(key);
|
|
2368
|
+
};
|
|
2369
|
+
const inlining = [];
|
|
2370
|
+
const substitutions = [];
|
|
2371
|
+
const concrete = (t) => {
|
|
2372
|
+
const top = substitutions[substitutions.length - 1];
|
|
2373
|
+
return top && t.isTypeParameter() ? top.get(t.id) ?? t : t;
|
|
2374
|
+
};
|
|
2375
|
+
const inline = (call, callee, scope, readArgs, fail) => {
|
|
2376
|
+
const caller = call.getSourceFile();
|
|
2377
|
+
const start = call.getStart(caller);
|
|
2378
|
+
if (c.typeErrors(caller.fileName).some((e) => e.pos < call.end && e.end > start)) fail(`the compiler reports an error on this call to ${callee.text}`);
|
|
2379
|
+
let symbol = c.checker.getSymbolAtLocation(callee);
|
|
2380
|
+
if (!symbol) return void 0;
|
|
2381
|
+
if (symbol.flags & SymbolFlags.Alias) symbol = c.checker.getAliasedSymbol(symbol);
|
|
2382
|
+
const decl = symbol.valueDeclaration?.resolve();
|
|
2383
|
+
if (!decl || !(is.isFunctionDeclaration(decl) || is.isVariableDeclaration(decl))) return void 0;
|
|
2384
|
+
const file = decl.getSourceFile();
|
|
2385
|
+
const name = decl.name && is.isIdentifier(decl.name) ? decl.name.text : symbol.name;
|
|
2386
|
+
const where = file === c.module ? name : `${name} (from ${file.fileName})`;
|
|
2387
|
+
if (file.isDeclarationFile) fail(`${where} has no body to read: it is declared in a declaration file`);
|
|
2388
|
+
const fns = functionsOf(file);
|
|
2389
|
+
const d = fns.declarations.get(name);
|
|
2390
|
+
if (!d || !decl.name || d.name.pos !== decl.name.pos) return void 0;
|
|
2391
|
+
if (c.parseError(file.fileName)) fail(`${where} is in a file the compiler cannot parse`);
|
|
2392
|
+
const untrusted = fns.untrusted.get(name);
|
|
2393
|
+
if (untrusted) fail(`${where} is outside the subset: ${untrusted.message}`);
|
|
2394
|
+
if (fns.overloaded.has(name)) fail(`${where} is declared more than once (overloads)`);
|
|
2395
|
+
const body = d.node.body;
|
|
2396
|
+
if (!body) fail(`${where} has no body to read`);
|
|
2397
|
+
const bad = vet(file, d.node, rangeOf(d));
|
|
2398
|
+
if (bad) fail(`${where} is outside the subset: ${bad.message} (line ${bad.line}${file === c.module ? "" : " of its file"})`);
|
|
2399
|
+
const signature = c.checker.getResolvedSignature(call);
|
|
2400
|
+
if (c.checker.isUnknownSignature(signature)) fail(`the call to ${where} does not resolve`);
|
|
2401
|
+
const reader = new ExprReader(file, {
|
|
2402
|
+
callable: () => false,
|
|
2403
|
+
target: (n) => n,
|
|
2404
|
+
declared: (n) => fns.declarations.has(n),
|
|
2405
|
+
spec: false,
|
|
2406
|
+
global: c.standardGlobal
|
|
2407
|
+
}, {
|
|
2408
|
+
annotation: (node, refuse) => c.types.of(concrete(c.checker.getTypeAtLocation(node)), refuse),
|
|
2409
|
+
contextual: c.typeSource.contextual
|
|
2410
|
+
}, c.ctx, void 0, inline, constant);
|
|
2411
|
+
const params = shape(reader, d.node);
|
|
2412
|
+
const symbols = signature.getParameters();
|
|
2413
|
+
if (symbols.length !== params.length || call.arguments.length !== params.length) fail(`${where} takes ${params.length} argument(s), called with ${call.arguments.length}`);
|
|
2414
|
+
const bound = /* @__PURE__ */ new Map();
|
|
2415
|
+
const declared = c.checker.getSignatureFromDeclaration(d.node);
|
|
2416
|
+
const generalReturn = c.checker.getReturnTypeOfSignature(declared);
|
|
2417
|
+
const context = d.node.typeParameters ? c.checker.getContextualType(call) : void 0;
|
|
2418
|
+
const matched = context ? match(generalReturn, concrete(context), bound) : void 0;
|
|
2419
|
+
const declaredParams = declared.getParameters();
|
|
2420
|
+
const generalParams = symbols.map((_, i) => {
|
|
2421
|
+
const own = declaredParams[i];
|
|
2422
|
+
return own ? c.checker.getTypeOfSymbol(own) : void 0;
|
|
2423
|
+
});
|
|
2424
|
+
const resolvedParams = symbols.map((p) => concrete(c.checker.getTypeOfSymbol(p)));
|
|
2425
|
+
const resolvedReturn = concrete(c.checker.getReturnTypeOfSignature(signature));
|
|
2426
|
+
generalParams.forEach((g, i) => {
|
|
2427
|
+
if (g) match(g, resolvedParams[i], bound);
|
|
2428
|
+
});
|
|
2429
|
+
match(generalReturn, resolvedReturn, bound);
|
|
2430
|
+
const types = symbols.map((_, i) => {
|
|
2431
|
+
const g = generalParams[i];
|
|
2432
|
+
const type = g?.isTypeParameter() && bound.has(g.id) ? concrete(bound.get(g.id)) : resolvedParams[i];
|
|
2433
|
+
return c.types.of(type, (what) => fail(`${where}, parameter ${params[i]} at this call: ${what}`));
|
|
2434
|
+
});
|
|
2435
|
+
const returns = c.types.of(matched ?? resolvedReturn, (what) => fail(`${where} returns, at this call, ${what}`));
|
|
2436
|
+
const own = new Map([...bound].map(([k, v]) => [k, concrete(v)]));
|
|
2437
|
+
const args = readArgs(types);
|
|
2438
|
+
const key = `${file.fileName}#${name}`;
|
|
2439
|
+
if (inlining.includes(key)) fail(`${where} is recursive, which a function read at its calls cannot be (recursion is in the subset only as a module's own structural recursion)`);
|
|
2440
|
+
inlining.push(key);
|
|
2441
|
+
substitutions.push(own);
|
|
2442
|
+
try {
|
|
2443
|
+
const inner = new Map(params.map((p, i) => [p, types[i]]));
|
|
2444
|
+
const readBody = () => {
|
|
2445
|
+
const read = returning(is.isBlock(body) ? reader.block(body.statements, inner, body) : reader.expression(body, inner), returns);
|
|
2446
|
+
const actual = reader.typeOfExpr(reader.narrowed(read, inner, body), inner, body, returns);
|
|
2447
|
+
if (!fits(actual, returns, c.ctx)) reader.fail(`returns a ${describe(actual)}, not the ${describe(returns)} called for`, body);
|
|
2448
|
+
return read;
|
|
2449
|
+
};
|
|
2450
|
+
let read;
|
|
2451
|
+
try {
|
|
2452
|
+
read = readBody();
|
|
2453
|
+
} catch (err) {
|
|
2454
|
+
if (!(err instanceof OutsideSubset)) throw err;
|
|
2455
|
+
fail(`${where}, read at this call, is outside the subset: ${err.message} (line ${err.line} of its file)`);
|
|
2456
|
+
}
|
|
2457
|
+
const callerNames = /* @__PURE__ */ new Set([...scope.keys(), ...args.flatMap((a) => [...boundNames(a)])]);
|
|
2458
|
+
const taken = /* @__PURE__ */ new Set([
|
|
2459
|
+
...callerNames,
|
|
2460
|
+
...boundNames(read),
|
|
2461
|
+
...params
|
|
2462
|
+
]);
|
|
2463
|
+
const renames = /* @__PURE__ */ new Map();
|
|
2464
|
+
for (const p of params) {
|
|
2465
|
+
const to = callerNames.has(p) ? fresh(p, taken) : p;
|
|
2466
|
+
taken.add(to);
|
|
2467
|
+
renames.set(p, to);
|
|
2468
|
+
}
|
|
2469
|
+
const renamed = renameVars(read, renames, taken, callerNames);
|
|
2470
|
+
return params.reduceRight((rest, p, i) => ({
|
|
2471
|
+
kind: "let",
|
|
2472
|
+
name: renames.get(p),
|
|
2473
|
+
value: args[i],
|
|
2474
|
+
body: rest,
|
|
2475
|
+
type: types[i]
|
|
2476
|
+
}), renamed);
|
|
2477
|
+
} finally {
|
|
2478
|
+
substitutions.pop();
|
|
2479
|
+
inlining.pop();
|
|
2480
|
+
}
|
|
2481
|
+
};
|
|
2482
|
+
const reading = [];
|
|
2483
|
+
const constant = (name, fail) => {
|
|
2484
|
+
let symbol = c.checker.getSymbolAtLocation(name);
|
|
2485
|
+
if (!symbol) return void 0;
|
|
2486
|
+
const imported = (symbol.flags & SymbolFlags.Alias) !== 0;
|
|
2487
|
+
if (imported) symbol = c.checker.getAliasedSymbol(symbol);
|
|
2488
|
+
const decl = symbol.valueDeclaration?.resolve();
|
|
2489
|
+
if (!decl || !is.isVariableDeclaration(decl) || !is.isIdentifier(decl.name)) return void 0;
|
|
2490
|
+
const list = decl.parent;
|
|
2491
|
+
const statement = list.parent;
|
|
2492
|
+
const file = decl.getSourceFile();
|
|
2493
|
+
if (!is.isVariableDeclarationList(list) || !is.isVariableStatement(statement)) return void 0;
|
|
2494
|
+
if (statement.parent !== file) fail(`${name.text}, which is declared after this use in its block`);
|
|
2495
|
+
const where = file === c.module ? decl.name.text : `${decl.name.text} (from ${file.fileName})`;
|
|
2496
|
+
if (file.isDeclarationFile && !imported) return void 0;
|
|
2497
|
+
if (file.isDeclarationFile) fail(`${where} has no value to read: it is declared in a declaration file`);
|
|
2498
|
+
if (!isConst(list)) fail(`${where} is a module-level let or var, which may be rebound`);
|
|
2499
|
+
const at = name.getSourceFile();
|
|
2500
|
+
const start = name.getStart(at);
|
|
2501
|
+
if (c.typeErrors(at.fileName).some((e) => e.pos < name.end && e.end > start)) fail(`the compiler reports an error on ${name.text} here`);
|
|
2502
|
+
if (c.parseError(file.fileName)) fail(`${where} is in a file the compiler cannot parse`);
|
|
2503
|
+
const init = decl.initializer;
|
|
2504
|
+
if (!init) fail(`${where} has no initializer`);
|
|
2505
|
+
if (is.isArrowFunction(init) || is.isFunctionExpression(init)) return void 0;
|
|
2506
|
+
const bad = vet(file, decl, {
|
|
2507
|
+
start: decl.pos,
|
|
2508
|
+
end: decl.end,
|
|
2509
|
+
lead: {
|
|
2510
|
+
start: statement.pos,
|
|
2511
|
+
end: statement.getStart(file)
|
|
2512
|
+
}
|
|
2513
|
+
});
|
|
2514
|
+
if (bad) fail(`${where} is outside the subset: ${bad.message} (line ${bad.line}${file === c.module ? "" : " of its file"})`);
|
|
2515
|
+
const key = `${file.fileName}#${decl.name.text}`;
|
|
2516
|
+
if (reading.includes(key)) fail(`${where} is defined in terms of itself`);
|
|
2517
|
+
const fns = functionsOf(file);
|
|
2518
|
+
if (fns.tainted) fail(`${where} is outside the subset: ${fns.tainted.message}`);
|
|
2519
|
+
const reader = new ExprReader(file, {
|
|
2520
|
+
callable: () => false,
|
|
2521
|
+
target: (n) => n,
|
|
2522
|
+
declared: (n) => fns.declarations.has(n),
|
|
2523
|
+
spec: false,
|
|
2524
|
+
global: c.standardGlobal
|
|
2525
|
+
}, c.typeSource, c.ctx, void 0, void 0, constant);
|
|
2526
|
+
reading.push(key);
|
|
2527
|
+
try {
|
|
2528
|
+
const value = reader.expression(init, /* @__PURE__ */ new Map());
|
|
2529
|
+
if (!isValue(value)) reader.fail(`${decl.name.text} holds something other than a number, boolean or string built from literals, operators and other such constants`, init);
|
|
2530
|
+
return value;
|
|
2531
|
+
} catch (err) {
|
|
2532
|
+
if (!(err instanceof OutsideSubset)) throw err;
|
|
2533
|
+
fail(`${where}, read where it is used, is outside the subset: ${err.message} (line ${err.line} of its file)`);
|
|
2534
|
+
} finally {
|
|
2535
|
+
reading.pop();
|
|
2536
|
+
}
|
|
2537
|
+
};
|
|
2538
|
+
return {
|
|
2539
|
+
inline,
|
|
2540
|
+
constant
|
|
2541
|
+
};
|
|
2542
|
+
}
|
|
2543
|
+
/**
|
|
2544
|
+
* Whether an expression is a value a constant may hold: literals of the
|
|
2545
|
+
* primitive types and the operators on them, with no name, call or record.
|
|
2546
|
+
*/
|
|
2547
|
+
function isValue(e) {
|
|
2548
|
+
switch (e.kind) {
|
|
2549
|
+
case "int":
|
|
2550
|
+
case "bool":
|
|
2551
|
+
case "string": return true;
|
|
2552
|
+
case "neg":
|
|
2553
|
+
case "not":
|
|
2554
|
+
case "isInteger":
|
|
2555
|
+
case "floor": return isValue(e.operand);
|
|
2556
|
+
case "binary": return isValue(e.left) && isValue(e.right);
|
|
2557
|
+
case "cond": return isValue(e.test) && isValue(e.ifTrue) && isValue(e.ifFalse);
|
|
2558
|
+
default: return false;
|
|
2559
|
+
}
|
|
2560
|
+
}
|
|
2561
|
+
/**
|
|
2562
|
+
* The expression with the record literals it returns typed `t`, where
|
|
2563
|
+
* they have no type of their own: a function inlined at a call returns
|
|
2564
|
+
* its instantiated type, which a literal in a generic body cannot name.
|
|
2565
|
+
*/
|
|
2566
|
+
function returning(e, t) {
|
|
2567
|
+
const target = t.kind === "nullable" ? t.inner : t;
|
|
2568
|
+
if (target.kind !== "record" && target.kind !== "union") return e;
|
|
2569
|
+
switch (e.kind) {
|
|
2570
|
+
case "record": return e.type ? e : {
|
|
2571
|
+
...e,
|
|
2572
|
+
type: target
|
|
2573
|
+
};
|
|
2574
|
+
case "let":
|
|
2575
|
+
case "narrow":
|
|
2576
|
+
case "narrowTag": return {
|
|
2577
|
+
...e,
|
|
2578
|
+
body: returning(e.body, t)
|
|
2579
|
+
};
|
|
2580
|
+
case "cond": return {
|
|
2581
|
+
...e,
|
|
2582
|
+
ifTrue: returning(e.ifTrue, t),
|
|
2583
|
+
ifFalse: returning(e.ifFalse, t)
|
|
2584
|
+
};
|
|
2585
|
+
default: return e;
|
|
2586
|
+
}
|
|
2587
|
+
}
|
|
2588
|
+
/**
|
|
2445
2589
|
* Read a module: every function the subset takes (in source order, so
|
|
2446
2590
|
* callees come before callers), the record types and unions they use,
|
|
2447
2591
|
* and, for the other functions, why not. A function calling one outside
|
|
@@ -2454,16 +2598,12 @@ function readSubset(source, functions, options = {}) {
|
|
|
2454
2598
|
return withProgram([{
|
|
2455
2599
|
path,
|
|
2456
2600
|
text: source
|
|
2457
|
-
}], ({ checker, file, parseError }) => {
|
|
2601
|
+
}, ...options.files ?? []], ({ checker, file, parseError, typeErrors, standardGlobal }) => {
|
|
2458
2602
|
const sf = file(path);
|
|
2459
|
-
const
|
|
2460
|
-
const
|
|
2461
|
-
for (const st of sf.statements) {
|
|
2462
|
-
if (!is.isFunctionDeclaration(st) || !st.name) continue;
|
|
2463
|
-
if (declarations.has(st.name.text)) overloaded.add(st.name.text);
|
|
2464
|
-
else declarations.set(st.name.text, st);
|
|
2465
|
-
}
|
|
2603
|
+
const own = fileFunctions(sf, checker, standardGlobal);
|
|
2604
|
+
const { declarations, overloaded } = own;
|
|
2466
2605
|
const declared = new Set(declarations.keys());
|
|
2606
|
+
const generic = new Set([...declarations].filter(([, d]) => d.node.typeParameters).map(([name]) => name));
|
|
2467
2607
|
const outside = /* @__PURE__ */ new Map();
|
|
2468
2608
|
const error = parseError(path);
|
|
2469
2609
|
if (error) {
|
|
@@ -2484,17 +2624,7 @@ function readSubset(source, functions, options = {}) {
|
|
|
2484
2624
|
line: 0,
|
|
2485
2625
|
message: `the module declares no function ${name} at its top level`
|
|
2486
2626
|
});
|
|
2487
|
-
const
|
|
2488
|
-
if (evalLine !== void 0) for (const name of declared) outside.set(name, {
|
|
2489
|
-
name,
|
|
2490
|
-
line: evalLine,
|
|
2491
|
-
message: "the module mentions eval directly, which can rebind any of its declarations"
|
|
2492
|
-
});
|
|
2493
|
-
for (const [name, line] of assigned(sf, checker, declarations)) if (!outside.has(name)) outside.set(name, {
|
|
2494
|
-
name,
|
|
2495
|
-
line,
|
|
2496
|
-
message: `${name} is assigned in the module, so what runs under its name may not be its declaration`
|
|
2497
|
-
});
|
|
2627
|
+
for (const [name, why] of own.untrusted) if (!outside.has(name)) outside.set(name, why);
|
|
2498
2628
|
const types = new SubsetTypes(checker);
|
|
2499
2629
|
const skip = Symbol("outside");
|
|
2500
2630
|
for (const st of sf.statements) {
|
|
@@ -2511,18 +2641,32 @@ function readSubset(source, functions, options = {}) {
|
|
|
2511
2641
|
}
|
|
2512
2642
|
}
|
|
2513
2643
|
const { ctx, signatures } = moduleContext(types.records);
|
|
2514
|
-
const
|
|
2515
|
-
callable: (n) => declared.has(n),
|
|
2644
|
+
const names = {
|
|
2645
|
+
callable: (n) => declared.has(n) && !generic.has(n),
|
|
2516
2646
|
target: (n) => n,
|
|
2517
2647
|
declared: (n) => declared.has(n),
|
|
2518
|
-
spec: false
|
|
2519
|
-
|
|
2648
|
+
spec: false,
|
|
2649
|
+
global: standardGlobal
|
|
2650
|
+
};
|
|
2651
|
+
const typeSource = {
|
|
2520
2652
|
annotation: (node, refuse) => types.of(checker.getTypeAtLocation(node), refuse),
|
|
2521
2653
|
contextual: (node) => contextualType(checker, types, node)
|
|
2522
|
-
}
|
|
2654
|
+
};
|
|
2655
|
+
const { inline, constant } = inliner({
|
|
2656
|
+
checker,
|
|
2657
|
+
types,
|
|
2658
|
+
typeSource,
|
|
2659
|
+
ctx,
|
|
2660
|
+
module: sf,
|
|
2661
|
+
own,
|
|
2662
|
+
parseError,
|
|
2663
|
+
typeErrors,
|
|
2664
|
+
standardGlobal
|
|
2665
|
+
});
|
|
2666
|
+
const reader = new ExprReader(sf, names, typeSource, ctx, void 0, inline, constant);
|
|
2523
2667
|
const heads = [];
|
|
2524
2668
|
for (const [name, decl] of declarations) try {
|
|
2525
|
-
if (overloaded.has(name)) reader.fail(`${name} is declared more than once (overloads)`, decl);
|
|
2669
|
+
if (overloaded.has(name)) reader.fail(`${name} is declared more than once (overloads)`, decl.statement);
|
|
2526
2670
|
const h = head(reader, types, checker, decl);
|
|
2527
2671
|
signatures.set(name, {
|
|
2528
2672
|
params: h.params,
|
|
@@ -2539,7 +2683,10 @@ function readSubset(source, functions, options = {}) {
|
|
|
2539
2683
|
}
|
|
2540
2684
|
const read = /* @__PURE__ */ new Map();
|
|
2541
2685
|
for (const h of heads) try {
|
|
2542
|
-
|
|
2686
|
+
const fn = declaration(reader, h);
|
|
2687
|
+
const bad = notCompiled(sf, typeErrors, rangeOf(declarations.get(h.name)));
|
|
2688
|
+
if (bad) throw new OutsideSubset(bad.message, bad.line);
|
|
2689
|
+
read.set(h.name, fn);
|
|
2543
2690
|
} catch (err) {
|
|
2544
2691
|
if (!(err instanceof OutsideSubset)) throw err;
|
|
2545
2692
|
outside.set(h.name, {
|
|
@@ -2630,7 +2777,8 @@ function arrowReader(sf, module, aliases) {
|
|
|
2630
2777
|
callable: (n) => callable.has(n),
|
|
2631
2778
|
target: (n) => aliases.get(n) ?? n,
|
|
2632
2779
|
declared: (n) => declared.has(n),
|
|
2633
|
-
spec: true
|
|
2780
|
+
spec: true,
|
|
2781
|
+
global: () => true
|
|
2634
2782
|
};
|
|
2635
2783
|
} else {
|
|
2636
2784
|
const declared = /* @__PURE__ */ new Set([...inSubset, ...module.outside.map((o) => o.name)]);
|
|
@@ -2638,7 +2786,8 @@ function arrowReader(sf, module, aliases) {
|
|
|
2638
2786
|
callable: (n) => inSubset.has(n),
|
|
2639
2787
|
target: (n) => n,
|
|
2640
2788
|
declared: (n) => declared.has(n),
|
|
2641
|
-
spec: false
|
|
2789
|
+
spec: false,
|
|
2790
|
+
global: () => true
|
|
2642
2791
|
};
|
|
2643
2792
|
}
|
|
2644
2793
|
const recordNames = new Set(records.keys());
|
|
@@ -2677,7 +2826,10 @@ function fragmentExpression(sf) {
|
|
|
2677
2826
|
* The scope maps the arrow's own parameter names to the binders' types;
|
|
2678
2827
|
* `aliases` maps the spec file's local names to the module's functions,
|
|
2679
2828
|
* and a free name that is neither is outside the subset: the spec file's
|
|
2680
|
-
* scope is its imports, never the module's.
|
|
2829
|
+
* scope is its imports, never the module's. `Math` and `Number` are the
|
|
2830
|
+
* globals wherever the arrow's own scope does not bind them: `readSpecs`
|
|
2831
|
+
* has checked that every built-in a claim names resolves to the standard
|
|
2832
|
+
* library in the spec file.
|
|
2681
2833
|
*/
|
|
2682
2834
|
function readArrowBody(arrow, scope, module, aliases = /* @__PURE__ */ new Map()) {
|
|
2683
2835
|
if (!arrow.block) return withSourceFile(`(${arrow.body}\n)`, (sf) => {
|
|
@@ -2738,7 +2890,8 @@ function children(e) {
|
|
|
2738
2890
|
case "narrowTag": return [e.body];
|
|
2739
2891
|
case "neg":
|
|
2740
2892
|
case "not":
|
|
2741
|
-
case "isInteger":
|
|
2893
|
+
case "isInteger":
|
|
2894
|
+
case "floor": return [e.operand];
|
|
2742
2895
|
case "binary": return [e.left, e.right];
|
|
2743
2896
|
case "cond": return [
|
|
2744
2897
|
e.test,
|
|
@@ -2760,128 +2913,661 @@ function children(e) {
|
|
|
2760
2913
|
];
|
|
2761
2914
|
}
|
|
2762
2915
|
}
|
|
2763
|
-
/** Whether an expression holds a node of the kinds named. */
|
|
2764
|
-
function hasNode(e, kinds) {
|
|
2765
|
-
if (kinds.has(e.kind)) return true;
|
|
2766
|
-
switch (e.kind) {
|
|
2767
|
-
case "int":
|
|
2768
|
-
case "bool":
|
|
2769
|
-
case "string":
|
|
2770
|
-
case "null":
|
|
2771
|
-
case "var": return false;
|
|
2772
|
-
case "narrow":
|
|
2773
|
-
case "narrowTag": return hasNode(e.body, kinds);
|
|
2774
|
-
case "neg":
|
|
2775
|
-
case "not":
|
|
2776
|
-
case "isInteger":
|
|
2777
|
-
case "
|
|
2778
|
-
case "
|
|
2779
|
-
case "
|
|
2780
|
-
case "
|
|
2781
|
-
case "
|
|
2782
|
-
case "
|
|
2783
|
-
case "
|
|
2784
|
-
case "
|
|
2785
|
-
case "
|
|
2786
|
-
case "
|
|
2787
|
-
case "
|
|
2788
|
-
|
|
2916
|
+
/** Whether an expression holds a node of the kinds named. */
|
|
2917
|
+
function hasNode(e, kinds) {
|
|
2918
|
+
if (kinds.has(e.kind)) return true;
|
|
2919
|
+
switch (e.kind) {
|
|
2920
|
+
case "int":
|
|
2921
|
+
case "bool":
|
|
2922
|
+
case "string":
|
|
2923
|
+
case "null":
|
|
2924
|
+
case "var": return false;
|
|
2925
|
+
case "narrow":
|
|
2926
|
+
case "narrowTag": return hasNode(e.body, kinds);
|
|
2927
|
+
case "neg":
|
|
2928
|
+
case "not":
|
|
2929
|
+
case "isInteger":
|
|
2930
|
+
case "floor": return hasNode(e.operand, kinds);
|
|
2931
|
+
case "binary": return hasNode(e.left, kinds) || hasNode(e.right, kinds);
|
|
2932
|
+
case "cond": return hasNode(e.test, kinds) || hasNode(e.ifTrue, kinds) || hasNode(e.ifFalse, kinds);
|
|
2933
|
+
case "call": return e.args.some((a) => hasNode(a, kinds));
|
|
2934
|
+
case "field": return hasNode(e.object, kinds);
|
|
2935
|
+
case "record": return e.fields.some((f) => hasNode(f.value, kinds));
|
|
2936
|
+
case "let": return hasNode(e.value, kinds) || hasNode(e.body, kinds);
|
|
2937
|
+
case "list": return e.items.some((x) => hasNode(x, kinds)) || (e.rest ? hasNode(e.rest, kinds) : false);
|
|
2938
|
+
case "tail": return hasNode(e.list, kinds);
|
|
2939
|
+
case "headOr": return hasNode(e.list, kinds) || hasNode(e.fallback, kinds);
|
|
2940
|
+
case "iterate": return hasNode(e.list, kinds) || hasNode(e.body, kinds);
|
|
2941
|
+
case "fold": return hasNode(e.list, kinds) || hasNode(e.init, kinds) || hasNode(e.body, kinds);
|
|
2942
|
+
}
|
|
2943
|
+
}
|
|
2944
|
+
/**
|
|
2945
|
+
* The module as an engine that takes only some of the subset's types sees
|
|
2946
|
+
* it: records with a field of a type it does not take are dropped, and so
|
|
2947
|
+
* are functions whose signature holds one, whose body uses what the
|
|
2948
|
+
* types bring (`null`, narrowing), or which call such a function; each is
|
|
2949
|
+
* reported outside with `reason`.
|
|
2950
|
+
*/
|
|
2951
|
+
function restrictModule(module, takes, reason, bodies = /* @__PURE__ */ new Set([
|
|
2952
|
+
"null",
|
|
2953
|
+
"narrow",
|
|
2954
|
+
"narrowTag"
|
|
2955
|
+
]), refused) {
|
|
2956
|
+
const badRecords = /* @__PURE__ */ new Set();
|
|
2957
|
+
for (const u of module.unions) if (!takes({
|
|
2958
|
+
kind: "union",
|
|
2959
|
+
name: u.name
|
|
2960
|
+
})) badRecords.add(`union:${u.name}`);
|
|
2961
|
+
for (let changed = true; changed;) {
|
|
2962
|
+
changed = false;
|
|
2963
|
+
for (const rec of module.records) if (!badRecords.has(rec.name) && rec.fields.some((f) => !typeTaken(f.type, takes, badRecords))) {
|
|
2964
|
+
badRecords.add(rec.name);
|
|
2965
|
+
changed = true;
|
|
2966
|
+
}
|
|
2967
|
+
for (const u of module.unions) if (!badRecords.has(`union:${u.name}`) && u.members.some((m) => badRecords.has(m.record))) {
|
|
2968
|
+
badRecords.add(`union:${u.name}`);
|
|
2969
|
+
changed = true;
|
|
2970
|
+
}
|
|
2971
|
+
}
|
|
2972
|
+
const outside = new Map(module.outside.map((o) => [o.name, o]));
|
|
2973
|
+
const kept = new Map(module.functions.map((f) => [f.name, f]));
|
|
2974
|
+
const uses = (f) => !f.params.every((p) => typeTaken(p.type, takes, badRecords)) || !typeTaken(f.returns, takes, badRecords) || annotations(f.body).some((t) => !typeTaken(t, takes, badRecords)) || hasNode(f.body, bodies) || refused?.(f.body) === true;
|
|
2975
|
+
for (const f of module.functions) if (uses(f)) {
|
|
2976
|
+
kept.delete(f.name);
|
|
2977
|
+
outside.set(f.name, {
|
|
2978
|
+
name: f.name,
|
|
2979
|
+
line: f.line,
|
|
2980
|
+
message: reason
|
|
2981
|
+
});
|
|
2982
|
+
}
|
|
2983
|
+
for (let changed = true; changed;) {
|
|
2984
|
+
changed = false;
|
|
2985
|
+
for (const [name, f] of kept) {
|
|
2986
|
+
const bad = [...callees(f.body)].find((c) => outside.has(c));
|
|
2987
|
+
if (bad === void 0) continue;
|
|
2988
|
+
kept.delete(name);
|
|
2989
|
+
outside.set(name, {
|
|
2990
|
+
name,
|
|
2991
|
+
line: f.line,
|
|
2992
|
+
message: `calls ${bad}, which is outside the engine's subset: ${outside.get(bad)?.message}`
|
|
2993
|
+
});
|
|
2994
|
+
changed = true;
|
|
2995
|
+
}
|
|
2996
|
+
}
|
|
2997
|
+
return {
|
|
2998
|
+
records: module.records.filter((r) => !badRecords.has(r.name)).map((r) => {
|
|
2999
|
+
const unions = r.unions?.filter((u) => !badRecords.has(`union:${u}`));
|
|
3000
|
+
if (unions === r.unions) return r;
|
|
3001
|
+
const { unions: _, ...rest } = r;
|
|
3002
|
+
return unions && unions.length > 0 ? {
|
|
3003
|
+
...rest,
|
|
3004
|
+
unions
|
|
3005
|
+
} : rest;
|
|
3006
|
+
}),
|
|
3007
|
+
unions: module.unions.filter((u) => !badRecords.has(`union:${u.name}`)),
|
|
3008
|
+
functions: module.functions.filter((f) => kept.has(f.name)),
|
|
3009
|
+
outside: [...outside.values()]
|
|
3010
|
+
};
|
|
3011
|
+
}
|
|
3012
|
+
function typeTaken(t, takes, badRecords) {
|
|
3013
|
+
if (!takes(t)) return false;
|
|
3014
|
+
if (t.kind === "record") return !badRecords.has(t.name);
|
|
3015
|
+
if (t.kind === "union") return !badRecords.has(`union:${t.name}`);
|
|
3016
|
+
if (t.kind === "nullable") return typeTaken(t.inner, takes, badRecords);
|
|
3017
|
+
if (t.kind === "list") return typeTaken(t.element, takes, badRecords);
|
|
3018
|
+
return true;
|
|
3019
|
+
}
|
|
3020
|
+
/** The types a body's `const` annotations and its record literals' contexts name. */
|
|
3021
|
+
function annotations(e, out = []) {
|
|
3022
|
+
if ((e.kind === "let" || e.kind === "record") && e.type) out.push(e.type);
|
|
3023
|
+
for (const c of children(e)) annotations(c, out);
|
|
3024
|
+
return out;
|
|
3025
|
+
}
|
|
3026
|
+
/** The expression kinds only lists bring, for an engine that does not take them. */
|
|
3027
|
+
const listKinds = /* @__PURE__ */ new Set([
|
|
3028
|
+
"list",
|
|
3029
|
+
"tail",
|
|
3030
|
+
"headOr",
|
|
3031
|
+
"iterate",
|
|
3032
|
+
"fold"
|
|
3033
|
+
]);
|
|
3034
|
+
/** Whether an expression is one only lists bring (a type guard over `listKinds`). */
|
|
3035
|
+
const isListExpr = (e) => listKinds.has(e.kind);
|
|
3036
|
+
// packages/prover/src/reader/specs.ts
|
|
3037
|
+
/** The parameters of a function-like declaration: `name?: T = default`, `...rest`, destructured. */
|
|
3038
|
+
function readParams(checker, fn) {
|
|
3039
|
+
const params = [];
|
|
3040
|
+
for (const p of fn.parameters) {
|
|
3041
|
+
const name = is.isIdentifier(p.name) ? p.name.text : null;
|
|
3042
|
+
if (name === "this") continue;
|
|
3043
|
+
if (p.dotDotDotToken) {
|
|
3044
|
+
params.push({
|
|
3045
|
+
name: null,
|
|
3046
|
+
type: {
|
|
3047
|
+
kind: "unknown",
|
|
3048
|
+
text: `...${name ?? ""}`
|
|
3049
|
+
}
|
|
3050
|
+
});
|
|
3051
|
+
continue;
|
|
3052
|
+
}
|
|
3053
|
+
let type;
|
|
3054
|
+
if (p.type) type = specTypeOf(checker, checker.getTypeAtLocation(p.type));
|
|
3055
|
+
else if (p.initializer) type = specTypeOf(checker, checker.getTypeAtLocation(p));
|
|
3056
|
+
else type = {
|
|
3057
|
+
kind: "unknown",
|
|
3058
|
+
text: "(no type annotation)"
|
|
3059
|
+
};
|
|
3060
|
+
if (p.questionToken || p.initializer) type = unionOf([type, { kind: "undefined" }]);
|
|
3061
|
+
params.push({
|
|
3062
|
+
name,
|
|
3063
|
+
type
|
|
3064
|
+
});
|
|
3065
|
+
}
|
|
3066
|
+
return params;
|
|
3067
|
+
}
|
|
3068
|
+
function readModuleSide(sf, checker) {
|
|
3069
|
+
const errors = [];
|
|
3070
|
+
const declarations = /* @__PURE__ */ new Map();
|
|
3071
|
+
const exports = /* @__PURE__ */ new Map();
|
|
3072
|
+
const declare = (name, fn, at) => {
|
|
3073
|
+
const offset = openParen(sf, fn);
|
|
3074
|
+
if (offset === void 0) return;
|
|
3075
|
+
if (declarations.has(name)) {
|
|
3076
|
+
errors.push({
|
|
3077
|
+
line: lineAt(sf, at),
|
|
3078
|
+
message: `${name} is declared more than once (overloads): a spec is checked against one signature`,
|
|
3079
|
+
inModule: true
|
|
3080
|
+
});
|
|
3081
|
+
return;
|
|
3082
|
+
}
|
|
3083
|
+
declarations.set(name, {
|
|
3084
|
+
name,
|
|
3085
|
+
params: readParams(checker, fn),
|
|
3086
|
+
line: lineAt(sf, at),
|
|
3087
|
+
offset
|
|
3088
|
+
});
|
|
3089
|
+
};
|
|
3090
|
+
for (const st of sf.statements) {
|
|
3091
|
+
if (is.isFunctionDeclaration(st)) {
|
|
3092
|
+
if (!st.name) continue;
|
|
3093
|
+
declare(st.name.text, st, st);
|
|
3094
|
+
if (isExported(st)) exports.set(st.name.text, st.name.text);
|
|
3095
|
+
continue;
|
|
3096
|
+
}
|
|
3097
|
+
if (is.isVariableStatement(st)) {
|
|
3098
|
+
for (const d of st.declarationList.declarations) {
|
|
3099
|
+
if (!is.isIdentifier(d.name) || !d.initializer) continue;
|
|
3100
|
+
let init = d.initializer;
|
|
3101
|
+
while (is.isParenthesizedExpression(init)) init = init.expression;
|
|
3102
|
+
if (!is.isArrowFunction(init) && !is.isFunctionExpression(init)) continue;
|
|
3103
|
+
declare(d.name.text, init, st);
|
|
3104
|
+
if (isExported(st)) exports.set(d.name.text, d.name.text);
|
|
3105
|
+
}
|
|
3106
|
+
continue;
|
|
3107
|
+
}
|
|
3108
|
+
if (is.isExportDeclaration(st) && !st.moduleSpecifier && !st.isTypeOnly && st.exportClause) {
|
|
3109
|
+
if (!is.isNamedExports(st.exportClause)) continue;
|
|
3110
|
+
for (const e of st.exportClause.elements) {
|
|
3111
|
+
if (e.isTypeOnly) continue;
|
|
3112
|
+
const local = e.propertyName ?? e.name;
|
|
3113
|
+
if (is.isIdentifier(local) && is.isIdentifier(e.name)) exports.set(e.name.text, local.text);
|
|
3114
|
+
}
|
|
3115
|
+
}
|
|
3116
|
+
}
|
|
3117
|
+
return {
|
|
3118
|
+
declarations,
|
|
3119
|
+
exports,
|
|
3120
|
+
errors
|
|
3121
|
+
};
|
|
3122
|
+
}
|
|
3123
|
+
/** `import { a, b as c } from "x"`, `import * as ns from "x"`, `import d from "x"`; type-only imports skipped. */
|
|
3124
|
+
function imports(sf) {
|
|
3125
|
+
const out = /* @__PURE__ */ new Map();
|
|
3126
|
+
for (const st of sf.statements) {
|
|
3127
|
+
if (!is.isImportDeclaration(st) || !st.importClause) continue;
|
|
3128
|
+
const clause = st.importClause;
|
|
3129
|
+
if (clause.phaseModifier === SyntaxKind.TypeKeyword) continue;
|
|
3130
|
+
if (!is.isStringLiteral(st.moduleSpecifier)) continue;
|
|
3131
|
+
const from = st.moduleSpecifier.text;
|
|
3132
|
+
if (clause.name) out.set(clause.name.text, {
|
|
3133
|
+
from,
|
|
3134
|
+
name: "default",
|
|
3135
|
+
declaration: st
|
|
3136
|
+
});
|
|
3137
|
+
const bindings = clause.namedBindings;
|
|
3138
|
+
if (!bindings) continue;
|
|
3139
|
+
if (is.isNamespaceImport(bindings)) out.set(bindings.name.text, {
|
|
3140
|
+
from,
|
|
3141
|
+
name: "*",
|
|
3142
|
+
declaration: st
|
|
3143
|
+
});
|
|
3144
|
+
else for (const e of bindings.elements) {
|
|
3145
|
+
if (e.isTypeOnly) continue;
|
|
3146
|
+
const imported = e.propertyName ?? e.name;
|
|
3147
|
+
const name = is.isIdentifier(imported) ? imported.text : imported.text;
|
|
3148
|
+
out.set(e.name.text, {
|
|
3149
|
+
from,
|
|
3150
|
+
name,
|
|
3151
|
+
declaration: st
|
|
3152
|
+
});
|
|
3153
|
+
}
|
|
3154
|
+
}
|
|
3155
|
+
return out;
|
|
3156
|
+
}
|
|
3157
|
+
/** `1`, `-1`, `1_000`, `1.5`, `10n` as an endpoint value; undefined otherwise. */
|
|
3158
|
+
function numberText(sf, node) {
|
|
3159
|
+
if (is.isNumericLiteral(node) || is.isBigIntLiteral(node)) return textOf(sf, node).replace(/_/g, "");
|
|
3160
|
+
if (is.isPrefixUnaryExpression(node) && node.operator === SyntaxKind.MinusToken && (is.isNumericLiteral(node.operand) || is.isBigIntLiteral(node.operand))) return `-${textOf(sf, node.operand).replace(/_/g, "")}`;
|
|
3161
|
+
}
|
|
3162
|
+
/** The top-level conjuncts of an expression, parentheses stripped. */
|
|
3163
|
+
function conjuncts(node, out = []) {
|
|
3164
|
+
let e = node;
|
|
3165
|
+
while (is.isParenthesizedExpression(e)) e = e.expression;
|
|
3166
|
+
if (is.isBinaryExpression(e) && e.operatorToken.kind === SyntaxKind.AmpersandAmpersandToken) {
|
|
3167
|
+
conjuncts(e.left, out);
|
|
3168
|
+
conjuncts(e.right, out);
|
|
3169
|
+
} else out.push(e);
|
|
3170
|
+
return out;
|
|
2789
3171
|
}
|
|
3172
|
+
const comparisons = {
|
|
3173
|
+
[SyntaxKind.LessThanToken]: "<",
|
|
3174
|
+
[SyntaxKind.LessThanEqualsToken]: "<=",
|
|
3175
|
+
[SyntaxKind.GreaterThanToken]: ">",
|
|
3176
|
+
[SyntaxKind.GreaterThanEqualsToken]: ">="
|
|
3177
|
+
};
|
|
2790
3178
|
/**
|
|
2791
|
-
*
|
|
2792
|
-
*
|
|
2793
|
-
*
|
|
2794
|
-
*
|
|
2795
|
-
* reported outside with `reason`.
|
|
3179
|
+
* What an expression says about each of the named parameters on its own:
|
|
3180
|
+
* its top-level conjuncts of the forms `Number.isInteger(x)`, `x < n`,
|
|
3181
|
+
* `n <= x` (and the other comparisons) and `/re/.test(x)`, by parameter
|
|
3182
|
+
* index.
|
|
2796
3183
|
*/
|
|
2797
|
-
function
|
|
2798
|
-
|
|
2799
|
-
|
|
2800
|
-
|
|
2801
|
-
|
|
2802
|
-
|
|
2803
|
-
|
|
2804
|
-
|
|
2805
|
-
|
|
2806
|
-
|
|
2807
|
-
|
|
2808
|
-
|
|
2809
|
-
|
|
2810
|
-
|
|
2811
|
-
|
|
3184
|
+
function hintsIn(sf, body, params) {
|
|
3185
|
+
const out = /* @__PURE__ */ new Map();
|
|
3186
|
+
const position = /* @__PURE__ */ new Map();
|
|
3187
|
+
params.forEach((p, i) => {
|
|
3188
|
+
if (p !== null) position.set(p, i);
|
|
3189
|
+
});
|
|
3190
|
+
const merge = (i, h) => {
|
|
3191
|
+
const old = out.get(i) ?? {};
|
|
3192
|
+
out.set(i, {
|
|
3193
|
+
...old,
|
|
3194
|
+
...h
|
|
3195
|
+
});
|
|
3196
|
+
};
|
|
3197
|
+
for (const conjunct of conjuncts(body)) {
|
|
3198
|
+
if (is.isCallExpression(conjunct)) {
|
|
3199
|
+
const callee = conjunct.expression;
|
|
3200
|
+
const [arg, extra] = conjunct.arguments;
|
|
3201
|
+
if (!is.isPropertyAccessExpression(callee) || !is.isIdentifier(callee.name) || !arg || extra) continue;
|
|
3202
|
+
if (!is.isIdentifier(arg)) continue;
|
|
3203
|
+
const at = position.get(arg.text);
|
|
3204
|
+
if (at === void 0) continue;
|
|
3205
|
+
if (is.isIdentifier(callee.expression) && callee.expression.text === "Number" && callee.name.text === "isInteger") merge(at, { integer: true });
|
|
3206
|
+
else if (is.isRegularExpressionLiteral(callee.expression) && callee.name.text === "test") {
|
|
3207
|
+
const m = /^\/([\s\S]*)\/([a-z]*)$/.exec(textOf(sf, callee.expression));
|
|
3208
|
+
if (m) merge(at, { regex: {
|
|
3209
|
+
pattern: m[1],
|
|
3210
|
+
flags: m[2]
|
|
3211
|
+
} });
|
|
3212
|
+
}
|
|
3213
|
+
continue;
|
|
3214
|
+
}
|
|
3215
|
+
if (!is.isBinaryExpression(conjunct)) continue;
|
|
3216
|
+
const op = comparisons[conjunct.operatorToken.kind];
|
|
3217
|
+
if (op === void 0) continue;
|
|
3218
|
+
const bound = (variable, literal, variableOnLeft) => {
|
|
3219
|
+
if (!is.isIdentifier(variable)) return;
|
|
3220
|
+
const value = numberText(sf, literal);
|
|
3221
|
+
if (value === void 0) return;
|
|
3222
|
+
const at = position.get(variable.text);
|
|
3223
|
+
if (at === void 0) return;
|
|
3224
|
+
const above = variableOnLeft ? op.startsWith("<") : op.startsWith(">");
|
|
3225
|
+
const endpoint = {
|
|
3226
|
+
value,
|
|
3227
|
+
inclusive: op.endsWith("=")
|
|
3228
|
+
};
|
|
3229
|
+
merge(at, above ? { upper: endpoint } : { lower: endpoint });
|
|
3230
|
+
};
|
|
3231
|
+
if (is.isIdentifier(conjunct.left)) bound(conjunct.left, conjunct.right, true);
|
|
3232
|
+
else if (is.isIdentifier(conjunct.right)) bound(conjunct.right, conjunct.left, false);
|
|
3233
|
+
}
|
|
3234
|
+
return out;
|
|
3235
|
+
}
|
|
3236
|
+
var SpecFail = class extends Error {
|
|
3237
|
+
line;
|
|
3238
|
+
constructor(message, line) {
|
|
3239
|
+
super(message);
|
|
3240
|
+
this.line = line;
|
|
3241
|
+
}
|
|
3242
|
+
};
|
|
3243
|
+
/** Read the spec file's exports. */
|
|
3244
|
+
function readSpecSide(sf, { program, checker, standardGlobal }, modulePath, moduleKey, specSpecifiers) {
|
|
3245
|
+
const errors = [];
|
|
3246
|
+
const bound = imports(sf);
|
|
3247
|
+
const specs = [];
|
|
3248
|
+
function fail(message, at) {
|
|
3249
|
+
throw new SpecFail(message, lineAt(sf, at));
|
|
3250
|
+
}
|
|
3251
|
+
const resolvesToModule = /* @__PURE__ */ new Map();
|
|
3252
|
+
const fromModule = (imp) => {
|
|
3253
|
+
const known = resolvesToModule.get(imp.from);
|
|
3254
|
+
if (known !== void 0) return known;
|
|
3255
|
+
const resolved = program.getResolvedModuleFromModuleSpecifier(imp.declaration.moduleSpecifier, sf.fileName);
|
|
3256
|
+
const target = resolved ? program.getSourceFile(resolved.resolvedFileName) : void 0;
|
|
3257
|
+
const is = target !== void 0 && target.path === moduleKey;
|
|
3258
|
+
resolvesToModule.set(imp.from, is);
|
|
3259
|
+
return is;
|
|
3260
|
+
};
|
|
3261
|
+
/** The combinator a callee names (`forall`, `ns.forall`), or undefined. */
|
|
3262
|
+
const combinator = (callee) => {
|
|
3263
|
+
if (is.isPropertyAccessExpression(callee)) {
|
|
3264
|
+
if (!is.isIdentifier(callee.expression) || !is.isIdentifier(callee.name)) return void 0;
|
|
3265
|
+
const ns = bound.get(callee.expression.text);
|
|
3266
|
+
const member = callee.name.text;
|
|
3267
|
+
if (ns?.name === "*" && specSpecifiers.has(ns.from) && (member === "forall" || member === "total")) return member;
|
|
3268
|
+
return;
|
|
3269
|
+
}
|
|
3270
|
+
if (!is.isIdentifier(callee)) return void 0;
|
|
3271
|
+
const imp = bound.get(callee.text);
|
|
3272
|
+
if (imp && specSpecifiers.has(imp.from) && (imp.name === "forall" || imp.name === "total")) return imp.name;
|
|
3273
|
+
};
|
|
3274
|
+
/** The module function a first argument names, or why not. */
|
|
3275
|
+
const functionArg = (arg, call) => {
|
|
3276
|
+
if (!arg) return fail("the first argument must name a function of the module, found the end", call);
|
|
3277
|
+
if (is.isPropertyAccessExpression(arg) && is.isIdentifier(arg.expression) && is.isIdentifier(arg.name)) {
|
|
3278
|
+
const ns = bound.get(arg.expression.text);
|
|
3279
|
+
if (ns?.name === "*" && fromModule(ns)) return arg.name.text;
|
|
3280
|
+
return fail(`${textOf(sf, arg)} is not a function imported from the module`, arg);
|
|
2812
3281
|
}
|
|
2813
|
-
|
|
2814
|
-
|
|
2815
|
-
|
|
2816
|
-
|
|
3282
|
+
if (!is.isIdentifier(arg)) return fail(`the first argument must name a function of the module, found ${textOf(sf, arg)}`, arg);
|
|
3283
|
+
const imp = bound.get(arg.text);
|
|
3284
|
+
if (!imp) return fail(`${arg.text} is not imported from the module (import it from ./${modulePath.split("/").pop()})`, arg);
|
|
3285
|
+
if (!fromModule(imp)) return fail(`${arg.text} is imported from ${JSON.stringify(imp.from)}, not from the module beside this spec file`, arg);
|
|
3286
|
+
if (imp.name === "*" || imp.name === "default") return fail(`${arg.text} must be a named import of the module's function`, arg);
|
|
3287
|
+
return imp.name;
|
|
3288
|
+
};
|
|
3289
|
+
/**
|
|
3290
|
+
* A claim is read from its arrow's text alone, where `Math` and `Number`
|
|
3291
|
+
* are the globals unless the arrow binds them itself: an arrow naming
|
|
3292
|
+
* one that resolves to anything else here (a binding of the spec file,
|
|
3293
|
+
* an import, a const of the arrow's own block declared after the use)
|
|
3294
|
+
* is refused, so a claim is never read as something it does not
|
|
3295
|
+
* compute. A parameter or const of the arrow bound before the use is
|
|
3296
|
+
* the arrow reader's own name for it (a parameter named `Math` reads as
|
|
3297
|
+
* that parameter), and a binding the claims do not name, or a type-only
|
|
3298
|
+
* import, is fine.
|
|
3299
|
+
*/
|
|
3300
|
+
const builtins = (arrow, node, what) => {
|
|
3301
|
+
if (is.isPropertyAccessExpression(node) && is.isIdentifier(node.expression) && (node.expression.text === "Math" || node.expression.text === "Number") && !standardGlobal(node.expression)) {
|
|
3302
|
+
const id = node.expression;
|
|
3303
|
+
const bound = checker.getSymbolAtLocation(id)?.declarations[0]?.resolve();
|
|
3304
|
+
if (!(bound !== void 0 && bound.getSourceFile() === sf && bound.pos >= arrow.pos && bound.end <= arrow.end && bound.getStart(sf) < id.getStart(sf))) {
|
|
3305
|
+
const file = bound?.getSourceFile();
|
|
3306
|
+
const where = bound && file ? ` (bound at line ${lineAt(file, bound)}${file === sf ? "" : ` of ${file.fileName}`})` : "";
|
|
3307
|
+
fail(`${what} names ${id.text}, which is not the global ${id.text} here${where}; rename the binding`, id);
|
|
2817
3308
|
}
|
|
2818
|
-
|
|
2819
|
-
|
|
2820
|
-
|
|
2821
|
-
|
|
2822
|
-
|
|
2823
|
-
|
|
2824
|
-
|
|
3309
|
+
}
|
|
3310
|
+
node.forEachChild((child) => builtins(arrow, child, what));
|
|
3311
|
+
};
|
|
3312
|
+
/** An arrow function: its params, body text and whether the body is a block. */
|
|
3313
|
+
const arrow = (node, what) => {
|
|
3314
|
+
if (!is.isArrowFunction(node)) return fail(`${what} must be an arrow function, found ${textOf(sf, node).split(/\s/)[0] ?? ""}`, node);
|
|
3315
|
+
if (isAsync(node)) fail(`${what} is an async arrow; it must be synchronous`, node);
|
|
3316
|
+
builtins(node, node.body, what);
|
|
3317
|
+
const params = node.parameters.map((p) => !p.dotDotDotToken && is.isIdentifier(p.name) ? p.name.text : null);
|
|
3318
|
+
const body = node.body;
|
|
3319
|
+
const line = lineAt(sf, node);
|
|
3320
|
+
if (is.isBlock(body)) return {
|
|
3321
|
+
arrow: {
|
|
3322
|
+
params,
|
|
3323
|
+
body: sf.text.slice(body.getStart(sf) + 1, body.end - 1),
|
|
3324
|
+
block: true,
|
|
3325
|
+
line
|
|
3326
|
+
},
|
|
3327
|
+
node
|
|
3328
|
+
};
|
|
3329
|
+
return {
|
|
3330
|
+
arrow: {
|
|
3331
|
+
params,
|
|
3332
|
+
body: textOf(sf, body),
|
|
3333
|
+
block: false,
|
|
3334
|
+
line
|
|
3335
|
+
},
|
|
3336
|
+
node
|
|
3337
|
+
};
|
|
3338
|
+
};
|
|
3339
|
+
for (const st of sf.statements) {
|
|
3340
|
+
if (!is.isVariableStatement(st)) continue;
|
|
3341
|
+
const exported = isExported(st);
|
|
3342
|
+
const constant = isConst(st.declarationList);
|
|
3343
|
+
for (const d of st.declarationList.declarations) {
|
|
3344
|
+
if (!is.isIdentifier(d.name) || !d.initializer) continue;
|
|
3345
|
+
const name = d.name.text;
|
|
3346
|
+
let init = d.initializer;
|
|
3347
|
+
while (is.isParenthesizedExpression(init) || is.isSatisfiesExpression(init) || is.isAsExpression(init) || is.isNonNullExpression(init)) init = init.expression;
|
|
3348
|
+
if (!is.isCallExpression(init)) continue;
|
|
3349
|
+
const kind = combinator(init.expression);
|
|
3350
|
+
if (!kind) continue;
|
|
3351
|
+
const line = lineAt(sf, st);
|
|
3352
|
+
try {
|
|
3353
|
+
if (!exported) fail(`${name} is a spec but not exported, so nothing would check it`, st);
|
|
3354
|
+
if (!constant) fail(`a spec must be a const export, not ${textOf(sf, st).split(/\s/)[exported ? 1 : 0] ?? "let"}`, st);
|
|
3355
|
+
const [first, second, third] = init.arguments;
|
|
3356
|
+
const fn = functionArg(first, init);
|
|
3357
|
+
if (kind === "total") {
|
|
3358
|
+
if (second) fail("total takes the function alone", second);
|
|
3359
|
+
specs.push({
|
|
3360
|
+
name,
|
|
3361
|
+
kind: "total",
|
|
3362
|
+
fn,
|
|
3363
|
+
text: `total(${fn})`,
|
|
3364
|
+
line,
|
|
3365
|
+
hints: /* @__PURE__ */ new Map()
|
|
3366
|
+
});
|
|
3367
|
+
continue;
|
|
3368
|
+
}
|
|
3369
|
+
if (!second) return fail("forall takes the function, then { when, ensures }", init);
|
|
3370
|
+
if (third) return fail(`unexpected ${textOf(sf, third)} after forall's arguments`, third);
|
|
3371
|
+
if (!is.isObjectLiteralExpression(second)) return fail("forall's second argument must be an object literal { when, ensures }", second);
|
|
3372
|
+
let sample;
|
|
3373
|
+
let when;
|
|
3374
|
+
let ensures;
|
|
3375
|
+
for (const prop of second.properties) {
|
|
3376
|
+
const key = is.isPropertyAssignment(prop) || is.isShorthandPropertyAssignment(prop) || is.isMethodDeclaration(prop) ? prop.name : void 0;
|
|
3377
|
+
const keyName = key && is.isIdentifier(key) ? key.text : key ? textOf(sf, key) : textOf(sf, prop);
|
|
3378
|
+
if (keyName !== "sample" && keyName !== "when" && keyName !== "ensures") fail(`forall's properties are sample, when and ensures, found ${keyName}`, prop);
|
|
3379
|
+
if (!is.isPropertyAssignment(prop)) fail(`${keyName} must be written as ${keyName}: (…) => …`, prop);
|
|
3380
|
+
const read = arrow(prop.initializer, keyName);
|
|
3381
|
+
if (keyName === "sample") {
|
|
3382
|
+
if (sample) fail("sample is given twice", prop);
|
|
3383
|
+
sample = read;
|
|
3384
|
+
} else if (keyName === "when") {
|
|
3385
|
+
if (when) fail("when is given twice", prop);
|
|
3386
|
+
when = read;
|
|
3387
|
+
} else {
|
|
3388
|
+
if (ensures) fail("ensures is given twice", prop);
|
|
3389
|
+
ensures = read;
|
|
3390
|
+
}
|
|
3391
|
+
}
|
|
3392
|
+
if (!ensures) return fail("forall needs an ensures", second);
|
|
3393
|
+
const hintsOfArrow = (a) => a && !is.isBlock(a.node.body) ? hintsIn(sf, a.node.body, a.arrow.params) : /* @__PURE__ */ new Map();
|
|
3394
|
+
const fromSample = hintsOfArrow(sample);
|
|
3395
|
+
const fromWhen = hintsOfArrow(when);
|
|
3396
|
+
const hints = /* @__PURE__ */ new Map();
|
|
3397
|
+
for (const i of /* @__PURE__ */ new Set([...fromSample.keys(), ...fromWhen.keys()])) {
|
|
3398
|
+
const h = combineHints(fromWhen.get(i), fromSample.get(i));
|
|
3399
|
+
if (h) hints.set(i, h);
|
|
2825
3400
|
}
|
|
3401
|
+
specs.push({
|
|
3402
|
+
name,
|
|
3403
|
+
kind: "forall",
|
|
3404
|
+
fn,
|
|
3405
|
+
...sample ? { sample: sample.arrow } : {},
|
|
3406
|
+
...when ? { when: when.arrow } : {},
|
|
3407
|
+
ensures: ensures.arrow,
|
|
3408
|
+
text: ensures.arrow.body.replace(/\s+/g, " ").trim(),
|
|
3409
|
+
line,
|
|
3410
|
+
hints
|
|
3411
|
+
});
|
|
3412
|
+
} catch (err) {
|
|
3413
|
+
if (!(err instanceof SpecFail)) throw err;
|
|
3414
|
+
errors.push({
|
|
3415
|
+
line: err.line,
|
|
3416
|
+
message: `${name}: ${err.message}`
|
|
3417
|
+
});
|
|
2826
3418
|
}
|
|
2827
3419
|
}
|
|
2828
3420
|
}
|
|
2829
|
-
|
|
2830
|
-
|
|
2831
|
-
|
|
2832
|
-
|
|
2833
|
-
|
|
2834
|
-
|
|
2835
|
-
|
|
2836
|
-
|
|
2837
|
-
|
|
2838
|
-
|
|
2839
|
-
|
|
2840
|
-
|
|
2841
|
-
|
|
2842
|
-
|
|
2843
|
-
|
|
2844
|
-
|
|
2845
|
-
|
|
2846
|
-
|
|
2847
|
-
|
|
2848
|
-
|
|
2849
|
-
|
|
2850
|
-
|
|
2851
|
-
|
|
3421
|
+
return {
|
|
3422
|
+
specs,
|
|
3423
|
+
errors,
|
|
3424
|
+
imports: [...bound].filter(([, imp]) => imp.name !== "*" && imp.name !== "default" && fromModule(imp)).map(([local, imp]) => ({
|
|
3425
|
+
local,
|
|
3426
|
+
name: imp.name
|
|
3427
|
+
}))
|
|
3428
|
+
};
|
|
3429
|
+
}
|
|
3430
|
+
/** The tighter of two endpoints on one side; the first when they cannot be compared. */
|
|
3431
|
+
function tighter(first, second, side) {
|
|
3432
|
+
if (!first) return second;
|
|
3433
|
+
if (!second) return first;
|
|
3434
|
+
const integral = (e) => !/[.eE]/.test(e.value);
|
|
3435
|
+
let order;
|
|
3436
|
+
try {
|
|
3437
|
+
if (integral(first) && integral(second)) {
|
|
3438
|
+
const a = endpointBigInt(first.value);
|
|
3439
|
+
const b = endpointBigInt(second.value);
|
|
3440
|
+
order = a === b ? 0 : a > b ? 1 : -1;
|
|
3441
|
+
} else {
|
|
3442
|
+
const a = endpointNumber(first.value);
|
|
3443
|
+
const b = endpointNumber(second.value);
|
|
3444
|
+
if (Number.isNaN(a) || Number.isNaN(b)) return first;
|
|
3445
|
+
order = a === b ? 0 : a > b ? 1 : -1;
|
|
2852
3446
|
}
|
|
3447
|
+
} catch {
|
|
3448
|
+
return first;
|
|
2853
3449
|
}
|
|
3450
|
+
if (order !== 0) return (side === "lower" ? order > 0 : order < 0) ? first : second;
|
|
3451
|
+
return first.inclusive ? second : first;
|
|
3452
|
+
}
|
|
3453
|
+
/**
|
|
3454
|
+
* Two hints on one binder as one: integer when either says so, the
|
|
3455
|
+
* tighter bound on each side, the first's regex (two cannot be combined,
|
|
3456
|
+
* and the draws are checked against both arrows anyway).
|
|
3457
|
+
*/
|
|
3458
|
+
function combineHints(first, second) {
|
|
3459
|
+
if (!first) return second;
|
|
3460
|
+
if (!second) return first;
|
|
3461
|
+
const lower = tighter(first.lower, second.lower, "lower");
|
|
3462
|
+
const upper = tighter(first.upper, second.upper, "upper");
|
|
3463
|
+
const regex = first.regex ?? second.regex;
|
|
2854
3464
|
return {
|
|
2855
|
-
|
|
2856
|
-
|
|
2857
|
-
|
|
2858
|
-
|
|
3465
|
+
...first.integer || second.integer ? { integer: true } : {},
|
|
3466
|
+
...lower ? { lower } : {},
|
|
3467
|
+
...upper ? { upper } : {},
|
|
3468
|
+
...regex ? { regex } : {}
|
|
2859
3469
|
};
|
|
2860
3470
|
}
|
|
2861
|
-
|
|
2862
|
-
|
|
2863
|
-
|
|
2864
|
-
|
|
2865
|
-
|
|
2866
|
-
|
|
2867
|
-
|
|
2868
|
-
}
|
|
2869
|
-
|
|
2870
|
-
|
|
2871
|
-
|
|
2872
|
-
|
|
2873
|
-
|
|
3471
|
+
/** Read a module and its spec file. */
|
|
3472
|
+
function readSpecs(input) {
|
|
3473
|
+
const modulePath = input.modulePath;
|
|
3474
|
+
const specPath = input.specPath ?? modulePath.replace(/\.ts$/, ".props.ts");
|
|
3475
|
+
return withProgram([{
|
|
3476
|
+
path: modulePath,
|
|
3477
|
+
text: input.module
|
|
3478
|
+
}, {
|
|
3479
|
+
path: specPath,
|
|
3480
|
+
text: input.spec
|
|
3481
|
+
}], (opened) => {
|
|
3482
|
+
const { checker, file, parseError } = opened;
|
|
3483
|
+
const moduleError = parseError(modulePath);
|
|
3484
|
+
const specError = parseError(specPath);
|
|
3485
|
+
const errors = [];
|
|
3486
|
+
if (moduleError) errors.push({
|
|
3487
|
+
line: moduleError.line,
|
|
3488
|
+
message: `the module could not be parsed: ${moduleError.message}`,
|
|
3489
|
+
inModule: true
|
|
3490
|
+
});
|
|
3491
|
+
if (specError) errors.push({
|
|
3492
|
+
line: specError.line,
|
|
3493
|
+
message: `the spec file could not be parsed: ${specError.message}`
|
|
3494
|
+
});
|
|
3495
|
+
if (moduleError || specError) return {
|
|
3496
|
+
functions: [],
|
|
3497
|
+
errors
|
|
3498
|
+
};
|
|
3499
|
+
const moduleFile = file(modulePath);
|
|
3500
|
+
const moduleSide = readModuleSide(moduleFile, checker);
|
|
3501
|
+
const specSide = readSpecSide(file(specPath), opened, modulePath, moduleFile.path, new Set(input.specSpecifiers ?? ["eutaxy/spec", "@eutaxy/spec"]));
|
|
3502
|
+
errors.push(...moduleSide.errors, ...specSide.errors);
|
|
3503
|
+
const patched = rebound(file(specPath), checker, opened.standardGlobal);
|
|
3504
|
+
if (patched) errors.push({
|
|
3505
|
+
line: patched.line,
|
|
3506
|
+
message: `the spec file assigns to ${patched.target}, so the built-ins its claims are read with may not be the standard ones`
|
|
3507
|
+
});
|
|
3508
|
+
const imports = specSide.imports.flatMap((i) => {
|
|
3509
|
+
const fn = moduleSide.exports.get(i.name);
|
|
3510
|
+
return fn === void 0 ? [] : [{
|
|
3511
|
+
local: i.local,
|
|
3512
|
+
fn
|
|
3513
|
+
}];
|
|
3514
|
+
});
|
|
3515
|
+
const byFunction = /* @__PURE__ */ new Map();
|
|
3516
|
+
for (const s of specSide.specs) {
|
|
3517
|
+
const local = moduleSide.exports.get(s.fn);
|
|
3518
|
+
const decl = local === void 0 ? void 0 : moduleSide.declarations.get(local);
|
|
3519
|
+
if (!decl) {
|
|
3520
|
+
errors.push({
|
|
3521
|
+
line: s.line,
|
|
3522
|
+
message: `${s.name}: the module exports no function ${s.fn} whose parameters the reader can read (a function declaration or a const arrow)`
|
|
3523
|
+
});
|
|
3524
|
+
continue;
|
|
3525
|
+
}
|
|
3526
|
+
const entry = byFunction.get(s.fn) ?? {
|
|
3527
|
+
decl,
|
|
3528
|
+
properties: []
|
|
3529
|
+
};
|
|
3530
|
+
if (entry.properties.some((p) => p.name === s.name)) {
|
|
3531
|
+
errors.push({
|
|
3532
|
+
line: s.line,
|
|
3533
|
+
message: `${s.name} is exported twice`
|
|
3534
|
+
});
|
|
3535
|
+
continue;
|
|
3536
|
+
}
|
|
3537
|
+
const binders = decl.params.map((p, i) => {
|
|
3538
|
+
const name = s.ensures?.params[i] ?? p.name ?? `arg${i}`;
|
|
3539
|
+
const hint = s.hints.get(i);
|
|
3540
|
+
return {
|
|
3541
|
+
name,
|
|
3542
|
+
type: p.type,
|
|
3543
|
+
...hint ? { hint } : {}
|
|
3544
|
+
};
|
|
3545
|
+
});
|
|
3546
|
+
entry.properties.push({
|
|
3547
|
+
name: s.name,
|
|
3548
|
+
kind: s.kind,
|
|
3549
|
+
binders,
|
|
3550
|
+
...s.sample ? { sample: s.sample } : {},
|
|
3551
|
+
...s.when ? { when: s.when } : {},
|
|
3552
|
+
...s.ensures ? { ensures: s.ensures } : {},
|
|
3553
|
+
imports,
|
|
3554
|
+
text: s.text,
|
|
3555
|
+
line: s.line
|
|
3556
|
+
});
|
|
3557
|
+
byFunction.set(s.fn, entry);
|
|
3558
|
+
}
|
|
3559
|
+
return {
|
|
3560
|
+
functions: [...byFunction.entries()].map(([name, { decl, properties }]) => ({
|
|
3561
|
+
name,
|
|
3562
|
+
params: decl.params,
|
|
3563
|
+
properties,
|
|
3564
|
+
line: decl.line,
|
|
3565
|
+
offset: decl.offset
|
|
3566
|
+
})),
|
|
3567
|
+
errors
|
|
3568
|
+
};
|
|
3569
|
+
});
|
|
2874
3570
|
}
|
|
2875
|
-
/** The expression kinds only lists bring, for an engine that does not take them. */
|
|
2876
|
-
const listKinds = /* @__PURE__ */ new Set([
|
|
2877
|
-
"list",
|
|
2878
|
-
"tail",
|
|
2879
|
-
"headOr",
|
|
2880
|
-
"iterate",
|
|
2881
|
-
"fold"
|
|
2882
|
-
]);
|
|
2883
|
-
/** Whether an expression is one only lists bring (a type guard over `listKinds`). */
|
|
2884
|
-
const isListExpr = (e) => listKinds.has(e.kind);
|
|
2885
3571
|
// packages/prover-lean/src/emit.ts
|
|
2886
3572
|
/**
|
|
2887
3573
|
* Lean 4 for a module in the subset and the properties on it. The
|
|
@@ -2947,6 +3633,31 @@ function env$1(module) {
|
|
|
2947
3633
|
}
|
|
2948
3634
|
};
|
|
2949
3635
|
}
|
|
3636
|
+
const divisionOutside = "division other than Math.floor(x / c) with c a positive integer constant: this engine models numbers as integers, which / leaves (the SMT engine takes it)";
|
|
3637
|
+
/** Whether an expression divides other than as Math.floor(x / c), c a positive integer constant. */
|
|
3638
|
+
function dividesOutside(e) {
|
|
3639
|
+
if (e.kind === "floor" && e.operand.kind === "binary" && e.operand.op === "/") {
|
|
3640
|
+
const c = integerValue(e.operand.right);
|
|
3641
|
+
if (c !== void 0 && c > 0n) return dividesOutside(e.operand.left);
|
|
3642
|
+
}
|
|
3643
|
+
if (e.kind === "binary" && e.op === "/") return true;
|
|
3644
|
+
return children(e).some(dividesOutside);
|
|
3645
|
+
}
|
|
3646
|
+
/** The value of an integer expression built from literals by + - * and negation, if it is one. */
|
|
3647
|
+
function integerValue(e) {
|
|
3648
|
+
if (e.kind === "int") return BigInt(e.value);
|
|
3649
|
+
if (e.kind === "neg") {
|
|
3650
|
+
const v = integerValue(e.operand);
|
|
3651
|
+
return v === void 0 ? void 0 : -v;
|
|
3652
|
+
}
|
|
3653
|
+
if (e.kind !== "binary") return void 0;
|
|
3654
|
+
const l = integerValue(e.left);
|
|
3655
|
+
const r = integerValue(e.right);
|
|
3656
|
+
if (l === void 0 || r === void 0) return void 0;
|
|
3657
|
+
if (e.op === "+") return l + r;
|
|
3658
|
+
if (e.op === "-") return l - r;
|
|
3659
|
+
if (e.op === "*") return l * r;
|
|
3660
|
+
}
|
|
2950
3661
|
const fail$1 = (message) => {
|
|
2951
3662
|
throw new OutsideSubset(message, 0);
|
|
2952
3663
|
};
|
|
@@ -2967,7 +3678,15 @@ function term$1(e, scope, env) {
|
|
|
2967
3678
|
case "not": return `(!${t(e.operand)})`;
|
|
2968
3679
|
case "isInteger":
|
|
2969
3680
|
typeOf(e.operand, scope, env.ctx, fail$1);
|
|
3681
|
+
t(e.operand);
|
|
2970
3682
|
return "true";
|
|
3683
|
+
case "floor": {
|
|
3684
|
+
const o = e.operand;
|
|
3685
|
+
if (o.kind !== "binary" || o.op !== "/") return t(o);
|
|
3686
|
+
const c = integerValue(o.right);
|
|
3687
|
+
if (c === void 0 || c <= 0n) fail$1(divisionOutside);
|
|
3688
|
+
return `(${t(o.left)} / (${c} : Int))`;
|
|
3689
|
+
}
|
|
2971
3690
|
case "binary":
|
|
2972
3691
|
switch (e.op) {
|
|
2973
3692
|
case "+": {
|
|
@@ -2976,6 +3695,7 @@ function term$1(e, scope, env) {
|
|
|
2976
3695
|
}
|
|
2977
3696
|
case "-":
|
|
2978
3697
|
case "*": return `(${t(e.left)} ${e.op} ${t(e.right)})`;
|
|
3698
|
+
case "/": return fail$1(divisionOutside);
|
|
2979
3699
|
case "<":
|
|
2980
3700
|
case ">": return `(decide (${t(e.left)} ${e.op} ${t(e.right)}))`;
|
|
2981
3701
|
case "<=": return `(decide (${t(e.left)} ≤ ${t(e.right)}))`;
|
|
@@ -3652,7 +4372,8 @@ const leanTakes = (t) => t.kind === "int" || t.kind === "bool" || t.kind === "st
|
|
|
3652
4372
|
const engineAssumptions$1 = [
|
|
3653
4373
|
"number is modelled as the unbounded integers: no overflow, no fractions, no NaN",
|
|
3654
4374
|
"string is modelled as Lean's String, a sequence of Unicode characters: a lone surrogate, which a JavaScript string can hold, is outside every string binder's domain",
|
|
3655
|
-
"the function and its callees are the module's own,
|
|
4375
|
+
"the function and its callees are pure and total: the module's own, or generic or imported ones read at each call from their own files; nothing else is modelled",
|
|
4376
|
+
builtinsAssumption,
|
|
3656
4377
|
`the proof was checked by the Lean ${leanVersion} kernel on the emitted statement, not by Eutaxy`
|
|
3657
4378
|
];
|
|
3658
4379
|
/** What a PROVEN over arrays rests on besides: the list model. */
|
|
@@ -3688,7 +4409,7 @@ function prepare$1(input) {
|
|
|
3688
4409
|
const specs = input.specs;
|
|
3689
4410
|
const wanted = input.functions ? new Set(input.functions) : void 0;
|
|
3690
4411
|
const fns = specs.functions.filter((f) => !wanted || wanted.has(f.name));
|
|
3691
|
-
const module = restrictModule(readSubset(input.source, fns.map((f) => f.name), input.modulePath === void 0 ? {} : { path: input.modulePath }), leanTakes, "nullable types and tagged unions are not in the Lean engine's subset yet");
|
|
4412
|
+
const module = restrictModule(restrictModule(readSubset(input.source, fns.map((f) => f.name), input.modulePath === void 0 ? {} : { path: input.modulePath }), leanTakes, "nullable types and tagged unions are not in the Lean engine's subset yet"), () => true, divisionOutside, /* @__PURE__ */ new Set(), dividesOutside);
|
|
3692
4413
|
const outside = /* @__PURE__ */ new Map();
|
|
3693
4414
|
for (const o of module.outside) if (fns.some((f) => f.name === o.name)) outside.set(o.name, `outside the engine's subset${o.line > 0 ? ` (line ${o.line})` : ""}: ${o.message}`);
|
|
3694
4415
|
for (const fn of fns) {
|
|
@@ -3906,7 +4627,10 @@ function usesLists(property, roots, module) {
|
|
|
3906
4627
|
* NaN, the infinities and -0 are in every binder's domain and `===` is
|
|
3907
4628
|
* `fp.eq`, as in JavaScript), `string` a sequence of 16-bit code units,
|
|
3908
4629
|
* `boolean` Bool, a record a datatype with one constructor, a tagged
|
|
3909
|
-
* union a datatype with one constructor per member
|
|
4630
|
+
* union a datatype with one constructor per member holding that member's
|
|
4631
|
+
* record (so a record may be a member of several unions: a member is
|
|
4632
|
+
* wrapped where one of its unions is expected, and unwrapped where a test
|
|
4633
|
+
* of the tag narrows the union to it), a nullable type an
|
|
3910
4634
|
* option datatype (`none`, `some`), with a name narrowed by a null check
|
|
3911
4635
|
* bound to its value in the branch the check guards. Each property is one
|
|
3912
4636
|
* script: the definitions, the binders as constants with what their
|
|
@@ -3925,9 +4649,12 @@ function symbol(name) {
|
|
|
3925
4649
|
/** TypeScript names as SMT symbols that cannot clash with each other or with the theories' names. */
|
|
3926
4650
|
const ident = {
|
|
3927
4651
|
fn: (name) => symbol(`f_${name}`),
|
|
3928
|
-
/** The datatype of a record
|
|
4652
|
+
/** The datatype of a record, or of a union. */
|
|
3929
4653
|
record: (name) => symbol(`R_${name}`),
|
|
3930
4654
|
constructor: (name) => symbol(`mk_${name}`),
|
|
4655
|
+
/** A union's constructor for one member, holding the member's record, and its selector. */
|
|
4656
|
+
inject: (union, member) => symbol(`in.${union}.${member}`),
|
|
4657
|
+
project: (union, member) => symbol(`out.${union}.${member}`),
|
|
3931
4658
|
field: (record, field) => symbol(`fld.${record}.${field}`),
|
|
3932
4659
|
variable: (name) => symbol(`v_${name}`),
|
|
3933
4660
|
/** The option datatype over a sort, and its constructors and selector. */
|
|
@@ -3943,16 +4670,12 @@ function sortName(t, module) {
|
|
|
3943
4670
|
case "int": return "F64";
|
|
3944
4671
|
case "bool": return "Bool";
|
|
3945
4672
|
case "string": return "Str";
|
|
3946
|
-
case "record":
|
|
4673
|
+
case "record":
|
|
3947
4674
|
case "union": return ident.record(t.name);
|
|
3948
4675
|
case "nullable": return ident.option(sortName(t.inner, module));
|
|
3949
4676
|
case "null": return fail("null has no sort of its own");
|
|
3950
4677
|
}
|
|
3951
4678
|
}
|
|
3952
|
-
/** The union a record is a member of, by the record's name. */
|
|
3953
|
-
function unionOf(record, module) {
|
|
3954
|
-
return module.records.find((r) => r.name === record)?.union;
|
|
3955
|
-
}
|
|
3956
4679
|
function sort(t, module) {
|
|
3957
4680
|
if (t.kind === "list" || t.kind === "nothing") return fail(listsOutside);
|
|
3958
4681
|
switch (t.kind) {
|
|
@@ -4035,9 +4758,27 @@ function sameAs(a, b, t, env) {
|
|
|
4035
4758
|
}
|
|
4036
4759
|
}
|
|
4037
4760
|
/**
|
|
4761
|
+
* A term of type `actual` as a value of type `want`: a member record
|
|
4762
|
+
* wrapped in the union's constructor for it, a value wrapped in `some`
|
|
4763
|
+
* where a nullable is wanted, a nullable member mapped into the nullable
|
|
4764
|
+
* union. Anything else is already of the sort wanted.
|
|
4765
|
+
*/
|
|
4766
|
+
function lift(inner, actual, want, module) {
|
|
4767
|
+
if (want.kind === "union" && actual.kind === "record") return `(${ident.inject(want.name, actual.name)} ${inner})`;
|
|
4768
|
+
if (want.kind !== "nullable") return inner;
|
|
4769
|
+
if (actual.kind === "null") return inner;
|
|
4770
|
+
if (actual.kind === "nullable") {
|
|
4771
|
+
if (want.inner.kind !== "union" || actual.inner.kind !== "record") return inner;
|
|
4772
|
+
const from = sortName(actual.inner, module);
|
|
4773
|
+
const to = sortName(want.inner, module);
|
|
4774
|
+
return `(ite (${tester(ident.none(from))} ${inner}) ${ident.none(to)} (${ident.some(to)} ${lift(`(${ident.val(from)} ${inner})`, actual.inner, want.inner, module)}))`;
|
|
4775
|
+
}
|
|
4776
|
+
return `(${ident.some(sortName(want.inner, module))} ${lift(inner, actual, want.inner, module)})`;
|
|
4777
|
+
}
|
|
4778
|
+
/**
|
|
4038
4779
|
* A term of the expression's type, or of `expected` where one is given:
|
|
4039
4780
|
* `null` and a non-null value become the option's constructors where a
|
|
4040
|
-
* nullable is expected, and a member record
|
|
4781
|
+
* nullable is expected, and a member record its union's where the union is.
|
|
4041
4782
|
*/
|
|
4042
4783
|
function term(e, scope, env, expected) {
|
|
4043
4784
|
const t = (x, want) => term(x, scope, env, want);
|
|
@@ -4059,9 +4800,7 @@ function term(e, scope, env, expected) {
|
|
|
4059
4800
|
const coerceIn = (x, want, sc) => {
|
|
4060
4801
|
if (x.kind === "cond" || x.kind === "let" || x.kind === "narrow" || x.kind === "narrowTag" || x.kind === "null") return term(x, sc, env, want);
|
|
4061
4802
|
const actual = sc === scope ? typed(x) : typeOf(x, sc, env.ctx, fail);
|
|
4062
|
-
|
|
4063
|
-
if (want.kind === "nullable" && actual.kind !== "nullable" && actual.kind !== "null") return `(${ident.some(sortName(want.inner, env.module))} ${inner})`;
|
|
4064
|
-
return inner;
|
|
4803
|
+
return lift(term(x, sc, env, want), actual, want, env.module);
|
|
4065
4804
|
};
|
|
4066
4805
|
const coerce = (x, want) => coerceIn(x, want, scope);
|
|
4067
4806
|
const narrowed = (body, inner) => expected ? coerceIn(body, expected, inner) : term(body, inner, env);
|
|
@@ -4082,17 +4821,20 @@ function term(e, scope, env, expected) {
|
|
|
4082
4821
|
return `(let ((${ident.variable(e.name)} (${ident.val(base)} ${ident.variable(e.name)}))) ${narrowed(e.body, inner)})`;
|
|
4083
4822
|
}
|
|
4084
4823
|
case "narrowTag": {
|
|
4085
|
-
|
|
4824
|
+
const nt = scope.get(e.name);
|
|
4825
|
+
if (nt?.kind !== "union") fail(`${e.name} is narrowed by a tag but is not a union`);
|
|
4086
4826
|
const inner = new Map(scope);
|
|
4087
4827
|
inner.set(e.name, {
|
|
4088
4828
|
kind: "record",
|
|
4089
4829
|
name: e.member
|
|
4090
4830
|
});
|
|
4091
|
-
|
|
4831
|
+
const v = ident.variable(e.name);
|
|
4832
|
+
return `(let ((${v} (${ident.project(nt.name, e.member)} ${v}))) ${narrowed(e.body, inner)})`;
|
|
4092
4833
|
}
|
|
4093
4834
|
case "neg": return `(fp.neg ${t(e.operand)})`;
|
|
4094
4835
|
case "not": return `(not ${t(e.operand)})`;
|
|
4095
4836
|
case "isInteger": return isIntegerTerm(t(e.operand));
|
|
4837
|
+
case "floor": return `(fp.roundToIntegral RTN ${t(e.operand)})`;
|
|
4096
4838
|
case "binary": {
|
|
4097
4839
|
const lt = typed(e.left);
|
|
4098
4840
|
const rt = typed(e.right);
|
|
@@ -4100,6 +4842,7 @@ function term(e, scope, env, expected) {
|
|
|
4100
4842
|
case "+": return lt.kind === "string" ? `(seq.++ ${t(e.left)} ${t(e.right)})` : `(fp.add RNE ${t(e.left)} ${t(e.right)})`;
|
|
4101
4843
|
case "-": return `(fp.sub RNE ${t(e.left)} ${t(e.right)})`;
|
|
4102
4844
|
case "*": return `(fp.mul RNE ${t(e.left)} ${t(e.right)})`;
|
|
4845
|
+
case "/": return `(fp.div RNE ${t(e.left)} ${t(e.right)})`;
|
|
4103
4846
|
case "<": return `(fp.lt ${t(e.left)} ${t(e.right)})`;
|
|
4104
4847
|
case "<=": return `(fp.leq ${t(e.left)} ${t(e.right)})`;
|
|
4105
4848
|
case ">": return `(fp.gt ${t(e.left)} ${t(e.right)})`;
|
|
@@ -4139,8 +4882,8 @@ function term(e, scope, env, expected) {
|
|
|
4139
4882
|
const o = typed(e.object);
|
|
4140
4883
|
const obj = t(e.object);
|
|
4141
4884
|
if (o.kind === "union") return membersOf(o.name, env).reduceRight((rest, m) => {
|
|
4142
|
-
const read = `(${ident.field(m.name, e.field)} ${obj})`;
|
|
4143
|
-
return rest === void 0 ? read : `(ite (${tester(ident.
|
|
4885
|
+
const read = `(${ident.field(m.name, e.field)} (${ident.project(o.name, m.name)} ${obj}))`;
|
|
4886
|
+
return rest === void 0 ? read : `(ite (${tester(ident.inject(o.name, m.name))} ${obj}) ${read} ${rest})`;
|
|
4144
4887
|
}, void 0);
|
|
4145
4888
|
if (o.kind !== "record") fail(`field ${e.field} read from a ${o.kind}`);
|
|
4146
4889
|
return `(${ident.field(o.name, e.field)} ${obj})`;
|
|
@@ -4159,7 +4902,7 @@ function term(e, scope, env, expected) {
|
|
|
4159
4902
|
const bound = e.type ?? typed(e.value);
|
|
4160
4903
|
inner.set(e.name, bound);
|
|
4161
4904
|
const value = e.type ? coerce(e.value, e.type) : t(e.value);
|
|
4162
|
-
return `(let ((${ident.variable(e.name)} ${value})) ${
|
|
4905
|
+
return `(let ((${ident.variable(e.name)} ${value})) ${narrowed(e.body, inner)})`;
|
|
4163
4906
|
}
|
|
4164
4907
|
}
|
|
4165
4908
|
}
|
|
@@ -4170,15 +4913,13 @@ function emitFunction(f, module) {
|
|
|
4170
4913
|
const body = (() => {
|
|
4171
4914
|
const b = f.body;
|
|
4172
4915
|
if (b.kind === "cond" || b.kind === "let" || b.kind === "narrow" || b.kind === "narrowTag" || b.kind === "null") return term(b, scope, e, f.returns);
|
|
4173
|
-
|
|
4174
|
-
const inner = term(b, scope, e, f.returns);
|
|
4175
|
-
return f.returns.kind === "nullable" && actual.kind !== "nullable" && actual.kind !== "null" ? `(${ident.some(sortName(f.returns.inner, module))} ${inner})` : inner;
|
|
4916
|
+
return lift(term(b, scope, e, f.returns), typeOf(b, scope, e.ctx, fail), f.returns, module);
|
|
4176
4917
|
})();
|
|
4177
4918
|
return `(define-fun ${ident.fn(f.name)} (${params}) ${sort(f.returns, module)}\n ${body})`;
|
|
4178
4919
|
}
|
|
4179
4920
|
/**
|
|
4180
4921
|
* An option sort over every sort the module could mention: the primitives,
|
|
4181
|
-
* every record
|
|
4922
|
+
* every record, every union. A body may join a
|
|
4182
4923
|
* value with `null` in a `const` that no signature shows, so nothing is
|
|
4183
4924
|
* left to discovery.
|
|
4184
4925
|
*/
|
|
@@ -4188,7 +4929,7 @@ function optionSorts(module) {
|
|
|
4188
4929
|
{ kind: "int" },
|
|
4189
4930
|
{ kind: "bool" },
|
|
4190
4931
|
{ kind: "string" },
|
|
4191
|
-
...module.records.
|
|
4932
|
+
...module.records.map((r) => ({
|
|
4192
4933
|
kind: "record",
|
|
4193
4934
|
name: r.name
|
|
4194
4935
|
})),
|
|
@@ -4203,10 +4944,11 @@ function optionSorts(module) {
|
|
|
4203
4944
|
/**
|
|
4204
4945
|
* Every datatype in one declaration, so records, unions and options may
|
|
4205
4946
|
* refer to one another in any order: a record is one constructor, a union
|
|
4206
|
-
* one per member, an option `none` and `some` over its
|
|
4947
|
+
* one per member holding its record, an option `none` and `some` over its
|
|
4948
|
+
* base sort.
|
|
4207
4949
|
*/
|
|
4208
4950
|
function emitDatatypes(module) {
|
|
4209
|
-
const plain = module.records
|
|
4951
|
+
const plain = module.records;
|
|
4210
4952
|
const unions = module.unions;
|
|
4211
4953
|
const options = optionSorts(module);
|
|
4212
4954
|
const names = [
|
|
@@ -4218,7 +4960,7 @@ function emitDatatypes(module) {
|
|
|
4218
4960
|
const constructorOf = (r) => `(${ident.constructor(r.name)}${r.fields.map((f) => ` (${ident.field(r.name, f.name)} ${sort(f.type, module)})`).join("")})`;
|
|
4219
4961
|
const bodies = [
|
|
4220
4962
|
...plain.map((r) => `(${constructorOf(r)})`),
|
|
4221
|
-
...unions.map((u) => `(${u.members.map((m) =>
|
|
4963
|
+
...unions.map((u) => `(${u.members.map((m) => `(${ident.inject(u.name, m.record)} (${ident.project(u.name, m.record)} ${ident.record(m.record)}))`).join(" ")})`),
|
|
4222
4964
|
...[...options].map(([base, inner]) => `((${ident.none(base)}) (${ident.some(base)} (${ident.val(base)} ${sort(inner, module)})))`)
|
|
4223
4965
|
];
|
|
4224
4966
|
return `(declare-datatypes (${names.map((n) => `(${n} 0)`).join(" ")}) (${bodies.join(" ")}))`;
|
|
@@ -4253,7 +4995,7 @@ function binderType(name, t, module) {
|
|
|
4253
4995
|
else if (rest.length === 1) inner = binderType(name, rest[0], module);
|
|
4254
4996
|
else if (rest.every((m) => m.kind === "record")) {
|
|
4255
4997
|
const union = findUnion(rest, module);
|
|
4256
|
-
if (!union) fail(`binder ${name} over ${describeType(t)}: no union the module declares has these members`);
|
|
4998
|
+
if (!union) fail(`binder ${name} over ${describeType(t)}: no one union the module declares has exactly these members`);
|
|
4257
4999
|
inner = {
|
|
4258
5000
|
kind: "union",
|
|
4259
5001
|
name: union.name
|
|
@@ -4281,20 +5023,65 @@ function binderType(name, t, module) {
|
|
|
4281
5023
|
case "unknown": fail(`binder ${name} over ${t.text}, which the reader could not read`);
|
|
4282
5024
|
}
|
|
4283
5025
|
}
|
|
4284
|
-
/**
|
|
5026
|
+
/**
|
|
5027
|
+
* The one declared union these member types are, compared field by field
|
|
5028
|
+
* and type by type: a field holding one literal is that literal in the
|
|
5029
|
+
* union's member, a union of literals is a field of no literal, and
|
|
5030
|
+
* everything else reads to the field's own type. A record may be a member
|
|
5031
|
+
* of several unions, so tags and field names alone could name the wrong
|
|
5032
|
+
* one; when more than one union fits, none is chosen.
|
|
5033
|
+
*/
|
|
4285
5034
|
function findUnion(members, module) {
|
|
4286
|
-
|
|
5035
|
+
const recordOf = (name) => module.records.find((r) => r.name === name);
|
|
5036
|
+
const recordFits = (sm, rec) => sm.fields.length === rec.fields.length && rec.fields.every((f) => {
|
|
5037
|
+
const sf = sm.fields.find((x) => x.name === f.name);
|
|
5038
|
+
return sf !== void 0 && fieldFits(sf.type, f);
|
|
5039
|
+
});
|
|
5040
|
+
const typeFits = (sf, t) => {
|
|
5041
|
+
if (t.kind === "record") {
|
|
5042
|
+
const rec = recordOf(t.name);
|
|
5043
|
+
return sf.kind === "record" && rec !== void 0 && recordFits(sf, rec);
|
|
5044
|
+
}
|
|
5045
|
+
if (t.kind === "nullable" && sf.kind === "union" && sf.members.some((m) => m.kind === "null")) {
|
|
5046
|
+
const rest = sf.members.filter((m) => m.kind !== "null");
|
|
5047
|
+
const inner = rest.length === 1 ? rest[0] : {
|
|
5048
|
+
kind: "union",
|
|
5049
|
+
members: rest
|
|
5050
|
+
};
|
|
5051
|
+
return typeFits(inner, t.inner);
|
|
5052
|
+
}
|
|
5053
|
+
if (t.kind === "union") {
|
|
5054
|
+
const u = module.unions.find((x) => x.name === t.name);
|
|
5055
|
+
if (!u || sf.kind !== "union" || sf.members.length !== u.members.length) return false;
|
|
5056
|
+
return u.members.every((m) => {
|
|
5057
|
+
const rec = recordOf(m.record);
|
|
5058
|
+
return rec !== void 0 && sf.members.some((sm) => sm.kind === "record" && recordFits(sm, rec));
|
|
5059
|
+
});
|
|
5060
|
+
}
|
|
5061
|
+
try {
|
|
5062
|
+
return JSON.stringify(binderType("field", sf, module)) === JSON.stringify(t);
|
|
5063
|
+
} catch (err) {
|
|
5064
|
+
if (err instanceof OutsideSubset) return false;
|
|
5065
|
+
throw err;
|
|
5066
|
+
}
|
|
5067
|
+
};
|
|
5068
|
+
function fieldFits(sf, f) {
|
|
5069
|
+
if (f.literal !== void 0) return sf.kind === "literal" && sf.value === f.literal;
|
|
5070
|
+
if (sf.kind === "literal") return false;
|
|
5071
|
+
return typeFits(sf, f.type);
|
|
5072
|
+
}
|
|
5073
|
+
const fitting = module.unions.filter((u) => {
|
|
4287
5074
|
if (u.members.length !== members.length) return false;
|
|
4288
5075
|
return u.members.every((m) => {
|
|
4289
|
-
const rec =
|
|
4290
|
-
|
|
4291
|
-
return members.some((sm) => sm.fields.length === rec.fields.length && sm.fields.every((f) => rec.fields.some((rf) => rf.name === f.name)) && sm.fields.some((f) => f.name === u.tag && f.type.kind === "literal" && f.type.value === m.tag));
|
|
5076
|
+
const rec = recordOf(m.record);
|
|
5077
|
+
return rec !== void 0 && members.some((sm) => recordFits(sm, rec));
|
|
4292
5078
|
});
|
|
4293
5079
|
});
|
|
5080
|
+
return fitting.length === 1 ? fitting[0] : void 0;
|
|
4294
5081
|
}
|
|
4295
5082
|
/**
|
|
4296
|
-
* What a binder's subset type says that its sort does not: a
|
|
4297
|
-
*
|
|
5083
|
+
* What a binder's subset type says that its sort does not: a union's
|
|
5084
|
+
* members carry their tags, and so on
|
|
4298
5085
|
* into fields and under an option. Undefined when the sort says it all.
|
|
4299
5086
|
*/
|
|
4300
5087
|
function wellFormed(target, t, module) {
|
|
@@ -4312,7 +5099,6 @@ function wellFormed(target, t, module) {
|
|
|
4312
5099
|
const rec = module.records.find((r) => r.name === t.name);
|
|
4313
5100
|
if (!rec) return void 0;
|
|
4314
5101
|
const parts = [];
|
|
4315
|
-
if (rec.union !== void 0) parts.push(`(${tester(ident.constructor(rec.name))} ${target})`);
|
|
4316
5102
|
for (const f of rec.fields) {
|
|
4317
5103
|
const read = `(${ident.field(rec.name, f.name)} ${target})`;
|
|
4318
5104
|
if (f.literal !== void 0) parts.push(typeof f.literal === "string" ? `(= ${read} ${stringTerm(f.literal)})` : `(= ${read} ${f.literal ? "true" : "false"})`);
|
|
@@ -4325,10 +5111,12 @@ function wellFormed(target, t, module) {
|
|
|
4325
5111
|
const u = module.unions.find((x) => x.name === t.name);
|
|
4326
5112
|
if (!u) return void 0;
|
|
4327
5113
|
return `(or ${u.members.map((m) => {
|
|
4328
|
-
|
|
5114
|
+
const is = `(${tester(ident.inject(u.name, m.record))} ${target})`;
|
|
5115
|
+
const inner = wellFormed(`(${ident.project(u.name, m.record)} ${target})`, {
|
|
4329
5116
|
kind: "record",
|
|
4330
5117
|
name: m.record
|
|
4331
|
-
}, module)
|
|
5118
|
+
}, module);
|
|
5119
|
+
return inner === void 0 ? is : `(and ${is} ${inner})`;
|
|
4332
5120
|
}).join(" ")})`;
|
|
4333
5121
|
}
|
|
4334
5122
|
}
|
|
@@ -4528,9 +5316,9 @@ function decode(x, t, module) {
|
|
|
4528
5316
|
const u = module.unions.find((y) => y.name === t.name);
|
|
4529
5317
|
if (!u) throw new UnreadableModel(`no union ${t.name}`);
|
|
4530
5318
|
const head = Array.isArray(x) ? x[0] : x;
|
|
4531
|
-
const member = u.members.find((m) => ident.
|
|
4532
|
-
if (!member) throw new UnreadableModel(`not a ${t.name}: ${show(x)}`);
|
|
4533
|
-
return decode(x, {
|
|
5319
|
+
const member = u.members.find((m) => ident.inject(u.name, m.record) === head);
|
|
5320
|
+
if (!member || !Array.isArray(x) || x.length !== 2) throw new UnreadableModel(`not a ${t.name}: ${show(x)}`);
|
|
5321
|
+
return decode(x[1], {
|
|
4534
5322
|
kind: "record",
|
|
4535
5323
|
name: member.record
|
|
4536
5324
|
}, module);
|
|
@@ -4722,7 +5510,8 @@ const proven = {
|
|
|
4722
5510
|
assumptions: [
|
|
4723
5511
|
"number is modelled as the IEEE double (the floating-point theory): NaN, the infinities and -0 are in every binder's domain, and === is fp.eq",
|
|
4724
5512
|
"string is modelled as a sequence of 16-bit code units, as JavaScript holds it",
|
|
4725
|
-
"the function and its callees are the module's own,
|
|
5513
|
+
"the function and its callees are pure and total: the module's own, or generic or imported ones read at each call from their own files; nothing else is modelled",
|
|
5514
|
+
builtinsAssumption,
|
|
4726
5515
|
`Z3 ${z3Version} found the claim's negation unsatisfiable under a resource limit; no proof object was checked by a kernel`
|
|
4727
5516
|
]
|
|
4728
5517
|
};
|
|
@@ -5325,12 +6114,18 @@ async function runCheck(o) {
|
|
|
5325
6114
|
* `eutaxy report [dir]`: every spec file under a directory through the
|
|
5326
6115
|
* ladder, on the Node side. No scenario runs, so the ladder starts at
|
|
5327
6116
|
* `TESTED` (inputs drawn from the parameter types); `--prover` adds the
|
|
5328
|
-
* `PROVEN` rung. Each module runs in a
|
|
6117
|
+
* `PROVEN` rung. Each module runs in a child process of its own, started
|
|
5329
6118
|
* on this file: what the module prints goes to stderr, its state starts
|
|
5330
6119
|
* fresh, and a property that never returns ends with the module's budget.
|
|
6120
|
+
* A process, not a worker thread: Node strips types with WebAssembly, and
|
|
6121
|
+
* V8 shares compiled wasm code between the threads of a process; V8 on
|
|
6122
|
+
* Node 24 can abort while one thread frees that code as another uses it
|
|
6123
|
+
* (seen as SIGSEGV, SIGBUS or SIGTRAP of the whole process).
|
|
5331
6124
|
* A module that only loads inside workerd gets `UNKNOWN` until an engine
|
|
5332
6125
|
* reads it.
|
|
5333
6126
|
*/
|
|
6127
|
+
/** The argument a module's process is started with, so this file knows to run it. */
|
|
6128
|
+
const moduleFlag = "--eutaxy-report-module";
|
|
5334
6129
|
function unknownAll(m, cause, reason) {
|
|
5335
6130
|
return m.specs.functions.flatMap((fn) => fn.properties.map((p) => ({
|
|
5336
6131
|
module: m.key,
|
|
@@ -5344,7 +6139,7 @@ function unknownAll(m, cause, reason) {
|
|
|
5344
6139
|
})));
|
|
5345
6140
|
}
|
|
5346
6141
|
/**
|
|
5347
|
-
* Inside the
|
|
6142
|
+
* Inside the module's process: a relative import from a `.ts` file that Node cannot
|
|
5348
6143
|
* resolve is tried as TypeScript resolves it, so `./domain.js` and
|
|
5349
6144
|
* `./domain` find `domain.ts` (or `domain/index.ts`), as `tsc` would.
|
|
5350
6145
|
*/
|
|
@@ -5362,7 +6157,7 @@ function resolveAsTypeScript() {
|
|
|
5362
6157
|
}
|
|
5363
6158
|
} });
|
|
5364
6159
|
}
|
|
5365
|
-
/** Inside the
|
|
6160
|
+
/** Inside the module's process: load the module and its spec file, run the `TESTED` rung. */
|
|
5366
6161
|
async function testHere(m, seed) {
|
|
5367
6162
|
resolveAsTypeScript();
|
|
5368
6163
|
let namespace;
|
|
@@ -5381,38 +6176,65 @@ async function testHere(m, seed) {
|
|
|
5381
6176
|
tested: { seed }
|
|
5382
6177
|
});
|
|
5383
6178
|
}
|
|
5384
|
-
const
|
|
5385
|
-
if (
|
|
6179
|
+
const send = process.send?.bind(process);
|
|
6180
|
+
if (process.argv[2] === moduleFlag && send) {
|
|
6181
|
+
process.once("disconnect", () => process.exit(0));
|
|
6182
|
+
process.once("message", async (input) => {
|
|
6183
|
+
const verdicts = await testHere(input.module, input.seed);
|
|
6184
|
+
send({
|
|
6185
|
+
kind: "eutaxy-report-verdicts",
|
|
6186
|
+
verdicts
|
|
6187
|
+
}, () => process.stdout.write("", () => process.stderr.write("", () => process.exit(0))));
|
|
6188
|
+
});
|
|
6189
|
+
}
|
|
5386
6190
|
/**
|
|
5387
|
-
* One module's verdicts at the `TESTED` rung, from a
|
|
6191
|
+
* One module's verdicts at the `TESTED` rung, from a child process. What
|
|
5388
6192
|
* the module writes goes to `stderr`; a module that does not load, or does
|
|
5389
6193
|
* not finish within the budget, leaves each property `UNKNOWN`.
|
|
5390
6194
|
*/
|
|
5391
6195
|
function testModule(m, seed, budgetMs, stderr) {
|
|
5392
6196
|
return new Promise((done) => {
|
|
5393
|
-
const
|
|
5394
|
-
|
|
5395
|
-
|
|
5396
|
-
|
|
5397
|
-
|
|
5398
|
-
|
|
5399
|
-
|
|
5400
|
-
|
|
6197
|
+
const child = fork(fileURLToPath(import.meta.url), [moduleFlag], {
|
|
6198
|
+
stdio: [
|
|
6199
|
+
"ignore",
|
|
6200
|
+
"pipe",
|
|
6201
|
+
"pipe",
|
|
6202
|
+
"ipc"
|
|
6203
|
+
],
|
|
6204
|
+
serialization: "advanced"
|
|
5401
6205
|
});
|
|
5402
|
-
|
|
5403
|
-
|
|
6206
|
+
child.stdout?.on("data", (d) => stderr(d.toString()));
|
|
6207
|
+
child.stderr?.on("data", (d) => stderr(d.toString()));
|
|
6208
|
+
let reported;
|
|
6209
|
+
let ended;
|
|
5404
6210
|
let settled = false;
|
|
5405
|
-
const
|
|
6211
|
+
const settle = (verdicts) => {
|
|
5406
6212
|
if (settled) return;
|
|
5407
6213
|
settled = true;
|
|
5408
6214
|
clearTimeout(timer);
|
|
5409
|
-
worker.terminate();
|
|
5410
6215
|
done(verdicts);
|
|
5411
6216
|
};
|
|
5412
|
-
const timer = setTimeout(() =>
|
|
5413
|
-
|
|
5414
|
-
|
|
5415
|
-
|
|
6217
|
+
const timer = setTimeout(() => {
|
|
6218
|
+
ended = unknownAll(m, "gave_up", `the module's properties did not finish within ${budgetMs} ms on generated inputs (one may never return)`);
|
|
6219
|
+
child.kill("SIGKILL");
|
|
6220
|
+
child.stdout?.destroy();
|
|
6221
|
+
child.stderr?.destroy();
|
|
6222
|
+
}, budgetMs);
|
|
6223
|
+
child.on("message", (message) => {
|
|
6224
|
+
if (message?.kind === "eutaxy-report-verdicts" && Array.isArray(message.verdicts)) reported ??= message.verdicts;
|
|
6225
|
+
});
|
|
6226
|
+
child.once("error", (err) => {
|
|
6227
|
+
ended ??= unknownAll(m, "unavailable", `the module's process failed: ${err.message}`);
|
|
6228
|
+
if (child.pid === void 0) settle(ended);
|
|
6229
|
+
else child.kill("SIGKILL");
|
|
6230
|
+
});
|
|
6231
|
+
child.once("close", (code, signal) => {
|
|
6232
|
+
settle(reported ?? ended ?? unknownAll(m, "unavailable", `the module's process exited (${signal ?? code}) before reporting`));
|
|
6233
|
+
});
|
|
6234
|
+
child.send({
|
|
6235
|
+
module: m,
|
|
6236
|
+
seed
|
|
6237
|
+
});
|
|
5416
6238
|
});
|
|
5417
6239
|
}
|
|
5418
6240
|
async function runReport(o) {
|
|
@@ -8528,4 +9350,4 @@ async function checkInWorkerd(input) {
|
|
|
8528
9350
|
}
|
|
8529
9351
|
export { snapshotD1 as A, r2Rows as C, workflow as D, unique as E, expectHolds as M, main as N, workflowRows as O, cloudflareRegressionTest as P, r2Op as S, refines as T, httpResponse as _, d1Param as a, queueAck as b, d1Schema as c, durableObject as d, durableObjectRows as f, http as g, fetchCall as h, atLeastOncePerMessage as i, check as j, workflowStep as k, d1Write as l, external as m, runDifferential as n, d1Read as o, everyRow as p, createCloudflarePlatform as r, d1Rows as s, checkInWorkerd as t, defineScenario as u, implies as v, references as w, r2Bucket as x, queue as y };
|
|
8530
9352
|
|
|
8531
|
-
//# sourceMappingURL=src-
|
|
9353
|
+
//# sourceMappingURL=src-BnTcWa-4.mjs.map
|