eutaxy 0.18.0 → 0.19.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 +15 -12
- package/dist/aws.d.mts +3 -3
- package/dist/aws.d.mts.map +1 -1
- package/dist/aws.mjs +13 -4
- package/dist/aws.mjs.map +1 -1
- package/dist/bin.mjs +1 -1
- package/dist/check-zkHLdWyf.mjs +1281 -0
- package/dist/check-zkHLdWyf.mjs.map +1 -0
- package/dist/cli-Bxjvq4p9.mjs +297 -0
- package/dist/cli-Bxjvq4p9.mjs.map +1 -0
- package/dist/cli.d.mts.map +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/cloudflare.d.mts +38 -6
- package/dist/cloudflare.d.mts.map +1 -1
- package/dist/cloudflare.mjs +6466 -3
- package/dist/cloudflare.mjs.map +1 -0
- package/dist/{delivery-invariants-D-_GPOqE.d.mts → delivery-invariants-C3GXJIbg.d.mts} +2 -2
- package/dist/{delivery-invariants-D-_GPOqE.d.mts.map → delivery-invariants-C3GXJIbg.d.mts.map} +1 -1
- package/dist/{delivery-invariants-BRwfZJrs.mjs → delivery-invariants-DsBHpT1n.mjs} +2 -2
- package/dist/{delivery-invariants-BRwfZJrs.mjs.map → delivery-invariants-DsBHpT1n.mjs.map} +1 -1
- package/dist/draft-DEUDffHa.mjs +467 -0
- package/dist/draft-DEUDffHa.mjs.map +1 -0
- package/dist/{src-H1Q8ytEx.mjs → generate-TBJM3-2P.mjs} +3 -618
- package/dist/generate-TBJM3-2P.mjs.map +1 -0
- package/dist/index.d.mts +36 -36
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +6 -3
- package/dist/index.mjs.map +1 -1
- package/dist/install-DkzpGA5D.mjs +611 -0
- package/dist/install-DkzpGA5D.mjs.map +1 -0
- package/dist/{explore-D33RP9hF.d.mts → ir-KpC2epGn.d.mts} +70 -70
- package/dist/ir-KpC2epGn.d.mts.map +1 -0
- package/dist/keys-xtanNmuR.mjs +111 -0
- package/dist/keys-xtanNmuR.mjs.map +1 -0
- package/dist/mcp-DEn3HnLz.mjs +539 -0
- package/dist/mcp-DEn3HnLz.mjs.map +1 -0
- package/dist/{platform-CawKCUru.d.mts → platform-Cs9V9t2k.d.mts} +25 -11
- package/dist/platform-Cs9V9t2k.d.mts.map +1 -0
- package/dist/pool-CXN4CwGY.mjs +61 -0
- package/dist/pool-CXN4CwGY.mjs.map +1 -0
- package/dist/{provers-DS44OeEm.mjs → provers-D8VaY_OM.mjs} +18 -2
- package/dist/provers-D8VaY_OM.mjs.map +1 -0
- package/dist/reader-B9FSoEYW.mjs +1 -0
- package/dist/reader-Cz6_bLf6.mjs +3774 -0
- package/dist/reader-Cz6_bLf6.mjs.map +1 -0
- package/dist/report-_Vzavqg0.mjs +310 -0
- package/dist/report-_Vzavqg0.mjs.map +1 -0
- package/dist/src-B2DpVbMN.mjs +2 -0
- package/dist/src-BFGTvuA_.mjs +1235 -0
- package/dist/src-BFGTvuA_.mjs.map +1 -0
- package/dist/src-BtLZPRyG.mjs +120 -0
- package/dist/src-BtLZPRyG.mjs.map +1 -0
- package/dist/src-CB8DcvsK.mjs +1 -0
- package/dist/src-COuquJvI.mjs +269 -0
- package/dist/src-COuquJvI.mjs.map +1 -0
- package/dist/src-Chn-m_r1.mjs +1082 -0
- package/dist/src-Chn-m_r1.mjs.map +1 -0
- package/dist/{src-Whn0RMSh.mjs → src-D-MeEFn3.mjs} +589 -517
- package/dist/src-D-MeEFn3.mjs.map +1 -0
- package/dist/src-DwYD3QQJ.mjs +346 -0
- package/dist/src-DwYD3QQJ.mjs.map +1 -0
- package/dist/toolchain-DWfymxAJ.mjs +80 -0
- package/dist/toolchain-DWfymxAJ.mjs.map +1 -0
- package/dist/verdict-evEM5Gxx.mjs +12 -0
- package/dist/verdict-evEM5Gxx.mjs.map +1 -0
- package/package.json +4 -1
- package/dist/cli-DyA7uTBg.mjs +0 -9447
- package/dist/cli-DyA7uTBg.mjs.map +0 -1
- package/dist/explore-D33RP9hF.d.mts.map +0 -1
- package/dist/platform-CawKCUru.d.mts.map +0 -1
- package/dist/provers-DS44OeEm.mjs.map +0 -1
- package/dist/src-H1Q8ytEx.mjs.map +0 -1
- package/dist/src-Whn0RMSh.mjs.map +0 -1
- package/dist/workerd-tI8INa6v.mjs +0 -6334
- package/dist/workerd-tI8INa6v.mjs.map +0 -1
|
@@ -0,0 +1,3774 @@
|
|
|
1
|
+
import { f as describeType, o as endpointBigInt, s as endpointNumber } from "./generate-TBJM3-2P.mjs";
|
|
2
|
+
import { n as proofsOf, r as unknownOutcome } from "./provers-D8VaY_OM.mjs";
|
|
3
|
+
import { InternalSymbolName, ModifierFlags, NodeFlags, SyntaxKind, forEachLeadingCommentRange, forEachTrailingCommentRange } from "typescript/ast";
|
|
4
|
+
import { createFileSystemLayer } from "typescript/fs";
|
|
5
|
+
import { API, DiagnosticCategory, SymbolFlags, TypeFlags, TypeFormatFlags } from "typescript/sync";
|
|
6
|
+
import * as is from "typescript/ast/is";
|
|
7
|
+
// packages/prover/src/reader/tree.ts
|
|
8
|
+
/**
|
|
9
|
+
* The subset's tree: its types (`SubsetType`, records, tagged unions),
|
|
10
|
+
* its expressions (`Expr`), and a module as read (`SubsetModule`: the
|
|
11
|
+
* functions the subset takes and, for the others, why not), with what
|
|
12
|
+
* depends on the tree alone: `describe`, `children`, `callees`, the list
|
|
13
|
+
* kinds.
|
|
14
|
+
* Every other module of the reader imports this one, and it imports none
|
|
15
|
+
* of them.
|
|
16
|
+
*/
|
|
17
|
+
var OutsideSubset = class extends Error {
|
|
18
|
+
line;
|
|
19
|
+
constructor(message, line) {
|
|
20
|
+
super(message);
|
|
21
|
+
this.line = line;
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
/** Whether a record is a member of a union. */
|
|
25
|
+
function isMember(record, union) {
|
|
26
|
+
return record?.unions?.includes(union) ?? false;
|
|
27
|
+
}
|
|
28
|
+
/** Whether a string holds a surrogate code unit without its pair: no Lean character corresponds to it. */
|
|
29
|
+
function hasLoneSurrogate(s) {
|
|
30
|
+
return /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/.test(s);
|
|
31
|
+
}
|
|
32
|
+
/** A type, for messages. */
|
|
33
|
+
function describe(t) {
|
|
34
|
+
switch (t.kind) {
|
|
35
|
+
case "record":
|
|
36
|
+
case "union": return t.name;
|
|
37
|
+
case "nullable": return `${describe(t.inner)} | null`;
|
|
38
|
+
case "list": return t.element.kind === "nullable" ? `(${describe(t.element)})[]` : `${describe(t.element)}[]`;
|
|
39
|
+
default: return t.kind;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/** The functions an expression calls. */
|
|
43
|
+
function callees(e, out = /* @__PURE__ */ new Set()) {
|
|
44
|
+
switch (e.kind) {
|
|
45
|
+
case "int":
|
|
46
|
+
case "bool":
|
|
47
|
+
case "string":
|
|
48
|
+
case "null":
|
|
49
|
+
case "var": return out;
|
|
50
|
+
case "narrow":
|
|
51
|
+
case "narrowTag": return callees(e.body, out);
|
|
52
|
+
case "neg":
|
|
53
|
+
case "not":
|
|
54
|
+
case "isInteger":
|
|
55
|
+
case "floor": return callees(e.operand, out);
|
|
56
|
+
case "binary":
|
|
57
|
+
callees(e.left, out);
|
|
58
|
+
return callees(e.right, out);
|
|
59
|
+
case "cond":
|
|
60
|
+
callees(e.test, out);
|
|
61
|
+
callees(e.ifTrue, out);
|
|
62
|
+
return callees(e.ifFalse, out);
|
|
63
|
+
case "call":
|
|
64
|
+
out.add(e.callee);
|
|
65
|
+
for (const a of e.args) callees(a, out);
|
|
66
|
+
return out;
|
|
67
|
+
case "field": return callees(e.object, out);
|
|
68
|
+
case "record":
|
|
69
|
+
for (const f of e.fields) callees(f.value, out);
|
|
70
|
+
return out;
|
|
71
|
+
case "let":
|
|
72
|
+
callees(e.value, out);
|
|
73
|
+
return callees(e.body, out);
|
|
74
|
+
case "list":
|
|
75
|
+
for (const x of e.items) callees(x, out);
|
|
76
|
+
return e.rest ? callees(e.rest, out) : out;
|
|
77
|
+
case "tail": return callees(e.list, out);
|
|
78
|
+
case "headOr":
|
|
79
|
+
callees(e.list, out);
|
|
80
|
+
return callees(e.fallback, out);
|
|
81
|
+
case "iterate":
|
|
82
|
+
callees(e.list, out);
|
|
83
|
+
return callees(e.body, out);
|
|
84
|
+
case "fold":
|
|
85
|
+
callees(e.list, out);
|
|
86
|
+
callees(e.init, out);
|
|
87
|
+
return callees(e.body, out);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/** An expression's direct subexpressions. */
|
|
91
|
+
function children(e) {
|
|
92
|
+
switch (e.kind) {
|
|
93
|
+
case "int":
|
|
94
|
+
case "bool":
|
|
95
|
+
case "string":
|
|
96
|
+
case "null":
|
|
97
|
+
case "var": return [];
|
|
98
|
+
case "narrow":
|
|
99
|
+
case "narrowTag": return [e.body];
|
|
100
|
+
case "neg":
|
|
101
|
+
case "not":
|
|
102
|
+
case "isInteger":
|
|
103
|
+
case "floor": return [e.operand];
|
|
104
|
+
case "binary": return [e.left, e.right];
|
|
105
|
+
case "cond": return [
|
|
106
|
+
e.test,
|
|
107
|
+
e.ifTrue,
|
|
108
|
+
e.ifFalse
|
|
109
|
+
];
|
|
110
|
+
case "call": return [...e.args];
|
|
111
|
+
case "field": return [e.object];
|
|
112
|
+
case "record": return e.fields.map((f) => f.value);
|
|
113
|
+
case "let": return [e.value, e.body];
|
|
114
|
+
case "list": return [...e.items, ...e.rest ? [e.rest] : []];
|
|
115
|
+
case "tail": return [e.list];
|
|
116
|
+
case "headOr": return [e.list, e.fallback];
|
|
117
|
+
case "iterate": return [e.list, e.body];
|
|
118
|
+
case "fold": return [
|
|
119
|
+
e.list,
|
|
120
|
+
e.init,
|
|
121
|
+
e.body
|
|
122
|
+
];
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
/** The expression kinds only lists bring, for an engine that does not take them. */
|
|
126
|
+
const listKinds = /* @__PURE__ */ new Set([
|
|
127
|
+
"list",
|
|
128
|
+
"tail",
|
|
129
|
+
"headOr",
|
|
130
|
+
"iterate",
|
|
131
|
+
"fold"
|
|
132
|
+
]);
|
|
133
|
+
/** Whether an expression is one only lists bring (a type guard over `listKinds`). */
|
|
134
|
+
const isListExpr = (e) => listKinds.has(e.kind);
|
|
135
|
+
// packages/prover/src/reader/binders.ts
|
|
136
|
+
/**
|
|
137
|
+
* A spec's binder type read into the subset's type, once for every
|
|
138
|
+
* engine: `number`, `boolean` and `string` to their own, a literal to its
|
|
139
|
+
* primitive, a union of string literals to a string, a declared record to
|
|
140
|
+
* the module's record of that name, `T | null` to the nullable type over
|
|
141
|
+
* `T`, a union of records to the one declared union whose members match,
|
|
142
|
+
* an array to a list. What an engine does not take is its `BinderRule`:
|
|
143
|
+
* it names the reason, and the binder is refused with it where the engine
|
|
144
|
+
* would have refused it itself, so a user reads the engine's own words.
|
|
145
|
+
* Bigint, `undefined` and what the spec reader could not read are outside
|
|
146
|
+
* for every engine.
|
|
147
|
+
*/
|
|
148
|
+
const fail = (message) => {
|
|
149
|
+
throw new OutsideSubset(message, 0);
|
|
150
|
+
};
|
|
151
|
+
/** The subset type a binder ranges over under an engine's rule, or `OutsideSubset` with why. */
|
|
152
|
+
function readBinderType(name, t, module, rule) {
|
|
153
|
+
const over = `binder ${name} over ${describeType(t)}`;
|
|
154
|
+
switch (t.kind) {
|
|
155
|
+
case "number": return { kind: "int" };
|
|
156
|
+
case "boolean": return { kind: "bool" };
|
|
157
|
+
case "string": return { kind: "string" };
|
|
158
|
+
case "literal":
|
|
159
|
+
if (typeof t.value === "string") return { kind: "string" };
|
|
160
|
+
if (typeof t.value === "boolean") return { kind: "bool" };
|
|
161
|
+
return { kind: "int" };
|
|
162
|
+
case "bigint": return fail(`binder ${name} over bigint: the subset has no bigint`);
|
|
163
|
+
case "union": {
|
|
164
|
+
const strings = (ms) => ms.every((m) => m.kind === "literal" && typeof m.value === "string");
|
|
165
|
+
if (rule.union !== void 0) {
|
|
166
|
+
if (strings(t.members)) return { kind: "string" };
|
|
167
|
+
if (rule.nullable !== void 0 && t.members.some((m) => m.kind === "null" || m.kind === "undefined")) return fail(`${over}: ${rule.nullable}`);
|
|
168
|
+
return fail(`${over}: ${rule.union}`);
|
|
169
|
+
}
|
|
170
|
+
const nulls = t.members.filter((m) => m.kind === "null");
|
|
171
|
+
const undefineds = t.members.some((m) => m.kind === "undefined");
|
|
172
|
+
if (rule.nullable !== void 0 && (nulls.length > 0 || undefineds)) return fail(`${over}: ${rule.nullable}`);
|
|
173
|
+
if (undefineds) return fail(`${over}: undefined is not in the subset (null is)`);
|
|
174
|
+
const rest = t.members.filter((m) => m.kind !== "null");
|
|
175
|
+
let inner;
|
|
176
|
+
if (strings(rest)) inner = { kind: "string" };
|
|
177
|
+
else if (rest.every((m) => m.kind === "literal" && typeof m.value === "boolean")) inner = { kind: "bool" };
|
|
178
|
+
else if (rest.length === 1) inner = readBinderType(name, rest[0], module, rule);
|
|
179
|
+
else if (rest.every((m) => m.kind === "record")) {
|
|
180
|
+
const union = findUnion(rest, module, rule);
|
|
181
|
+
if (!union) return fail(`${over}: no one union the module declares has exactly these members`);
|
|
182
|
+
inner = {
|
|
183
|
+
kind: "union",
|
|
184
|
+
name: union.name
|
|
185
|
+
};
|
|
186
|
+
} else return fail(`${over}: a union the subset does not read`);
|
|
187
|
+
return nulls.length > 0 ? {
|
|
188
|
+
kind: "nullable",
|
|
189
|
+
inner
|
|
190
|
+
} : inner;
|
|
191
|
+
}
|
|
192
|
+
case "record":
|
|
193
|
+
if (t.name !== void 0 && module.records.some((r) => r.name === t.name)) return {
|
|
194
|
+
kind: "record",
|
|
195
|
+
name: t.name
|
|
196
|
+
};
|
|
197
|
+
return fail(`${over}: ${t.name === void 0 ? "an inline record type" : `record type ${t.name} is outside the subset`}`);
|
|
198
|
+
case "null":
|
|
199
|
+
case "undefined": return fail(`binder ${name} over ${t.kind}`);
|
|
200
|
+
case "array":
|
|
201
|
+
if (rule.array !== void 0) return fail(`${over}: ${rule.array}`);
|
|
202
|
+
return {
|
|
203
|
+
kind: "list",
|
|
204
|
+
element: readBinderType(name, t.element, module, rule)
|
|
205
|
+
};
|
|
206
|
+
case "unknown": return fail(`binder ${name} over ${t.text}, which the reader could not read`);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* The one declared union these member types are, compared field by field
|
|
211
|
+
* and type by type: a field holding one literal is that literal in the
|
|
212
|
+
* union's member, a union of literals is a field of no literal, and
|
|
213
|
+
* everything else reads to the field's own type. A record may be a member
|
|
214
|
+
* of several unions, so tags and field names alone could name the wrong
|
|
215
|
+
* one; when more than one union fits, none is chosen.
|
|
216
|
+
*/
|
|
217
|
+
function findUnion(members, module, rule) {
|
|
218
|
+
const recordOf = (name) => module.records.find((r) => r.name === name);
|
|
219
|
+
const recordFits = (sm, rec) => sm.fields.length === rec.fields.length && rec.fields.every((f) => {
|
|
220
|
+
const sf = sm.fields.find((x) => x.name === f.name);
|
|
221
|
+
return sf !== void 0 && fieldFits(sf.type, f);
|
|
222
|
+
});
|
|
223
|
+
const typeFits = (sf, t) => {
|
|
224
|
+
if (t.kind === "record") {
|
|
225
|
+
const rec = recordOf(t.name);
|
|
226
|
+
return sf.kind === "record" && rec !== void 0 && recordFits(sf, rec);
|
|
227
|
+
}
|
|
228
|
+
if (t.kind === "nullable" && sf.kind === "union" && sf.members.some((m) => m.kind === "null")) {
|
|
229
|
+
const rest = sf.members.filter((m) => m.kind !== "null");
|
|
230
|
+
const inner = rest.length === 1 ? rest[0] : {
|
|
231
|
+
kind: "union",
|
|
232
|
+
members: rest
|
|
233
|
+
};
|
|
234
|
+
return typeFits(inner, t.inner);
|
|
235
|
+
}
|
|
236
|
+
if (t.kind === "union") {
|
|
237
|
+
const u = module.unions.find((x) => x.name === t.name);
|
|
238
|
+
if (!u || sf.kind !== "union" || sf.members.length !== u.members.length) return false;
|
|
239
|
+
return u.members.every((m) => {
|
|
240
|
+
const rec = recordOf(m.record);
|
|
241
|
+
return rec !== void 0 && sf.members.some((sm) => sm.kind === "record" && recordFits(sm, rec));
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
try {
|
|
245
|
+
return JSON.stringify(readBinderType("field", sf, module, rule)) === JSON.stringify(t);
|
|
246
|
+
} catch (err) {
|
|
247
|
+
if (err instanceof OutsideSubset) return false;
|
|
248
|
+
throw err;
|
|
249
|
+
}
|
|
250
|
+
};
|
|
251
|
+
function fieldFits(sf, f) {
|
|
252
|
+
if (f.literal !== void 0) return sf.kind === "literal" && sf.value === f.literal;
|
|
253
|
+
if (sf.kind === "literal") return false;
|
|
254
|
+
return typeFits(sf, f.type);
|
|
255
|
+
}
|
|
256
|
+
const fitting = module.unions.filter((u) => {
|
|
257
|
+
if (u.members.length !== members.length) return false;
|
|
258
|
+
return u.members.every((m) => {
|
|
259
|
+
const rec = recordOf(m.record);
|
|
260
|
+
return rec !== void 0 && members.some((sm) => recordFits(sm, rec));
|
|
261
|
+
});
|
|
262
|
+
});
|
|
263
|
+
return fitting.length === 1 ? fitting[0] : void 0;
|
|
264
|
+
}
|
|
265
|
+
// packages/prover/src/reader/compiler.ts
|
|
266
|
+
/**
|
|
267
|
+
* The TypeScript compiler, through its API (7.1): one compiler process per
|
|
268
|
+
* Node process, started on first use; a program per read, over an
|
|
269
|
+
* in-memory layer holding the files being read on top of the host's own
|
|
270
|
+
* files, so imports resolve as the user's compiler resolves them; a
|
|
271
|
+
* standalone source file for text that is not a module (a spec file's
|
|
272
|
+
* arrow, read back from its text). Every handle the compiler process
|
|
273
|
+
* holds for a read is released when the read ends. Nothing else in Eutaxy
|
|
274
|
+
* imports the compiler API: a change to it lands here.
|
|
275
|
+
*/
|
|
276
|
+
let api;
|
|
277
|
+
function compiler() {
|
|
278
|
+
api ??= new API({});
|
|
279
|
+
return api;
|
|
280
|
+
}
|
|
281
|
+
/** Stop the compiler process; the next read starts another. */
|
|
282
|
+
function closeCompiler() {
|
|
283
|
+
api?.close();
|
|
284
|
+
api = void 0;
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* The options every read compiles under: strict, the latest language
|
|
288
|
+
* level, bundler-style resolution with `.ts` imports allowed, and the
|
|
289
|
+
* standard library alone (`types: []`), so a module's own types resolve
|
|
290
|
+
* and nothing is emitted. The user's configuration is not read: a type
|
|
291
|
+
* Eutaxy cannot resolve under these options is reported unknown, never
|
|
292
|
+
* guessed.
|
|
293
|
+
*/
|
|
294
|
+
const options = {
|
|
295
|
+
strict: true,
|
|
296
|
+
target: 99,
|
|
297
|
+
module: 99,
|
|
298
|
+
moduleResolution: 100,
|
|
299
|
+
allowImportingTsExtensions: true,
|
|
300
|
+
noEmit: true,
|
|
301
|
+
skipLibCheck: true,
|
|
302
|
+
types: [],
|
|
303
|
+
lib: ["es2023"]
|
|
304
|
+
};
|
|
305
|
+
/** Run `fn` over a program whose root files are the inputs, released afterwards. */
|
|
306
|
+
function withProgram(files, fn) {
|
|
307
|
+
const snapshot = compiler().createSnapshot({
|
|
308
|
+
fileSystem: createFileSystemLayer(files.map((f) => [f.path, f.text])),
|
|
309
|
+
createPrograms: [{
|
|
310
|
+
rootFiles: files.map((f) => f.path),
|
|
311
|
+
compilerOptions: options
|
|
312
|
+
}]
|
|
313
|
+
});
|
|
314
|
+
try {
|
|
315
|
+
const program = snapshot.operation.createdPrograms[0];
|
|
316
|
+
const checker = program.getProject().checker;
|
|
317
|
+
const file = (path) => {
|
|
318
|
+
const sf = program.getSourceFile(path);
|
|
319
|
+
if (!sf) throw new Error(`the compiler holds no source file for ${path}`);
|
|
320
|
+
return sf;
|
|
321
|
+
};
|
|
322
|
+
const parseError = (path) => {
|
|
323
|
+
const first = program.getSyntacticDiagnostics(path)[0];
|
|
324
|
+
return first ? {
|
|
325
|
+
line: (first.startPosition?.line ?? 0) + 1,
|
|
326
|
+
message: first.text
|
|
327
|
+
} : void 0;
|
|
328
|
+
};
|
|
329
|
+
const errors = /* @__PURE__ */ new Map();
|
|
330
|
+
const typeErrors = (path) => {
|
|
331
|
+
let found = errors.get(path);
|
|
332
|
+
if (!found) {
|
|
333
|
+
found = program.getSemanticDiagnostics(path).filter((d) => d.category === DiagnosticCategory.Error).map((d) => ({
|
|
334
|
+
pos: d.pos,
|
|
335
|
+
end: d.end,
|
|
336
|
+
message: d.text,
|
|
337
|
+
line: (d.startPosition?.line ?? 0) + 1
|
|
338
|
+
}));
|
|
339
|
+
errors.set(path, found);
|
|
340
|
+
}
|
|
341
|
+
return found;
|
|
342
|
+
};
|
|
343
|
+
const standard = /* @__PURE__ */ new Map();
|
|
344
|
+
const typeOnly = /* @__PURE__ */ new Set([SyntaxKind.InterfaceDeclaration, SyntaxKind.TypeAliasDeclaration]);
|
|
345
|
+
const standardGlobal = (id) => {
|
|
346
|
+
const symbol = checker.getSymbolAtLocation(id);
|
|
347
|
+
if (!symbol) return false;
|
|
348
|
+
let known = standard.get(symbol.id);
|
|
349
|
+
if (known === void 0) {
|
|
350
|
+
const values = symbol.declarations.filter((d) => !typeOnly.has(d.kind));
|
|
351
|
+
known = values.length > 0 && values.every((d) => {
|
|
352
|
+
const sf = d.resolve()?.getSourceFile();
|
|
353
|
+
return sf !== void 0 && program.isSourceFileDefaultLibrary(sf);
|
|
354
|
+
});
|
|
355
|
+
standard.set(symbol.id, known);
|
|
356
|
+
}
|
|
357
|
+
return known;
|
|
358
|
+
};
|
|
359
|
+
return fn({
|
|
360
|
+
program,
|
|
361
|
+
checker,
|
|
362
|
+
file,
|
|
363
|
+
parseError,
|
|
364
|
+
typeErrors,
|
|
365
|
+
standardGlobal
|
|
366
|
+
});
|
|
367
|
+
} finally {
|
|
368
|
+
snapshot.dispose();
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
/** Run `fn` over a source file parsed from `text` alone (no program, no checker), released afterwards. */
|
|
372
|
+
function withSourceFile(text, fn) {
|
|
373
|
+
const lease = compiler().createSourceFile("/eutaxy/reader/fragment.ts", text);
|
|
374
|
+
try {
|
|
375
|
+
return fn(lease.sourceFile);
|
|
376
|
+
} finally {
|
|
377
|
+
lease.dispose();
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
/** 1-based line of a node's first token. */
|
|
381
|
+
function lineAt(sf, node) {
|
|
382
|
+
return sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1;
|
|
383
|
+
}
|
|
384
|
+
/** A node's text, leading trivia excluded. */
|
|
385
|
+
function textOf(sf, node) {
|
|
386
|
+
return sf.text.slice(node.getStart(sf), node.end);
|
|
387
|
+
}
|
|
388
|
+
function isExported(node) {
|
|
389
|
+
return (node.modifierFlags & ModifierFlags.Export) !== 0;
|
|
390
|
+
}
|
|
391
|
+
function isAsync(node) {
|
|
392
|
+
return (node.modifierFlags & ModifierFlags.Async) !== 0;
|
|
393
|
+
}
|
|
394
|
+
function isConst(list) {
|
|
395
|
+
return (list.flags & NodeFlags.Const) !== 0;
|
|
396
|
+
}
|
|
397
|
+
/**
|
|
398
|
+
* The offset of the `(` opening a function's parameter list: the
|
|
399
|
+
* declaration's identity, as the spec reader and the subset reader both
|
|
400
|
+
* record it. Undefined for an arrow written without parentheses.
|
|
401
|
+
*/
|
|
402
|
+
function openParen(sf, fn) {
|
|
403
|
+
const at = fn.parameters.pos - 1;
|
|
404
|
+
return sf.text[at] === "(" ? at : void 0;
|
|
405
|
+
}
|
|
406
|
+
/** The name of a syntax kind, for messages. */
|
|
407
|
+
function kindName(kind) {
|
|
408
|
+
return SyntaxKind[kind] ?? String(kind);
|
|
409
|
+
}
|
|
410
|
+
// packages/prover/src/reader/restrict.ts
|
|
411
|
+
/**
|
|
412
|
+
* `restrictModule`: the module as an engine that takes only some of the
|
|
413
|
+
* subset's types sees it.
|
|
414
|
+
*/
|
|
415
|
+
/** Whether an expression holds a node of the kinds named. */
|
|
416
|
+
function hasNode(e, kinds) {
|
|
417
|
+
if (kinds.has(e.kind)) return true;
|
|
418
|
+
switch (e.kind) {
|
|
419
|
+
case "int":
|
|
420
|
+
case "bool":
|
|
421
|
+
case "string":
|
|
422
|
+
case "null":
|
|
423
|
+
case "var": return false;
|
|
424
|
+
case "narrow":
|
|
425
|
+
case "narrowTag": return hasNode(e.body, kinds);
|
|
426
|
+
case "neg":
|
|
427
|
+
case "not":
|
|
428
|
+
case "isInteger":
|
|
429
|
+
case "floor": return hasNode(e.operand, kinds);
|
|
430
|
+
case "binary": return hasNode(e.left, kinds) || hasNode(e.right, kinds);
|
|
431
|
+
case "cond": return hasNode(e.test, kinds) || hasNode(e.ifTrue, kinds) || hasNode(e.ifFalse, kinds);
|
|
432
|
+
case "call": return e.args.some((a) => hasNode(a, kinds));
|
|
433
|
+
case "field": return hasNode(e.object, kinds);
|
|
434
|
+
case "record": return e.fields.some((f) => hasNode(f.value, kinds));
|
|
435
|
+
case "let": return hasNode(e.value, kinds) || hasNode(e.body, kinds);
|
|
436
|
+
case "list": return e.items.some((x) => hasNode(x, kinds)) || (e.rest ? hasNode(e.rest, kinds) : false);
|
|
437
|
+
case "tail": return hasNode(e.list, kinds);
|
|
438
|
+
case "headOr": return hasNode(e.list, kinds) || hasNode(e.fallback, kinds);
|
|
439
|
+
case "iterate": return hasNode(e.list, kinds) || hasNode(e.body, kinds);
|
|
440
|
+
case "fold": return hasNode(e.list, kinds) || hasNode(e.init, kinds) || hasNode(e.body, kinds);
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
/**
|
|
444
|
+
* The module as an engine that takes only some of the subset's types sees
|
|
445
|
+
* it: records with a field of a type it does not take are dropped, and so
|
|
446
|
+
* are functions whose signature holds one, whose body uses what the
|
|
447
|
+
* types bring (`null`, narrowing), or which call such a function; each is
|
|
448
|
+
* reported outside with `reason`.
|
|
449
|
+
*/
|
|
450
|
+
function restrictModule(module, takes, reason, bodies = /* @__PURE__ */ new Set([
|
|
451
|
+
"null",
|
|
452
|
+
"narrow",
|
|
453
|
+
"narrowTag"
|
|
454
|
+
]), refused) {
|
|
455
|
+
const badRecords = /* @__PURE__ */ new Set();
|
|
456
|
+
for (const u of module.unions) if (!takes({
|
|
457
|
+
kind: "union",
|
|
458
|
+
name: u.name
|
|
459
|
+
})) badRecords.add(`union:${u.name}`);
|
|
460
|
+
for (let changed = true; changed;) {
|
|
461
|
+
changed = false;
|
|
462
|
+
for (const rec of module.records) if (!badRecords.has(rec.name) && rec.fields.some((f) => !typeTaken(f.type, takes, badRecords))) {
|
|
463
|
+
badRecords.add(rec.name);
|
|
464
|
+
changed = true;
|
|
465
|
+
}
|
|
466
|
+
for (const u of module.unions) if (!badRecords.has(`union:${u.name}`) && u.members.some((m) => badRecords.has(m.record))) {
|
|
467
|
+
badRecords.add(`union:${u.name}`);
|
|
468
|
+
changed = true;
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
const outside = new Map(module.outside.map((o) => [o.name, o]));
|
|
472
|
+
const kept = new Map(module.functions.map((f) => [f.name, f]));
|
|
473
|
+
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;
|
|
474
|
+
for (const f of module.functions) if (uses(f)) {
|
|
475
|
+
kept.delete(f.name);
|
|
476
|
+
outside.set(f.name, {
|
|
477
|
+
name: f.name,
|
|
478
|
+
line: f.line,
|
|
479
|
+
message: reason
|
|
480
|
+
});
|
|
481
|
+
}
|
|
482
|
+
for (let changed = true; changed;) {
|
|
483
|
+
changed = false;
|
|
484
|
+
for (const [name, f] of kept) {
|
|
485
|
+
const bad = [...callees(f.body)].find((c) => outside.has(c));
|
|
486
|
+
if (bad === void 0) continue;
|
|
487
|
+
kept.delete(name);
|
|
488
|
+
outside.set(name, {
|
|
489
|
+
name,
|
|
490
|
+
line: f.line,
|
|
491
|
+
message: `calls ${bad}, which is outside the engine's subset: ${outside.get(bad)?.message}`
|
|
492
|
+
});
|
|
493
|
+
changed = true;
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
return {
|
|
497
|
+
records: module.records.filter((r) => !badRecords.has(r.name)).map((r) => {
|
|
498
|
+
const unions = r.unions?.filter((u) => !badRecords.has(`union:${u}`));
|
|
499
|
+
if (unions === r.unions) return r;
|
|
500
|
+
const { unions: _, ...rest } = r;
|
|
501
|
+
return unions && unions.length > 0 ? {
|
|
502
|
+
...rest,
|
|
503
|
+
unions
|
|
504
|
+
} : rest;
|
|
505
|
+
}),
|
|
506
|
+
unions: module.unions.filter((u) => !badRecords.has(`union:${u.name}`)),
|
|
507
|
+
functions: module.functions.filter((f) => kept.has(f.name)),
|
|
508
|
+
outside: [...outside.values()]
|
|
509
|
+
};
|
|
510
|
+
}
|
|
511
|
+
function typeTaken(t, takes, badRecords) {
|
|
512
|
+
if (!takes(t)) return false;
|
|
513
|
+
if (t.kind === "record") return !badRecords.has(t.name);
|
|
514
|
+
if (t.kind === "union") return !badRecords.has(`union:${t.name}`);
|
|
515
|
+
if (t.kind === "nullable") return typeTaken(t.inner, takes, badRecords);
|
|
516
|
+
if (t.kind === "list") return typeTaken(t.element, takes, badRecords);
|
|
517
|
+
return true;
|
|
518
|
+
}
|
|
519
|
+
/** The types a body's `const` annotations and its record literals' contexts name. */
|
|
520
|
+
function annotations(e, out = []) {
|
|
521
|
+
if ((e.kind === "let" || e.kind === "record") && e.type) out.push(e.type);
|
|
522
|
+
for (const c of children(e)) annotations(c, out);
|
|
523
|
+
return out;
|
|
524
|
+
}
|
|
525
|
+
// packages/prover/src/reader/rebinding.ts
|
|
526
|
+
/**
|
|
527
|
+
* What a file may rebind, found in its syntax: a direct `eval`, a write
|
|
528
|
+
* to a name (`isWritten`), and a direct assignment to a global of the
|
|
529
|
+
* standard library or a property of one (`rebound`). What such an
|
|
530
|
+
* assignment could reach another way is `builtinsAssumption`.
|
|
531
|
+
*/
|
|
532
|
+
/** The line of the first direct `eval` in the file: a mention that is not a property of something else. */
|
|
533
|
+
function directEval(sf) {
|
|
534
|
+
let line;
|
|
535
|
+
const visit = (node) => {
|
|
536
|
+
if (line !== void 0) return;
|
|
537
|
+
if (is.isIdentifier(node) && node.text === "eval") {
|
|
538
|
+
const parent = node.parent;
|
|
539
|
+
if (!(is.isPropertyAccessExpression(parent) && parent.name === node || is.isPropertyAssignment(parent) && parent.name === node)) {
|
|
540
|
+
line = lineAt(sf, node);
|
|
541
|
+
return;
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
node.forEachChild(visit);
|
|
545
|
+
};
|
|
546
|
+
visit(sf);
|
|
547
|
+
return line;
|
|
548
|
+
}
|
|
549
|
+
function isWrapper(n) {
|
|
550
|
+
return is.isParenthesizedExpression(n) || is.isNonNullExpression(n) || is.isAsExpression(n) || is.isSatisfiesExpression(n) || is.isTypeAssertion(n);
|
|
551
|
+
}
|
|
552
|
+
/** Whether a node is written to: assigned, updated, or bound by a destructuring or a `for` head. */
|
|
553
|
+
function isWritten(node) {
|
|
554
|
+
let n = node;
|
|
555
|
+
for (;;) {
|
|
556
|
+
const p = n.parent;
|
|
557
|
+
if (!p) return false;
|
|
558
|
+
if (isWrapper(p) && p.expression === n) {
|
|
559
|
+
n = p;
|
|
560
|
+
continue;
|
|
561
|
+
}
|
|
562
|
+
if (is.isBinaryExpression(p)) {
|
|
563
|
+
const k = p.operatorToken.kind;
|
|
564
|
+
if (p.left === n && k >= SyntaxKind.FirstAssignment && k <= SyntaxKind.LastAssignment) return true;
|
|
565
|
+
return false;
|
|
566
|
+
}
|
|
567
|
+
if (is.isPrefixUnaryExpression(p) || is.isPostfixUnaryExpression(p)) return p.operator === SyntaxKind.PlusPlusToken || p.operator === SyntaxKind.MinusMinusToken;
|
|
568
|
+
if (is.isForInStatement(p) || is.isForOfStatement(p)) return p.initializer === n;
|
|
569
|
+
if (is.isArrayLiteralExpression(p) || is.isSpreadElement(p) || is.isSpreadAssignment(p)) {
|
|
570
|
+
n = p;
|
|
571
|
+
continue;
|
|
572
|
+
}
|
|
573
|
+
if (is.isPropertyAssignment(p) && p.initializer === n) {
|
|
574
|
+
n = p.parent;
|
|
575
|
+
continue;
|
|
576
|
+
}
|
|
577
|
+
if (is.isShorthandPropertyAssignment(p) && p.name === n) {
|
|
578
|
+
n = p.parent;
|
|
579
|
+
continue;
|
|
580
|
+
}
|
|
581
|
+
if (is.isObjectLiteralExpression(p)) {
|
|
582
|
+
n = p;
|
|
583
|
+
continue;
|
|
584
|
+
}
|
|
585
|
+
return false;
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
/** What every PROVEN rests on besides the engine's model: the reader's assumption about the built-ins. */
|
|
589
|
+
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";
|
|
590
|
+
/** Names a file reaches the globals through that the library the reads compile against does not declare. */
|
|
591
|
+
const globalObjects = /* @__PURE__ */ new Set([
|
|
592
|
+
"globalThis",
|
|
593
|
+
"self",
|
|
594
|
+
"window",
|
|
595
|
+
"global"
|
|
596
|
+
]);
|
|
597
|
+
/**
|
|
598
|
+
* The first direct assignment (or `delete`) in a file whose target is a
|
|
599
|
+
* global of the compiler's standard library or a property of one, at any
|
|
600
|
+
* depth (`Math.floor = …`, `Number["isInteger"] = …`, `Array.prototype.map
|
|
601
|
+
* = …`, `Math = …`), or anything under `globalThis`, `self`, `window` or
|
|
602
|
+
* `global`, with its line; inside a function or not. The chain's root is
|
|
603
|
+
* resolved by the compiler, so a local's `prototype` field is the local's.
|
|
604
|
+
* What reaches a built-in another way (`Object.defineProperty`, an alias)
|
|
605
|
+
* is not seen: `builtinsAssumption` says so.
|
|
606
|
+
*/
|
|
607
|
+
function rebound(sf, checker, standardGlobal) {
|
|
608
|
+
let found;
|
|
609
|
+
const globalObject = (r) => {
|
|
610
|
+
if (!globalObjects.has(r.text)) return false;
|
|
611
|
+
const decl = checker.getSymbolAtLocation(r)?.valueDeclaration?.resolve();
|
|
612
|
+
if (!decl) return true;
|
|
613
|
+
if (decl.kind === SyntaxKind.Parameter) return false;
|
|
614
|
+
return !(is.isVariableDeclaration(decl) && decl.parent.parent.parent !== decl.getSourceFile());
|
|
615
|
+
};
|
|
616
|
+
const outermost = (node) => {
|
|
617
|
+
let out = node;
|
|
618
|
+
for (let p = out.parent; p && isWrapper(p) && p.expression === out; p = p.parent) out = p;
|
|
619
|
+
return out;
|
|
620
|
+
};
|
|
621
|
+
const root = (node) => {
|
|
622
|
+
let n = node;
|
|
623
|
+
while (is.isPropertyAccessExpression(n) || is.isElementAccessExpression(n) || isWrapper(n)) n = n.expression;
|
|
624
|
+
return n;
|
|
625
|
+
};
|
|
626
|
+
const builtin = (node) => {
|
|
627
|
+
const r = root(node);
|
|
628
|
+
return is.isIdentifier(r) && (globalObject(r) || standardGlobal(r));
|
|
629
|
+
};
|
|
630
|
+
const visit = (node) => {
|
|
631
|
+
if (found) return;
|
|
632
|
+
if ((is.isPropertyAccessExpression(node) || is.isElementAccessExpression(node) || is.isIdentifier(node)) && (isWritten(node) || is.isDeleteExpression(outermost(node).parent)) && builtin(node)) {
|
|
633
|
+
found = {
|
|
634
|
+
line: lineAt(sf, node),
|
|
635
|
+
target: textOf(sf, node)
|
|
636
|
+
};
|
|
637
|
+
return;
|
|
638
|
+
}
|
|
639
|
+
node.forEachChild(visit);
|
|
640
|
+
};
|
|
641
|
+
visit(sf);
|
|
642
|
+
return found;
|
|
643
|
+
}
|
|
644
|
+
// packages/prover/src/reader/typing.ts
|
|
645
|
+
/**
|
|
646
|
+
* The subset's typing: `typeOf` types an expression in a scope, against
|
|
647
|
+
* the records, unions and callee signatures of a `TypeContext`; `fits` is
|
|
648
|
+
* the subset's assignability (a member where its union is, `null` or the
|
|
649
|
+
* inner type where a nullable is).
|
|
650
|
+
*/
|
|
651
|
+
/** A union's members among the records known, in the order they were read. */
|
|
652
|
+
function membersIn(union, ctx) {
|
|
653
|
+
return [...ctx.records.values()].filter((rec) => isMember(rec, union));
|
|
654
|
+
}
|
|
655
|
+
const sameType = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
|
656
|
+
/**
|
|
657
|
+
* Whether a value of one type may stand where another is expected: the
|
|
658
|
+
* same type; a member record where its union is; `null`, or the inner
|
|
659
|
+
* type, where a nullable is.
|
|
660
|
+
*/
|
|
661
|
+
function fits(actual, expected, ctx) {
|
|
662
|
+
if (sameType(actual, expected)) return true;
|
|
663
|
+
if (actual.kind === "nothing") return true;
|
|
664
|
+
if (actual.kind === "list" && expected.kind === "list") return fits(actual.element, expected.element, ctx);
|
|
665
|
+
if (expected.kind === "union") return actual.kind === "record" && isMember(ctx.records.get(actual.name), expected.name);
|
|
666
|
+
if (expected.kind === "nullable") return actual.kind === "null" || (actual.kind === "nullable" ? fits(actual.inner, expected.inner, ctx) : fits(actual, expected.inner, ctx));
|
|
667
|
+
return false;
|
|
668
|
+
}
|
|
669
|
+
/** The type two branches share, or undefined when they share none. */
|
|
670
|
+
function join(a, b, ctx) {
|
|
671
|
+
if (fits(a, b, ctx)) return b;
|
|
672
|
+
if (fits(b, a, ctx)) return a;
|
|
673
|
+
if (a.kind === "list" && b.kind === "list") {
|
|
674
|
+
const element = join(a.element, b.element, ctx);
|
|
675
|
+
return element && {
|
|
676
|
+
kind: "list",
|
|
677
|
+
element
|
|
678
|
+
};
|
|
679
|
+
}
|
|
680
|
+
if (a.kind === "record" && b.kind === "record") {
|
|
681
|
+
const ub = ctx.records.get(b.name)?.unions ?? [];
|
|
682
|
+
const common = (ctx.records.get(a.name)?.unions ?? []).filter((u) => ub.includes(u));
|
|
683
|
+
if (common.length === 1) return {
|
|
684
|
+
kind: "union",
|
|
685
|
+
name: common[0]
|
|
686
|
+
};
|
|
687
|
+
}
|
|
688
|
+
if (a.kind === "nullable" && b.kind === "nullable") {
|
|
689
|
+
const inner = join(a.inner, b.inner, ctx);
|
|
690
|
+
return inner && {
|
|
691
|
+
kind: "nullable",
|
|
692
|
+
inner
|
|
693
|
+
};
|
|
694
|
+
}
|
|
695
|
+
if (a.kind === "null" && b.kind !== "null") return {
|
|
696
|
+
kind: "nullable",
|
|
697
|
+
inner: b
|
|
698
|
+
};
|
|
699
|
+
if (b.kind === "null" && a.kind !== "null") return {
|
|
700
|
+
kind: "nullable",
|
|
701
|
+
inner: a
|
|
702
|
+
};
|
|
703
|
+
if (a.kind === "nullable" && b.kind !== "null" && b.kind !== "nullable") {
|
|
704
|
+
const inner = join(a.inner, b, ctx);
|
|
705
|
+
return inner && {
|
|
706
|
+
kind: "nullable",
|
|
707
|
+
inner
|
|
708
|
+
};
|
|
709
|
+
}
|
|
710
|
+
if (b.kind === "nullable" && a.kind !== "null" && a.kind !== "nullable") {
|
|
711
|
+
const inner = join(a, b.inner, ctx);
|
|
712
|
+
return inner && {
|
|
713
|
+
kind: "nullable",
|
|
714
|
+
inner
|
|
715
|
+
};
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
/** Whether `===` between the two types is in the subset, and on records (references in JavaScript) it is not. */
|
|
719
|
+
function comparable(l, r) {
|
|
720
|
+
const base = (t) => t.kind === "nullable" ? t.inner : t;
|
|
721
|
+
if (l.kind === "null" && r.kind === "null") return false;
|
|
722
|
+
if (l.kind === "null") return r.kind === "nullable";
|
|
723
|
+
if (r.kind === "null") return l.kind === "nullable";
|
|
724
|
+
return sameType(base(l), base(r)) && !isReference(base(l));
|
|
725
|
+
}
|
|
726
|
+
const isReference = (t) => t.kind === "record" || t.kind === "union" || t.kind === "list";
|
|
727
|
+
/**
|
|
728
|
+
* The element type of a list expression's type. An operation on an empty
|
|
729
|
+
* array no type is given for (`[].length`, `[].slice(1)`) is refused: an
|
|
730
|
+
* engine could only guess the element type, and such code has a plain
|
|
731
|
+
* value to write instead; `const xs: T[] = []` gives one.
|
|
732
|
+
*/
|
|
733
|
+
function elementOf(t, what, fail) {
|
|
734
|
+
if (t.kind !== "list") fail(`${what} on a ${describe(t)}, not a list`);
|
|
735
|
+
if (holdsNothing(t)) fail(`${what} on an empty array of no declared type (annotate it: const xs: T[] = [])`);
|
|
736
|
+
return t.element;
|
|
737
|
+
}
|
|
738
|
+
/** Whether a type holds the element type of an empty array literal anywhere in it (`[[]]` does). */
|
|
739
|
+
function holdsNothing(t) {
|
|
740
|
+
if (t.kind === "nothing") return true;
|
|
741
|
+
if (t.kind === "list") return holdsNothing(t.element);
|
|
742
|
+
if (t.kind === "nullable") return holdsNothing(t.inner);
|
|
743
|
+
return false;
|
|
744
|
+
}
|
|
745
|
+
/** The scope inside an iteration's callback: the item an element, the index an integer. */
|
|
746
|
+
function iterateScope(e, list, scope, ctx, fail) {
|
|
747
|
+
const inner = new Map(scope);
|
|
748
|
+
inner.set(e.item, elementOf(typeOf(list, scope, ctx, fail), e.op, fail));
|
|
749
|
+
if (e.index !== void 0) inner.set(e.index, { kind: "int" });
|
|
750
|
+
return inner;
|
|
751
|
+
}
|
|
752
|
+
/**
|
|
753
|
+
* The scope inside a fold's callback and the accumulator's type: the
|
|
754
|
+
* initial value's, widened once to the body's when the body's holds it.
|
|
755
|
+
* A callback that takes the accumulator apart as a list needs the initial
|
|
756
|
+
* value typed (`xs.reduce((acc, x) => [x, ...acc], [])` does not
|
|
757
|
+
* type-check in TypeScript either).
|
|
758
|
+
*/
|
|
759
|
+
function foldScope(e, list, init, scope, ctx, fail) {
|
|
760
|
+
const item = elementOf(typeOf(list, scope, ctx, fail), "reduce", fail);
|
|
761
|
+
const at = (acc) => new Map([
|
|
762
|
+
...scope,
|
|
763
|
+
[e.acc, acc],
|
|
764
|
+
[e.item, item]
|
|
765
|
+
]);
|
|
766
|
+
const start = typeOf(init, scope, ctx, fail);
|
|
767
|
+
const body = typeOf(e.body, at(start), ctx, fail);
|
|
768
|
+
if (fits(body, start, ctx)) return {
|
|
769
|
+
scope: at(start),
|
|
770
|
+
acc: start
|
|
771
|
+
};
|
|
772
|
+
if (fits(start, body, ctx) && fits(typeOf(e.body, at(body), ctx, fail), body, ctx)) return {
|
|
773
|
+
scope: at(body),
|
|
774
|
+
acc: body
|
|
775
|
+
};
|
|
776
|
+
fail(`reduce's callback makes a ${describe(body)} from an accumulator of ${describe(start)}`);
|
|
777
|
+
}
|
|
778
|
+
/** The type of an expression in a scope; records are matched by their fields' names. */
|
|
779
|
+
function typeOf(e, scope, ctx, fail, expected) {
|
|
780
|
+
switch (e.kind) {
|
|
781
|
+
case "int": return { kind: "int" };
|
|
782
|
+
case "bool": return { kind: "bool" };
|
|
783
|
+
case "string": return { kind: "string" };
|
|
784
|
+
case "null": return { kind: "null" };
|
|
785
|
+
case "var": {
|
|
786
|
+
const t = scope.get(e.name);
|
|
787
|
+
if (!t) fail(`${e.name} is not in scope`);
|
|
788
|
+
return t;
|
|
789
|
+
}
|
|
790
|
+
case "narrow": {
|
|
791
|
+
const t = scope.get(e.name);
|
|
792
|
+
if (!t) fail(`${e.name} is not in scope`);
|
|
793
|
+
if (t.kind !== "nullable") fail(`${e.name} is narrowed but is a ${describe(t)}, not a nullable`);
|
|
794
|
+
return typeOf(e.body, new Map([...scope, [e.name, t.inner]]), ctx, fail, expected);
|
|
795
|
+
}
|
|
796
|
+
case "narrowTag": {
|
|
797
|
+
const t = scope.get(e.name);
|
|
798
|
+
if (!t) fail(`${e.name} is not in scope`);
|
|
799
|
+
if (t.kind !== "union") fail(`${e.name} is narrowed by a tag but is a ${describe(t)}, not a union`);
|
|
800
|
+
if (!isMember(ctx.records.get(e.member), t.name)) fail(`${e.member} is not a member of ${t.name}`);
|
|
801
|
+
return typeOf(e.body, new Map([...scope, [e.name, {
|
|
802
|
+
kind: "record",
|
|
803
|
+
name: e.member
|
|
804
|
+
}]]), ctx, fail, expected);
|
|
805
|
+
}
|
|
806
|
+
case "binary": {
|
|
807
|
+
const l = typeOf(e.left, scope, ctx, fail);
|
|
808
|
+
const r = typeOf(e.right, scope, ctx, fail);
|
|
809
|
+
if (e.op === "+" && l.kind === "string" && r.kind === "string") return { kind: "string" };
|
|
810
|
+
if ([
|
|
811
|
+
"+",
|
|
812
|
+
"-",
|
|
813
|
+
"*",
|
|
814
|
+
"/",
|
|
815
|
+
"<",
|
|
816
|
+
"<=",
|
|
817
|
+
">",
|
|
818
|
+
">="
|
|
819
|
+
].includes(e.op) && (l.kind !== "int" || r.kind !== "int")) fail(`${e.op} on a ${l.kind} and a ${r.kind} (the subset has it on integers${e.op === "+" ? ", and + on two strings" : ""})`);
|
|
820
|
+
if ((e.op === "&&" || e.op === "||") && (l.kind !== "bool" || r.kind !== "bool")) fail(`${e.op} on a ${l.kind} and a ${r.kind} (the subset has it on booleans)`);
|
|
821
|
+
if (e.op === "===" || e.op === "!==") {
|
|
822
|
+
const againstNull = l.kind === "null" || r.kind === "null";
|
|
823
|
+
const base = (t) => t.kind === "nullable" ? t.inner : t;
|
|
824
|
+
if (!againstNull && (isReference(base(l)) || isReference(base(r)))) fail(`${e.op} on records compares references in JavaScript; compare their fields instead`);
|
|
825
|
+
if (!comparable(l, r)) fail(`${e.op} between a ${describe(l)} and a ${describe(r)}`);
|
|
826
|
+
}
|
|
827
|
+
return [
|
|
828
|
+
"+",
|
|
829
|
+
"-",
|
|
830
|
+
"*",
|
|
831
|
+
"/"
|
|
832
|
+
].includes(e.op) ? { kind: "int" } : { kind: "bool" };
|
|
833
|
+
}
|
|
834
|
+
case "neg": {
|
|
835
|
+
const t = typeOf(e.operand, scope, ctx, fail);
|
|
836
|
+
if (t.kind !== "int") fail(`unary minus on a ${t.kind}`);
|
|
837
|
+
return { kind: "int" };
|
|
838
|
+
}
|
|
839
|
+
case "not": {
|
|
840
|
+
const t = typeOf(e.operand, scope, ctx, fail);
|
|
841
|
+
if (t.kind !== "bool") fail(`! on a ${t.kind}`);
|
|
842
|
+
return { kind: "bool" };
|
|
843
|
+
}
|
|
844
|
+
case "isInteger": {
|
|
845
|
+
const t = typeOf(e.operand, scope, ctx, fail);
|
|
846
|
+
if (t.kind !== "int") fail(`Number.isInteger on a ${t.kind}`);
|
|
847
|
+
return { kind: "bool" };
|
|
848
|
+
}
|
|
849
|
+
case "floor": {
|
|
850
|
+
const t = typeOf(e.operand, scope, ctx, fail);
|
|
851
|
+
if (t.kind !== "int") fail(`Math.floor on a ${t.kind}`);
|
|
852
|
+
return { kind: "int" };
|
|
853
|
+
}
|
|
854
|
+
case "cond": {
|
|
855
|
+
const test = typeOf(e.test, scope, ctx, fail);
|
|
856
|
+
if (test.kind !== "bool") fail(`a condition that is a ${describe(test)} (truthiness is not in the subset; compare it)`);
|
|
857
|
+
const a = typeOf(e.ifTrue, scope, ctx, fail, expected);
|
|
858
|
+
const b = typeOf(e.ifFalse, scope, ctx, fail, expected);
|
|
859
|
+
const joined = join(a, b, ctx);
|
|
860
|
+
if (joined) return joined;
|
|
861
|
+
if (expected && fits(a, expected, ctx) && fits(b, expected, ctx)) return expected;
|
|
862
|
+
return fail(`the branches of a conditional have different types (${describe(a)} and ${describe(b)})`);
|
|
863
|
+
}
|
|
864
|
+
case "let": {
|
|
865
|
+
const inferred = typeOf(e.value, scope, ctx, fail, e.type);
|
|
866
|
+
if (e.type && !fits(inferred, e.type, ctx)) fail(`const ${e.name} is annotated ${describe(e.type)} but holds a ${describe(inferred)}`);
|
|
867
|
+
if (!e.type && holdsNothing(inferred)) fail(`const ${e.name} holds an empty array of no declared type (annotate it: const ${e.name}: T[] = [])`);
|
|
868
|
+
return typeOf(e.body, new Map([...scope, [e.name, e.type ?? inferred]]), ctx, fail, expected);
|
|
869
|
+
}
|
|
870
|
+
case "call": {
|
|
871
|
+
const sig = ctx.signatures.get(e.callee);
|
|
872
|
+
if (!sig) fail(`the signature of ${e.callee} is not known`);
|
|
873
|
+
if (sig.params.length !== e.args.length) fail(`${e.callee} takes ${sig.params.length} argument(s), called with ${e.args.length}`);
|
|
874
|
+
e.args.forEach((a, i) => {
|
|
875
|
+
const want = sig.params[i]?.type;
|
|
876
|
+
const got = typeOf(a, scope, ctx, fail, want);
|
|
877
|
+
if (!fits(got, want, ctx)) fail(`argument ${i + 1} of ${e.callee} is a ${describe(got)}, not the ${describe(want)} it takes`);
|
|
878
|
+
});
|
|
879
|
+
return sig.returns;
|
|
880
|
+
}
|
|
881
|
+
case "field": {
|
|
882
|
+
const o = typeOf(e.object, scope, ctx, fail);
|
|
883
|
+
if (o.kind === "list") {
|
|
884
|
+
if (e.field !== "length") fail(`${e.field} read from a list (the subset has length)`);
|
|
885
|
+
elementOf(o, "length", fail);
|
|
886
|
+
return { kind: "int" };
|
|
887
|
+
}
|
|
888
|
+
if (o.kind === "nullable") fail(`field ${e.field} read from a ${describe(o)}: compare it with null first, which narrows it`);
|
|
889
|
+
if (o.kind === "union") {
|
|
890
|
+
const types = membersIn(o.name, ctx).map((rec) => rec.fields.find((x) => x.name === e.field)?.type);
|
|
891
|
+
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)`);
|
|
892
|
+
const first = types[0];
|
|
893
|
+
if (!types.every((t) => sameType(t, first))) fail(`field ${e.field} has different types across the members of ${o.name}`);
|
|
894
|
+
return first;
|
|
895
|
+
}
|
|
896
|
+
if (o.kind !== "record") fail(`field ${e.field} read from a ${describe(o)}`);
|
|
897
|
+
const f = ctx.records.get(o.name)?.fields.find((x) => x.name === e.field);
|
|
898
|
+
if (!f) fail(`${o.name} has no field ${e.field}`);
|
|
899
|
+
return f.type;
|
|
900
|
+
}
|
|
901
|
+
case "record": {
|
|
902
|
+
const names = e.fields.map((f) => f.name).sort().join(",");
|
|
903
|
+
const context = e.type;
|
|
904
|
+
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);
|
|
905
|
+
if (byNames.length === 0) fail(`a record literal with fields ${names} matches no declared record type`);
|
|
906
|
+
const types = new Map(e.fields.map((f) => [f.name, typeOf(f.value, scope, ctx, fail)]));
|
|
907
|
+
const fitting = byNames.filter((rec) => rec.fields.every((f) => fits(types.get(f.name), f.type, ctx)));
|
|
908
|
+
if (fitting.length === 0) {
|
|
909
|
+
const rec = byNames[0];
|
|
910
|
+
const off = rec.fields.find((f) => !fits(types.get(f.name), f.type, ctx));
|
|
911
|
+
fail(`field ${off.name} of a ${rec.name} literal holds a ${describe(types.get(off.name))}, not a ${describe(off.type)}`);
|
|
912
|
+
}
|
|
913
|
+
const literalOf = (name) => {
|
|
914
|
+
const v = e.fields.find((f) => f.name === name)?.value;
|
|
915
|
+
return v?.kind === "string" || v?.kind === "bool" ? v.value : void 0;
|
|
916
|
+
};
|
|
917
|
+
const tagged = fitting.filter((rec) => rec.fields.every((f) => f.literal === void 0 || literalOf(f.name) === f.literal));
|
|
918
|
+
const chosen = tagged.length > 0 ? tagged : fitting;
|
|
919
|
+
if (chosen.length > 1) fail(`a record literal with fields ${names} matches ${chosen.map((r) => r.name).join(" and ")} alike`);
|
|
920
|
+
return {
|
|
921
|
+
kind: "record",
|
|
922
|
+
name: chosen[0].name
|
|
923
|
+
};
|
|
924
|
+
}
|
|
925
|
+
case "list": {
|
|
926
|
+
let element = { kind: "nothing" };
|
|
927
|
+
const add = (t) => {
|
|
928
|
+
const joined = join(element, t, ctx);
|
|
929
|
+
if (!joined) fail(`an array literal of a ${describe(element)} and a ${describe(t)}`);
|
|
930
|
+
element = joined;
|
|
931
|
+
};
|
|
932
|
+
for (const item of e.items) add(typeOf(item, scope, ctx, fail));
|
|
933
|
+
if (e.rest) add(elementOf(typeOf(e.rest, scope, ctx, fail), "a spread", fail));
|
|
934
|
+
return {
|
|
935
|
+
kind: "list",
|
|
936
|
+
element
|
|
937
|
+
};
|
|
938
|
+
}
|
|
939
|
+
case "tail": {
|
|
940
|
+
const t = typeOf(e.list, scope, ctx, fail);
|
|
941
|
+
elementOf(t, "slice", fail);
|
|
942
|
+
return t;
|
|
943
|
+
}
|
|
944
|
+
case "headOr": {
|
|
945
|
+
const element = elementOf(typeOf(e.list, scope, ctx, fail), "[0]", fail);
|
|
946
|
+
if (element.kind === "nullable" || element.kind === "null") fail("xs[0] ?? on a list of a nullable type (?? replaces a null element too)");
|
|
947
|
+
const fallback = typeOf(e.fallback, scope, ctx, fail);
|
|
948
|
+
const joined = join(element, fallback, ctx);
|
|
949
|
+
if (!joined) fail(`?? between a ${describe(element)} and a ${describe(fallback)}`);
|
|
950
|
+
return joined;
|
|
951
|
+
}
|
|
952
|
+
case "iterate": {
|
|
953
|
+
const body = typeOf(e.body, iterateScope(e, e.list, scope, ctx, fail), ctx, fail);
|
|
954
|
+
if (e.op === "map") return {
|
|
955
|
+
kind: "list",
|
|
956
|
+
element: body
|
|
957
|
+
};
|
|
958
|
+
if (e.op === "flatMap") return {
|
|
959
|
+
kind: "list",
|
|
960
|
+
element: elementOf(body, "flatMap's callback result", fail)
|
|
961
|
+
};
|
|
962
|
+
if (body.kind !== "bool") fail(`${e.op}'s callback returns a ${describe(body)}, not a boolean`);
|
|
963
|
+
return { kind: "bool" };
|
|
964
|
+
}
|
|
965
|
+
case "fold": return foldScope(e, e.list, e.init, scope, ctx, fail).acc;
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
// packages/prover/src/reader/declarations.ts
|
|
969
|
+
/**
|
|
970
|
+
* A file's functions as declared: its top-level functions and which of
|
|
971
|
+
* them may run something else (`fileFunctions`), a function's header and
|
|
972
|
+
* body read against it (`head`, `declaration`), and why a range of a file
|
|
973
|
+
* is not read: an error the compiler reports in it, or a directive that
|
|
974
|
+
* hides one (`notCompiled`).
|
|
975
|
+
*/
|
|
976
|
+
/**
|
|
977
|
+
* The first `@ts-ignore` or `@ts-expect-error` directive in a range of a
|
|
978
|
+
* file, with its position: a comment shaped as the compiler reads one (the
|
|
979
|
+
* directive opens a `//` comment, or the last line of a block comment),
|
|
980
|
+
* found as the compiler finds comments, leading or trailing a node's
|
|
981
|
+
* text, so the words in prose or in a string are not one. A comment
|
|
982
|
+
* before a closing token alone (`/* … *\/ }`) is not seen; what it could
|
|
983
|
+
* hide is on that token's line.
|
|
984
|
+
*/
|
|
985
|
+
function directiveIn(sf, start, end) {
|
|
986
|
+
const text = sf.text;
|
|
987
|
+
const singleLine = /^\/\/\/?\s*@ts-(ignore|expect-error)/;
|
|
988
|
+
const lastLine = /^(?:\/|\*)*\s*@ts-(ignore|expect-error)/;
|
|
989
|
+
let found;
|
|
990
|
+
const check = (pos, commentEnd) => {
|
|
991
|
+
if (found || pos < start || commentEnd > end) return;
|
|
992
|
+
const comment = text.slice(pos, commentEnd);
|
|
993
|
+
const m = comment.startsWith("//") ? singleLine.exec(comment) : lastLine.exec(comment.slice(comment.lastIndexOf("\n") + 1).trimStart());
|
|
994
|
+
if (m) found = {
|
|
995
|
+
text: `@ts-${m[1]}`,
|
|
996
|
+
pos
|
|
997
|
+
};
|
|
998
|
+
};
|
|
999
|
+
const visit = (node) => {
|
|
1000
|
+
if (found || node.end < start || node.pos > end) return;
|
|
1001
|
+
forEachLeadingCommentRange(text, node.pos, check);
|
|
1002
|
+
forEachTrailingCommentRange(text, node.end, check);
|
|
1003
|
+
node.forEachChild(visit);
|
|
1004
|
+
};
|
|
1005
|
+
visit(sf);
|
|
1006
|
+
return found;
|
|
1007
|
+
}
|
|
1008
|
+
/**
|
|
1009
|
+
* The line of a `@ts-nocheck` directive at the top of a file, which turns
|
|
1010
|
+
* the compiler's checks off for all of it: as the compiler reads it, a
|
|
1011
|
+
* `//` comment opening with it, the last of it and `@ts-check` deciding.
|
|
1012
|
+
*/
|
|
1013
|
+
function noCheckDirective(sf) {
|
|
1014
|
+
const text = sf.text;
|
|
1015
|
+
const from = text.startsWith("#!") ? Math.max(0, text.indexOf("\n")) : 0;
|
|
1016
|
+
let line;
|
|
1017
|
+
forEachLeadingCommentRange(text, from, (pos, end) => {
|
|
1018
|
+
const m = /^\/\/\/?\s*@ts-(check|nocheck)\b/.exec(text.slice(pos, end));
|
|
1019
|
+
if (m) line = m[1] === "nocheck" ? sf.getLineAndCharacterOfPosition(pos).line + 1 : void 0;
|
|
1020
|
+
});
|
|
1021
|
+
return line;
|
|
1022
|
+
}
|
|
1023
|
+
/**
|
|
1024
|
+
* Why a range of a file is not read: the first error the compiler reports
|
|
1025
|
+
* inside it, or a `@ts-ignore` or `@ts-expect-error` directive in it or
|
|
1026
|
+
* in the leading comments (where a directive reaches the first line),
|
|
1027
|
+
* which hides one from the reader. Undefined when the range is clean.
|
|
1028
|
+
*/
|
|
1029
|
+
function notCompiled(sf, typeErrors, { start, end, lead }) {
|
|
1030
|
+
const error = typeErrors(sf.fileName).find((e) => e.pos < end && e.end > start);
|
|
1031
|
+
if (error) return {
|
|
1032
|
+
message: `the compiler reports an error: ${error.message}`,
|
|
1033
|
+
line: error.line
|
|
1034
|
+
};
|
|
1035
|
+
const silenced = (lead ? directiveIn(sf, lead.start, lead.end) : void 0) ?? directiveIn(sf, start, end);
|
|
1036
|
+
if (silenced) return {
|
|
1037
|
+
message: `a ${silenced.text} comment, which hides a compiler error from the reader`,
|
|
1038
|
+
line: sf.getLineAndCharacterOfPosition(silenced.pos).line + 1
|
|
1039
|
+
};
|
|
1040
|
+
}
|
|
1041
|
+
/**
|
|
1042
|
+
* Where a declared function's errors are looked for: its own declaration
|
|
1043
|
+
* (in a `const` list, a sibling's error, or a directive in a sibling's
|
|
1044
|
+
* body, is the sibling's), and for directives the statement's leading
|
|
1045
|
+
* comments too, since a directive above the statement reaches its first
|
|
1046
|
+
* line, siblings included.
|
|
1047
|
+
*/
|
|
1048
|
+
function rangeOf(d) {
|
|
1049
|
+
let declaration = d.node;
|
|
1050
|
+
while (!is.isFunctionDeclaration(declaration) && !is.isVariableDeclaration(declaration)) declaration = declaration.parent;
|
|
1051
|
+
const sf = d.statement.getSourceFile();
|
|
1052
|
+
return {
|
|
1053
|
+
start: declaration.pos,
|
|
1054
|
+
end: declaration.end,
|
|
1055
|
+
lead: {
|
|
1056
|
+
start: d.statement.pos,
|
|
1057
|
+
end: d.statement.getStart(sf)
|
|
1058
|
+
}
|
|
1059
|
+
};
|
|
1060
|
+
}
|
|
1061
|
+
/**
|
|
1062
|
+
* The declared functions the module assigns to anywhere, with the line
|
|
1063
|
+
* of the first assignment: what runs under such a name may not be its
|
|
1064
|
+
* declaration. A name is confirmed through the compiler, so a local of
|
|
1065
|
+
* the same name assigned in some block is not the function.
|
|
1066
|
+
*/
|
|
1067
|
+
function assigned(sf, checker, declarations) {
|
|
1068
|
+
const out = /* @__PURE__ */ new Map();
|
|
1069
|
+
const symbolIds = /* @__PURE__ */ new Map();
|
|
1070
|
+
const idOf = (name) => {
|
|
1071
|
+
if (!symbolIds.has(name)) {
|
|
1072
|
+
const decl = declarations.get(name);
|
|
1073
|
+
symbolIds.set(name, decl ? checker.getSymbolAtLocation(decl.name)?.id : void 0);
|
|
1074
|
+
}
|
|
1075
|
+
return symbolIds.get(name);
|
|
1076
|
+
};
|
|
1077
|
+
const visit = (node) => {
|
|
1078
|
+
if (is.isIdentifier(node) && declarations.has(node.text) && !out.has(node.text) && isWritten(node)) {
|
|
1079
|
+
const id = idOf(node.text);
|
|
1080
|
+
const parent = node.parent;
|
|
1081
|
+
const symbol = is.isShorthandPropertyAssignment(parent) && parent.name === node ? checker.getShorthandAssignmentValueSymbol(parent) : checker.getSymbolAtLocation(node);
|
|
1082
|
+
if (id !== void 0 && symbol?.id === id) out.set(node.text, lineAt(sf, node));
|
|
1083
|
+
}
|
|
1084
|
+
node.forEachChild(visit);
|
|
1085
|
+
};
|
|
1086
|
+
visit(sf);
|
|
1087
|
+
return out;
|
|
1088
|
+
}
|
|
1089
|
+
/** The parameter names of a function the subset can take at all: synchronous, no generator, plain parameters. */
|
|
1090
|
+
function shape(reader, decl) {
|
|
1091
|
+
if (isAsync(decl)) reader.fail("an async function (core functions are synchronous)", decl);
|
|
1092
|
+
if (!is.isArrowFunction(decl) && decl.asteriskToken) reader.fail("a generator function", decl);
|
|
1093
|
+
return decl.parameters.map((p) => {
|
|
1094
|
+
if (!is.isIdentifier(p.name)) reader.fail("a destructured parameter", p);
|
|
1095
|
+
const pname = p.name.text;
|
|
1096
|
+
if (p.dotDotDotToken) reader.fail("a rest parameter", p);
|
|
1097
|
+
if (pname === "this") reader.fail("a this parameter (the receiver is not modelled)", p);
|
|
1098
|
+
if (p.questionToken) reader.fail(`optional parameter ${pname}`, p);
|
|
1099
|
+
if (p.initializer) reader.fail(`a default value for ${pname}`, p);
|
|
1100
|
+
return pname;
|
|
1101
|
+
});
|
|
1102
|
+
}
|
|
1103
|
+
/** `export function name(params): Type {` or `export const name = (params): Type => …` read, the types through the compiler. */
|
|
1104
|
+
function head(reader, types, checker, d) {
|
|
1105
|
+
const sf = reader.sf;
|
|
1106
|
+
const decl = d.node;
|
|
1107
|
+
const name = d.name.text;
|
|
1108
|
+
const pnames = shape(reader, decl);
|
|
1109
|
+
if (decl.typeParameters) reader.fail("type parameters", decl.typeParameters[0] ?? decl);
|
|
1110
|
+
const params = decl.parameters.map((p, i) => {
|
|
1111
|
+
const pname = pnames[i];
|
|
1112
|
+
if (!p.type) reader.fail(`parameter ${pname} without a type`, p);
|
|
1113
|
+
return {
|
|
1114
|
+
name: pname,
|
|
1115
|
+
type: types.of(checker.getTypeAtLocation(p.type), reader.refuseAt(p.type))
|
|
1116
|
+
};
|
|
1117
|
+
});
|
|
1118
|
+
if (!decl.type) reader.fail(`${name} without a return type (the subset needs it to name the record returned)`, decl);
|
|
1119
|
+
const returns = types.of(checker.getTypeAtLocation(decl.type), reader.refuseAt(decl.type));
|
|
1120
|
+
if (!decl.body) reader.fail("a function without a body", decl);
|
|
1121
|
+
const offset = openParen(sf, decl);
|
|
1122
|
+
if (offset === void 0) reader.fail("a function without a parameter list", decl);
|
|
1123
|
+
return {
|
|
1124
|
+
name,
|
|
1125
|
+
decl,
|
|
1126
|
+
params,
|
|
1127
|
+
returns,
|
|
1128
|
+
line: lineAt(sf, d.statement),
|
|
1129
|
+
offset
|
|
1130
|
+
};
|
|
1131
|
+
}
|
|
1132
|
+
/** The function, its body read and typed against its header. */
|
|
1133
|
+
function declaration(reader, h) {
|
|
1134
|
+
const body = h.decl.body;
|
|
1135
|
+
const scope = new Map(h.params.map((p) => [p.name, p.type]));
|
|
1136
|
+
const statements = is.isBlock(body) ? reader.block(body.statements, scope, body) : reader.expression(body, scope);
|
|
1137
|
+
const read = reader.narrowed(statements, scope, body);
|
|
1138
|
+
const actual = reader.typeOfExpr(read, scope, body, h.returns);
|
|
1139
|
+
if (!fits(actual, h.returns, reader.ctx)) reader.fail(`${h.name} returns a ${describe(actual)} but declares ${describe(h.returns)}`, body);
|
|
1140
|
+
return {
|
|
1141
|
+
name: h.name,
|
|
1142
|
+
params: h.params,
|
|
1143
|
+
returns: h.returns,
|
|
1144
|
+
body: read,
|
|
1145
|
+
line: h.line,
|
|
1146
|
+
offset: h.offset
|
|
1147
|
+
};
|
|
1148
|
+
}
|
|
1149
|
+
/**
|
|
1150
|
+
* A file's top-level functions: declarations, and the arrows module-level
|
|
1151
|
+
* consts hold. A binding that may be reassigned (let, var) or holds a
|
|
1152
|
+
* function expression is listed, for its callers' typing, and untrusted;
|
|
1153
|
+
* so is every function of a file mentioning eval directly or assigning to
|
|
1154
|
+
* a built-in, and a function the file assigns to.
|
|
1155
|
+
*/
|
|
1156
|
+
function fileFunctions(sf, checker, standardGlobal) {
|
|
1157
|
+
const declarations = /* @__PURE__ */ new Map();
|
|
1158
|
+
const overloaded = /* @__PURE__ */ new Set();
|
|
1159
|
+
const untrusted = /* @__PURE__ */ new Map();
|
|
1160
|
+
const declare = (name, node, statement) => {
|
|
1161
|
+
if (declarations.has(name.text)) overloaded.add(name.text);
|
|
1162
|
+
else declarations.set(name.text, {
|
|
1163
|
+
name,
|
|
1164
|
+
node,
|
|
1165
|
+
statement
|
|
1166
|
+
});
|
|
1167
|
+
};
|
|
1168
|
+
for (const st of sf.statements) {
|
|
1169
|
+
if (is.isFunctionDeclaration(st)) {
|
|
1170
|
+
if (st.name) declare(st.name, st, st);
|
|
1171
|
+
continue;
|
|
1172
|
+
}
|
|
1173
|
+
if (!is.isVariableStatement(st)) continue;
|
|
1174
|
+
for (const d of st.declarationList.declarations) {
|
|
1175
|
+
if (!is.isIdentifier(d.name) || !d.initializer) continue;
|
|
1176
|
+
let init = d.initializer;
|
|
1177
|
+
while (is.isParenthesizedExpression(init)) init = init.expression;
|
|
1178
|
+
if (!is.isArrowFunction(init) && !is.isFunctionExpression(init)) continue;
|
|
1179
|
+
const name = d.name.text;
|
|
1180
|
+
declare(d.name, init, st);
|
|
1181
|
+
if (!isConst(st.declarationList)) untrusted.set(name, {
|
|
1182
|
+
name,
|
|
1183
|
+
line: lineAt(sf, st),
|
|
1184
|
+
message: `${name} is declared with let or var, so what runs under its name may be another function`
|
|
1185
|
+
});
|
|
1186
|
+
else if (is.isFunctionExpression(init)) untrusted.set(name, {
|
|
1187
|
+
name,
|
|
1188
|
+
line: lineAt(sf, st),
|
|
1189
|
+
message: `${name} holds a function expression (write a function declaration or an arrow)`
|
|
1190
|
+
});
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
const evalLine = directEval(sf);
|
|
1194
|
+
const noCheck = noCheckDirective(sf);
|
|
1195
|
+
const patched = rebound(sf, checker, standardGlobal);
|
|
1196
|
+
const tainted = evalLine !== void 0 ? {
|
|
1197
|
+
line: evalLine,
|
|
1198
|
+
message: "the module mentions eval directly, which can rebind any of its declarations"
|
|
1199
|
+
} : noCheck !== void 0 ? {
|
|
1200
|
+
line: noCheck,
|
|
1201
|
+
message: "its file has a @ts-nocheck comment, which turns off the compiler's checks the reader relies on"
|
|
1202
|
+
} : patched !== void 0 ? {
|
|
1203
|
+
line: patched.line,
|
|
1204
|
+
message: `its file assigns to ${patched.target} (line ${patched.line}), so the built-ins its functions use may not be the standard ones`
|
|
1205
|
+
} : void 0;
|
|
1206
|
+
if (tainted) for (const name of declarations.keys()) untrusted.set(name, {
|
|
1207
|
+
name,
|
|
1208
|
+
...tainted
|
|
1209
|
+
});
|
|
1210
|
+
for (const [name, line] of assigned(sf, checker, declarations)) if (!untrusted.has(name)) untrusted.set(name, {
|
|
1211
|
+
name,
|
|
1212
|
+
line,
|
|
1213
|
+
message: `${name} is assigned in the module, so what runs under its name may not be its declaration`
|
|
1214
|
+
});
|
|
1215
|
+
return {
|
|
1216
|
+
declarations,
|
|
1217
|
+
overloaded,
|
|
1218
|
+
untrusted,
|
|
1219
|
+
...tainted ? { tainted } : {}
|
|
1220
|
+
};
|
|
1221
|
+
}
|
|
1222
|
+
// packages/prover/src/reader/narrowing.ts
|
|
1223
|
+
/**
|
|
1224
|
+
* The names a test, holding or failing, shows to be non-null: `x !== null`
|
|
1225
|
+
* holding, `x === null` failing, through `!`, `&&` (holding) and `||`
|
|
1226
|
+
* (failing).
|
|
1227
|
+
*/
|
|
1228
|
+
function narrowsOf(test, holds) {
|
|
1229
|
+
if (test.kind === "narrow" || test.kind === "narrowTag") return narrowsOf(test.body, holds);
|
|
1230
|
+
const isNull = (e) => e.kind === "null";
|
|
1231
|
+
if (test.kind === "binary" && (test.op === "===" || test.op === "!==")) {
|
|
1232
|
+
const other = isNull(test.right) ? test.left : isNull(test.left) ? test.right : void 0;
|
|
1233
|
+
if (other?.kind !== "var") return [];
|
|
1234
|
+
return test.op === "!==" === holds ? [other.name] : [];
|
|
1235
|
+
}
|
|
1236
|
+
if (test.kind === "not") return narrowsOf(test.operand, !holds);
|
|
1237
|
+
if (test.kind === "binary" && test.op === "&&" && holds) return [...narrowsOf(test.left, true), ...narrowsOf(test.right, true)];
|
|
1238
|
+
if (test.kind === "binary" && test.op === "||" && !holds) return [...narrowsOf(test.left, false), ...narrowsOf(test.right, false)];
|
|
1239
|
+
return [];
|
|
1240
|
+
}
|
|
1241
|
+
/**
|
|
1242
|
+
* The field that tells a union's members apart, as the union names it: the
|
|
1243
|
+
* one the types read chose (`UnionType.tag`), which the engines encode by.
|
|
1244
|
+
* Re-deriving it from the member records could pick another field where two
|
|
1245
|
+
* discriminate, and the reader would then refuse the test the engines take.
|
|
1246
|
+
*/
|
|
1247
|
+
function tagOf(union, ctx) {
|
|
1248
|
+
return ctx.unions.find((u) => u.name === union)?.tag;
|
|
1249
|
+
}
|
|
1250
|
+
/**
|
|
1251
|
+
* The names a test, holding or failing, shows to be one member of their
|
|
1252
|
+
* union, with that member: `x.tag === "a"` holding (or `!==` failing)
|
|
1253
|
+
* names the member tagged `"a"`; failing, the other member when the
|
|
1254
|
+
* union has two; `x.ok` alone is the test of a boolean tag; through `!`,
|
|
1255
|
+
* `&&` (holding) and `||` (failing) as null checks are.
|
|
1256
|
+
*/
|
|
1257
|
+
function tagNarrowsOf(test, holds, scope, ctx) {
|
|
1258
|
+
const tagged = (e) => {
|
|
1259
|
+
if (e.kind !== "field" || e.object.kind !== "var") return void 0;
|
|
1260
|
+
const t = scope.get(e.object.name);
|
|
1261
|
+
if (t?.kind !== "union" || tagOf(t.name, ctx) !== e.field) return void 0;
|
|
1262
|
+
return {
|
|
1263
|
+
name: e.object.name,
|
|
1264
|
+
members: membersIn(t.name, ctx)
|
|
1265
|
+
};
|
|
1266
|
+
};
|
|
1267
|
+
const byTag = (read, tag, value, isIt) => {
|
|
1268
|
+
const same = read.members.filter((m) => m.fields.find((f) => f.name === tag)?.literal === value);
|
|
1269
|
+
const chosen = isIt ? same : read.members.filter((m) => !same.includes(m));
|
|
1270
|
+
return chosen.length === 1 ? [{
|
|
1271
|
+
name: read.name,
|
|
1272
|
+
member: chosen[0].name
|
|
1273
|
+
}] : [];
|
|
1274
|
+
};
|
|
1275
|
+
if (test.kind === "narrow" || test.kind === "narrowTag") return tagNarrowsOf(test.body, holds, scope, ctx);
|
|
1276
|
+
if (test.kind === "binary" && (test.op === "===" || test.op === "!==")) {
|
|
1277
|
+
const literal = (e) => e.kind === "string" || e.kind === "bool" ? e.value : void 0;
|
|
1278
|
+
const [field, value] = literal(test.right) !== void 0 ? [test.left, literal(test.right)] : [test.right, literal(test.left)];
|
|
1279
|
+
if (value === void 0 || field.kind !== "field") return [];
|
|
1280
|
+
const read = tagged(field);
|
|
1281
|
+
if (!read) return [];
|
|
1282
|
+
return byTag(read, field.field, value, test.op === "===" === holds);
|
|
1283
|
+
}
|
|
1284
|
+
if (test.kind === "field") {
|
|
1285
|
+
const read = tagged(test);
|
|
1286
|
+
return read ? byTag(read, test.field, holds, true) : [];
|
|
1287
|
+
}
|
|
1288
|
+
if (test.kind === "not") return tagNarrowsOf(test.operand, !holds, scope, ctx);
|
|
1289
|
+
if (test.kind === "binary" && test.op === "&&" && holds) return [...tagNarrowsOf(test.left, true, scope, ctx), ...tagNarrowsOf(test.right, true, scope, ctx)];
|
|
1290
|
+
if (test.kind === "binary" && test.op === "||" && !holds) return [...tagNarrowsOf(test.left, false, scope, ctx), ...tagNarrowsOf(test.right, false, scope, ctx)];
|
|
1291
|
+
return [];
|
|
1292
|
+
}
|
|
1293
|
+
/**
|
|
1294
|
+
* `narrow` and `narrowTag` nodes inserted where a test guards: in a
|
|
1295
|
+
* conditional's branches, and in the right operand of `&&` and `||`, for
|
|
1296
|
+
* each nullable name the test shows to be non-null there and each union
|
|
1297
|
+
* name it shows to be one member there.
|
|
1298
|
+
*/
|
|
1299
|
+
function insertNarrows(e, scope, ctx, fail) {
|
|
1300
|
+
const go = (x, sc) => insertNarrows(x, sc, ctx, fail);
|
|
1301
|
+
const probe = Symbol("untyped");
|
|
1302
|
+
const condition = (x, sc) => {
|
|
1303
|
+
if (x.kind === "binary" && (x.op === "&&" || x.op === "||")) return {
|
|
1304
|
+
...x,
|
|
1305
|
+
left: condition(x.left, sc),
|
|
1306
|
+
right: condition(x.right, sc)
|
|
1307
|
+
};
|
|
1308
|
+
if (x.kind === "not") return {
|
|
1309
|
+
kind: "not",
|
|
1310
|
+
operand: condition(x.operand, sc)
|
|
1311
|
+
};
|
|
1312
|
+
let t;
|
|
1313
|
+
try {
|
|
1314
|
+
t = typeOf(x, sc, ctx, () => {
|
|
1315
|
+
throw probe;
|
|
1316
|
+
});
|
|
1317
|
+
} catch (err) {
|
|
1318
|
+
if (err === probe) return x;
|
|
1319
|
+
throw err;
|
|
1320
|
+
}
|
|
1321
|
+
if (t.kind === "nullable" && (t.inner.kind === "record" || t.inner.kind === "union")) return {
|
|
1322
|
+
kind: "binary",
|
|
1323
|
+
op: "!==",
|
|
1324
|
+
left: x,
|
|
1325
|
+
right: { kind: "null" }
|
|
1326
|
+
};
|
|
1327
|
+
return x;
|
|
1328
|
+
};
|
|
1329
|
+
const wrap = (body, test, holds, sc) => {
|
|
1330
|
+
const inner = new Map(sc);
|
|
1331
|
+
let out = body;
|
|
1332
|
+
const nullable = [...new Set(narrowsOf(test, holds))].filter((n) => sc.get(n)?.kind === "nullable");
|
|
1333
|
+
for (const n of nullable) inner.set(n, sc.get(n).inner);
|
|
1334
|
+
const tags = [];
|
|
1335
|
+
for (const t of tagNarrowsOf(test, holds, inner, ctx)) if (!tags.some((x) => x.name === t.name)) {
|
|
1336
|
+
tags.push(t);
|
|
1337
|
+
inner.set(t.name, {
|
|
1338
|
+
kind: "record",
|
|
1339
|
+
name: t.member
|
|
1340
|
+
});
|
|
1341
|
+
}
|
|
1342
|
+
out = go(out, inner);
|
|
1343
|
+
for (const t of tags.reverse()) out = {
|
|
1344
|
+
kind: "narrowTag",
|
|
1345
|
+
name: t.name,
|
|
1346
|
+
member: t.member,
|
|
1347
|
+
body: out
|
|
1348
|
+
};
|
|
1349
|
+
for (const n of nullable.reverse()) out = {
|
|
1350
|
+
kind: "narrow",
|
|
1351
|
+
name: n,
|
|
1352
|
+
body: out
|
|
1353
|
+
};
|
|
1354
|
+
return out;
|
|
1355
|
+
};
|
|
1356
|
+
switch (e.kind) {
|
|
1357
|
+
case "int":
|
|
1358
|
+
case "bool":
|
|
1359
|
+
case "string":
|
|
1360
|
+
case "null":
|
|
1361
|
+
case "var": return e;
|
|
1362
|
+
case "not": return {
|
|
1363
|
+
kind: "not",
|
|
1364
|
+
operand: go(condition(e.operand, scope), scope)
|
|
1365
|
+
};
|
|
1366
|
+
case "neg":
|
|
1367
|
+
case "isInteger":
|
|
1368
|
+
case "floor": return {
|
|
1369
|
+
kind: e.kind,
|
|
1370
|
+
operand: go(e.operand, scope)
|
|
1371
|
+
};
|
|
1372
|
+
case "narrow":
|
|
1373
|
+
case "narrowTag": return e;
|
|
1374
|
+
case "binary": {
|
|
1375
|
+
const left = go(e.left, scope);
|
|
1376
|
+
if (e.op === "&&") return {
|
|
1377
|
+
kind: "binary",
|
|
1378
|
+
op: e.op,
|
|
1379
|
+
left,
|
|
1380
|
+
right: wrap(e.right, left, true, scope)
|
|
1381
|
+
};
|
|
1382
|
+
if (e.op === "||") return {
|
|
1383
|
+
kind: "binary",
|
|
1384
|
+
op: e.op,
|
|
1385
|
+
left,
|
|
1386
|
+
right: wrap(e.right, left, false, scope)
|
|
1387
|
+
};
|
|
1388
|
+
return {
|
|
1389
|
+
kind: "binary",
|
|
1390
|
+
op: e.op,
|
|
1391
|
+
left,
|
|
1392
|
+
right: go(e.right, scope)
|
|
1393
|
+
};
|
|
1394
|
+
}
|
|
1395
|
+
case "cond": {
|
|
1396
|
+
const test = go(condition(e.test, scope), scope);
|
|
1397
|
+
return {
|
|
1398
|
+
kind: "cond",
|
|
1399
|
+
test,
|
|
1400
|
+
ifTrue: wrap(e.ifTrue, test, true, scope),
|
|
1401
|
+
ifFalse: wrap(e.ifFalse, test, false, scope)
|
|
1402
|
+
};
|
|
1403
|
+
}
|
|
1404
|
+
case "call": return {
|
|
1405
|
+
kind: "call",
|
|
1406
|
+
callee: e.callee,
|
|
1407
|
+
args: e.args.map((a) => go(a, scope))
|
|
1408
|
+
};
|
|
1409
|
+
case "field": return {
|
|
1410
|
+
kind: "field",
|
|
1411
|
+
object: go(e.object, scope),
|
|
1412
|
+
field: e.field
|
|
1413
|
+
};
|
|
1414
|
+
case "record": return {
|
|
1415
|
+
...e,
|
|
1416
|
+
fields: e.fields.map((f) => ({
|
|
1417
|
+
name: f.name,
|
|
1418
|
+
value: go(f.value, scope)
|
|
1419
|
+
}))
|
|
1420
|
+
};
|
|
1421
|
+
case "let": {
|
|
1422
|
+
const value = go(e.value, scope);
|
|
1423
|
+
const inner = new Map(scope);
|
|
1424
|
+
inner.set(e.name, e.type ?? typeOf(value, scope, ctx, fail));
|
|
1425
|
+
return {
|
|
1426
|
+
...e,
|
|
1427
|
+
value,
|
|
1428
|
+
body: go(e.body, inner)
|
|
1429
|
+
};
|
|
1430
|
+
}
|
|
1431
|
+
case "list": return {
|
|
1432
|
+
kind: "list",
|
|
1433
|
+
items: e.items.map((x) => go(x, scope)),
|
|
1434
|
+
...e.rest ? { rest: go(e.rest, scope) } : {}
|
|
1435
|
+
};
|
|
1436
|
+
case "tail": return {
|
|
1437
|
+
kind: "tail",
|
|
1438
|
+
list: go(e.list, scope)
|
|
1439
|
+
};
|
|
1440
|
+
case "headOr": return {
|
|
1441
|
+
kind: "headOr",
|
|
1442
|
+
list: go(e.list, scope),
|
|
1443
|
+
fallback: go(e.fallback, scope)
|
|
1444
|
+
};
|
|
1445
|
+
case "iterate": {
|
|
1446
|
+
const list = go(e.list, scope);
|
|
1447
|
+
return {
|
|
1448
|
+
...e,
|
|
1449
|
+
list,
|
|
1450
|
+
body: go(e.body, iterateScope(e, list, scope, ctx, fail))
|
|
1451
|
+
};
|
|
1452
|
+
}
|
|
1453
|
+
case "fold": {
|
|
1454
|
+
const list = go(e.list, scope);
|
|
1455
|
+
const init = go(e.init, scope);
|
|
1456
|
+
const inner = new Map(scope);
|
|
1457
|
+
inner.set(e.acc, typeOf(init, scope, ctx, fail));
|
|
1458
|
+
inner.set(e.item, elementOf(typeOf(list, scope, ctx, fail), "reduce", fail));
|
|
1459
|
+
return {
|
|
1460
|
+
...e,
|
|
1461
|
+
list,
|
|
1462
|
+
init,
|
|
1463
|
+
body: go(e.body, inner)
|
|
1464
|
+
};
|
|
1465
|
+
}
|
|
1466
|
+
}
|
|
1467
|
+
}
|
|
1468
|
+
// packages/prover/src/reader/expressions.ts
|
|
1469
|
+
/**
|
|
1470
|
+
* Function bodies and spec arrows read from the compiler's syntax tree
|
|
1471
|
+
* into the subset's `Expr`: `const` bindings, `if` with early returns,
|
|
1472
|
+
* `return`, and expressions from arithmetic, comparisons, `&& || !`, the
|
|
1473
|
+
* conditional operator, record and array literals, field reads, list
|
|
1474
|
+
* methods and calls to the module's own functions. What a name stands
|
|
1475
|
+
* for comes from the scope (parameters and consts) and from `Names`: the
|
|
1476
|
+
* module's own functions when the text is the module, the spec file's
|
|
1477
|
+
* imports when it is an arrow. Anything else is `OutsideSubset` with the
|
|
1478
|
+
* construct named and its line.
|
|
1479
|
+
*/
|
|
1480
|
+
const binaryOps = {
|
|
1481
|
+
[SyntaxKind.PlusToken]: "+",
|
|
1482
|
+
[SyntaxKind.MinusToken]: "-",
|
|
1483
|
+
[SyntaxKind.AsteriskToken]: "*",
|
|
1484
|
+
[SyntaxKind.SlashToken]: "/",
|
|
1485
|
+
[SyntaxKind.LessThanToken]: "<",
|
|
1486
|
+
[SyntaxKind.LessThanEqualsToken]: "<=",
|
|
1487
|
+
[SyntaxKind.GreaterThanToken]: ">",
|
|
1488
|
+
[SyntaxKind.GreaterThanEqualsToken]: ">=",
|
|
1489
|
+
[SyntaxKind.EqualsEqualsEqualsToken]: "===",
|
|
1490
|
+
[SyntaxKind.ExclamationEqualsEqualsToken]: "!==",
|
|
1491
|
+
[SyntaxKind.AmpersandAmpersandToken]: "&&",
|
|
1492
|
+
[SyntaxKind.BarBarToken]: "||"
|
|
1493
|
+
};
|
|
1494
|
+
const methods = /* @__PURE__ */ new Set([
|
|
1495
|
+
"slice",
|
|
1496
|
+
"map",
|
|
1497
|
+
"flatMap",
|
|
1498
|
+
"every",
|
|
1499
|
+
"some",
|
|
1500
|
+
"reduce"
|
|
1501
|
+
]);
|
|
1502
|
+
/** The reader of one text: a function body, or an arrow of the spec file. */
|
|
1503
|
+
var ExprReader = class {
|
|
1504
|
+
sf;
|
|
1505
|
+
names;
|
|
1506
|
+
types;
|
|
1507
|
+
ctx;
|
|
1508
|
+
/** The line a refusal reports for a node: the file's, or none for text whose position the caller knows. */
|
|
1509
|
+
lineOf;
|
|
1510
|
+
inline;
|
|
1511
|
+
constant;
|
|
1512
|
+
/** Record literals typed by the call they are passed to, in place of the compiler's contextual type. */
|
|
1513
|
+
typedAs = /* @__PURE__ */ new Map();
|
|
1514
|
+
constructor(sf, names, types, ctx, lineOf = (node) => lineAt(sf, node), inline, constant) {
|
|
1515
|
+
this.sf = sf;
|
|
1516
|
+
this.names = names;
|
|
1517
|
+
this.types = types;
|
|
1518
|
+
this.ctx = ctx;
|
|
1519
|
+
this.lineOf = lineOf;
|
|
1520
|
+
this.inline = inline;
|
|
1521
|
+
this.constant = constant;
|
|
1522
|
+
}
|
|
1523
|
+
/** Whether an identifier is the global of its name here: no scope or function shadows it, and the names confirm it. */
|
|
1524
|
+
global(id, scope) {
|
|
1525
|
+
return !scope.has(id.text) && !this.names.declared(id.text) && this.names.global(id);
|
|
1526
|
+
}
|
|
1527
|
+
fail(what, at) {
|
|
1528
|
+
throw new OutsideSubset(what, this.lineOf(at));
|
|
1529
|
+
}
|
|
1530
|
+
/** `OutsideSubset` at a node, for a type read there. */
|
|
1531
|
+
refuseAt(at) {
|
|
1532
|
+
return (what) => this.fail(what, at);
|
|
1533
|
+
}
|
|
1534
|
+
text(node) {
|
|
1535
|
+
return textOf(this.sf, node);
|
|
1536
|
+
}
|
|
1537
|
+
/** The expression with `narrow` nodes inserted where a null check guards a nullable name. */
|
|
1538
|
+
narrowed(e, scope, at) {
|
|
1539
|
+
return insertNarrows(e, scope, this.ctx, (m) => this.fail(m, at));
|
|
1540
|
+
}
|
|
1541
|
+
typeOfExpr(e, scope, at, expected) {
|
|
1542
|
+
return typeOf(e, scope, this.ctx, (m) => this.fail(m, at), expected);
|
|
1543
|
+
}
|
|
1544
|
+
/**
|
|
1545
|
+
* A block's statements as one expression: `const` becomes `let`, `if (c)
|
|
1546
|
+
* return a; rest` a conditional, and the last statement must return:
|
|
1547
|
+
* every path ends in a `return`.
|
|
1548
|
+
*/
|
|
1549
|
+
block(statements, scope, end) {
|
|
1550
|
+
return this.statements(statements, 0, scope, end);
|
|
1551
|
+
}
|
|
1552
|
+
statements(statements, i, scope, end) {
|
|
1553
|
+
const s = statements[i];
|
|
1554
|
+
if (!s) this.fail("a path that does not return", end);
|
|
1555
|
+
if (is.isEmptyStatement(s)) return this.statements(statements, i + 1, scope, end);
|
|
1556
|
+
if (is.isVariableStatement(s)) {
|
|
1557
|
+
const list = s.declarationList;
|
|
1558
|
+
if (!isConst(list)) this.fail("a mutable binding (use const)", s);
|
|
1559
|
+
const [decl, second] = list.declarations;
|
|
1560
|
+
if (!decl || second) this.fail("several bindings in one const", s);
|
|
1561
|
+
if (!is.isIdentifier(decl.name)) this.fail("a destructured const", decl.name);
|
|
1562
|
+
const name = decl.name.text;
|
|
1563
|
+
if (this.names.declared(name)) this.fail(`const ${name} shadows the module's function ${name} in its block`, decl.name);
|
|
1564
|
+
if (scope.has(name)) this.fail(`const ${name} redeclares a name already bound here`, decl.name);
|
|
1565
|
+
const annotated = decl.type ? this.types.annotation(decl.type, this.refuseAt(decl.type)) : void 0;
|
|
1566
|
+
if (!decl.initializer) this.fail(`const ${name} without a value`, decl);
|
|
1567
|
+
const value = this.expression(decl.initializer, scope);
|
|
1568
|
+
const inner = new Map(scope);
|
|
1569
|
+
inner.set(name, annotated ?? { kind: "null" });
|
|
1570
|
+
return {
|
|
1571
|
+
kind: "let",
|
|
1572
|
+
name,
|
|
1573
|
+
value,
|
|
1574
|
+
body: this.statements(statements, i + 1, inner, end),
|
|
1575
|
+
...annotated ? { type: annotated } : {}
|
|
1576
|
+
};
|
|
1577
|
+
}
|
|
1578
|
+
if (is.isIfStatement(s)) {
|
|
1579
|
+
const test = this.expression(s.expression, scope);
|
|
1580
|
+
const then = this.branch(s.thenStatement, scope);
|
|
1581
|
+
if (s.elseStatement) {
|
|
1582
|
+
const otherwise = this.branch(s.elseStatement, scope);
|
|
1583
|
+
const after = statements[i + 1];
|
|
1584
|
+
if (after) this.fail("statements after an if/else that both return", after);
|
|
1585
|
+
return {
|
|
1586
|
+
kind: "cond",
|
|
1587
|
+
test,
|
|
1588
|
+
ifTrue: then,
|
|
1589
|
+
ifFalse: otherwise
|
|
1590
|
+
};
|
|
1591
|
+
}
|
|
1592
|
+
return {
|
|
1593
|
+
kind: "cond",
|
|
1594
|
+
test,
|
|
1595
|
+
ifTrue: then,
|
|
1596
|
+
ifFalse: this.statements(statements, i + 1, scope, end)
|
|
1597
|
+
};
|
|
1598
|
+
}
|
|
1599
|
+
if (is.isReturnStatement(s)) {
|
|
1600
|
+
const after = statements[i + 1];
|
|
1601
|
+
if (!s.expression && after) {
|
|
1602
|
+
const gap = this.sf.text.slice(s.getStart(this.sf) + 6, after.getStart(this.sf));
|
|
1603
|
+
if (/[\n\r\u2028\u2029]/.test(gap)) this.fail("a line break after return (JavaScript inserts a semicolon and returns undefined)", s);
|
|
1604
|
+
}
|
|
1605
|
+
const value = this.returned(s, scope);
|
|
1606
|
+
if (after) this.fail("statements after a return", after);
|
|
1607
|
+
return value;
|
|
1608
|
+
}
|
|
1609
|
+
if (is.isForStatement(s) || is.isForOfStatement(s) || is.isForInStatement(s) || is.isWhileStatement(s) || is.isDoStatement(s)) this.fail("a loop", s);
|
|
1610
|
+
if (is.isThrowStatement(s)) this.fail("throw", s);
|
|
1611
|
+
if (is.isSwitchStatement(s)) this.fail("switch", s);
|
|
1612
|
+
if (is.isTryStatement(s)) this.fail("try", s);
|
|
1613
|
+
if (is.isFunctionDeclaration(s)) this.fail("a nested function", s);
|
|
1614
|
+
this.fail(`statement starting with ${this.text(s).split(/\s/)[0] ?? kindName(s.kind)}`, s);
|
|
1615
|
+
}
|
|
1616
|
+
/** An `if` branch: `return e;` or `{ ...statements ending in return }`. */
|
|
1617
|
+
branch(s, scope) {
|
|
1618
|
+
if (is.isBlock(s)) return this.block(s.statements, scope, s);
|
|
1619
|
+
if (is.isReturnStatement(s)) return this.returned(s, scope);
|
|
1620
|
+
this.fail("an if branch that does not return", s);
|
|
1621
|
+
}
|
|
1622
|
+
/** `return e;`. A line break after `return` makes JavaScript return undefined: no value, refused. */
|
|
1623
|
+
returned(s, scope) {
|
|
1624
|
+
if (!s.expression) this.fail("a return without a value", s);
|
|
1625
|
+
return this.expression(s.expression, scope);
|
|
1626
|
+
}
|
|
1627
|
+
expression(node, scope) {
|
|
1628
|
+
if (is.isParenthesizedExpression(node)) return this.expression(node.expression, scope);
|
|
1629
|
+
if (is.isIdentifier(node)) return this.identifier(node, scope);
|
|
1630
|
+
if (is.isNumericLiteral(node)) {
|
|
1631
|
+
const raw = this.text(node);
|
|
1632
|
+
if (!/^[0-9](_?[0-9])*$/.test(raw)) this.fail(`the numeric literal ${raw} (integers in decimal only)`, node);
|
|
1633
|
+
return {
|
|
1634
|
+
kind: "int",
|
|
1635
|
+
value: raw.replace(/_/g, "")
|
|
1636
|
+
};
|
|
1637
|
+
}
|
|
1638
|
+
if (is.isBigIntLiteral(node)) this.fail(`the bigint literal ${this.text(node)}`, node);
|
|
1639
|
+
if (is.isStringLiteral(node)) {
|
|
1640
|
+
if (hasLoneSurrogate(node.text)) this.fail("a string literal with a lone surrogate, which Lean's strings cannot hold", node);
|
|
1641
|
+
return {
|
|
1642
|
+
kind: "string",
|
|
1643
|
+
value: node.text
|
|
1644
|
+
};
|
|
1645
|
+
}
|
|
1646
|
+
if (is.isNoSubstitutionTemplateLiteral(node) || is.isTemplateExpression(node)) this.fail("a template literal", node);
|
|
1647
|
+
if (is.isRegularExpressionLiteral(node)) this.fail("a regular expression", node);
|
|
1648
|
+
if (node.kind === SyntaxKind.TrueKeyword) return {
|
|
1649
|
+
kind: "bool",
|
|
1650
|
+
value: true
|
|
1651
|
+
};
|
|
1652
|
+
if (node.kind === SyntaxKind.FalseKeyword) return {
|
|
1653
|
+
kind: "bool",
|
|
1654
|
+
value: false
|
|
1655
|
+
};
|
|
1656
|
+
if (node.kind === SyntaxKind.NullKeyword) return { kind: "null" };
|
|
1657
|
+
if (is.isPrefixUnaryExpression(node)) {
|
|
1658
|
+
if (node.operator === SyntaxKind.ExclamationToken) return {
|
|
1659
|
+
kind: "not",
|
|
1660
|
+
operand: this.expression(node.operand, scope)
|
|
1661
|
+
};
|
|
1662
|
+
if (node.operator === SyntaxKind.MinusToken) {
|
|
1663
|
+
const operand = this.expression(node.operand, scope);
|
|
1664
|
+
return operand.kind === "int" ? {
|
|
1665
|
+
kind: "int",
|
|
1666
|
+
value: operand.value.startsWith("-") ? operand.value.slice(1) : `-${operand.value}`
|
|
1667
|
+
} : {
|
|
1668
|
+
kind: "neg",
|
|
1669
|
+
operand
|
|
1670
|
+
};
|
|
1671
|
+
}
|
|
1672
|
+
if (node.operator === SyntaxKind.PlusToken) this.fail("unary plus", node);
|
|
1673
|
+
this.fail(`the ${this.text(node).slice(0, 2)} operator`, node);
|
|
1674
|
+
}
|
|
1675
|
+
if (is.isPostfixUnaryExpression(node)) this.fail(`the ${this.text(node).slice(-2)} operator`, node);
|
|
1676
|
+
if (is.isTypeOfExpression(node)) this.fail("the typeof operator", node);
|
|
1677
|
+
if (is.isVoidExpression(node)) this.fail("the void operator", node);
|
|
1678
|
+
if (is.isAwaitExpression(node)) this.fail("the await operator", node);
|
|
1679
|
+
if (is.isNewExpression(node)) this.fail("the new operator", node);
|
|
1680
|
+
if (is.isDeleteExpression(node)) this.fail("the delete operator", node);
|
|
1681
|
+
if (is.isBinaryExpression(node)) return this.binary(node, scope);
|
|
1682
|
+
if (is.isConditionalExpression(node)) return {
|
|
1683
|
+
kind: "cond",
|
|
1684
|
+
test: this.expression(node.condition, scope),
|
|
1685
|
+
ifTrue: this.expression(node.whenTrue, scope),
|
|
1686
|
+
ifFalse: this.expression(node.whenFalse, scope)
|
|
1687
|
+
};
|
|
1688
|
+
if (is.isCallExpression(node)) return this.call(node, scope);
|
|
1689
|
+
if (is.isPropertyAccessExpression(node)) {
|
|
1690
|
+
if (node.questionDotToken) this.fail("optional chaining", node);
|
|
1691
|
+
if (!is.isIdentifier(node.name)) this.fail("a private field", node.name);
|
|
1692
|
+
return {
|
|
1693
|
+
kind: "field",
|
|
1694
|
+
object: this.expression(node.expression, scope),
|
|
1695
|
+
field: node.name.text
|
|
1696
|
+
};
|
|
1697
|
+
}
|
|
1698
|
+
if (is.isElementAccessExpression(node)) {
|
|
1699
|
+
if (this.isHead(node)) this.fail("xs[0] without ?? fallback (it is undefined on an empty list)", node);
|
|
1700
|
+
this.fail("index access other than xs[0] ?? fallback", node);
|
|
1701
|
+
}
|
|
1702
|
+
if (is.isObjectLiteralExpression(node)) return this.record(node, scope);
|
|
1703
|
+
if (is.isArrayLiteralExpression(node)) {
|
|
1704
|
+
const items = [];
|
|
1705
|
+
let rest;
|
|
1706
|
+
for (const item of node.elements) {
|
|
1707
|
+
if (rest) this.fail("a spread that is not last in an array literal", item);
|
|
1708
|
+
if (is.isSpreadElement(item)) rest = this.expression(item.expression, scope);
|
|
1709
|
+
else if (is.isOmittedExpression(item)) this.fail("a hole in an array literal", item);
|
|
1710
|
+
else items.push(this.expression(item, scope));
|
|
1711
|
+
}
|
|
1712
|
+
return {
|
|
1713
|
+
kind: "list",
|
|
1714
|
+
items,
|
|
1715
|
+
...rest ? { rest } : {}
|
|
1716
|
+
};
|
|
1717
|
+
}
|
|
1718
|
+
if (is.isArrowFunction(node) || is.isFunctionExpression(node)) this.fail("a function expression (the subset has callbacks of list methods only)", node);
|
|
1719
|
+
if (is.isAsExpression(node)) this.fail("the as operator", node);
|
|
1720
|
+
if (is.isSatisfiesExpression(node)) this.fail("the satisfies operator", node);
|
|
1721
|
+
if (is.isNonNullExpression(node)) this.fail("the ! assertion", node);
|
|
1722
|
+
if (is.isTypeAssertion(node)) this.fail("a type assertion", node);
|
|
1723
|
+
if (node.kind === SyntaxKind.ThisKeyword) this.fail("this", node);
|
|
1724
|
+
this.fail(`unexpected ${this.text(node) || kindName(node.kind)}`, node);
|
|
1725
|
+
}
|
|
1726
|
+
identifier(node, scope) {
|
|
1727
|
+
const name = node.text;
|
|
1728
|
+
if (name === "undefined") this.fail("undefined (the subset has null)", node);
|
|
1729
|
+
if (scope.has(name) || this.names.declared(name)) return {
|
|
1730
|
+
kind: "var",
|
|
1731
|
+
name
|
|
1732
|
+
};
|
|
1733
|
+
const constant = this.constant?.(node, (what) => this.fail(what, node));
|
|
1734
|
+
if (constant) return constant;
|
|
1735
|
+
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);
|
|
1736
|
+
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);
|
|
1737
|
+
}
|
|
1738
|
+
/** Whether an element access is `xs[0]`. */
|
|
1739
|
+
isHead(node) {
|
|
1740
|
+
return is.isElementAccessExpression(node) && is.isNumericLiteral(node.argumentExpression) && this.text(node.argumentExpression) === "0";
|
|
1741
|
+
}
|
|
1742
|
+
binary(node, scope) {
|
|
1743
|
+
const kind = node.operatorToken.kind;
|
|
1744
|
+
const op = binaryOps[kind];
|
|
1745
|
+
if (op) return {
|
|
1746
|
+
kind: "binary",
|
|
1747
|
+
op,
|
|
1748
|
+
left: this.expression(node.left, scope),
|
|
1749
|
+
right: this.expression(node.right, scope)
|
|
1750
|
+
};
|
|
1751
|
+
if (kind === SyntaxKind.QuestionQuestionToken) {
|
|
1752
|
+
if (is.isBinaryExpression(node.left) && node.left.operatorToken.kind === kind) this.fail("a chain of ??", node);
|
|
1753
|
+
if (is.isElementAccessExpression(node.left) && !this.isHead(node.left)) this.fail("index access other than xs[0] ?? fallback", node.left);
|
|
1754
|
+
if (!is.isElementAccessExpression(node.left)) this.fail("?? after anything but xs[0] (write xs[0] ?? fallback, parenthesized where it meets other operators)", node);
|
|
1755
|
+
if (node.left.questionDotToken) this.fail("optional chaining", node.left);
|
|
1756
|
+
return {
|
|
1757
|
+
kind: "headOr",
|
|
1758
|
+
list: this.expression(node.left.expression, scope),
|
|
1759
|
+
fallback: this.expression(node.right, scope)
|
|
1760
|
+
};
|
|
1761
|
+
}
|
|
1762
|
+
if (kind >= SyntaxKind.FirstAssignment && kind <= SyntaxKind.LastAssignment) this.fail("an assignment", node);
|
|
1763
|
+
if (kind === SyntaxKind.CommaToken) this.fail("the comma operator", node);
|
|
1764
|
+
if (kind === SyntaxKind.InKeyword || kind === SyntaxKind.InstanceOfKeyword) this.fail(`the ${this.text(node.operatorToken)} operator`, node);
|
|
1765
|
+
this.fail(`the ${this.text(node.operatorToken)} operator`, node);
|
|
1766
|
+
}
|
|
1767
|
+
call(node, scope) {
|
|
1768
|
+
if (node.questionDotToken) this.fail("optional chaining", node);
|
|
1769
|
+
let callee = node.expression;
|
|
1770
|
+
while (is.isParenthesizedExpression(callee)) callee = callee.expression;
|
|
1771
|
+
if (is.isPropertyAccessExpression(callee)) {
|
|
1772
|
+
if (callee.questionDotToken) this.fail("optional chaining", callee);
|
|
1773
|
+
if (!is.isIdentifier(callee.name)) this.fail("a private method", callee.name);
|
|
1774
|
+
const method = callee.name.text;
|
|
1775
|
+
const receiver = callee.expression;
|
|
1776
|
+
if (is.isIdentifier(receiver) && receiver.text === "Number" && method === "isInteger" && this.global(receiver, scope)) {
|
|
1777
|
+
const [arg, extra] = node.arguments;
|
|
1778
|
+
if (!arg || extra) this.fail("Number.isInteger takes one argument", node);
|
|
1779
|
+
return {
|
|
1780
|
+
kind: "isInteger",
|
|
1781
|
+
operand: this.expression(arg, scope)
|
|
1782
|
+
};
|
|
1783
|
+
}
|
|
1784
|
+
if (is.isIdentifier(receiver) && receiver.text === "Math" && method === "floor" && this.global(receiver, scope)) {
|
|
1785
|
+
const [arg, extra] = node.arguments;
|
|
1786
|
+
if (!arg || extra) this.fail("Math.floor takes one argument", node);
|
|
1787
|
+
return {
|
|
1788
|
+
kind: "floor",
|
|
1789
|
+
operand: this.expression(arg, scope)
|
|
1790
|
+
};
|
|
1791
|
+
}
|
|
1792
|
+
const list = this.expression(receiver, scope);
|
|
1793
|
+
if (!methods.has(method)) this.fail(`the method ${method} (the subset has slice(1), map, flatMap, every, some and reduce)`, callee.name);
|
|
1794
|
+
return this.method(node, list, method, scope);
|
|
1795
|
+
}
|
|
1796
|
+
if (!is.isIdentifier(callee)) this.fail("a call to a computed callee", callee);
|
|
1797
|
+
const name = callee.text;
|
|
1798
|
+
if (scope.has(name)) this.fail(`a call to ${name}, which names a value here, not the module's function`, callee);
|
|
1799
|
+
if (!this.names.callable(name) && this.inline) {
|
|
1800
|
+
const readArgs = (types) => node.arguments.map((a, i) => {
|
|
1801
|
+
if (is.isSpreadElement(a)) this.fail("a spread argument", a);
|
|
1802
|
+
const type = types[i];
|
|
1803
|
+
if (!type) return this.expression(a, scope);
|
|
1804
|
+
const literals = [];
|
|
1805
|
+
const collect = (e) => {
|
|
1806
|
+
if (is.isParenthesizedExpression(e)) collect(e.expression);
|
|
1807
|
+
else if (is.isConditionalExpression(e)) {
|
|
1808
|
+
collect(e.whenTrue);
|
|
1809
|
+
collect(e.whenFalse);
|
|
1810
|
+
} else if (is.isObjectLiteralExpression(e)) literals.push(e);
|
|
1811
|
+
};
|
|
1812
|
+
collect(a);
|
|
1813
|
+
for (const l of literals) this.typedAs.set(l, type);
|
|
1814
|
+
try {
|
|
1815
|
+
return this.expression(a, scope);
|
|
1816
|
+
} finally {
|
|
1817
|
+
for (const l of literals) this.typedAs.delete(l);
|
|
1818
|
+
}
|
|
1819
|
+
});
|
|
1820
|
+
const inlined = this.inline(node, callee, scope, readArgs, (what) => this.fail(what, node));
|
|
1821
|
+
if (inlined) return inlined;
|
|
1822
|
+
}
|
|
1823
|
+
if (!this.names.declared(name)) this.identifier(callee, scope);
|
|
1824
|
+
if (!this.names.callable(name)) this.fail(`a call to ${name}, which is outside the subset`, callee);
|
|
1825
|
+
return {
|
|
1826
|
+
kind: "call",
|
|
1827
|
+
callee: this.names.target(name),
|
|
1828
|
+
args: node.arguments.map((a) => {
|
|
1829
|
+
if (is.isSpreadElement(a)) this.fail("a spread argument", a);
|
|
1830
|
+
return this.expression(a, scope);
|
|
1831
|
+
})
|
|
1832
|
+
};
|
|
1833
|
+
}
|
|
1834
|
+
/** `(a, b) => body` or `a => body`, an expression body only; the names it binds go into scope. */
|
|
1835
|
+
callback(node, scope, arity, what) {
|
|
1836
|
+
if (!is.isArrowFunction(node)) this.fail(`${what} takes an arrow function`, node);
|
|
1837
|
+
const arrow = node;
|
|
1838
|
+
if (isAsync(arrow)) this.fail(`an async callback in ${what}`, arrow);
|
|
1839
|
+
const names = [];
|
|
1840
|
+
for (const p of arrow.parameters) {
|
|
1841
|
+
if (!is.isIdentifier(p.name)) this.fail(`a destructured parameter of ${what}'s callback`, p);
|
|
1842
|
+
if (p.type) this.fail(`a type annotation on ${what}'s parameter`, p.type);
|
|
1843
|
+
if (p.initializer) this.fail(`a default value on ${what}'s parameter`, p);
|
|
1844
|
+
if (p.dotDotDotToken) this.fail(`a rest parameter on ${what}'s callback`, p);
|
|
1845
|
+
names.push(p.name.text);
|
|
1846
|
+
}
|
|
1847
|
+
if (names.length === 0 || names.length > arity) this.fail(`${what} takes a callback of 1 to ${arity} parameter(s), given ${names.length}`, arrow);
|
|
1848
|
+
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);
|
|
1849
|
+
if (new Set(names).size !== names.length) this.fail(`${what}'s parameters repeat a name`, arrow);
|
|
1850
|
+
if (is.isBlock(arrow.body)) this.fail(`a block body in ${what}'s callback (write an expression)`, arrow.body);
|
|
1851
|
+
const inner = new Map(scope);
|
|
1852
|
+
for (const n of names) inner.set(n, { kind: "null" });
|
|
1853
|
+
return {
|
|
1854
|
+
names,
|
|
1855
|
+
body: this.expression(arrow.body, inner)
|
|
1856
|
+
};
|
|
1857
|
+
}
|
|
1858
|
+
/** A method call on a list: slice(1), map, flatMap, every, some, reduce. */
|
|
1859
|
+
method(node, list, name, scope) {
|
|
1860
|
+
const args = node.arguments;
|
|
1861
|
+
if (name === "slice") {
|
|
1862
|
+
const [one, extra] = args;
|
|
1863
|
+
if (!one || extra || !is.isNumericLiteral(one) || this.text(one) !== "1") this.fail("slice with an argument other than 1", one ?? node);
|
|
1864
|
+
return {
|
|
1865
|
+
kind: "tail",
|
|
1866
|
+
list
|
|
1867
|
+
};
|
|
1868
|
+
}
|
|
1869
|
+
if (name === "reduce") {
|
|
1870
|
+
const [cb, init, extra] = args;
|
|
1871
|
+
if (!cb || !init || extra) this.fail("reduce takes a callback and an initial value", node);
|
|
1872
|
+
const { names, body } = this.callback(cb, scope, 2, "reduce");
|
|
1873
|
+
if (names.length !== 2) this.fail("reduce takes a callback of (accumulator, item)", cb);
|
|
1874
|
+
return {
|
|
1875
|
+
kind: "fold",
|
|
1876
|
+
list,
|
|
1877
|
+
acc: names[0],
|
|
1878
|
+
item: names[1],
|
|
1879
|
+
body,
|
|
1880
|
+
init: this.expression(init, scope)
|
|
1881
|
+
};
|
|
1882
|
+
}
|
|
1883
|
+
const [cb, extra] = args;
|
|
1884
|
+
if (!cb || extra) this.fail(`${name} takes one callback`, node);
|
|
1885
|
+
const { names, body } = this.callback(cb, scope, 2, name);
|
|
1886
|
+
return {
|
|
1887
|
+
kind: "iterate",
|
|
1888
|
+
op: name,
|
|
1889
|
+
list,
|
|
1890
|
+
item: names[0],
|
|
1891
|
+
...names[1] === void 0 ? {} : { index: names[1] },
|
|
1892
|
+
body
|
|
1893
|
+
};
|
|
1894
|
+
}
|
|
1895
|
+
record(node, scope) {
|
|
1896
|
+
const fields = [];
|
|
1897
|
+
for (const p of node.properties) {
|
|
1898
|
+
if (is.isSpreadAssignment(p)) this.fail("spread in a record literal", p);
|
|
1899
|
+
if (is.isShorthandPropertyAssignment(p)) {
|
|
1900
|
+
if (!is.isIdentifier(p.name)) this.fail(`a key that is not a name: ${this.text(p.name)}`, p.name);
|
|
1901
|
+
const name = p.name.text;
|
|
1902
|
+
if (name === "__proto__") this.fail("a __proto__ key, which sets the prototype, not a field", p);
|
|
1903
|
+
if (!scope.has(name)) this.fail(`shorthand ${name} names nothing in scope`, p);
|
|
1904
|
+
fields.push({
|
|
1905
|
+
name,
|
|
1906
|
+
value: {
|
|
1907
|
+
kind: "var",
|
|
1908
|
+
name
|
|
1909
|
+
}
|
|
1910
|
+
});
|
|
1911
|
+
continue;
|
|
1912
|
+
}
|
|
1913
|
+
if (!is.isPropertyAssignment(p)) this.fail(`a method ${this.text(p).split("(")[0] ?? ""}`, p);
|
|
1914
|
+
if (is.isComputedPropertyName(p.name)) this.fail("a computed key", p.name);
|
|
1915
|
+
if (!is.isIdentifier(p.name)) this.fail(`a key that is not a name: ${this.text(p.name)}`, p.name);
|
|
1916
|
+
if (p.name.text === "__proto__") this.fail("a __proto__ key, which sets the prototype, not a field", p.name);
|
|
1917
|
+
fields.push({
|
|
1918
|
+
name: p.name.text,
|
|
1919
|
+
value: this.expression(p.initializer, scope)
|
|
1920
|
+
});
|
|
1921
|
+
}
|
|
1922
|
+
const type = this.typedAs.get(node) ?? this.types.contextual(node);
|
|
1923
|
+
const literal = (fs) => ({
|
|
1924
|
+
kind: "record",
|
|
1925
|
+
fields: fs,
|
|
1926
|
+
...type ? { type } : {}
|
|
1927
|
+
});
|
|
1928
|
+
const tag = type?.kind === "union" ? tagOf(type.name, this.ctx) : void 0;
|
|
1929
|
+
const chosen = tag === void 0 ? void 0 : fields.find((f) => f.name === tag);
|
|
1930
|
+
if (chosen?.value.kind === "cond") {
|
|
1931
|
+
const split = (value) => value.kind === "cond" ? {
|
|
1932
|
+
kind: "cond",
|
|
1933
|
+
test: value.test,
|
|
1934
|
+
ifTrue: split(value.ifTrue),
|
|
1935
|
+
ifFalse: split(value.ifFalse)
|
|
1936
|
+
} : literal(fields.map((f) => f === chosen ? {
|
|
1937
|
+
name: f.name,
|
|
1938
|
+
value
|
|
1939
|
+
} : f));
|
|
1940
|
+
return split(chosen.value);
|
|
1941
|
+
}
|
|
1942
|
+
return literal(fields);
|
|
1943
|
+
}
|
|
1944
|
+
};
|
|
1945
|
+
/**
|
|
1946
|
+
* A `const` annotation inside a spec arrow, read from its syntax against
|
|
1947
|
+
* the module's declared types: no compiler stands behind an arrow's
|
|
1948
|
+
* text, so a name must be a record or union the module reads, and the
|
|
1949
|
+
* forms are the primitives, `null`, literals, unions of those and arrays.
|
|
1950
|
+
*/
|
|
1951
|
+
function syntacticType(sf, node, records, unions, refuse) {
|
|
1952
|
+
const go = (n) => syntacticType(sf, n, records, unions, refuse);
|
|
1953
|
+
if (is.isParenthesizedTypeNode(node)) return go(node.type);
|
|
1954
|
+
if (is.isTypeOperatorNode(node) && node.operator === SyntaxKind.ReadonlyKeyword) {
|
|
1955
|
+
if (!is.isArrayTypeNode(node.type)) return refuse("readonly before a type that is not an array");
|
|
1956
|
+
return go(node.type);
|
|
1957
|
+
}
|
|
1958
|
+
if (is.isArrayTypeNode(node)) return {
|
|
1959
|
+
kind: "list",
|
|
1960
|
+
element: go(node.elementType)
|
|
1961
|
+
};
|
|
1962
|
+
if (node.kind === SyntaxKind.NumberKeyword) return { kind: "int" };
|
|
1963
|
+
if (node.kind === SyntaxKind.BooleanKeyword) return { kind: "bool" };
|
|
1964
|
+
if (node.kind === SyntaxKind.StringKeyword) return { kind: "string" };
|
|
1965
|
+
if (node.kind === SyntaxKind.UndefinedKeyword) return refuse("undefined in a type (the subset has null)");
|
|
1966
|
+
if (is.isLiteralTypeNode(node)) {
|
|
1967
|
+
const lit = node.literal;
|
|
1968
|
+
if (lit.kind === SyntaxKind.NullKeyword) return { kind: "null" };
|
|
1969
|
+
if (lit.kind === SyntaxKind.TrueKeyword || lit.kind === SyntaxKind.FalseKeyword) return { kind: "bool" };
|
|
1970
|
+
if (is.isStringLiteral(lit)) return { kind: "string" };
|
|
1971
|
+
return refuse(`the literal type ${textOf(sf, node)}`);
|
|
1972
|
+
}
|
|
1973
|
+
if (is.isTypeReferenceNode(node)) {
|
|
1974
|
+
if (node.typeArguments) return refuse(`type ${textOf(sf, node)} (a generic type in an arrow's const)`);
|
|
1975
|
+
if (!is.isIdentifier(node.typeName)) return refuse(`type ${textOf(sf, node)}`);
|
|
1976
|
+
const name = node.typeName.text;
|
|
1977
|
+
if (records.has(name)) return {
|
|
1978
|
+
kind: "record",
|
|
1979
|
+
name
|
|
1980
|
+
};
|
|
1981
|
+
if (unions.has(name)) return {
|
|
1982
|
+
kind: "union",
|
|
1983
|
+
name
|
|
1984
|
+
};
|
|
1985
|
+
return refuse(`type ${name} (the subset has number, boolean, string, null, and the module's own record types and unions)`);
|
|
1986
|
+
}
|
|
1987
|
+
if (is.isUnionTypeNode(node)) {
|
|
1988
|
+
const members = node.types.map(go);
|
|
1989
|
+
const nulls = members.filter((m) => m.kind === "null");
|
|
1990
|
+
const rest = members.filter((m) => m.kind !== "null");
|
|
1991
|
+
const first = rest[0];
|
|
1992
|
+
if (!first) return refuse("null alone is not a type the subset takes");
|
|
1993
|
+
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)");
|
|
1994
|
+
if (nulls.length === 0) return first;
|
|
1995
|
+
return first.kind === "nullable" ? first : {
|
|
1996
|
+
kind: "nullable",
|
|
1997
|
+
inner: first
|
|
1998
|
+
};
|
|
1999
|
+
}
|
|
2000
|
+
return refuse(`type ${textOf(sf, node)}`);
|
|
2001
|
+
}
|
|
2002
|
+
/**
|
|
2003
|
+
* The block body of an arrow read from a parsed fragment: the statements
|
|
2004
|
+
* between the braces, every path returning.
|
|
2005
|
+
*/
|
|
2006
|
+
function blockOf(sf) {
|
|
2007
|
+
const [first, second] = sf.statements;
|
|
2008
|
+
return first && !second && is.isBlock(first) ? first : void 0;
|
|
2009
|
+
}
|
|
2010
|
+
// packages/prover/src/reader/rename.ts
|
|
2011
|
+
/** Every name an expression binds or refers to: its variables and its lets. */
|
|
2012
|
+
function boundNames(e, out = /* @__PURE__ */ new Set()) {
|
|
2013
|
+
switch (e.kind) {
|
|
2014
|
+
case "int":
|
|
2015
|
+
case "bool":
|
|
2016
|
+
case "string":
|
|
2017
|
+
case "null": return out;
|
|
2018
|
+
case "var":
|
|
2019
|
+
out.add(e.name);
|
|
2020
|
+
return out;
|
|
2021
|
+
case "narrow":
|
|
2022
|
+
case "narrowTag":
|
|
2023
|
+
out.add(e.name);
|
|
2024
|
+
return boundNames(e.body, out);
|
|
2025
|
+
case "neg":
|
|
2026
|
+
case "not":
|
|
2027
|
+
case "isInteger":
|
|
2028
|
+
case "floor": return boundNames(e.operand, out);
|
|
2029
|
+
case "binary":
|
|
2030
|
+
boundNames(e.left, out);
|
|
2031
|
+
return boundNames(e.right, out);
|
|
2032
|
+
case "cond":
|
|
2033
|
+
boundNames(e.test, out);
|
|
2034
|
+
boundNames(e.ifTrue, out);
|
|
2035
|
+
return boundNames(e.ifFalse, out);
|
|
2036
|
+
case "call":
|
|
2037
|
+
for (const a of e.args) boundNames(a, out);
|
|
2038
|
+
return out;
|
|
2039
|
+
case "field": return boundNames(e.object, out);
|
|
2040
|
+
case "record":
|
|
2041
|
+
for (const f of e.fields) boundNames(f.value, out);
|
|
2042
|
+
return out;
|
|
2043
|
+
case "let":
|
|
2044
|
+
out.add(e.name);
|
|
2045
|
+
boundNames(e.value, out);
|
|
2046
|
+
return boundNames(e.body, out);
|
|
2047
|
+
case "list":
|
|
2048
|
+
for (const x of e.items) boundNames(x, out);
|
|
2049
|
+
return e.rest ? boundNames(e.rest, out) : out;
|
|
2050
|
+
case "tail": return boundNames(e.list, out);
|
|
2051
|
+
case "headOr":
|
|
2052
|
+
boundNames(e.list, out);
|
|
2053
|
+
return boundNames(e.fallback, out);
|
|
2054
|
+
case "iterate":
|
|
2055
|
+
out.add(e.item);
|
|
2056
|
+
if (e.index !== void 0) out.add(e.index);
|
|
2057
|
+
boundNames(e.list, out);
|
|
2058
|
+
return boundNames(e.body, out);
|
|
2059
|
+
case "fold":
|
|
2060
|
+
out.add(e.acc);
|
|
2061
|
+
out.add(e.item);
|
|
2062
|
+
boundNames(e.list, out);
|
|
2063
|
+
boundNames(e.init, out);
|
|
2064
|
+
return boundNames(e.body, out);
|
|
2065
|
+
}
|
|
2066
|
+
}
|
|
2067
|
+
/** A name not among `taken`: the name with underscores appended. */
|
|
2068
|
+
function fresh(name, taken) {
|
|
2069
|
+
let out = `${name}_`;
|
|
2070
|
+
while (taken.has(out)) out += "_";
|
|
2071
|
+
return out;
|
|
2072
|
+
}
|
|
2073
|
+
/**
|
|
2074
|
+
* The expression with its variables renamed (an arrow's own parameter
|
|
2075
|
+
* names to the binders'). A `let` whose name is a rename's target would
|
|
2076
|
+
* capture the renamed references in its body, so such a let is renamed to
|
|
2077
|
+
* a fresh name first; a let whose name is a rename's source shadows it.
|
|
2078
|
+
*/
|
|
2079
|
+
function renameVars(e, names, taken = /* @__PURE__ */ new Set([
|
|
2080
|
+
...names.keys(),
|
|
2081
|
+
...names.values(),
|
|
2082
|
+
...boundNames(e)
|
|
2083
|
+
]), avoid = /* @__PURE__ */ new Set()) {
|
|
2084
|
+
const go = (x) => renameVars(x, names, taken, avoid);
|
|
2085
|
+
switch (e.kind) {
|
|
2086
|
+
case "int":
|
|
2087
|
+
case "bool":
|
|
2088
|
+
case "string":
|
|
2089
|
+
case "null": return e;
|
|
2090
|
+
case "var": return {
|
|
2091
|
+
kind: "var",
|
|
2092
|
+
name: names.get(e.name) ?? e.name
|
|
2093
|
+
};
|
|
2094
|
+
case "narrow": return {
|
|
2095
|
+
kind: "narrow",
|
|
2096
|
+
name: names.get(e.name) ?? e.name,
|
|
2097
|
+
body: go(e.body)
|
|
2098
|
+
};
|
|
2099
|
+
case "narrowTag": return {
|
|
2100
|
+
...e,
|
|
2101
|
+
name: names.get(e.name) ?? e.name,
|
|
2102
|
+
body: go(e.body)
|
|
2103
|
+
};
|
|
2104
|
+
case "neg":
|
|
2105
|
+
case "not":
|
|
2106
|
+
case "isInteger":
|
|
2107
|
+
case "floor": return {
|
|
2108
|
+
kind: e.kind,
|
|
2109
|
+
operand: go(e.operand)
|
|
2110
|
+
};
|
|
2111
|
+
case "binary": return {
|
|
2112
|
+
kind: "binary",
|
|
2113
|
+
op: e.op,
|
|
2114
|
+
left: go(e.left),
|
|
2115
|
+
right: go(e.right)
|
|
2116
|
+
};
|
|
2117
|
+
case "cond": return {
|
|
2118
|
+
kind: "cond",
|
|
2119
|
+
test: go(e.test),
|
|
2120
|
+
ifTrue: go(e.ifTrue),
|
|
2121
|
+
ifFalse: go(e.ifFalse)
|
|
2122
|
+
};
|
|
2123
|
+
case "call": return {
|
|
2124
|
+
kind: "call",
|
|
2125
|
+
callee: e.callee,
|
|
2126
|
+
args: e.args.map(go)
|
|
2127
|
+
};
|
|
2128
|
+
case "field": return {
|
|
2129
|
+
kind: "field",
|
|
2130
|
+
object: go(e.object),
|
|
2131
|
+
field: e.field
|
|
2132
|
+
};
|
|
2133
|
+
case "record": return {
|
|
2134
|
+
...e,
|
|
2135
|
+
fields: e.fields.map((f) => ({
|
|
2136
|
+
name: f.name,
|
|
2137
|
+
value: go(f.value)
|
|
2138
|
+
}))
|
|
2139
|
+
};
|
|
2140
|
+
case "let": {
|
|
2141
|
+
const inner = new Map(names);
|
|
2142
|
+
inner.delete(e.name);
|
|
2143
|
+
let bound = e.name;
|
|
2144
|
+
if ((/* @__PURE__ */ new Set([...names.values(), ...avoid])).has(e.name)) {
|
|
2145
|
+
bound = fresh(e.name, taken);
|
|
2146
|
+
inner.set(e.name, bound);
|
|
2147
|
+
}
|
|
2148
|
+
return {
|
|
2149
|
+
...e,
|
|
2150
|
+
name: bound,
|
|
2151
|
+
value: go(e.value),
|
|
2152
|
+
body: renameVars(e.body, inner, /* @__PURE__ */ new Set([...taken, bound]), avoid)
|
|
2153
|
+
};
|
|
2154
|
+
}
|
|
2155
|
+
case "list": return {
|
|
2156
|
+
kind: "list",
|
|
2157
|
+
items: e.items.map(go),
|
|
2158
|
+
...e.rest ? { rest: go(e.rest) } : {}
|
|
2159
|
+
};
|
|
2160
|
+
case "tail": return {
|
|
2161
|
+
kind: "tail",
|
|
2162
|
+
list: go(e.list)
|
|
2163
|
+
};
|
|
2164
|
+
case "headOr": return {
|
|
2165
|
+
kind: "headOr",
|
|
2166
|
+
list: go(e.list),
|
|
2167
|
+
fallback: go(e.fallback)
|
|
2168
|
+
};
|
|
2169
|
+
case "iterate": {
|
|
2170
|
+
const { inner, bound, scoped } = bindAll([e.item, ...e.index === void 0 ? [] : [e.index]], names, taken, avoid);
|
|
2171
|
+
return {
|
|
2172
|
+
...e,
|
|
2173
|
+
list: go(e.list),
|
|
2174
|
+
item: bound[0],
|
|
2175
|
+
...e.index === void 0 ? {} : { index: bound[1] },
|
|
2176
|
+
body: renameVars(e.body, inner, scoped, avoid)
|
|
2177
|
+
};
|
|
2178
|
+
}
|
|
2179
|
+
case "fold": {
|
|
2180
|
+
const { inner, bound, scoped } = bindAll([e.acc, e.item], names, taken, avoid);
|
|
2181
|
+
return {
|
|
2182
|
+
...e,
|
|
2183
|
+
list: go(e.list),
|
|
2184
|
+
init: go(e.init),
|
|
2185
|
+
acc: bound[0],
|
|
2186
|
+
item: bound[1],
|
|
2187
|
+
body: renameVars(e.body, inner, scoped, avoid)
|
|
2188
|
+
};
|
|
2189
|
+
}
|
|
2190
|
+
}
|
|
2191
|
+
}
|
|
2192
|
+
/**
|
|
2193
|
+
* The renames inside a callback that binds `own` names, as for a let:
|
|
2194
|
+
* each shadows a rename of its own name, and one that is a rename's target
|
|
2195
|
+
* moves to a fresh name so it captures nothing.
|
|
2196
|
+
*/
|
|
2197
|
+
function bindAll(own, names, taken, avoid) {
|
|
2198
|
+
const inner = new Map(names);
|
|
2199
|
+
const targets = /* @__PURE__ */ new Set([...names.values(), ...avoid]);
|
|
2200
|
+
const scoped = new Set(taken);
|
|
2201
|
+
return {
|
|
2202
|
+
inner,
|
|
2203
|
+
bound: own.map((n) => {
|
|
2204
|
+
inner.delete(n);
|
|
2205
|
+
if (!targets.has(n)) return n;
|
|
2206
|
+
const moved = fresh(n, scoped);
|
|
2207
|
+
scoped.add(moved);
|
|
2208
|
+
inner.set(n, moved);
|
|
2209
|
+
return moved;
|
|
2210
|
+
}),
|
|
2211
|
+
scoped
|
|
2212
|
+
};
|
|
2213
|
+
}
|
|
2214
|
+
// packages/prover/src/reader/inline.ts
|
|
2215
|
+
/**
|
|
2216
|
+
* Bind the type parameters in `declared` so that it is `expected`, or a
|
|
2217
|
+
* member of `expected` when that is a union: a parameter binds to what it
|
|
2218
|
+
* meets, and two instantiations of one alias match argument by argument.
|
|
2219
|
+
* Returns the type matched (the union member, say), or undefined, with
|
|
2220
|
+
* `bound` unchanged by a member that did not match.
|
|
2221
|
+
*/
|
|
2222
|
+
function match(declared, expected, bound) {
|
|
2223
|
+
if (declared.isTypeParameter()) {
|
|
2224
|
+
const had = bound.get(declared.id);
|
|
2225
|
+
if (had && had.id !== expected.id) return void 0;
|
|
2226
|
+
bound.set(declared.id, expected);
|
|
2227
|
+
return expected;
|
|
2228
|
+
}
|
|
2229
|
+
const alias = declared.getAliasSymbol();
|
|
2230
|
+
const other = expected.getAliasSymbol();
|
|
2231
|
+
if (alias && other && alias.id === other.id) {
|
|
2232
|
+
const xs = declared.getAliasTypeArguments();
|
|
2233
|
+
const ys = expected.getAliasTypeArguments();
|
|
2234
|
+
if (xs.length !== ys.length) return void 0;
|
|
2235
|
+
const trial = new Map(bound);
|
|
2236
|
+
for (let i = 0; i < xs.length; i++) if (!match(xs[i], ys[i], trial)) return void 0;
|
|
2237
|
+
for (const [k, v] of trial) bound.set(k, v);
|
|
2238
|
+
return expected;
|
|
2239
|
+
}
|
|
2240
|
+
if (expected.isUnionType()) for (const member of expected.getTypes()) {
|
|
2241
|
+
const trial = new Map(bound);
|
|
2242
|
+
if (match(declared, member, trial)) {
|
|
2243
|
+
for (const [k, v] of trial) bound.set(k, v);
|
|
2244
|
+
return member;
|
|
2245
|
+
}
|
|
2246
|
+
}
|
|
2247
|
+
}
|
|
2248
|
+
/**
|
|
2249
|
+
* Calls to functions the module cannot name as its own, read inlined: a
|
|
2250
|
+
* generic function (of the module or not) at the call's instantiation,
|
|
2251
|
+
* and a function of another file, as the compiler resolves the import.
|
|
2252
|
+
* The callee's body is read in its own file under the parameter types the
|
|
2253
|
+
* call's resolved signature gives, its literals typed by the resolved
|
|
2254
|
+
* return type, its names moved away from the caller's, and bound by `let`
|
|
2255
|
+
* to the arguments in order: a pure function called by value computes
|
|
2256
|
+
* exactly that. The callee's own calls inline the same way, so the
|
|
2257
|
+
* helpers of its file come with it. A callee with no body here (a
|
|
2258
|
+
* declaration file), one its file may rebind, or one reached again while
|
|
2259
|
+
* it is being inlined (recursion) is outside the subset, with why.
|
|
2260
|
+
*/
|
|
2261
|
+
function inliner(c) {
|
|
2262
|
+
const files = /* @__PURE__ */ new Map([[c.module, c.own]]);
|
|
2263
|
+
const functionsOf = (file) => {
|
|
2264
|
+
let found = files.get(file);
|
|
2265
|
+
if (!found) {
|
|
2266
|
+
found = fileFunctions(file, c.checker, c.standardGlobal);
|
|
2267
|
+
files.set(file, found);
|
|
2268
|
+
}
|
|
2269
|
+
return found;
|
|
2270
|
+
};
|
|
2271
|
+
const vetted = /* @__PURE__ */ new Map();
|
|
2272
|
+
const vet = (file, key, range) => {
|
|
2273
|
+
if (!vetted.has(key)) vetted.set(key, notCompiled(file, c.typeErrors, range));
|
|
2274
|
+
return vetted.get(key);
|
|
2275
|
+
};
|
|
2276
|
+
const inlining = [];
|
|
2277
|
+
const substitutions = [];
|
|
2278
|
+
const concrete = (t) => {
|
|
2279
|
+
const top = substitutions[substitutions.length - 1];
|
|
2280
|
+
return top && t.isTypeParameter() ? top.get(t.id) ?? t : t;
|
|
2281
|
+
};
|
|
2282
|
+
const inline = (call, callee, scope, readArgs, fail) => {
|
|
2283
|
+
const caller = call.getSourceFile();
|
|
2284
|
+
const start = call.getStart(caller);
|
|
2285
|
+
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}`);
|
|
2286
|
+
let symbol = c.checker.getSymbolAtLocation(callee);
|
|
2287
|
+
if (!symbol) return void 0;
|
|
2288
|
+
if (symbol.flags & SymbolFlags.Alias) symbol = c.checker.getAliasedSymbol(symbol);
|
|
2289
|
+
const decl = symbol.valueDeclaration?.resolve();
|
|
2290
|
+
if (!decl || !(is.isFunctionDeclaration(decl) || is.isVariableDeclaration(decl))) return void 0;
|
|
2291
|
+
const file = decl.getSourceFile();
|
|
2292
|
+
const name = decl.name && is.isIdentifier(decl.name) ? decl.name.text : symbol.name;
|
|
2293
|
+
const where = file === c.module ? name : `${name} (from ${file.fileName})`;
|
|
2294
|
+
if (file.isDeclarationFile) fail(`${where} has no body to read: it is declared in a declaration file`);
|
|
2295
|
+
const fns = functionsOf(file);
|
|
2296
|
+
const d = fns.declarations.get(name);
|
|
2297
|
+
if (!d || !decl.name || d.name.pos !== decl.name.pos) return void 0;
|
|
2298
|
+
if (c.parseError(file.fileName)) fail(`${where} is in a file the compiler cannot parse`);
|
|
2299
|
+
const untrusted = fns.untrusted.get(name);
|
|
2300
|
+
if (untrusted) fail(`${where} is outside the subset: ${untrusted.message}`);
|
|
2301
|
+
if (fns.overloaded.has(name)) fail(`${where} is declared more than once (overloads)`);
|
|
2302
|
+
const body = d.node.body;
|
|
2303
|
+
if (!body) fail(`${where} has no body to read`);
|
|
2304
|
+
const bad = vet(file, d.node, rangeOf(d));
|
|
2305
|
+
if (bad) fail(`${where} is outside the subset: ${bad.message} (line ${bad.line}${file === c.module ? "" : " of its file"})`);
|
|
2306
|
+
const signature = c.checker.getResolvedSignature(call);
|
|
2307
|
+
if (c.checker.isUnknownSignature(signature)) fail(`the call to ${where} does not resolve`);
|
|
2308
|
+
const reader = new ExprReader(file, {
|
|
2309
|
+
callable: () => false,
|
|
2310
|
+
target: (n) => n,
|
|
2311
|
+
declared: (n) => fns.declarations.has(n),
|
|
2312
|
+
spec: false,
|
|
2313
|
+
global: c.standardGlobal
|
|
2314
|
+
}, {
|
|
2315
|
+
annotation: (node, refuse) => c.types.of(concrete(c.checker.getTypeAtLocation(node)), refuse),
|
|
2316
|
+
contextual: c.typeSource.contextual
|
|
2317
|
+
}, c.ctx, void 0, inline, constant);
|
|
2318
|
+
const params = shape(reader, d.node);
|
|
2319
|
+
const symbols = signature.getParameters();
|
|
2320
|
+
if (symbols.length !== params.length || call.arguments.length !== params.length) fail(`${where} takes ${params.length} argument(s), called with ${call.arguments.length}`);
|
|
2321
|
+
const bound = /* @__PURE__ */ new Map();
|
|
2322
|
+
const declared = c.checker.getSignatureFromDeclaration(d.node);
|
|
2323
|
+
const generalReturn = c.checker.getReturnTypeOfSignature(declared);
|
|
2324
|
+
const context = d.node.typeParameters ? c.checker.getContextualType(call) : void 0;
|
|
2325
|
+
const matched = context ? match(generalReturn, concrete(context), bound) : void 0;
|
|
2326
|
+
const declaredParams = declared.getParameters();
|
|
2327
|
+
const generalParams = symbols.map((_, i) => {
|
|
2328
|
+
const own = declaredParams[i];
|
|
2329
|
+
return own ? c.checker.getTypeOfSymbol(own) : void 0;
|
|
2330
|
+
});
|
|
2331
|
+
const resolvedParams = symbols.map((p) => concrete(c.checker.getTypeOfSymbol(p)));
|
|
2332
|
+
const resolvedReturn = concrete(c.checker.getReturnTypeOfSignature(signature));
|
|
2333
|
+
generalParams.forEach((g, i) => {
|
|
2334
|
+
if (g) match(g, resolvedParams[i], bound);
|
|
2335
|
+
});
|
|
2336
|
+
match(generalReturn, resolvedReturn, bound);
|
|
2337
|
+
const types = symbols.map((_, i) => {
|
|
2338
|
+
const g = generalParams[i];
|
|
2339
|
+
const type = g?.isTypeParameter() && bound.has(g.id) ? concrete(bound.get(g.id)) : resolvedParams[i];
|
|
2340
|
+
return c.types.of(type, (what) => fail(`${where}, parameter ${params[i]} at this call: ${what}`));
|
|
2341
|
+
});
|
|
2342
|
+
const returns = c.types.of(matched ?? resolvedReturn, (what) => fail(`${where} returns, at this call, ${what}`));
|
|
2343
|
+
const own = new Map([...bound].map(([k, v]) => [k, concrete(v)]));
|
|
2344
|
+
const args = readArgs(types);
|
|
2345
|
+
const key = `${file.fileName}#${name}`;
|
|
2346
|
+
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)`);
|
|
2347
|
+
inlining.push(key);
|
|
2348
|
+
substitutions.push(own);
|
|
2349
|
+
try {
|
|
2350
|
+
const inner = new Map(params.map((p, i) => [p, types[i]]));
|
|
2351
|
+
const readBody = () => {
|
|
2352
|
+
const read = returning(is.isBlock(body) ? reader.block(body.statements, inner, body) : reader.expression(body, inner), returns);
|
|
2353
|
+
const actual = reader.typeOfExpr(reader.narrowed(read, inner, body), inner, body, returns);
|
|
2354
|
+
if (!fits(actual, returns, c.ctx)) reader.fail(`returns a ${describe(actual)}, not the ${describe(returns)} called for`, body);
|
|
2355
|
+
return read;
|
|
2356
|
+
};
|
|
2357
|
+
let read;
|
|
2358
|
+
try {
|
|
2359
|
+
read = readBody();
|
|
2360
|
+
} catch (err) {
|
|
2361
|
+
if (!(err instanceof OutsideSubset)) throw err;
|
|
2362
|
+
fail(`${where}, read at this call, is outside the subset: ${err.message} (line ${err.line} of its file)`);
|
|
2363
|
+
}
|
|
2364
|
+
const callerNames = /* @__PURE__ */ new Set([...scope.keys(), ...args.flatMap((a) => [...boundNames(a)])]);
|
|
2365
|
+
const taken = /* @__PURE__ */ new Set([
|
|
2366
|
+
...callerNames,
|
|
2367
|
+
...boundNames(read),
|
|
2368
|
+
...params
|
|
2369
|
+
]);
|
|
2370
|
+
const renames = /* @__PURE__ */ new Map();
|
|
2371
|
+
for (const p of params) {
|
|
2372
|
+
const to = callerNames.has(p) ? fresh(p, taken) : p;
|
|
2373
|
+
taken.add(to);
|
|
2374
|
+
renames.set(p, to);
|
|
2375
|
+
}
|
|
2376
|
+
const renamed = renameVars(read, renames, taken, callerNames);
|
|
2377
|
+
return params.reduceRight((rest, p, i) => ({
|
|
2378
|
+
kind: "let",
|
|
2379
|
+
name: renames.get(p),
|
|
2380
|
+
value: args[i],
|
|
2381
|
+
body: rest,
|
|
2382
|
+
type: types[i]
|
|
2383
|
+
}), renamed);
|
|
2384
|
+
} finally {
|
|
2385
|
+
substitutions.pop();
|
|
2386
|
+
inlining.pop();
|
|
2387
|
+
}
|
|
2388
|
+
};
|
|
2389
|
+
const reading = [];
|
|
2390
|
+
const constant = (name, fail) => {
|
|
2391
|
+
let symbol = c.checker.getSymbolAtLocation(name);
|
|
2392
|
+
if (!symbol) return void 0;
|
|
2393
|
+
const imported = (symbol.flags & SymbolFlags.Alias) !== 0;
|
|
2394
|
+
if (imported) symbol = c.checker.getAliasedSymbol(symbol);
|
|
2395
|
+
const decl = symbol.valueDeclaration?.resolve();
|
|
2396
|
+
if (!decl || !is.isVariableDeclaration(decl) || !is.isIdentifier(decl.name)) return void 0;
|
|
2397
|
+
const list = decl.parent;
|
|
2398
|
+
const statement = list.parent;
|
|
2399
|
+
const file = decl.getSourceFile();
|
|
2400
|
+
if (!is.isVariableDeclarationList(list) || !is.isVariableStatement(statement)) return void 0;
|
|
2401
|
+
if (statement.parent !== file) fail(`${name.text}, which is declared after this use in its block`);
|
|
2402
|
+
const where = file === c.module ? decl.name.text : `${decl.name.text} (from ${file.fileName})`;
|
|
2403
|
+
if (file.isDeclarationFile && !imported) return void 0;
|
|
2404
|
+
if (file.isDeclarationFile) fail(`${where} has no value to read: it is declared in a declaration file`);
|
|
2405
|
+
if (!isConst(list)) fail(`${where} is a module-level let or var, which may be rebound`);
|
|
2406
|
+
const at = name.getSourceFile();
|
|
2407
|
+
const start = name.getStart(at);
|
|
2408
|
+
if (c.typeErrors(at.fileName).some((e) => e.pos < name.end && e.end > start)) fail(`the compiler reports an error on ${name.text} here`);
|
|
2409
|
+
if (c.parseError(file.fileName)) fail(`${where} is in a file the compiler cannot parse`);
|
|
2410
|
+
const init = decl.initializer;
|
|
2411
|
+
if (!init) fail(`${where} has no initializer`);
|
|
2412
|
+
if (is.isArrowFunction(init) || is.isFunctionExpression(init)) return void 0;
|
|
2413
|
+
const bad = vet(file, decl, {
|
|
2414
|
+
start: decl.pos,
|
|
2415
|
+
end: decl.end,
|
|
2416
|
+
lead: {
|
|
2417
|
+
start: statement.pos,
|
|
2418
|
+
end: statement.getStart(file)
|
|
2419
|
+
}
|
|
2420
|
+
});
|
|
2421
|
+
if (bad) fail(`${where} is outside the subset: ${bad.message} (line ${bad.line}${file === c.module ? "" : " of its file"})`);
|
|
2422
|
+
const key = `${file.fileName}#${decl.name.text}`;
|
|
2423
|
+
if (reading.includes(key)) fail(`${where} is defined in terms of itself`);
|
|
2424
|
+
const fns = functionsOf(file);
|
|
2425
|
+
if (fns.tainted) fail(`${where} is outside the subset: ${fns.tainted.message}`);
|
|
2426
|
+
const reader = new ExprReader(file, {
|
|
2427
|
+
callable: () => false,
|
|
2428
|
+
target: (n) => n,
|
|
2429
|
+
declared: (n) => fns.declarations.has(n),
|
|
2430
|
+
spec: false,
|
|
2431
|
+
global: c.standardGlobal
|
|
2432
|
+
}, c.typeSource, c.ctx, void 0, void 0, constant);
|
|
2433
|
+
reading.push(key);
|
|
2434
|
+
try {
|
|
2435
|
+
const value = reader.expression(init, /* @__PURE__ */ new Map());
|
|
2436
|
+
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);
|
|
2437
|
+
return value;
|
|
2438
|
+
} catch (err) {
|
|
2439
|
+
if (!(err instanceof OutsideSubset)) throw err;
|
|
2440
|
+
fail(`${where}, read where it is used, is outside the subset: ${err.message} (line ${err.line} of its file)`);
|
|
2441
|
+
} finally {
|
|
2442
|
+
reading.pop();
|
|
2443
|
+
}
|
|
2444
|
+
};
|
|
2445
|
+
return {
|
|
2446
|
+
inline,
|
|
2447
|
+
constant
|
|
2448
|
+
};
|
|
2449
|
+
}
|
|
2450
|
+
/**
|
|
2451
|
+
* Whether an expression is a value a constant may hold: literals of the
|
|
2452
|
+
* primitive types and the operators on them, with no name, call or record.
|
|
2453
|
+
*/
|
|
2454
|
+
function isValue(e) {
|
|
2455
|
+
switch (e.kind) {
|
|
2456
|
+
case "int":
|
|
2457
|
+
case "bool":
|
|
2458
|
+
case "string": return true;
|
|
2459
|
+
case "neg":
|
|
2460
|
+
case "not":
|
|
2461
|
+
case "isInteger":
|
|
2462
|
+
case "floor": return isValue(e.operand);
|
|
2463
|
+
case "binary": return isValue(e.left) && isValue(e.right);
|
|
2464
|
+
case "cond": return isValue(e.test) && isValue(e.ifTrue) && isValue(e.ifFalse);
|
|
2465
|
+
default: return false;
|
|
2466
|
+
}
|
|
2467
|
+
}
|
|
2468
|
+
/**
|
|
2469
|
+
* The expression with the record literals it returns typed `t`, where
|
|
2470
|
+
* they have no type of their own: a function inlined at a call returns
|
|
2471
|
+
* its instantiated type, which a literal in a generic body cannot name.
|
|
2472
|
+
*/
|
|
2473
|
+
function returning(e, t) {
|
|
2474
|
+
const target = t.kind === "nullable" ? t.inner : t;
|
|
2475
|
+
if (target.kind !== "record" && target.kind !== "union") return e;
|
|
2476
|
+
switch (e.kind) {
|
|
2477
|
+
case "record": return e.type ? e : {
|
|
2478
|
+
...e,
|
|
2479
|
+
type: target
|
|
2480
|
+
};
|
|
2481
|
+
case "let":
|
|
2482
|
+
case "narrow":
|
|
2483
|
+
case "narrowTag": return {
|
|
2484
|
+
...e,
|
|
2485
|
+
body: returning(e.body, t)
|
|
2486
|
+
};
|
|
2487
|
+
case "cond": return {
|
|
2488
|
+
...e,
|
|
2489
|
+
ifTrue: returning(e.ifTrue, t),
|
|
2490
|
+
ifFalse: returning(e.ifFalse, t)
|
|
2491
|
+
};
|
|
2492
|
+
default: return e;
|
|
2493
|
+
}
|
|
2494
|
+
}
|
|
2495
|
+
// packages/prover/src/reader/types.ts
|
|
2496
|
+
/** 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). */
|
|
2497
|
+
const maxDepth = 16;
|
|
2498
|
+
/**
|
|
2499
|
+
* Why an object type is not plain data, or undefined when it is: a class
|
|
2500
|
+
* (an instance is more than its fields: nominal, with private ones), or an
|
|
2501
|
+
* interface over a base the compiler could not resolve (it then shows the
|
|
2502
|
+
* interface's own fields alone) or over a class.
|
|
2503
|
+
*/
|
|
2504
|
+
function notPlain(checker, type, seen = /* @__PURE__ */ new Set()) {
|
|
2505
|
+
const symbol = type.getSymbol();
|
|
2506
|
+
if (!symbol || seen.has(type.id)) return void 0;
|
|
2507
|
+
seen.add(type.id);
|
|
2508
|
+
if ((symbol.flags & SymbolFlags.Class) !== 0) return "a class (an instance is more than a record of its fields)";
|
|
2509
|
+
if ((symbol.flags & SymbolFlags.Interface) === 0) return void 0;
|
|
2510
|
+
for (const handle of symbol.declarations) {
|
|
2511
|
+
if (handle.kind !== SyntaxKind.InterfaceDeclaration) continue;
|
|
2512
|
+
const decl = handle.resolve();
|
|
2513
|
+
if (!decl || !is.isInterfaceDeclaration(decl)) continue;
|
|
2514
|
+
for (const clause of decl.heritageClauses ?? []) for (const base of clause.types) {
|
|
2515
|
+
const baseType = checker.getTypeAtLocation(base);
|
|
2516
|
+
if (baseType.isErrorType()) return `extends ${base.getText()}, which does not resolve`;
|
|
2517
|
+
const why = notPlain(checker, baseType, seen);
|
|
2518
|
+
if (why !== void 0) return `extends ${base.getText()}: ${why}`;
|
|
2519
|
+
}
|
|
2520
|
+
}
|
|
2521
|
+
}
|
|
2522
|
+
/** A type as the compiler prints it, in full. */
|
|
2523
|
+
function printType(checker, type) {
|
|
2524
|
+
return checker.typeToString(type, void 0, TypeFormatFlags.NoTruncation);
|
|
2525
|
+
}
|
|
2526
|
+
/**
|
|
2527
|
+
* The name a record or union goes by: its alias or interface name when
|
|
2528
|
+
* declared without type arguments, otherwise the type as the compiler
|
|
2529
|
+
* prints it (`Result<true, Locked>`, `{ readonly ok: boolean; }`).
|
|
2530
|
+
*/
|
|
2531
|
+
function nameOfType(checker, type) {
|
|
2532
|
+
const alias = type.getAliasSymbol();
|
|
2533
|
+
if (alias) return type.getAliasTypeArguments().length === 0 ? alias.name : printType(checker, type);
|
|
2534
|
+
const symbol = type.getSymbol();
|
|
2535
|
+
if (symbol && (symbol.flags & (SymbolFlags.Interface | SymbolFlags.Class)) !== 0 && !(type.isTypeReference() && checker.getTypeArguments(type).length > 0)) return symbol.name;
|
|
2536
|
+
return printType(checker, type);
|
|
2537
|
+
}
|
|
2538
|
+
/** A union's members with `true | false` folded back into `boolean`, which the compiler keeps apart. */
|
|
2539
|
+
function foldBooleans(members) {
|
|
2540
|
+
const isTrue = (t) => t.isBooleanLiteralType() && t.value === true;
|
|
2541
|
+
const isFalse = (t) => t.isBooleanLiteralType() && t.value === false;
|
|
2542
|
+
if (!members.some(isTrue) || !members.some(isFalse)) return [...members];
|
|
2543
|
+
const out = [];
|
|
2544
|
+
let folded = false;
|
|
2545
|
+
for (const m of members) if (isTrue(m) || isFalse(m)) {
|
|
2546
|
+
if (!folded) out.push("boolean");
|
|
2547
|
+
folded = true;
|
|
2548
|
+
} else out.push(m);
|
|
2549
|
+
return out;
|
|
2550
|
+
}
|
|
2551
|
+
/** The members of a union as one type: flattened, deduplicated, one member alone. */
|
|
2552
|
+
function unionOf(members) {
|
|
2553
|
+
const flat = members.flatMap((m) => m.kind === "union" ? m.members : [m]);
|
|
2554
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2555
|
+
const unique = flat.filter((m) => {
|
|
2556
|
+
const key = JSON.stringify(m);
|
|
2557
|
+
if (seen.has(key)) return false;
|
|
2558
|
+
seen.add(key);
|
|
2559
|
+
return true;
|
|
2560
|
+
});
|
|
2561
|
+
return unique.length === 1 ? unique[0] : {
|
|
2562
|
+
kind: "union",
|
|
2563
|
+
members: unique
|
|
2564
|
+
};
|
|
2565
|
+
}
|
|
2566
|
+
/** A type into `SpecType`; what the spec surface does not describe is `unknown` with the type's text. */
|
|
2567
|
+
function specTypeOf(checker, type, seen = /* @__PURE__ */ new Set()) {
|
|
2568
|
+
const unknown = () => ({
|
|
2569
|
+
kind: "unknown",
|
|
2570
|
+
text: printType(checker, type)
|
|
2571
|
+
});
|
|
2572
|
+
const flags = type.flags;
|
|
2573
|
+
if (type.isErrorType()) return unknown();
|
|
2574
|
+
if (flags & TypeFlags.Number) return { kind: "number" };
|
|
2575
|
+
if (flags & TypeFlags.String) return { kind: "string" };
|
|
2576
|
+
if (flags & TypeFlags.Boolean) return { kind: "boolean" };
|
|
2577
|
+
if (flags & TypeFlags.BigInt) return { kind: "bigint" };
|
|
2578
|
+
if (type.isStringLiteralType() || type.isNumberLiteralType() || type.isBooleanLiteralType()) return {
|
|
2579
|
+
kind: "literal",
|
|
2580
|
+
value: type.value
|
|
2581
|
+
};
|
|
2582
|
+
if (flags & TypeFlags.Null) return { kind: "null" };
|
|
2583
|
+
if (flags & (TypeFlags.Undefined | TypeFlags.Void)) return { kind: "undefined" };
|
|
2584
|
+
if (type.isUnionType()) return unionOf(foldBooleans(type.getTypes()).map((m) => m === "boolean" ? { kind: "boolean" } : specTypeOf(checker, m, seen)));
|
|
2585
|
+
if (!type.isObjectType()) return unknown();
|
|
2586
|
+
if (seen.has(type.id) || seen.size >= maxDepth) return unknown();
|
|
2587
|
+
const inner = new Set(seen).add(type.id);
|
|
2588
|
+
if (checker.isArrayType(type)) {
|
|
2589
|
+
const element = checker.getTypeArguments(type)[0];
|
|
2590
|
+
return element ? {
|
|
2591
|
+
kind: "array",
|
|
2592
|
+
element: specTypeOf(checker, element, inner)
|
|
2593
|
+
} : unknown();
|
|
2594
|
+
}
|
|
2595
|
+
if (type.isTupleType() || type.getCallSignatures().length > 0 || type.getConstructSignatures().length > 0 || type.getIndexInfos().length > 0) return unknown();
|
|
2596
|
+
if (notPlain(checker, type) !== void 0) return unknown();
|
|
2597
|
+
const properties = type.getProperties();
|
|
2598
|
+
const computed = SymbolFlags.Method | SymbolFlags.GetAccessor | SymbolFlags.SetAccessor;
|
|
2599
|
+
if (properties.some((p) => (p.flags & computed) !== 0 || isSymbolKey(p.name))) return unknown();
|
|
2600
|
+
const fields = properties.map((p) => ({
|
|
2601
|
+
name: p.name,
|
|
2602
|
+
type: specTypeOf(checker, checker.getTypeOfSymbol(p), inner)
|
|
2603
|
+
}));
|
|
2604
|
+
return {
|
|
2605
|
+
kind: "record",
|
|
2606
|
+
name: nameOfType(checker, type),
|
|
2607
|
+
fields
|
|
2608
|
+
};
|
|
2609
|
+
}
|
|
2610
|
+
/** Whether a property's name is the compiler's spelling of a symbol key, which no string names. */
|
|
2611
|
+
const isSymbolKey = (name) => name.startsWith("__@");
|
|
2612
|
+
/** Names a Lean structure declaration generates itself, which a field cannot take. */
|
|
2613
|
+
const structureNames = /* @__PURE__ */ new Set([
|
|
2614
|
+
"mk",
|
|
2615
|
+
"rec",
|
|
2616
|
+
"recOn",
|
|
2617
|
+
"casesOn",
|
|
2618
|
+
"noConfusion",
|
|
2619
|
+
"noConfusionType",
|
|
2620
|
+
"injEq"
|
|
2621
|
+
]);
|
|
2622
|
+
/**
|
|
2623
|
+
* The subset's types read from the compiler's, with every record and
|
|
2624
|
+
* union met along the way kept by name, in the order met, for the engines
|
|
2625
|
+
* to declare. One type is read once: a second meeting gives the same
|
|
2626
|
+
* record, and so does another compiler type of the same name and the
|
|
2627
|
+
* same fields (an inline type written twice). A type the subset does not
|
|
2628
|
+
* take is refused with the construct named, and a read that is refused
|
|
2629
|
+
* leaves nothing behind: whatever it registered on the way is taken back,
|
|
2630
|
+
* so no record belongs to a union that was never declared.
|
|
2631
|
+
*/
|
|
2632
|
+
var SubsetTypes = class {
|
|
2633
|
+
records = /* @__PURE__ */ new Map();
|
|
2634
|
+
unions = [];
|
|
2635
|
+
checker;
|
|
2636
|
+
/** By the compiler's type id. */
|
|
2637
|
+
byId = /* @__PURE__ */ new Map();
|
|
2638
|
+
idOfName = /* @__PURE__ */ new Map();
|
|
2639
|
+
/** Types being read now, to refuse a type that holds itself. */
|
|
2640
|
+
reading = /* @__PURE__ */ new Set();
|
|
2641
|
+
constructor(checker) {
|
|
2642
|
+
this.checker = checker;
|
|
2643
|
+
}
|
|
2644
|
+
/** The subset type of a compiler type, or a refusal, after which nothing of the read remains. */
|
|
2645
|
+
of(type, refuse) {
|
|
2646
|
+
const cached = this.byId.get(type.id);
|
|
2647
|
+
if (cached) return cached;
|
|
2648
|
+
if (this.reading.size > 0) return this.enter(type, refuse);
|
|
2649
|
+
const saved = {
|
|
2650
|
+
records: new Map(this.records),
|
|
2651
|
+
idOfName: new Map(this.idOfName),
|
|
2652
|
+
byId: new Map(this.byId),
|
|
2653
|
+
unions: this.unions.length
|
|
2654
|
+
};
|
|
2655
|
+
try {
|
|
2656
|
+
return this.enter(type, refuse);
|
|
2657
|
+
} catch (err) {
|
|
2658
|
+
this.records.clear();
|
|
2659
|
+
for (const [k, v] of saved.records) this.records.set(k, v);
|
|
2660
|
+
this.idOfName.clear();
|
|
2661
|
+
for (const [k, v] of saved.idOfName) this.idOfName.set(k, v);
|
|
2662
|
+
this.byId.clear();
|
|
2663
|
+
for (const [k, v] of saved.byId) this.byId.set(k, v);
|
|
2664
|
+
this.unions.length = saved.unions;
|
|
2665
|
+
throw err;
|
|
2666
|
+
}
|
|
2667
|
+
}
|
|
2668
|
+
/** A type read under the recursion guard. */
|
|
2669
|
+
enter(type, refuse) {
|
|
2670
|
+
if (this.reading.has(type.id)) return refuse(`${nameOfType(this.checker, type)} holds itself (a recursive type)`);
|
|
2671
|
+
if (this.reading.size >= maxDepth) return refuse(`${nameOfType(this.checker, type)} is nested too deep (more than ${maxDepth} levels)`);
|
|
2672
|
+
this.reading.add(type.id);
|
|
2673
|
+
try {
|
|
2674
|
+
const out = this.read(type, refuse);
|
|
2675
|
+
this.byId.set(type.id, out);
|
|
2676
|
+
return out;
|
|
2677
|
+
} finally {
|
|
2678
|
+
this.reading.delete(type.id);
|
|
2679
|
+
}
|
|
2680
|
+
}
|
|
2681
|
+
read(type, refuse) {
|
|
2682
|
+
const checker = this.checker;
|
|
2683
|
+
const text = () => printType(checker, type);
|
|
2684
|
+
const flags = type.flags;
|
|
2685
|
+
if (type.isErrorType()) return refuse(`type ${text()}, which does not resolve`);
|
|
2686
|
+
if (flags & TypeFlags.Number) return { kind: "int" };
|
|
2687
|
+
if (flags & (TypeFlags.String | TypeFlags.StringLiteral)) return { kind: "string" };
|
|
2688
|
+
if (flags & (TypeFlags.Boolean | TypeFlags.BooleanLiteral)) return { kind: "bool" };
|
|
2689
|
+
if (flags & TypeFlags.Null) return refuse("null alone is not a type the subset takes");
|
|
2690
|
+
if (flags & (TypeFlags.Undefined | TypeFlags.Void)) return refuse("undefined in a type (the subset has null)");
|
|
2691
|
+
if (flags & TypeFlags.NumberLiteral) return refuse(`the numeric literal type ${text()} (the subset has number)`);
|
|
2692
|
+
if (flags & TypeFlags.BigInt) return refuse("bigint (the subset has number)");
|
|
2693
|
+
if (flags & TypeFlags.TypeParameter) return refuse("type parameters");
|
|
2694
|
+
if (type.isUnionType()) return this.union(type, refuse);
|
|
2695
|
+
if (type.isIntersectionType()) return refuse("an intersection type");
|
|
2696
|
+
if (!type.isObjectType()) return refuse(`type ${text()} (the subset has number, boolean, string, null, and record types, unions and arrays of them)`);
|
|
2697
|
+
if (checker.isArrayType(type)) {
|
|
2698
|
+
const element = checker.getTypeArguments(type)[0];
|
|
2699
|
+
if (!element) return refuse(`type ${text()}`);
|
|
2700
|
+
return {
|
|
2701
|
+
kind: "list",
|
|
2702
|
+
element: this.of(element, refuse)
|
|
2703
|
+
};
|
|
2704
|
+
}
|
|
2705
|
+
if (type.isTupleType()) return refuse("a tuple type");
|
|
2706
|
+
if (type.getCallSignatures().length > 0 || type.getConstructSignatures().length > 0) return refuse("a function type");
|
|
2707
|
+
if (type.getIndexInfos().length > 0) return refuse("an index signature");
|
|
2708
|
+
const why = notPlain(checker, type);
|
|
2709
|
+
if (why !== void 0) return refuse(`type ${text()} is outside the subset: ${why}`);
|
|
2710
|
+
return {
|
|
2711
|
+
kind: "record",
|
|
2712
|
+
name: this.record(type, nameOfType(checker, type), refuse).name
|
|
2713
|
+
};
|
|
2714
|
+
}
|
|
2715
|
+
/** A union: `T | null` a nullable, literals their base type, several records a tagged union. */
|
|
2716
|
+
union(type, refuse) {
|
|
2717
|
+
const members = type.isUnionType() ? type.getTypes() : [type];
|
|
2718
|
+
if (members.some((m) => (m.flags & (TypeFlags.Undefined | TypeFlags.Void)) !== 0)) return refuse("undefined in a type (the subset has null)");
|
|
2719
|
+
const nulls = members.filter((m) => (m.flags & TypeFlags.Null) !== 0);
|
|
2720
|
+
const rest = members.filter((m) => (m.flags & TypeFlags.Null) === 0);
|
|
2721
|
+
const bare = nulls.length === 0 ? type : type.getNonNullableType();
|
|
2722
|
+
let base;
|
|
2723
|
+
if (rest.length === 0) return refuse("null alone is not a type the subset takes");
|
|
2724
|
+
else if (rest.every((m) => (m.flags & (TypeFlags.String | TypeFlags.StringLiteral)) !== 0)) base = { kind: "string" };
|
|
2725
|
+
else if (rest.every((m) => (m.flags & (TypeFlags.Boolean | TypeFlags.BooleanLiteral)) !== 0)) base = { kind: "bool" };
|
|
2726
|
+
else if (rest.length === 1) base = this.of(rest[0], refuse);
|
|
2727
|
+
else if (rest.every((m) => m.isObjectType() && !this.checker.isArrayType(m))) base = this.taggedUnion(bare, rest, refuse);
|
|
2728
|
+
else if (rest.some((m) => m.isObjectType())) return refuse("a union mixing records with other types");
|
|
2729
|
+
else if (rest.every((m) => (m.flags & TypeFlags.NumberLiteral) !== 0)) return refuse(`the numeric literal type ${printType(this.checker, type)} (the subset has number)`);
|
|
2730
|
+
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`);
|
|
2731
|
+
if (nulls.length === 0) return base;
|
|
2732
|
+
if (base.kind === "nullable") return base;
|
|
2733
|
+
return {
|
|
2734
|
+
kind: "nullable",
|
|
2735
|
+
inner: base
|
|
2736
|
+
};
|
|
2737
|
+
}
|
|
2738
|
+
/**
|
|
2739
|
+
* A union of records, told apart by a tag: a literal-typed field every
|
|
2740
|
+
* member has, holding a different literal in each. Members declared
|
|
2741
|
+
* inline are named by the union and their tag (`Outcome.true`); a
|
|
2742
|
+
* record declared on its own keeps its name, and may be a member of several unions.
|
|
2743
|
+
*/
|
|
2744
|
+
taggedUnion(type, members, refuse) {
|
|
2745
|
+
const cached = this.byId.get(type.id);
|
|
2746
|
+
if (cached) return cached;
|
|
2747
|
+
const checker = this.checker;
|
|
2748
|
+
const name = nameOfType(checker, type);
|
|
2749
|
+
const taken = this.idOfName.get(name);
|
|
2750
|
+
if (taken !== void 0 && taken !== type.id) return refuse(`two types named ${name}`);
|
|
2751
|
+
if (taken === void 0 && (this.records.has(name) || this.unions.some((u) => u.name === name))) return refuse(`two types named ${name}`);
|
|
2752
|
+
const literalFields = (m) => {
|
|
2753
|
+
const out = /* @__PURE__ */ new Map();
|
|
2754
|
+
for (const p of m.getProperties()) {
|
|
2755
|
+
const t = checker.getTypeOfSymbol(p);
|
|
2756
|
+
if (t.isStringLiteralType() || t.isBooleanLiteralType()) out.set(p.name, t.value);
|
|
2757
|
+
}
|
|
2758
|
+
return out;
|
|
2759
|
+
};
|
|
2760
|
+
const literals = members.map(literalFields);
|
|
2761
|
+
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);
|
|
2762
|
+
if (tag === void 0) return refuse(`${name}: a union of records without a tag (a literal-typed field every member has, different in each)`);
|
|
2763
|
+
const isAnonymous = (m) => !m.getAliasSymbol() && ((m.getSymbol()?.flags ?? 0) & (SymbolFlags.Interface | SymbolFlags.Class)) === 0;
|
|
2764
|
+
const union = {
|
|
2765
|
+
name,
|
|
2766
|
+
tag,
|
|
2767
|
+
members: members.map((m, i) => {
|
|
2768
|
+
const value = literals[i].get(tag);
|
|
2769
|
+
const memberName = isAnonymous(m) ? `${name}.${String(value)}` : nameOfType(checker, m);
|
|
2770
|
+
return {
|
|
2771
|
+
tag: value,
|
|
2772
|
+
record: this.record(m, memberName, refuse, name).name
|
|
2773
|
+
};
|
|
2774
|
+
})
|
|
2775
|
+
};
|
|
2776
|
+
this.unions.push(union);
|
|
2777
|
+
this.idOfName.set(name, type.id);
|
|
2778
|
+
const out = {
|
|
2779
|
+
kind: "union",
|
|
2780
|
+
name
|
|
2781
|
+
};
|
|
2782
|
+
this.byId.set(type.id, out);
|
|
2783
|
+
return out;
|
|
2784
|
+
}
|
|
2785
|
+
/** A record under `name`: its fields read, the record kept; a member of `union` when given. */
|
|
2786
|
+
record(type, name, refuse, union) {
|
|
2787
|
+
let known = this.records.get(name);
|
|
2788
|
+
if (!known && this.unions.some((u) => u.name === name)) return refuse(`two types named ${name}`);
|
|
2789
|
+
if (known && this.idOfName.get(name) !== type.id) {
|
|
2790
|
+
const fields = this.fieldsOf(type, name, refuse);
|
|
2791
|
+
if (JSON.stringify(fields) !== JSON.stringify(known.fields)) return refuse(`two types named ${name}`);
|
|
2792
|
+
this.byId.set(type.id, {
|
|
2793
|
+
kind: "record",
|
|
2794
|
+
name
|
|
2795
|
+
});
|
|
2796
|
+
}
|
|
2797
|
+
if (known) {
|
|
2798
|
+
if (union !== void 0 && !known.unions?.includes(union)) {
|
|
2799
|
+
known = {
|
|
2800
|
+
...known,
|
|
2801
|
+
unions: [...known.unions ?? [], union]
|
|
2802
|
+
};
|
|
2803
|
+
this.records.set(name, known);
|
|
2804
|
+
}
|
|
2805
|
+
return known;
|
|
2806
|
+
}
|
|
2807
|
+
const record = {
|
|
2808
|
+
name,
|
|
2809
|
+
fields: this.fieldsOf(type, name, refuse),
|
|
2810
|
+
...union === void 0 ? {} : { unions: [union] }
|
|
2811
|
+
};
|
|
2812
|
+
this.records.set(name, record);
|
|
2813
|
+
this.idOfName.set(name, type.id);
|
|
2814
|
+
this.byId.set(type.id, {
|
|
2815
|
+
kind: "record",
|
|
2816
|
+
name
|
|
2817
|
+
});
|
|
2818
|
+
return record;
|
|
2819
|
+
}
|
|
2820
|
+
/** The fields of a record type, each a stored value the subset takes. */
|
|
2821
|
+
fieldsOf(type, name, refuse) {
|
|
2822
|
+
const guard = !this.reading.has(type.id);
|
|
2823
|
+
if (guard) this.reading.add(type.id);
|
|
2824
|
+
try {
|
|
2825
|
+
const checker = this.checker;
|
|
2826
|
+
const fields = [];
|
|
2827
|
+
const outside = (what) => refuse(`type ${name} is outside the subset: ${what}`);
|
|
2828
|
+
for (const p of type.getProperties()) {
|
|
2829
|
+
if (isSymbolKey(p.name)) return outside("a field keyed by a symbol");
|
|
2830
|
+
if ((p.flags & SymbolFlags.Optional) !== 0) return outside(`optional field ${p.name}`);
|
|
2831
|
+
if ((p.flags & SymbolFlags.Method) !== 0) return outside(`a method ${p.name}`);
|
|
2832
|
+
if ((p.flags & (SymbolFlags.GetAccessor | SymbolFlags.SetAccessor)) !== 0) return outside(`an accessor ${p.name}`);
|
|
2833
|
+
if (structureNames.has(p.name)) return outside(`field ${p.name} takes a name Lean's structures reserve`);
|
|
2834
|
+
if (p.name === "__proto__") return outside("a field named __proto__, which JavaScript treats specially");
|
|
2835
|
+
const fieldType = checker.getTypeOfSymbol(p);
|
|
2836
|
+
const read = this.of(fieldType, (what) => outside(`field ${p.name}: ${what}`));
|
|
2837
|
+
const literal = fieldType.isStringLiteralType() ? fieldType.value : fieldType.isBooleanLiteralType() ? fieldType.value : void 0;
|
|
2838
|
+
fields.push({
|
|
2839
|
+
name: p.name,
|
|
2840
|
+
type: read,
|
|
2841
|
+
...literal === void 0 ? {} : { literal }
|
|
2842
|
+
});
|
|
2843
|
+
}
|
|
2844
|
+
return fields;
|
|
2845
|
+
} finally {
|
|
2846
|
+
if (guard) this.reading.delete(type.id);
|
|
2847
|
+
}
|
|
2848
|
+
}
|
|
2849
|
+
};
|
|
2850
|
+
// packages/prover/src/reader/subset.ts
|
|
2851
|
+
/** The path a module read from text alone is compiled under: an import of another file does not resolve from it. */
|
|
2852
|
+
const virtualModulePath = "/eutaxy/reader/module.ts";
|
|
2853
|
+
/** What typing a module's expressions needs, shared by every function read. */
|
|
2854
|
+
function moduleContext(records, unions) {
|
|
2855
|
+
const signatures = /* @__PURE__ */ new Map();
|
|
2856
|
+
return {
|
|
2857
|
+
ctx: {
|
|
2858
|
+
records,
|
|
2859
|
+
unions,
|
|
2860
|
+
signatures
|
|
2861
|
+
},
|
|
2862
|
+
signatures
|
|
2863
|
+
};
|
|
2864
|
+
}
|
|
2865
|
+
/** The contextual type the compiler gives a record literal, as the subset reads it; undefined where it has none the subset takes. */
|
|
2866
|
+
function contextualType(checker, types, node) {
|
|
2867
|
+
const type = checker.getContextualType(node);
|
|
2868
|
+
if (!type) return void 0;
|
|
2869
|
+
const fromLiteral = (t) => t.isObjectType() && t.getSymbol()?.name === InternalSymbolName.Object;
|
|
2870
|
+
if (fromLiteral(type) || type.isUnionType() && type.getTypes().some(fromLiteral)) return void 0;
|
|
2871
|
+
const skip = Symbol("outside");
|
|
2872
|
+
try {
|
|
2873
|
+
const read = types.of(type, () => {
|
|
2874
|
+
throw skip;
|
|
2875
|
+
});
|
|
2876
|
+
return read.kind === "nullable" ? read.inner : read;
|
|
2877
|
+
} catch (err) {
|
|
2878
|
+
if (err === skip) return void 0;
|
|
2879
|
+
throw err;
|
|
2880
|
+
}
|
|
2881
|
+
}
|
|
2882
|
+
/**
|
|
2883
|
+
* Read a module: every function the subset takes (in source order, so
|
|
2884
|
+
* callees come before callers), the record types and unions they use,
|
|
2885
|
+
* and, for the other functions, why not. A function calling one outside
|
|
2886
|
+
* the subset is outside it too. The names given are what the caller
|
|
2887
|
+
* cares about; one the module does not declare at its top level is
|
|
2888
|
+
* reported among the others, not thrown.
|
|
2889
|
+
*/
|
|
2890
|
+
function readSubset(source, functions, options = {}) {
|
|
2891
|
+
const path = options.path ?? virtualModulePath;
|
|
2892
|
+
return withProgram([{
|
|
2893
|
+
path,
|
|
2894
|
+
text: source
|
|
2895
|
+
}, ...options.files ?? []], ({ checker, file, parseError, typeErrors, standardGlobal }) => {
|
|
2896
|
+
const sf = file(path);
|
|
2897
|
+
const own = fileFunctions(sf, checker, standardGlobal);
|
|
2898
|
+
const { declarations, overloaded } = own;
|
|
2899
|
+
const declared = new Set(declarations.keys());
|
|
2900
|
+
const generic = new Set([...declarations].filter(([, d]) => d.node.typeParameters).map(([name]) => name));
|
|
2901
|
+
const outside = /* @__PURE__ */ new Map();
|
|
2902
|
+
const error = parseError(path);
|
|
2903
|
+
if (error) {
|
|
2904
|
+
for (const name of /* @__PURE__ */ new Set([...declared, ...functions ?? []])) outside.set(name, {
|
|
2905
|
+
name,
|
|
2906
|
+
line: 0,
|
|
2907
|
+
message: `the module could not be parsed: ${error.message} (line ${error.line})`
|
|
2908
|
+
});
|
|
2909
|
+
return {
|
|
2910
|
+
records: [],
|
|
2911
|
+
unions: [],
|
|
2912
|
+
functions: [],
|
|
2913
|
+
outside: [...outside.values()]
|
|
2914
|
+
};
|
|
2915
|
+
}
|
|
2916
|
+
for (const name of functions ?? []) if (!declared.has(name)) outside.set(name, {
|
|
2917
|
+
name,
|
|
2918
|
+
line: 0,
|
|
2919
|
+
message: `the module declares no function ${name} at its top level`
|
|
2920
|
+
});
|
|
2921
|
+
for (const [name, why] of own.untrusted) if (!outside.has(name)) outside.set(name, why);
|
|
2922
|
+
const types = new SubsetTypes(checker);
|
|
2923
|
+
const skip = Symbol("outside");
|
|
2924
|
+
for (const st of sf.statements) {
|
|
2925
|
+
if (!is.isInterfaceDeclaration(st) && !is.isTypeAliasDeclaration(st)) continue;
|
|
2926
|
+
if (st.typeParameters) continue;
|
|
2927
|
+
const symbol = checker.getSymbolAtLocation(st.name);
|
|
2928
|
+
if (!symbol) continue;
|
|
2929
|
+
try {
|
|
2930
|
+
types.of(checker.getDeclaredTypeOfSymbol(symbol), () => {
|
|
2931
|
+
throw skip;
|
|
2932
|
+
});
|
|
2933
|
+
} catch (err) {
|
|
2934
|
+
if (err !== skip) throw err;
|
|
2935
|
+
}
|
|
2936
|
+
}
|
|
2937
|
+
const { ctx, signatures } = moduleContext(types.records, types.unions);
|
|
2938
|
+
const names = {
|
|
2939
|
+
callable: (n) => declared.has(n) && !generic.has(n),
|
|
2940
|
+
target: (n) => n,
|
|
2941
|
+
declared: (n) => declared.has(n),
|
|
2942
|
+
spec: false,
|
|
2943
|
+
global: standardGlobal
|
|
2944
|
+
};
|
|
2945
|
+
const typeSource = {
|
|
2946
|
+
annotation: (node, refuse) => types.of(checker.getTypeAtLocation(node), refuse),
|
|
2947
|
+
contextual: (node) => contextualType(checker, types, node)
|
|
2948
|
+
};
|
|
2949
|
+
const { inline, constant } = inliner({
|
|
2950
|
+
checker,
|
|
2951
|
+
types,
|
|
2952
|
+
typeSource,
|
|
2953
|
+
ctx,
|
|
2954
|
+
module: sf,
|
|
2955
|
+
own,
|
|
2956
|
+
parseError,
|
|
2957
|
+
typeErrors,
|
|
2958
|
+
standardGlobal
|
|
2959
|
+
});
|
|
2960
|
+
const reader = new ExprReader(sf, names, typeSource, ctx, void 0, inline, constant);
|
|
2961
|
+
const heads = [];
|
|
2962
|
+
for (const [name, decl] of declarations) try {
|
|
2963
|
+
if (overloaded.has(name)) reader.fail(`${name} is declared more than once (overloads)`, decl.statement);
|
|
2964
|
+
const h = head(reader, types, checker, decl);
|
|
2965
|
+
signatures.set(name, {
|
|
2966
|
+
params: h.params,
|
|
2967
|
+
returns: h.returns
|
|
2968
|
+
});
|
|
2969
|
+
if (!outside.has(name)) heads.push(h);
|
|
2970
|
+
} catch (err) {
|
|
2971
|
+
if (!(err instanceof OutsideSubset)) throw err;
|
|
2972
|
+
if (!outside.has(name)) outside.set(name, {
|
|
2973
|
+
name,
|
|
2974
|
+
line: err.line,
|
|
2975
|
+
message: err.message
|
|
2976
|
+
});
|
|
2977
|
+
}
|
|
2978
|
+
const read = /* @__PURE__ */ new Map();
|
|
2979
|
+
for (const h of heads) try {
|
|
2980
|
+
const fn = declaration(reader, h);
|
|
2981
|
+
const bad = notCompiled(sf, typeErrors, rangeOf(declarations.get(h.name)));
|
|
2982
|
+
if (bad) throw new OutsideSubset(bad.message, bad.line);
|
|
2983
|
+
read.set(h.name, fn);
|
|
2984
|
+
} catch (err) {
|
|
2985
|
+
if (!(err instanceof OutsideSubset)) throw err;
|
|
2986
|
+
outside.set(h.name, {
|
|
2987
|
+
name: h.name,
|
|
2988
|
+
line: err.line,
|
|
2989
|
+
message: err.message
|
|
2990
|
+
});
|
|
2991
|
+
}
|
|
2992
|
+
closeOverCallees(read, outside);
|
|
2993
|
+
const reaches = (from, target, seen = /* @__PURE__ */ new Set()) => {
|
|
2994
|
+
const fn = read.get(from);
|
|
2995
|
+
if (!fn) return false;
|
|
2996
|
+
for (const c of callees(fn.body)) {
|
|
2997
|
+
if (c === target) return true;
|
|
2998
|
+
if (!seen.has(c)) {
|
|
2999
|
+
seen.add(c);
|
|
3000
|
+
if (reaches(c, target, seen)) return true;
|
|
3001
|
+
}
|
|
3002
|
+
}
|
|
3003
|
+
return false;
|
|
3004
|
+
};
|
|
3005
|
+
for (const [name, fn] of [...read]) if (reaches(name, name)) {
|
|
3006
|
+
const on = [...callees(fn.body)].every((c) => c === name || !reaches(c, name)) ? structuralOn(fn) : void 0;
|
|
3007
|
+
if (on !== void 0) {
|
|
3008
|
+
read.set(name, {
|
|
3009
|
+
...fn,
|
|
3010
|
+
structural: on
|
|
3011
|
+
});
|
|
3012
|
+
continue;
|
|
3013
|
+
}
|
|
3014
|
+
read.delete(name);
|
|
3015
|
+
outside.set(name, {
|
|
3016
|
+
name,
|
|
3017
|
+
line: fn.line,
|
|
3018
|
+
message: `${name} is recursive in a way the subset does not take: it takes a function calling itself on a list parameter's slice(1), after a first test of that list's length against 0 (if (xs.length === 0) return …)`
|
|
3019
|
+
});
|
|
3020
|
+
}
|
|
3021
|
+
closeOverCallees(read, outside);
|
|
3022
|
+
const ordered = [];
|
|
3023
|
+
const placed = /* @__PURE__ */ new Set();
|
|
3024
|
+
while (ordered.length < read.size) for (const [name, fn] of read) if (!placed.has(name) && [...callees(fn.body)].every((c) => c === name || placed.has(c))) {
|
|
3025
|
+
ordered.push(fn);
|
|
3026
|
+
placed.add(name);
|
|
3027
|
+
}
|
|
3028
|
+
return {
|
|
3029
|
+
records: [...types.records.values()],
|
|
3030
|
+
unions: types.unions,
|
|
3031
|
+
functions: ordered,
|
|
3032
|
+
outside: [...outside.values()]
|
|
3033
|
+
};
|
|
3034
|
+
});
|
|
3035
|
+
}
|
|
3036
|
+
/** A caller of a function outside the subset is outside it too, however many steps away. */
|
|
3037
|
+
function closeOverCallees(read, outside) {
|
|
3038
|
+
for (let changed = true; changed;) {
|
|
3039
|
+
changed = false;
|
|
3040
|
+
for (const [name, fn] of read) {
|
|
3041
|
+
const bad = [...callees(fn.body)].find((c) => outside.has(c));
|
|
3042
|
+
if (bad === void 0) continue;
|
|
3043
|
+
read.delete(name);
|
|
3044
|
+
outside.set(name, {
|
|
3045
|
+
name,
|
|
3046
|
+
line: fn.line,
|
|
3047
|
+
message: `calls ${bad}, which is outside the subset: ${outside.get(bad)?.message}`
|
|
3048
|
+
});
|
|
3049
|
+
changed = true;
|
|
3050
|
+
}
|
|
3051
|
+
}
|
|
3052
|
+
}
|
|
3053
|
+
/**
|
|
3054
|
+
* A reader over text that is not the module: with `aliases`, the text is
|
|
3055
|
+
* a spec file's, whose names for the module's functions are its own
|
|
3056
|
+
* imports and nothing else; without, the text sees the module's names.
|
|
3057
|
+
* No compiler stands behind the text, so a `const` annotation is read
|
|
3058
|
+
* from its syntax against the module's declared types, and a record
|
|
3059
|
+
* literal has no contextual type. Lines are not reported: the text's
|
|
3060
|
+
* position is the caller's to know.
|
|
3061
|
+
*/
|
|
3062
|
+
function arrowReader(sf, module, aliases) {
|
|
3063
|
+
const records = new Map(module.records.map((rec) => [rec.name, rec]));
|
|
3064
|
+
const unionNames = new Set(module.unions.map((u) => u.name));
|
|
3065
|
+
const inSubset = new Set(module.functions.map((f) => f.name));
|
|
3066
|
+
let names;
|
|
3067
|
+
if (aliases) {
|
|
3068
|
+
const declared = new Set(aliases.keys());
|
|
3069
|
+
const callable = new Set([...aliases].filter(([, fn]) => inSubset.has(fn)).map(([local]) => local));
|
|
3070
|
+
names = {
|
|
3071
|
+
callable: (n) => callable.has(n),
|
|
3072
|
+
target: (n) => aliases.get(n) ?? n,
|
|
3073
|
+
declared: (n) => declared.has(n),
|
|
3074
|
+
spec: true,
|
|
3075
|
+
global: () => true
|
|
3076
|
+
};
|
|
3077
|
+
} else {
|
|
3078
|
+
const declared = /* @__PURE__ */ new Set([...inSubset, ...module.outside.map((o) => o.name)]);
|
|
3079
|
+
names = {
|
|
3080
|
+
callable: (n) => inSubset.has(n),
|
|
3081
|
+
target: (n) => n,
|
|
3082
|
+
declared: (n) => declared.has(n),
|
|
3083
|
+
spec: false,
|
|
3084
|
+
global: () => true
|
|
3085
|
+
};
|
|
3086
|
+
}
|
|
3087
|
+
const recordNames = new Set(records.keys());
|
|
3088
|
+
const typeSource = {
|
|
3089
|
+
annotation: (node, refuse) => syntacticType(sf, node, recordNames, unionNames, refuse),
|
|
3090
|
+
contextual: () => void 0
|
|
3091
|
+
};
|
|
3092
|
+
const signatures = new Map(module.functions.map((f) => [f.name, {
|
|
3093
|
+
params: f.params,
|
|
3094
|
+
returns: f.returns
|
|
3095
|
+
}]));
|
|
3096
|
+
return new ExprReader(sf, names, typeSource, {
|
|
3097
|
+
records,
|
|
3098
|
+
unions: module.unions,
|
|
3099
|
+
signatures
|
|
3100
|
+
}, () => 0);
|
|
3101
|
+
}
|
|
3102
|
+
/** The one expression a fragment `(text)` parsed to, or why the text is not one expression. */
|
|
3103
|
+
function fragmentExpression(sf) {
|
|
3104
|
+
const [first, second] = sf.statements;
|
|
3105
|
+
if (second) throw new OutsideSubset(`unexpected ${textOf(sf, second)} after the expression`, 0);
|
|
3106
|
+
if (!first || !is.isExpressionStatement(first) || !is.isParenthesizedExpression(first.expression)) throw new OutsideSubset("could not be parsed as an expression", 0);
|
|
3107
|
+
let broken;
|
|
3108
|
+
const visit = (node) => {
|
|
3109
|
+
if (broken !== void 0) return;
|
|
3110
|
+
if (is.isIdentifier(node) && node.text === "") broken = "could not be parsed (something is missing)";
|
|
3111
|
+
node.forEachChild(visit);
|
|
3112
|
+
};
|
|
3113
|
+
visit(first);
|
|
3114
|
+
if (broken !== void 0) throw new OutsideSubset(broken, 0);
|
|
3115
|
+
return first.expression.expression;
|
|
3116
|
+
}
|
|
3117
|
+
/**
|
|
3118
|
+
* One TypeScript expression (a claim's body, say) in a scope of typed
|
|
3119
|
+
* names, over a module already read. The whole text must be the
|
|
3120
|
+
* expression.
|
|
3121
|
+
*/
|
|
3122
|
+
function readExpression(text, scope, module, aliases) {
|
|
3123
|
+
return withSourceFile(`(${text}\n)`, (sf) => {
|
|
3124
|
+
const expr = fragmentExpression(sf);
|
|
3125
|
+
return arrowReader(sf, module, aliases).expression(expr, scope);
|
|
3126
|
+
});
|
|
3127
|
+
}
|
|
3128
|
+
/**
|
|
3129
|
+
* The body of a spec file's arrow (`when` or `ensures`) as a boolean
|
|
3130
|
+
* expression: an expression body as it is, a block body through the same
|
|
3131
|
+
* statement reader as a function body (`const`, `if`, early returns).
|
|
3132
|
+
* The scope maps the arrow's own parameter names to the binders' types;
|
|
3133
|
+
* `aliases` maps the spec file's local names to the module's functions,
|
|
3134
|
+
* and a free name that is neither is outside the subset: the spec file's
|
|
3135
|
+
* scope is its imports, never the module's. `Math` and `Number` are the
|
|
3136
|
+
* globals wherever the arrow's own scope does not bind them: `readSpecs`
|
|
3137
|
+
* has checked that every built-in a claim names resolves to the standard
|
|
3138
|
+
* library in the spec file.
|
|
3139
|
+
*/
|
|
3140
|
+
function readArrowBody(arrow, scope, module, aliases = /* @__PURE__ */ new Map()) {
|
|
3141
|
+
if (!arrow.block) return withSourceFile(`(${arrow.body}\n)`, (sf) => {
|
|
3142
|
+
const expr = fragmentExpression(sf);
|
|
3143
|
+
const reader = arrowReader(sf, module, aliases);
|
|
3144
|
+
return reader.narrowed(reader.expression(expr, scope), scope, sf);
|
|
3145
|
+
});
|
|
3146
|
+
return withSourceFile(`{${arrow.body}\n}`, (sf) => {
|
|
3147
|
+
const block = blockOf(sf);
|
|
3148
|
+
if (!block) throw new OutsideSubset("could not be parsed as a block", 0);
|
|
3149
|
+
const reader = arrowReader(sf, module, aliases);
|
|
3150
|
+
return reader.narrowed(reader.block(block.statements, new Map(scope), block), scope, sf);
|
|
3151
|
+
});
|
|
3152
|
+
}
|
|
3153
|
+
/**
|
|
3154
|
+
* The list parameter a function recurses on structurally, or undefined:
|
|
3155
|
+
* its body is `if (p.length === 0) … else …` for a list parameter p, the
|
|
3156
|
+
* test and the first branch do not call it, and every call to it in the
|
|
3157
|
+
* other branch passes `p.slice(1)` for p. Lean takes such a definition as
|
|
3158
|
+
* a match on `[]` and `head :: tail`, recursing on the tail.
|
|
3159
|
+
*/
|
|
3160
|
+
function structuralOn(fn) {
|
|
3161
|
+
const body = fn.body;
|
|
3162
|
+
if (body.kind !== "cond") return void 0;
|
|
3163
|
+
const t = body.test;
|
|
3164
|
+
if (t.kind !== "binary" || t.op !== "===") return void 0;
|
|
3165
|
+
const sides = [t.left, t.right];
|
|
3166
|
+
const zero = sides.find((x) => x.kind === "int" && x.value === "0");
|
|
3167
|
+
const len = sides.find((x) => x !== zero);
|
|
3168
|
+
if (!zero || len?.kind !== "field" || len.field !== "length" || len.object.kind !== "var") return void 0;
|
|
3169
|
+
const list = len.object.name;
|
|
3170
|
+
const at = fn.params.findIndex((p) => p.name === list && p.type.kind === "list");
|
|
3171
|
+
if (at < 0) return void 0;
|
|
3172
|
+
if (callees(t).has(fn.name) || callees(body.ifTrue).has(fn.name)) return void 0;
|
|
3173
|
+
const calls = selfCalls(body.ifFalse, fn.name);
|
|
3174
|
+
const onTail = (a) => a?.kind === "tail" && a.list.kind === "var" && a.list.name === list;
|
|
3175
|
+
return calls.length > 0 && calls.every((c) => onTail(c.args[at])) ? at : void 0;
|
|
3176
|
+
}
|
|
3177
|
+
/** Every call to `name` in an expression. */
|
|
3178
|
+
function selfCalls(e, name) {
|
|
3179
|
+
const out = [];
|
|
3180
|
+
const walk = (x) => {
|
|
3181
|
+
if (x.kind === "call" && x.callee === name) out.push(x);
|
|
3182
|
+
for (const child of children(x)) walk(child);
|
|
3183
|
+
};
|
|
3184
|
+
walk(e);
|
|
3185
|
+
return out;
|
|
3186
|
+
}
|
|
3187
|
+
// packages/prover/src/reader/engine.ts
|
|
3188
|
+
/**
|
|
3189
|
+
* Read a module for an engine: the functions asked for (every one with
|
|
3190
|
+
* specs when none are named), the subset restricted by each of the
|
|
3191
|
+
* engine's restrictions in order, and the functions outside it, by the
|
|
3192
|
+
* reader's reason or because the spec names a declaration that is not the
|
|
3193
|
+
* module's top-level one of that name.
|
|
3194
|
+
*/
|
|
3195
|
+
function readForEngine(input, restrictions) {
|
|
3196
|
+
const wanted = input.functions ? new Set(input.functions) : void 0;
|
|
3197
|
+
const fns = input.specs.functions.filter((f) => !wanted || wanted.has(f.name));
|
|
3198
|
+
let module = readSubset(input.source, fns.map((f) => f.name), input.modulePath === void 0 ? {} : { path: input.modulePath });
|
|
3199
|
+
for (const r of restrictions) module = restrictModule(module, r.takes, r.reason, r.bodies, r.refused);
|
|
3200
|
+
const outside = /* @__PURE__ */ new Map();
|
|
3201
|
+
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}`);
|
|
3202
|
+
for (const fn of fns) {
|
|
3203
|
+
const read = module.functions.find((f) => f.name === fn.name);
|
|
3204
|
+
if (read && read.offset !== fn.offset) outside.set(fn.name, `outside the engine's subset (line ${fn.line}): the ${fn.name} the spec names is not the module's top-level declaration of that name (line ${read.line})`);
|
|
3205
|
+
}
|
|
3206
|
+
return {
|
|
3207
|
+
module,
|
|
3208
|
+
fns,
|
|
3209
|
+
outside
|
|
3210
|
+
};
|
|
3211
|
+
}
|
|
3212
|
+
/**
|
|
3213
|
+
* The emitter refused something the reader let through: an engine gap, so
|
|
3214
|
+
* every function is outside with that reason and none is guessed.
|
|
3215
|
+
*/
|
|
3216
|
+
function engineGap(read, message) {
|
|
3217
|
+
for (const fn of read.fns) read.outside.set(fn.name, `outside the engine's subset: ${message}`);
|
|
3218
|
+
}
|
|
3219
|
+
/** The outcomes of the functions outside the engine's subset: `unsupported`, each with its reason. */
|
|
3220
|
+
function outsideProofs(fns, outside) {
|
|
3221
|
+
return proofsOf(fns.filter((f) => outside.has(f.name)), (f) => unknownOutcome("unsupported", outside.get(f.name)));
|
|
3222
|
+
}
|
|
3223
|
+
// packages/prover/src/reader/specs.ts
|
|
3224
|
+
/** The parameters of a function-like declaration: `name?: T = default`, `...rest`, destructured. */
|
|
3225
|
+
function readParams(checker, fn) {
|
|
3226
|
+
const params = [];
|
|
3227
|
+
for (const p of fn.parameters) {
|
|
3228
|
+
const name = is.isIdentifier(p.name) ? p.name.text : null;
|
|
3229
|
+
if (name === "this") continue;
|
|
3230
|
+
if (p.dotDotDotToken) {
|
|
3231
|
+
params.push({
|
|
3232
|
+
name: null,
|
|
3233
|
+
type: {
|
|
3234
|
+
kind: "unknown",
|
|
3235
|
+
text: `...${name ?? ""}`
|
|
3236
|
+
}
|
|
3237
|
+
});
|
|
3238
|
+
continue;
|
|
3239
|
+
}
|
|
3240
|
+
let type;
|
|
3241
|
+
if (p.type) type = specTypeOf(checker, checker.getTypeAtLocation(p.type));
|
|
3242
|
+
else if (p.initializer) type = specTypeOf(checker, checker.getTypeAtLocation(p));
|
|
3243
|
+
else type = {
|
|
3244
|
+
kind: "unknown",
|
|
3245
|
+
text: "(no type annotation)"
|
|
3246
|
+
};
|
|
3247
|
+
if (p.questionToken || p.initializer) type = unionOf([type, { kind: "undefined" }]);
|
|
3248
|
+
params.push({
|
|
3249
|
+
name,
|
|
3250
|
+
type
|
|
3251
|
+
});
|
|
3252
|
+
}
|
|
3253
|
+
return params;
|
|
3254
|
+
}
|
|
3255
|
+
function readModuleSide(sf, checker) {
|
|
3256
|
+
const errors = [];
|
|
3257
|
+
const declarations = /* @__PURE__ */ new Map();
|
|
3258
|
+
const exports = /* @__PURE__ */ new Map();
|
|
3259
|
+
const declare = (name, fn, at) => {
|
|
3260
|
+
const offset = openParen(sf, fn);
|
|
3261
|
+
if (offset === void 0) return;
|
|
3262
|
+
if (declarations.has(name)) {
|
|
3263
|
+
errors.push({
|
|
3264
|
+
line: lineAt(sf, at),
|
|
3265
|
+
message: `${name} is declared more than once (overloads): a spec is checked against one signature`,
|
|
3266
|
+
inModule: true
|
|
3267
|
+
});
|
|
3268
|
+
return;
|
|
3269
|
+
}
|
|
3270
|
+
declarations.set(name, {
|
|
3271
|
+
name,
|
|
3272
|
+
params: readParams(checker, fn),
|
|
3273
|
+
line: lineAt(sf, at),
|
|
3274
|
+
offset
|
|
3275
|
+
});
|
|
3276
|
+
};
|
|
3277
|
+
for (const st of sf.statements) {
|
|
3278
|
+
if (is.isFunctionDeclaration(st)) {
|
|
3279
|
+
if (!st.name) continue;
|
|
3280
|
+
declare(st.name.text, st, st);
|
|
3281
|
+
if (isExported(st)) exports.set(st.name.text, st.name.text);
|
|
3282
|
+
continue;
|
|
3283
|
+
}
|
|
3284
|
+
if (is.isVariableStatement(st)) {
|
|
3285
|
+
for (const d of st.declarationList.declarations) {
|
|
3286
|
+
if (!is.isIdentifier(d.name) || !d.initializer) continue;
|
|
3287
|
+
let init = d.initializer;
|
|
3288
|
+
while (is.isParenthesizedExpression(init)) init = init.expression;
|
|
3289
|
+
if (!is.isArrowFunction(init) && !is.isFunctionExpression(init)) continue;
|
|
3290
|
+
declare(d.name.text, init, st);
|
|
3291
|
+
if (isExported(st)) exports.set(d.name.text, d.name.text);
|
|
3292
|
+
}
|
|
3293
|
+
continue;
|
|
3294
|
+
}
|
|
3295
|
+
if (is.isExportDeclaration(st) && !st.moduleSpecifier && !st.isTypeOnly && st.exportClause) {
|
|
3296
|
+
if (!is.isNamedExports(st.exportClause)) continue;
|
|
3297
|
+
for (const e of st.exportClause.elements) {
|
|
3298
|
+
if (e.isTypeOnly) continue;
|
|
3299
|
+
const local = e.propertyName ?? e.name;
|
|
3300
|
+
if (is.isIdentifier(local) && is.isIdentifier(e.name)) exports.set(e.name.text, local.text);
|
|
3301
|
+
}
|
|
3302
|
+
}
|
|
3303
|
+
}
|
|
3304
|
+
return {
|
|
3305
|
+
declarations,
|
|
3306
|
+
exports,
|
|
3307
|
+
errors
|
|
3308
|
+
};
|
|
3309
|
+
}
|
|
3310
|
+
/** `import { a, b as c } from "x"`, `import * as ns from "x"`, `import d from "x"`; type-only imports skipped. */
|
|
3311
|
+
function imports(sf) {
|
|
3312
|
+
const out = /* @__PURE__ */ new Map();
|
|
3313
|
+
for (const st of sf.statements) {
|
|
3314
|
+
if (!is.isImportDeclaration(st) || !st.importClause) continue;
|
|
3315
|
+
const clause = st.importClause;
|
|
3316
|
+
if (clause.phaseModifier === SyntaxKind.TypeKeyword) continue;
|
|
3317
|
+
if (!is.isStringLiteral(st.moduleSpecifier)) continue;
|
|
3318
|
+
const from = st.moduleSpecifier.text;
|
|
3319
|
+
if (clause.name) out.set(clause.name.text, {
|
|
3320
|
+
from,
|
|
3321
|
+
name: "default",
|
|
3322
|
+
declaration: st
|
|
3323
|
+
});
|
|
3324
|
+
const bindings = clause.namedBindings;
|
|
3325
|
+
if (!bindings) continue;
|
|
3326
|
+
if (is.isNamespaceImport(bindings)) out.set(bindings.name.text, {
|
|
3327
|
+
from,
|
|
3328
|
+
name: "*",
|
|
3329
|
+
declaration: st
|
|
3330
|
+
});
|
|
3331
|
+
else for (const e of bindings.elements) {
|
|
3332
|
+
if (e.isTypeOnly) continue;
|
|
3333
|
+
const imported = e.propertyName ?? e.name;
|
|
3334
|
+
const name = is.isIdentifier(imported) ? imported.text : imported.text;
|
|
3335
|
+
out.set(e.name.text, {
|
|
3336
|
+
from,
|
|
3337
|
+
name,
|
|
3338
|
+
declaration: st
|
|
3339
|
+
});
|
|
3340
|
+
}
|
|
3341
|
+
}
|
|
3342
|
+
return out;
|
|
3343
|
+
}
|
|
3344
|
+
/** `1`, `-1`, `1_000`, `1.5`, `10n` as an endpoint value; undefined otherwise. */
|
|
3345
|
+
function numberText(sf, node) {
|
|
3346
|
+
if (is.isNumericLiteral(node) || is.isBigIntLiteral(node)) return textOf(sf, node).replace(/_/g, "");
|
|
3347
|
+
if (is.isPrefixUnaryExpression(node) && node.operator === SyntaxKind.MinusToken && (is.isNumericLiteral(node.operand) || is.isBigIntLiteral(node.operand))) return `-${textOf(sf, node.operand).replace(/_/g, "")}`;
|
|
3348
|
+
}
|
|
3349
|
+
/** The top-level conjuncts of an expression, parentheses stripped. */
|
|
3350
|
+
function conjuncts(node, out = []) {
|
|
3351
|
+
let e = node;
|
|
3352
|
+
while (is.isParenthesizedExpression(e)) e = e.expression;
|
|
3353
|
+
if (is.isBinaryExpression(e) && e.operatorToken.kind === SyntaxKind.AmpersandAmpersandToken) {
|
|
3354
|
+
conjuncts(e.left, out);
|
|
3355
|
+
conjuncts(e.right, out);
|
|
3356
|
+
} else out.push(e);
|
|
3357
|
+
return out;
|
|
3358
|
+
}
|
|
3359
|
+
const comparisons = {
|
|
3360
|
+
[SyntaxKind.LessThanToken]: "<",
|
|
3361
|
+
[SyntaxKind.LessThanEqualsToken]: "<=",
|
|
3362
|
+
[SyntaxKind.GreaterThanToken]: ">",
|
|
3363
|
+
[SyntaxKind.GreaterThanEqualsToken]: ">="
|
|
3364
|
+
};
|
|
3365
|
+
/**
|
|
3366
|
+
* What an expression says about each of the named parameters on its own:
|
|
3367
|
+
* its top-level conjuncts of the forms `Number.isInteger(x)`, `x < n`,
|
|
3368
|
+
* `n <= x` (and the other comparisons) and `/re/.test(x)`, by parameter
|
|
3369
|
+
* index.
|
|
3370
|
+
*/
|
|
3371
|
+
function hintsIn(sf, body, params) {
|
|
3372
|
+
const out = /* @__PURE__ */ new Map();
|
|
3373
|
+
const position = /* @__PURE__ */ new Map();
|
|
3374
|
+
params.forEach((p, i) => {
|
|
3375
|
+
if (p !== null) position.set(p, i);
|
|
3376
|
+
});
|
|
3377
|
+
const merge = (i, h) => {
|
|
3378
|
+
const old = out.get(i) ?? {};
|
|
3379
|
+
out.set(i, {
|
|
3380
|
+
...old,
|
|
3381
|
+
...h
|
|
3382
|
+
});
|
|
3383
|
+
};
|
|
3384
|
+
for (const conjunct of conjuncts(body)) {
|
|
3385
|
+
if (is.isCallExpression(conjunct)) {
|
|
3386
|
+
const callee = conjunct.expression;
|
|
3387
|
+
const [arg, extra] = conjunct.arguments;
|
|
3388
|
+
if (!is.isPropertyAccessExpression(callee) || !is.isIdentifier(callee.name) || !arg || extra) continue;
|
|
3389
|
+
if (!is.isIdentifier(arg)) continue;
|
|
3390
|
+
const at = position.get(arg.text);
|
|
3391
|
+
if (at === void 0) continue;
|
|
3392
|
+
if (is.isIdentifier(callee.expression) && callee.expression.text === "Number" && callee.name.text === "isInteger") merge(at, { integer: true });
|
|
3393
|
+
else if (is.isRegularExpressionLiteral(callee.expression) && callee.name.text === "test") {
|
|
3394
|
+
const m = /^\/([\s\S]*)\/([a-z]*)$/.exec(textOf(sf, callee.expression));
|
|
3395
|
+
if (m) merge(at, { regex: {
|
|
3396
|
+
pattern: m[1],
|
|
3397
|
+
flags: m[2]
|
|
3398
|
+
} });
|
|
3399
|
+
}
|
|
3400
|
+
continue;
|
|
3401
|
+
}
|
|
3402
|
+
if (!is.isBinaryExpression(conjunct)) continue;
|
|
3403
|
+
const op = comparisons[conjunct.operatorToken.kind];
|
|
3404
|
+
if (op === void 0) continue;
|
|
3405
|
+
const bound = (variable, literal, variableOnLeft) => {
|
|
3406
|
+
if (!is.isIdentifier(variable)) return;
|
|
3407
|
+
const value = numberText(sf, literal);
|
|
3408
|
+
if (value === void 0) return;
|
|
3409
|
+
const at = position.get(variable.text);
|
|
3410
|
+
if (at === void 0) return;
|
|
3411
|
+
const above = variableOnLeft ? op.startsWith("<") : op.startsWith(">");
|
|
3412
|
+
const endpoint = {
|
|
3413
|
+
value,
|
|
3414
|
+
inclusive: op.endsWith("=")
|
|
3415
|
+
};
|
|
3416
|
+
merge(at, above ? { upper: endpoint } : { lower: endpoint });
|
|
3417
|
+
};
|
|
3418
|
+
if (is.isIdentifier(conjunct.left)) bound(conjunct.left, conjunct.right, true);
|
|
3419
|
+
else if (is.isIdentifier(conjunct.right)) bound(conjunct.right, conjunct.left, false);
|
|
3420
|
+
}
|
|
3421
|
+
return out;
|
|
3422
|
+
}
|
|
3423
|
+
/**
|
|
3424
|
+
* What the precondition says about each of its parameters on its own,
|
|
3425
|
+
* read from the arrow's text: see `hintsIn`. A block body gives none.
|
|
3426
|
+
*/
|
|
3427
|
+
function hintsOf(arrow) {
|
|
3428
|
+
if (arrow.block) return /* @__PURE__ */ new Map();
|
|
3429
|
+
return withSourceFile(`(${arrow.body}\n)`, (sf) => {
|
|
3430
|
+
const [first, second] = sf.statements;
|
|
3431
|
+
if (second || !first || !is.isExpressionStatement(first)) return /* @__PURE__ */ new Map();
|
|
3432
|
+
let e = first.expression;
|
|
3433
|
+
while (is.isParenthesizedExpression(e)) e = e.expression;
|
|
3434
|
+
return hintsIn(sf, e, arrow.params);
|
|
3435
|
+
});
|
|
3436
|
+
}
|
|
3437
|
+
var SpecFail = class extends Error {
|
|
3438
|
+
line;
|
|
3439
|
+
constructor(message, line) {
|
|
3440
|
+
super(message);
|
|
3441
|
+
this.line = line;
|
|
3442
|
+
}
|
|
3443
|
+
};
|
|
3444
|
+
/** Read the spec file's exports. */
|
|
3445
|
+
function readSpecSide(sf, { program, checker, standardGlobal }, modulePath, moduleKey, specSpecifiers) {
|
|
3446
|
+
const errors = [];
|
|
3447
|
+
const bound = imports(sf);
|
|
3448
|
+
const specs = [];
|
|
3449
|
+
function fail(message, at) {
|
|
3450
|
+
throw new SpecFail(message, lineAt(sf, at));
|
|
3451
|
+
}
|
|
3452
|
+
const resolvesToModule = /* @__PURE__ */ new Map();
|
|
3453
|
+
const fromModule = (imp) => {
|
|
3454
|
+
const known = resolvesToModule.get(imp.from);
|
|
3455
|
+
if (known !== void 0) return known;
|
|
3456
|
+
const resolved = program.getResolvedModuleFromModuleSpecifier(imp.declaration.moduleSpecifier, sf.fileName);
|
|
3457
|
+
const target = resolved ? program.getSourceFile(resolved.resolvedFileName) : void 0;
|
|
3458
|
+
const is = target !== void 0 && target.path === moduleKey;
|
|
3459
|
+
resolvesToModule.set(imp.from, is);
|
|
3460
|
+
return is;
|
|
3461
|
+
};
|
|
3462
|
+
/** The combinator a callee names (`forall`, `ns.forall`), or undefined. */
|
|
3463
|
+
const combinator = (callee) => {
|
|
3464
|
+
if (is.isPropertyAccessExpression(callee)) {
|
|
3465
|
+
if (!is.isIdentifier(callee.expression) || !is.isIdentifier(callee.name)) return void 0;
|
|
3466
|
+
const ns = bound.get(callee.expression.text);
|
|
3467
|
+
const member = callee.name.text;
|
|
3468
|
+
if (ns?.name === "*" && specSpecifiers.has(ns.from) && (member === "forall" || member === "total")) return member;
|
|
3469
|
+
return;
|
|
3470
|
+
}
|
|
3471
|
+
if (!is.isIdentifier(callee)) return void 0;
|
|
3472
|
+
const imp = bound.get(callee.text);
|
|
3473
|
+
if (imp && specSpecifiers.has(imp.from) && (imp.name === "forall" || imp.name === "total")) return imp.name;
|
|
3474
|
+
};
|
|
3475
|
+
/** The module function a first argument names, or why not. */
|
|
3476
|
+
const functionArg = (arg, call) => {
|
|
3477
|
+
if (!arg) return fail("the first argument must name a function of the module, found the end", call);
|
|
3478
|
+
if (is.isPropertyAccessExpression(arg) && is.isIdentifier(arg.expression) && is.isIdentifier(arg.name)) {
|
|
3479
|
+
const ns = bound.get(arg.expression.text);
|
|
3480
|
+
if (ns?.name === "*" && fromModule(ns)) return arg.name.text;
|
|
3481
|
+
return fail(`${textOf(sf, arg)} is not a function imported from the module`, arg);
|
|
3482
|
+
}
|
|
3483
|
+
if (!is.isIdentifier(arg)) return fail(`the first argument must name a function of the module, found ${textOf(sf, arg)}`, arg);
|
|
3484
|
+
const imp = bound.get(arg.text);
|
|
3485
|
+
if (!imp) return fail(`${arg.text} is not imported from the module (import it from ./${modulePath.split("/").pop()})`, arg);
|
|
3486
|
+
if (!fromModule(imp)) return fail(`${arg.text} is imported from ${JSON.stringify(imp.from)}, not from the module beside this spec file`, arg);
|
|
3487
|
+
if (imp.name === "*" || imp.name === "default") return fail(`${arg.text} must be a named import of the module's function`, arg);
|
|
3488
|
+
return imp.name;
|
|
3489
|
+
};
|
|
3490
|
+
/**
|
|
3491
|
+
* A claim is read from its arrow's text alone, where `Math` and `Number`
|
|
3492
|
+
* are the globals unless the arrow binds them itself: an arrow naming
|
|
3493
|
+
* one that resolves to anything else here (a binding of the spec file,
|
|
3494
|
+
* an import, a const of the arrow's own block declared after the use)
|
|
3495
|
+
* is refused, so a claim is never read as something it does not
|
|
3496
|
+
* compute. A parameter or const of the arrow bound before the use is
|
|
3497
|
+
* the arrow reader's own name for it (a parameter named `Math` reads as
|
|
3498
|
+
* that parameter), and a binding the claims do not name, or a type-only
|
|
3499
|
+
* import, is fine.
|
|
3500
|
+
*/
|
|
3501
|
+
const builtins = (arrow, node, what) => {
|
|
3502
|
+
if (is.isPropertyAccessExpression(node) && is.isIdentifier(node.expression) && (node.expression.text === "Math" || node.expression.text === "Number") && !standardGlobal(node.expression)) {
|
|
3503
|
+
const id = node.expression;
|
|
3504
|
+
const bound = checker.getSymbolAtLocation(id)?.declarations[0]?.resolve();
|
|
3505
|
+
if (!(bound !== void 0 && bound.getSourceFile() === sf && bound.pos >= arrow.pos && bound.end <= arrow.end && bound.getStart(sf) < id.getStart(sf))) {
|
|
3506
|
+
const file = bound?.getSourceFile();
|
|
3507
|
+
const where = bound && file ? ` (bound at line ${lineAt(file, bound)}${file === sf ? "" : ` of ${file.fileName}`})` : "";
|
|
3508
|
+
fail(`${what} names ${id.text}, which is not the global ${id.text} here${where}; rename the binding`, id);
|
|
3509
|
+
}
|
|
3510
|
+
}
|
|
3511
|
+
node.forEachChild((child) => builtins(arrow, child, what));
|
|
3512
|
+
};
|
|
3513
|
+
/** An arrow function: its params, body text and whether the body is a block. */
|
|
3514
|
+
const arrow = (node, what) => {
|
|
3515
|
+
if (!is.isArrowFunction(node)) return fail(`${what} must be an arrow function, found ${textOf(sf, node).split(/\s/)[0] ?? ""}`, node);
|
|
3516
|
+
if (isAsync(node)) fail(`${what} is an async arrow; it must be synchronous`, node);
|
|
3517
|
+
builtins(node, node.body, what);
|
|
3518
|
+
const params = node.parameters.map((p) => !p.dotDotDotToken && is.isIdentifier(p.name) ? p.name.text : null);
|
|
3519
|
+
const body = node.body;
|
|
3520
|
+
const line = lineAt(sf, node);
|
|
3521
|
+
if (is.isBlock(body)) return {
|
|
3522
|
+
arrow: {
|
|
3523
|
+
params,
|
|
3524
|
+
body: sf.text.slice(body.getStart(sf) + 1, body.end - 1),
|
|
3525
|
+
block: true,
|
|
3526
|
+
line
|
|
3527
|
+
},
|
|
3528
|
+
node
|
|
3529
|
+
};
|
|
3530
|
+
return {
|
|
3531
|
+
arrow: {
|
|
3532
|
+
params,
|
|
3533
|
+
body: textOf(sf, body),
|
|
3534
|
+
block: false,
|
|
3535
|
+
line
|
|
3536
|
+
},
|
|
3537
|
+
node
|
|
3538
|
+
};
|
|
3539
|
+
};
|
|
3540
|
+
for (const st of sf.statements) {
|
|
3541
|
+
if (!is.isVariableStatement(st)) continue;
|
|
3542
|
+
const exported = isExported(st);
|
|
3543
|
+
const constant = isConst(st.declarationList);
|
|
3544
|
+
for (const d of st.declarationList.declarations) {
|
|
3545
|
+
if (!is.isIdentifier(d.name) || !d.initializer) continue;
|
|
3546
|
+
const name = d.name.text;
|
|
3547
|
+
let init = d.initializer;
|
|
3548
|
+
while (is.isParenthesizedExpression(init) || is.isSatisfiesExpression(init) || is.isAsExpression(init) || is.isNonNullExpression(init)) init = init.expression;
|
|
3549
|
+
if (!is.isCallExpression(init)) continue;
|
|
3550
|
+
const kind = combinator(init.expression);
|
|
3551
|
+
if (!kind) continue;
|
|
3552
|
+
const line = lineAt(sf, st);
|
|
3553
|
+
try {
|
|
3554
|
+
if (!exported) fail(`${name} is a spec but not exported, so nothing would check it`, st);
|
|
3555
|
+
if (!constant) fail(`a spec must be a const export, not ${textOf(sf, st).split(/\s/)[exported ? 1 : 0] ?? "let"}`, st);
|
|
3556
|
+
const [first, second, third] = init.arguments;
|
|
3557
|
+
const fn = functionArg(first, init);
|
|
3558
|
+
if (kind === "total") {
|
|
3559
|
+
if (second) fail("total takes the function alone", second);
|
|
3560
|
+
specs.push({
|
|
3561
|
+
name,
|
|
3562
|
+
kind: "total",
|
|
3563
|
+
fn,
|
|
3564
|
+
text: `total(${fn})`,
|
|
3565
|
+
line,
|
|
3566
|
+
hints: /* @__PURE__ */ new Map()
|
|
3567
|
+
});
|
|
3568
|
+
continue;
|
|
3569
|
+
}
|
|
3570
|
+
if (!second) return fail("forall takes the function, then { when, ensures }", init);
|
|
3571
|
+
if (third) return fail(`unexpected ${textOf(sf, third)} after forall's arguments`, third);
|
|
3572
|
+
if (!is.isObjectLiteralExpression(second)) return fail("forall's second argument must be an object literal { when, ensures }", second);
|
|
3573
|
+
let sample;
|
|
3574
|
+
let when;
|
|
3575
|
+
let ensures;
|
|
3576
|
+
for (const prop of second.properties) {
|
|
3577
|
+
const key = is.isPropertyAssignment(prop) || is.isShorthandPropertyAssignment(prop) || is.isMethodDeclaration(prop) ? prop.name : void 0;
|
|
3578
|
+
const keyName = key && is.isIdentifier(key) ? key.text : key ? textOf(sf, key) : textOf(sf, prop);
|
|
3579
|
+
if (keyName !== "sample" && keyName !== "when" && keyName !== "ensures") fail(`forall's properties are sample, when and ensures, found ${keyName}`, prop);
|
|
3580
|
+
if (!is.isPropertyAssignment(prop)) fail(`${keyName} must be written as ${keyName}: (…) => …`, prop);
|
|
3581
|
+
const read = arrow(prop.initializer, keyName);
|
|
3582
|
+
if (keyName === "sample") {
|
|
3583
|
+
if (sample) fail("sample is given twice", prop);
|
|
3584
|
+
sample = read;
|
|
3585
|
+
} else if (keyName === "when") {
|
|
3586
|
+
if (when) fail("when is given twice", prop);
|
|
3587
|
+
when = read;
|
|
3588
|
+
} else {
|
|
3589
|
+
if (ensures) fail("ensures is given twice", prop);
|
|
3590
|
+
ensures = read;
|
|
3591
|
+
}
|
|
3592
|
+
}
|
|
3593
|
+
if (!ensures) return fail("forall needs an ensures", second);
|
|
3594
|
+
const hintsOfArrow = (a) => a && !is.isBlock(a.node.body) ? hintsIn(sf, a.node.body, a.arrow.params) : /* @__PURE__ */ new Map();
|
|
3595
|
+
const fromSample = hintsOfArrow(sample);
|
|
3596
|
+
const fromWhen = hintsOfArrow(when);
|
|
3597
|
+
const hints = /* @__PURE__ */ new Map();
|
|
3598
|
+
for (const i of /* @__PURE__ */ new Set([...fromSample.keys(), ...fromWhen.keys()])) {
|
|
3599
|
+
const h = combineHints(fromWhen.get(i), fromSample.get(i));
|
|
3600
|
+
if (h) hints.set(i, h);
|
|
3601
|
+
}
|
|
3602
|
+
specs.push({
|
|
3603
|
+
name,
|
|
3604
|
+
kind: "forall",
|
|
3605
|
+
fn,
|
|
3606
|
+
...sample ? { sample: sample.arrow } : {},
|
|
3607
|
+
...when ? { when: when.arrow } : {},
|
|
3608
|
+
ensures: ensures.arrow,
|
|
3609
|
+
text: ensures.arrow.body.replace(/\s+/g, " ").trim(),
|
|
3610
|
+
line,
|
|
3611
|
+
hints
|
|
3612
|
+
});
|
|
3613
|
+
} catch (err) {
|
|
3614
|
+
if (!(err instanceof SpecFail)) throw err;
|
|
3615
|
+
errors.push({
|
|
3616
|
+
line: err.line,
|
|
3617
|
+
message: `${name}: ${err.message}`
|
|
3618
|
+
});
|
|
3619
|
+
}
|
|
3620
|
+
}
|
|
3621
|
+
}
|
|
3622
|
+
return {
|
|
3623
|
+
specs,
|
|
3624
|
+
errors,
|
|
3625
|
+
imports: [...bound].filter(([, imp]) => imp.name !== "*" && imp.name !== "default" && fromModule(imp)).map(([local, imp]) => ({
|
|
3626
|
+
local,
|
|
3627
|
+
name: imp.name
|
|
3628
|
+
}))
|
|
3629
|
+
};
|
|
3630
|
+
}
|
|
3631
|
+
/** The tighter of two endpoints on one side; the first when they cannot be compared. */
|
|
3632
|
+
function tighter(first, second, side) {
|
|
3633
|
+
if (!first) return second;
|
|
3634
|
+
if (!second) return first;
|
|
3635
|
+
const integral = (e) => !/[.eE]/.test(e.value);
|
|
3636
|
+
let order;
|
|
3637
|
+
try {
|
|
3638
|
+
if (integral(first) && integral(second)) {
|
|
3639
|
+
const a = endpointBigInt(first.value);
|
|
3640
|
+
const b = endpointBigInt(second.value);
|
|
3641
|
+
order = a === b ? 0 : a > b ? 1 : -1;
|
|
3642
|
+
} else {
|
|
3643
|
+
const a = endpointNumber(first.value);
|
|
3644
|
+
const b = endpointNumber(second.value);
|
|
3645
|
+
if (Number.isNaN(a) || Number.isNaN(b)) return first;
|
|
3646
|
+
order = a === b ? 0 : a > b ? 1 : -1;
|
|
3647
|
+
}
|
|
3648
|
+
} catch {
|
|
3649
|
+
return first;
|
|
3650
|
+
}
|
|
3651
|
+
if (order !== 0) return (side === "lower" ? order > 0 : order < 0) ? first : second;
|
|
3652
|
+
return first.inclusive ? second : first;
|
|
3653
|
+
}
|
|
3654
|
+
/**
|
|
3655
|
+
* Two hints on one binder as one: integer when either says so, the
|
|
3656
|
+
* tighter bound on each side, the first's regex (two cannot be combined,
|
|
3657
|
+
* and the draws are checked against both arrows anyway).
|
|
3658
|
+
*/
|
|
3659
|
+
function combineHints(first, second) {
|
|
3660
|
+
if (!first) return second;
|
|
3661
|
+
if (!second) return first;
|
|
3662
|
+
const lower = tighter(first.lower, second.lower, "lower");
|
|
3663
|
+
const upper = tighter(first.upper, second.upper, "upper");
|
|
3664
|
+
const regex = first.regex ?? second.regex;
|
|
3665
|
+
return {
|
|
3666
|
+
...first.integer || second.integer ? { integer: true } : {},
|
|
3667
|
+
...lower ? { lower } : {},
|
|
3668
|
+
...upper ? { upper } : {},
|
|
3669
|
+
...regex ? { regex } : {}
|
|
3670
|
+
};
|
|
3671
|
+
}
|
|
3672
|
+
/** Read a module and its spec file. */
|
|
3673
|
+
function readSpecs(input) {
|
|
3674
|
+
const modulePath = input.modulePath;
|
|
3675
|
+
const specPath = input.specPath ?? modulePath.replace(/\.ts$/, ".props.ts");
|
|
3676
|
+
return withProgram([{
|
|
3677
|
+
path: modulePath,
|
|
3678
|
+
text: input.module
|
|
3679
|
+
}, {
|
|
3680
|
+
path: specPath,
|
|
3681
|
+
text: input.spec
|
|
3682
|
+
}], (opened) => {
|
|
3683
|
+
const { checker, file, parseError } = opened;
|
|
3684
|
+
const moduleError = parseError(modulePath);
|
|
3685
|
+
const specError = parseError(specPath);
|
|
3686
|
+
const errors = [];
|
|
3687
|
+
if (moduleError) errors.push({
|
|
3688
|
+
line: moduleError.line,
|
|
3689
|
+
message: `the module could not be parsed: ${moduleError.message}`,
|
|
3690
|
+
inModule: true
|
|
3691
|
+
});
|
|
3692
|
+
if (specError) errors.push({
|
|
3693
|
+
line: specError.line,
|
|
3694
|
+
message: `the spec file could not be parsed: ${specError.message}`
|
|
3695
|
+
});
|
|
3696
|
+
if (moduleError || specError) return {
|
|
3697
|
+
functions: [],
|
|
3698
|
+
errors
|
|
3699
|
+
};
|
|
3700
|
+
const moduleFile = file(modulePath);
|
|
3701
|
+
const moduleSide = readModuleSide(moduleFile, checker);
|
|
3702
|
+
const specSide = readSpecSide(file(specPath), opened, modulePath, moduleFile.path, new Set(input.specSpecifiers ?? ["eutaxy/spec", "@eutaxy/spec"]));
|
|
3703
|
+
errors.push(...moduleSide.errors, ...specSide.errors);
|
|
3704
|
+
const patched = rebound(file(specPath), checker, opened.standardGlobal);
|
|
3705
|
+
if (patched) errors.push({
|
|
3706
|
+
line: patched.line,
|
|
3707
|
+
message: `the spec file assigns to ${patched.target}, so the built-ins its claims are read with may not be the standard ones`
|
|
3708
|
+
});
|
|
3709
|
+
const imports = specSide.imports.flatMap((i) => {
|
|
3710
|
+
const fn = moduleSide.exports.get(i.name);
|
|
3711
|
+
return fn === void 0 ? [] : [{
|
|
3712
|
+
local: i.local,
|
|
3713
|
+
fn
|
|
3714
|
+
}];
|
|
3715
|
+
});
|
|
3716
|
+
const byFunction = /* @__PURE__ */ new Map();
|
|
3717
|
+
for (const s of specSide.specs) {
|
|
3718
|
+
const local = moduleSide.exports.get(s.fn);
|
|
3719
|
+
const decl = local === void 0 ? void 0 : moduleSide.declarations.get(local);
|
|
3720
|
+
if (!decl) {
|
|
3721
|
+
errors.push({
|
|
3722
|
+
line: s.line,
|
|
3723
|
+
message: `${s.name}: the module exports no function ${s.fn} whose parameters the reader can read (a function declaration or a const arrow)`
|
|
3724
|
+
});
|
|
3725
|
+
continue;
|
|
3726
|
+
}
|
|
3727
|
+
const entry = byFunction.get(s.fn) ?? {
|
|
3728
|
+
decl,
|
|
3729
|
+
properties: []
|
|
3730
|
+
};
|
|
3731
|
+
if (entry.properties.some((p) => p.name === s.name)) {
|
|
3732
|
+
errors.push({
|
|
3733
|
+
line: s.line,
|
|
3734
|
+
message: `${s.name} is exported twice`
|
|
3735
|
+
});
|
|
3736
|
+
continue;
|
|
3737
|
+
}
|
|
3738
|
+
const binders = decl.params.map((p, i) => {
|
|
3739
|
+
const name = s.ensures?.params[i] ?? p.name ?? `arg${i}`;
|
|
3740
|
+
const hint = s.hints.get(i);
|
|
3741
|
+
return {
|
|
3742
|
+
name,
|
|
3743
|
+
type: p.type,
|
|
3744
|
+
...hint ? { hint } : {}
|
|
3745
|
+
};
|
|
3746
|
+
});
|
|
3747
|
+
entry.properties.push({
|
|
3748
|
+
name: s.name,
|
|
3749
|
+
kind: s.kind,
|
|
3750
|
+
binders,
|
|
3751
|
+
...s.sample ? { sample: s.sample } : {},
|
|
3752
|
+
...s.when ? { when: s.when } : {},
|
|
3753
|
+
...s.ensures ? { ensures: s.ensures } : {},
|
|
3754
|
+
imports,
|
|
3755
|
+
text: s.text,
|
|
3756
|
+
line: s.line
|
|
3757
|
+
});
|
|
3758
|
+
byFunction.set(s.fn, entry);
|
|
3759
|
+
}
|
|
3760
|
+
return {
|
|
3761
|
+
functions: [...byFunction.entries()].map(([name, { decl, properties }]) => ({
|
|
3762
|
+
name,
|
|
3763
|
+
params: decl.params,
|
|
3764
|
+
properties,
|
|
3765
|
+
line: decl.line,
|
|
3766
|
+
offset: decl.offset
|
|
3767
|
+
})),
|
|
3768
|
+
errors
|
|
3769
|
+
};
|
|
3770
|
+
});
|
|
3771
|
+
}
|
|
3772
|
+
export { isListExpr as C, hasLoneSurrogate as S, closeCompiler as _, readForEngine as a, children as b, readSubset as c, narrowsOf as d, tagNarrowsOf as f, restrictModule as g, builtinsAssumption as h, outsideProofs as i, renameVars as l, typeOf as m, readSpecs as n, readArrowBody as o, fits as p, engineGap as r, readExpression as s, hintsOf as t, insertNarrows as u, readBinderType as v, listKinds as w, describe as x, OutsideSubset as y };
|
|
3773
|
+
|
|
3774
|
+
//# sourceMappingURL=reader-Cz6_bLf6.mjs.map
|