@bytewaveco/pudding 0.0.0-stage → 0.1.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +363 -2
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +143 -0
- package/dist/crosscheck.d.ts +63 -0
- package/dist/crosscheck.js +164 -0
- package/dist/index.d.ts +76 -0
- package/dist/index.js +72 -0
- package/dist/install.d.ts +25 -0
- package/dist/install.js +192 -0
- package/dist/ir.d.ts +93 -0
- package/dist/ir.js +331 -0
- package/dist/lean.d.ts +56 -0
- package/dist/lean.js +438 -0
- package/dist/report.d.ts +7 -0
- package/dist/report.js +74 -0
- package/dist/runner.d.ts +79 -0
- package/dist/runner.js +672 -0
- package/dist/search.d.ts +24 -0
- package/dist/search.js +137 -0
- package/dist/translate.d.ts +247 -0
- package/dist/translate.js +1938 -0
- package/dist/vitest.d.ts +8 -0
- package/dist/vitest.js +96 -0
- package/package.json +77 -4
|
@@ -0,0 +1,1938 @@
|
|
|
1
|
+
// Translate law files into proof obligations by evaluating the TypeScript
|
|
2
|
+
// symbolically. Functions are inlined at their call sites, records and arrays
|
|
3
|
+
// are resolved here, and anything outside the supported subset is refused at
|
|
4
|
+
// the exact node instead of being approximated.
|
|
5
|
+
import { ElementFlags, SignatureKind, SymbolFlags, TypeFlags } from "typescript/unstable/sync";
|
|
6
|
+
import { NodeFlags, SyntaxKind as K } from "typescript/unstable/ast";
|
|
7
|
+
import * as ir from "./ir.js";
|
|
8
|
+
export class Unsupported extends Error {
|
|
9
|
+
node;
|
|
10
|
+
constructor(message, node) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.node = node;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Raised where the translation needs a plain value, such as the number of
|
|
17
|
+
* times a loop runs, and has an expression in the inputs instead. If one of
|
|
18
|
+
* those inputs has few values, the law is translated once per value.
|
|
19
|
+
*/
|
|
20
|
+
class NeedsValue extends Error {
|
|
21
|
+
inputs;
|
|
22
|
+
refusal;
|
|
23
|
+
constructor(inputs, refusal) {
|
|
24
|
+
super(refusal.message);
|
|
25
|
+
this.inputs = inputs;
|
|
26
|
+
this.refusal = refusal;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Every binding made in a scope is logged, so that evaluating one branch of a
|
|
31
|
+
* condition can be undone before evaluating the other. Only scopes that
|
|
32
|
+
* existed before the branch are rolled back; scopes created inside it belong
|
|
33
|
+
* to whatever the branch produced, such as a closure it returned.
|
|
34
|
+
*/
|
|
35
|
+
let scopesCreated = 0;
|
|
36
|
+
const bindingLog = [];
|
|
37
|
+
class Env {
|
|
38
|
+
serial = scopesCreated++;
|
|
39
|
+
vars = new Map();
|
|
40
|
+
parent;
|
|
41
|
+
constructor(parent) {
|
|
42
|
+
this.parent = parent;
|
|
43
|
+
}
|
|
44
|
+
cell(name) {
|
|
45
|
+
return this.vars.get(name) ?? this.parent?.cell(name);
|
|
46
|
+
}
|
|
47
|
+
get(name) {
|
|
48
|
+
return this.cell(name)?.value;
|
|
49
|
+
}
|
|
50
|
+
set(name, value, mutable = false) {
|
|
51
|
+
const cell = { value, mutable };
|
|
52
|
+
bindingLog.push({ env: this, name, previous: this.vars.get(name) });
|
|
53
|
+
this.vars.set(name, cell);
|
|
54
|
+
return cell;
|
|
55
|
+
}
|
|
56
|
+
/** Put a binding back to what it was, or remove it. */
|
|
57
|
+
revert(name, previous) {
|
|
58
|
+
if (previous)
|
|
59
|
+
this.vars.set(name, previous);
|
|
60
|
+
else
|
|
61
|
+
this.vars.delete(name);
|
|
62
|
+
}
|
|
63
|
+
child() {
|
|
64
|
+
return new Env(this);
|
|
65
|
+
}
|
|
66
|
+
/** Names of the reassignable variables visible from here. */
|
|
67
|
+
mutableNames(into = new Set()) {
|
|
68
|
+
for (const [name, cell] of this.vars)
|
|
69
|
+
if (cell.mutable)
|
|
70
|
+
into.add(name);
|
|
71
|
+
return this.parent ? this.parent.mutableNames(into) : into;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
const BOTTOM = { k: "bottom" };
|
|
75
|
+
const VOID = { k: "void" };
|
|
76
|
+
const UNINITIALIZED = { k: "uninitialized" };
|
|
77
|
+
const MAX_STEPS = 200_000;
|
|
78
|
+
const COMPOUND = new Map([
|
|
79
|
+
[K.PlusEqualsToken, K.PlusToken], [K.MinusEqualsToken, K.MinusToken], [K.AsteriskEqualsToken, K.AsteriskToken],
|
|
80
|
+
[K.SlashEqualsToken, K.SlashToken], [K.PercentEqualsToken, K.PercentToken],
|
|
81
|
+
]);
|
|
82
|
+
const scalar = (e, num = false) => (num ? { k: "scalar", e, num } : { k: "scalar", e });
|
|
83
|
+
const isNumber = (value) => value.k === "scalar" && value.num === true;
|
|
84
|
+
/** Integer inputs with at most this many values are enumerated instead of quantified. */
|
|
85
|
+
const MAX_ENUMERATED_RANGE = 256n;
|
|
86
|
+
const MAX_ITERATIONS = 2_000;
|
|
87
|
+
const MAX_INSTANCES = 256;
|
|
88
|
+
const NUMBER_HELP = "`number` covers fractions, NaN and infinities, which are not modeled; use `Integer` from pudding for whole numbers, or bigint";
|
|
89
|
+
const MAX_ALTERNATIVES = 64;
|
|
90
|
+
const MODULE_DECLARATIONS = new Set([
|
|
91
|
+
K.ImportDeclaration, K.ExportDeclaration, K.ExportAssignment, K.VariableStatement, K.FunctionDeclaration, K.ClassDeclaration,
|
|
92
|
+
K.InterfaceDeclaration, K.TypeAliasDeclaration, K.EnumDeclaration, K.ModuleDeclaration, K.ImportEqualsDeclaration, K.EmptyStatement,
|
|
93
|
+
]);
|
|
94
|
+
const DECLARATIONS_WITHOUT_VALUE = new Set([K.ImportDeclaration, K.InterfaceDeclaration, K.TypeAliasDeclaration, K.EmptyStatement]);
|
|
95
|
+
/** Array methods that change nothing and return no reference into the array, given elements that are plain values. */
|
|
96
|
+
const READING_METHODS = new Set([
|
|
97
|
+
"includes", "some", "every", "map", "reduce", "reduceRight", "filter", "find", "findIndex", "findLast", "findLastIndex", "indexOf", "lastIndexOf",
|
|
98
|
+
"join", "slice", "concat", "at", "flat", "flatMap", "keys", "values", "entries", "toString",
|
|
99
|
+
]);
|
|
100
|
+
/** Functions that write to the object they are given first. */
|
|
101
|
+
const WRITERS = /^(Object\.(assign|defineProperty|defineProperties|setPrototypeOf)|Reflect\.(set|defineProperty|setPrototypeOf|deleteProperty))$/;
|
|
102
|
+
/** Built-in functions that only read what they are given. The last group returns what is inside it. */
|
|
103
|
+
const READERS = /^(Object\.(keys|isFrozen|hasOwn|getOwnPropertyNames)|Array\.isArray|JSON\.stringify|String|Boolean)$/;
|
|
104
|
+
const SHALLOW_READERS = /^(Object\.(values|entries|freeze|fromEntries)|Array\.from|structuredClone)$/;
|
|
105
|
+
const ARRAY_MUTATORS = new Set(["push", "pop", "shift", "unshift", "splice", "sort", "reverse", "fill", "copyWithin", "set", "delete", "clear", "add"]);
|
|
106
|
+
export function locate(node) {
|
|
107
|
+
const file = node.getSourceFile();
|
|
108
|
+
const at = file.getLineAndCharacterOfPosition(node.getStart(file));
|
|
109
|
+
return { file: file.fileName, line: at.line + 1, column: at.character + 1 };
|
|
110
|
+
}
|
|
111
|
+
function sourceText(node) {
|
|
112
|
+
const text = node.getText(node.getSourceFile()).replace(/\s+/g, " ");
|
|
113
|
+
return text.length > 140 ? text.slice(0, 137) + "..." : text;
|
|
114
|
+
}
|
|
115
|
+
function describe(value) {
|
|
116
|
+
switch (value.k) {
|
|
117
|
+
case "scalar": return value.num ? "a number" : { bool: "a boolean", int: "a bigint", str: "a string" }[value.e.ty];
|
|
118
|
+
case "record": return "an object";
|
|
119
|
+
case "array": return "an array";
|
|
120
|
+
case "closure": return "a function";
|
|
121
|
+
case "choice": return "a value that depends on a condition";
|
|
122
|
+
case "bottom": return "a thrown error";
|
|
123
|
+
case "void": return "nothing";
|
|
124
|
+
case "uninitialized": return "a variable that is not initialized yet";
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
export class Translator {
|
|
128
|
+
/** Source files whose code was read while translating. */
|
|
129
|
+
reached = new Set();
|
|
130
|
+
checker;
|
|
131
|
+
program;
|
|
132
|
+
moduleName;
|
|
133
|
+
constants = new Map();
|
|
134
|
+
mutationChecked = new Set();
|
|
135
|
+
stack = [];
|
|
136
|
+
pc = [];
|
|
137
|
+
/** Every reassignable variable that is live, so their values can be saved and merged around branches. */
|
|
138
|
+
cells = [];
|
|
139
|
+
/** For each function being evaluated, the names it assigns to anywhere in its body. */
|
|
140
|
+
assigned = [];
|
|
141
|
+
steps = 0;
|
|
142
|
+
/** How many merges of variable state are in progress in the function being evaluated. */
|
|
143
|
+
merging = 0;
|
|
144
|
+
/** Module constants whose initializers are being evaluated, innermost last. */
|
|
145
|
+
loading = [];
|
|
146
|
+
mentioned = [];
|
|
147
|
+
sites;
|
|
148
|
+
scanned = new Set();
|
|
149
|
+
importing = new Map();
|
|
150
|
+
exportsUsed = new Map();
|
|
151
|
+
/** Set when some file of the program replaces part of a built-in, which the models of built-ins cannot see. */
|
|
152
|
+
tampering = null;
|
|
153
|
+
facts = new Map();
|
|
154
|
+
instance;
|
|
155
|
+
constructor(program, checker, moduleName) {
|
|
156
|
+
this.program = program;
|
|
157
|
+
this.checker = checker;
|
|
158
|
+
this.moduleName = moduleName;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Translate every law of a file. `selected` decides by full name which laws
|
|
162
|
+
* to check; the rest are reported as skipped without being read.
|
|
163
|
+
*/
|
|
164
|
+
translateFile(file, selected = () => true) {
|
|
165
|
+
this.reached.add(file.fileName);
|
|
166
|
+
const laws = [];
|
|
167
|
+
this.translateBlock(file.statements, undefined, [], "run", laws, selected);
|
|
168
|
+
// As in Vitest, `.only` narrows the file to the laws that carry it.
|
|
169
|
+
if (laws.some(law => law.only))
|
|
170
|
+
for (const law of laws)
|
|
171
|
+
if (!law.only && law.mode === "run")
|
|
172
|
+
this.skip(law);
|
|
173
|
+
return laws;
|
|
174
|
+
}
|
|
175
|
+
skip(law) {
|
|
176
|
+
law.mode = "skip";
|
|
177
|
+
law.instances = [];
|
|
178
|
+
law.problem = undefined;
|
|
179
|
+
}
|
|
180
|
+
/** The `law` or `describe` call a statement makes, with its `.skip`, `.only` or `.todo` modifier. */
|
|
181
|
+
testCall(node) {
|
|
182
|
+
if (node?.kind !== K.CallExpression)
|
|
183
|
+
return undefined;
|
|
184
|
+
let callee = node.expression;
|
|
185
|
+
let modifier;
|
|
186
|
+
if (callee.kind === K.PropertyAccessExpression && callee.expression.kind === K.Identifier) {
|
|
187
|
+
modifier = callee.name.text;
|
|
188
|
+
callee = callee.expression;
|
|
189
|
+
}
|
|
190
|
+
if (callee.kind !== K.Identifier)
|
|
191
|
+
return undefined;
|
|
192
|
+
const name = this.libraryExport(callee);
|
|
193
|
+
return name === "law" || name === "describe" ? { kind: name, modifier } : undefined;
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* The export of this library that an identifier refers to, if any. Decided
|
|
197
|
+
* by following the name to its import, because a local declaration can
|
|
198
|
+
* reuse any of these names and the code being read may be in any module.
|
|
199
|
+
*/
|
|
200
|
+
libraryExport(identifier) {
|
|
201
|
+
let known = this.exportsUsed.get(identifier);
|
|
202
|
+
if (known === undefined) {
|
|
203
|
+
const declaration = this.checker.getSymbolAtLocation(identifier)?.declarations[0]?.resolve();
|
|
204
|
+
known = declaration?.kind === K.ImportSpecifier && declaration.parent.parent.parent.moduleSpecifier.text === this.moduleName
|
|
205
|
+
? (declaration.propertyName ?? declaration.name).text : "";
|
|
206
|
+
this.exportsUsed.set(identifier, known);
|
|
207
|
+
}
|
|
208
|
+
return known || undefined;
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Walk the statements of a law file or of a `describe` callback. At the top
|
|
212
|
+
* level, declarations are resolved on demand through the checker; inside
|
|
213
|
+
* `describe` they are local, so they are evaluated into `env` as they appear.
|
|
214
|
+
*/
|
|
215
|
+
translateBlock(statements, env, path, mode, laws, selected) {
|
|
216
|
+
if (env)
|
|
217
|
+
this.enter(statements, env);
|
|
218
|
+
const invalid = (statement, message) => laws.push({
|
|
219
|
+
name: sourceText(statement), ...locate(statement), index: -1, mode: "run", proof: undefined, instances: [], mentioned: [], expectSites: new Map(),
|
|
220
|
+
problem: { kind: "invalid", message, ...locate(statement) },
|
|
221
|
+
});
|
|
222
|
+
for (const statement of statements) {
|
|
223
|
+
if (statement.kind !== K.ExpressionStatement) {
|
|
224
|
+
// Anything else at the top of a law file could register laws that are never read, such as `if (x) law(...)`.
|
|
225
|
+
if (!env && !MODULE_DECLARATIONS.has(statement.kind))
|
|
226
|
+
invalid(statement, "only law() and describe() calls and declarations are allowed in a law file");
|
|
227
|
+
if (!env || DECLARATIONS_WITHOUT_VALUE.has(statement.kind))
|
|
228
|
+
continue;
|
|
229
|
+
try {
|
|
230
|
+
if (statement.kind === K.VariableStatement)
|
|
231
|
+
this.declare(statement, env);
|
|
232
|
+
else if (statement.kind !== K.FunctionDeclaration)
|
|
233
|
+
invalid(statement, "only laws and declarations are allowed inside describe()");
|
|
234
|
+
}
|
|
235
|
+
catch (error) {
|
|
236
|
+
if (!(error instanceof Unsupported))
|
|
237
|
+
throw error;
|
|
238
|
+
invalid(error.node ?? statement, error.message);
|
|
239
|
+
}
|
|
240
|
+
continue;
|
|
241
|
+
}
|
|
242
|
+
const call = statement.expression;
|
|
243
|
+
const test = this.testCall(call);
|
|
244
|
+
if (!test) {
|
|
245
|
+
invalid(statement, "only law() and describe() calls and declarations are allowed in a law file");
|
|
246
|
+
continue;
|
|
247
|
+
}
|
|
248
|
+
const { modifier } = test;
|
|
249
|
+
if (modifier !== undefined && modifier !== "skip" && modifier !== "only" && !(modifier === "todo" && test.kind === "law")) {
|
|
250
|
+
invalid(statement, `\`.${modifier}\` is not a modifier Pudding knows; use .skip, .only or .todo`);
|
|
251
|
+
continue;
|
|
252
|
+
}
|
|
253
|
+
const own = modifier === "skip" || mode === "skip" ? "skip" : modifier === "only" || mode === "only" ? "only" : "run";
|
|
254
|
+
const nameNode = call.arguments[0];
|
|
255
|
+
if (nameNode?.kind !== K.StringLiteral && nameNode?.kind !== K.NoSubstitutionTemplateLiteral) {
|
|
256
|
+
invalid(statement, `the first argument of ${test.kind}() must be a string literal`);
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
259
|
+
if (test.kind === "describe") {
|
|
260
|
+
const body = call.arguments[1];
|
|
261
|
+
if ((body?.kind !== K.ArrowFunction && body?.kind !== K.FunctionExpression) || body.body.kind !== K.Block || body.parameters.length) {
|
|
262
|
+
invalid(statement, "describe() takes a name and a callback with a block body");
|
|
263
|
+
continue;
|
|
264
|
+
}
|
|
265
|
+
this.translateBlock(body.body.statements, (env ?? new Env()).child(), [...path, nameNode.text], own, laws, selected);
|
|
266
|
+
continue;
|
|
267
|
+
}
|
|
268
|
+
const name = [...path, nameNode.text].join(" > ");
|
|
269
|
+
const index = laws.filter(law => law.index >= 0).length;
|
|
270
|
+
if (modifier === "todo" || own === "skip" || !selected(name)) {
|
|
271
|
+
laws.push({
|
|
272
|
+
name, ...locate(call), index, mode: modifier === "todo" ? "todo" : "skip", proof: undefined, instances: [], mentioned: [], expectSites: new Map(), problem: undefined,
|
|
273
|
+
// A law marked `only` narrows its file even when a name filter leaves it out.
|
|
274
|
+
...(own === "only" && modifier !== "todo" ? { only: true } : {}),
|
|
275
|
+
});
|
|
276
|
+
continue;
|
|
277
|
+
}
|
|
278
|
+
const law = this.translateLaw(call, index, name, env);
|
|
279
|
+
if (own === "only")
|
|
280
|
+
law.only = true;
|
|
281
|
+
laws.push(law);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
isCallTo(node, name) {
|
|
285
|
+
return node?.kind === K.CallExpression && node.expression.kind === K.Identifier && this.libraryExport(node.expression) === name;
|
|
286
|
+
}
|
|
287
|
+
translateLaw(call, index, name, scope) {
|
|
288
|
+
const args = call.arguments;
|
|
289
|
+
const law = {
|
|
290
|
+
name, ...locate(call), index, mode: "run", proof: undefined, instances: [], mentioned: [], expectSites: new Map(), problem: undefined,
|
|
291
|
+
};
|
|
292
|
+
const invalid = (message, node) => {
|
|
293
|
+
law.problem = { kind: "invalid", message, ...locate(node) };
|
|
294
|
+
return law;
|
|
295
|
+
};
|
|
296
|
+
const hasDomain = this.isCallTo(args[1], "domain");
|
|
297
|
+
const callback = args[hasDomain ? 2 : 1];
|
|
298
|
+
const options = args[hasDomain ? 3 : 2];
|
|
299
|
+
if (callback?.kind !== K.ArrowFunction && callback?.kind !== K.FunctionExpression)
|
|
300
|
+
return invalid("law() needs a callback", call);
|
|
301
|
+
if (callback.parameters.length !== (hasDomain ? 1 : 0))
|
|
302
|
+
return invalid(hasDomain ? "the callback takes exactly one parameter" : "a law without a domain takes no parameter", callback);
|
|
303
|
+
if (callback.asteriskToken || callback.modifiers?.some((m) => m.kind === K.AsyncKeyword))
|
|
304
|
+
return invalid("a law callback must be an ordinary synchronous function", callback);
|
|
305
|
+
const [parameter] = callback.parameters;
|
|
306
|
+
if (parameter && (parameter.dotDotDotToken || parameter.initializer || parameter.questionToken))
|
|
307
|
+
return invalid("the callback's parameter must be plain: no rest, default or optional marker", parameter);
|
|
308
|
+
if (options) {
|
|
309
|
+
if (options.kind !== K.ObjectLiteralExpression)
|
|
310
|
+
return invalid("law() options must be an object literal", options);
|
|
311
|
+
for (const property of options.properties) {
|
|
312
|
+
const value = property.initializer;
|
|
313
|
+
if (property.kind !== K.PropertyAssignment || property.name.text !== "proof" ||
|
|
314
|
+
(value.kind !== K.StringLiteral && value.kind !== K.NoSubstitutionTemplateLiteral))
|
|
315
|
+
return invalid("the only option is `proof`, a string literal holding a Lean tactic script", property);
|
|
316
|
+
law.proof = value.text;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
this.collectExpectSites(callback.body, law);
|
|
320
|
+
this.mentioned = law.mentioned;
|
|
321
|
+
this.sites = law.expectSites;
|
|
322
|
+
try {
|
|
323
|
+
let alternatives = [{ k: "tuple", items: [] }];
|
|
324
|
+
if (hasDomain) {
|
|
325
|
+
const typeNode = args[1].typeArguments?.[0];
|
|
326
|
+
if (!typeNode)
|
|
327
|
+
return invalid("domain<T>() needs a type argument", args[1]);
|
|
328
|
+
const type = this.checker.getTypeFromTypeNode(typeNode);
|
|
329
|
+
if (!type)
|
|
330
|
+
return invalid("the domain type could not be resolved", typeNode);
|
|
331
|
+
alternatives = this.expand(this.shapeOf(type, typeNode), typeNode);
|
|
332
|
+
}
|
|
333
|
+
for (const alternative of alternatives) {
|
|
334
|
+
const instance = { assumptions: [], fixed: new Map(), binders: [], arg: undefined, obligations: [] };
|
|
335
|
+
this.instance = instance;
|
|
336
|
+
if (hasDomain)
|
|
337
|
+
instance.arg = this.instantiate(alternative, instance);
|
|
338
|
+
law.instances.push(instance);
|
|
339
|
+
}
|
|
340
|
+
const waiting = law.instances;
|
|
341
|
+
law.instances = [];
|
|
342
|
+
while (waiting.length) {
|
|
343
|
+
const instance = waiting.shift();
|
|
344
|
+
this.instance = instance;
|
|
345
|
+
this.pc = [...instance.assumptions];
|
|
346
|
+
this.stack = [];
|
|
347
|
+
this.cells = [];
|
|
348
|
+
bindingLog.length = 0;
|
|
349
|
+
this.steps = 0;
|
|
350
|
+
const facts = this.factsOf(callback);
|
|
351
|
+
if (facts.usesVar)
|
|
352
|
+
throw new Unsupported("`var` is not supported; use `const` or `let`", facts.usesVar);
|
|
353
|
+
this.assigned = [facts.assigned];
|
|
354
|
+
const env = scope ? scope.child() : new Env();
|
|
355
|
+
try {
|
|
356
|
+
if (instance.arg)
|
|
357
|
+
this.bind(callback.parameters[0].name, this.valueOf(instance.arg), env, true, true);
|
|
358
|
+
const body = callback.body;
|
|
359
|
+
if (body.kind === K.Block)
|
|
360
|
+
this.block(body.statements, env, { next: () => VOID });
|
|
361
|
+
else
|
|
362
|
+
this.effect(body, env);
|
|
363
|
+
law.instances.push(instance);
|
|
364
|
+
}
|
|
365
|
+
catch (error) {
|
|
366
|
+
// Split on an input that has few values, and translate each case on its own.
|
|
367
|
+
const input = error instanceof NeedsValue ? instance.binders.find(b => error.inputs.has(b.name) && b.domain && b.domain.length > 1) : undefined;
|
|
368
|
+
if (!input || law.instances.length + waiting.length + input.domain.length > MAX_INSTANCES) {
|
|
369
|
+
// The law is refused as a whole. Keep every instance, so it can still be executed.
|
|
370
|
+
law.instances.push(instance, ...waiting);
|
|
371
|
+
throw error instanceof NeedsValue ? error.refusal : error;
|
|
372
|
+
}
|
|
373
|
+
waiting.unshift(...input.domain.map(value => ({
|
|
374
|
+
...instance,
|
|
375
|
+
obligations: [],
|
|
376
|
+
binders: instance.binders.map(b => (b === input ? { ...b, domain: [value] } : { ...b })),
|
|
377
|
+
fixed: new Map(instance.fixed).set(input.name, ir.lit(value)),
|
|
378
|
+
})));
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
// Whatever a law uses, its model assumes the language's own behaviour.
|
|
382
|
+
// Checked last, so that a law refused for this still has named inputs to be executed with.
|
|
383
|
+
this.assertBuiltinsIntact(call);
|
|
384
|
+
const asserts = law.expectSites.size > 0 || law.instances.some(instance => instance.obligations.some(o => o.kind === "expect"));
|
|
385
|
+
if (!asserts)
|
|
386
|
+
return invalid("the law contains no expect() assertion", callback);
|
|
387
|
+
}
|
|
388
|
+
catch (error) {
|
|
389
|
+
if (!(error instanceof Unsupported))
|
|
390
|
+
throw error;
|
|
391
|
+
law.problem = { kind: "unsupported", message: error.message, ...locate(error.node ?? call) };
|
|
392
|
+
for (const instance of law.instances)
|
|
393
|
+
instance.obligations = [];
|
|
394
|
+
}
|
|
395
|
+
finally {
|
|
396
|
+
this.instance = undefined;
|
|
397
|
+
this.assigned = [];
|
|
398
|
+
this.cells = [];
|
|
399
|
+
this.sites = undefined;
|
|
400
|
+
this.scanned = new Set();
|
|
401
|
+
}
|
|
402
|
+
return law;
|
|
403
|
+
}
|
|
404
|
+
/**
|
|
405
|
+
* Record the expectations a called function contains, so one that is never
|
|
406
|
+
* reached is noticed like one written in the law itself. Only files that
|
|
407
|
+
* import this library can contain any.
|
|
408
|
+
*/
|
|
409
|
+
noteExpectations(fn) {
|
|
410
|
+
if (!this.sites || this.scanned.has(fn))
|
|
411
|
+
return;
|
|
412
|
+
this.scanned.add(fn);
|
|
413
|
+
const file = fn.getSourceFile();
|
|
414
|
+
let uses = this.importing.get(file.fileName);
|
|
415
|
+
if (uses === undefined) {
|
|
416
|
+
uses = file.statements.some(s => s.kind === K.ImportDeclaration && s.moduleSpecifier.text === this.moduleName);
|
|
417
|
+
this.importing.set(file.fileName, uses);
|
|
418
|
+
}
|
|
419
|
+
if (!uses || !fn.body)
|
|
420
|
+
return;
|
|
421
|
+
const visit = (n) => {
|
|
422
|
+
if (this.isExpect(n)) {
|
|
423
|
+
let statement = n;
|
|
424
|
+
while (statement.parent && statement.kind !== K.ExpressionStatement && statement !== fn.body)
|
|
425
|
+
statement = statement.parent;
|
|
426
|
+
const at = locate(statement);
|
|
427
|
+
this.sites.set(`${at.file}:${at.line}:${at.column}`, { file: at.file, line: at.line, column: at.column, text: sourceText(statement) });
|
|
428
|
+
}
|
|
429
|
+
n.forEachChild(visit);
|
|
430
|
+
};
|
|
431
|
+
visit(fn.body);
|
|
432
|
+
}
|
|
433
|
+
collectExpectSites(node, law) {
|
|
434
|
+
const visit = (n) => {
|
|
435
|
+
if (this.isExpect(n)) {
|
|
436
|
+
let statement = n;
|
|
437
|
+
while (statement.parent && statement.kind !== K.ExpressionStatement && statement !== node)
|
|
438
|
+
statement = statement.parent;
|
|
439
|
+
const at = locate(statement);
|
|
440
|
+
law.expectSites.set(`${at.file}:${at.line}:${at.column}`, { file: at.file, line: at.line, column: at.column, text: sourceText(statement) });
|
|
441
|
+
}
|
|
442
|
+
n.forEachChild(visit);
|
|
443
|
+
};
|
|
444
|
+
visit(node);
|
|
445
|
+
}
|
|
446
|
+
// ---------------------------------------------------------------- domains
|
|
447
|
+
shapeOf(type, at) {
|
|
448
|
+
const flags = type.flags;
|
|
449
|
+
const name = () => this.checker.typeToString(type);
|
|
450
|
+
if (flags & TypeFlags.Boolean)
|
|
451
|
+
return { k: "scalar", ty: "bool", values: [true, false] };
|
|
452
|
+
if (flags & TypeFlags.BooleanLiteral)
|
|
453
|
+
return { k: "scalar", ty: "bool", values: [name() === "true"] };
|
|
454
|
+
if (flags & TypeFlags.BigInt)
|
|
455
|
+
return { k: "scalar", ty: "int" };
|
|
456
|
+
if (flags & TypeFlags.BigIntLiteral)
|
|
457
|
+
return { k: "scalar", ty: "int", values: [BigInt(name().replace(/n$/, ""))] };
|
|
458
|
+
if (flags & TypeFlags.String)
|
|
459
|
+
return { k: "scalar", ty: "str" };
|
|
460
|
+
if (flags & TypeFlags.StringLiteral)
|
|
461
|
+
return { k: "scalar", ty: "str", values: [this.wellFormed(String(type.value), at)] };
|
|
462
|
+
if (flags & TypeFlags.NumberLiteral) {
|
|
463
|
+
const value = Number(type.value);
|
|
464
|
+
if (!Number.isSafeInteger(value))
|
|
465
|
+
throw new Unsupported(`the number ${name()} is not a whole number that can be held exactly`, at);
|
|
466
|
+
return { k: "scalar", ty: "int", num: true, values: [BigInt(value)] };
|
|
467
|
+
}
|
|
468
|
+
if (flags & TypeFlags.Number)
|
|
469
|
+
throw new Unsupported(NUMBER_HELP, at);
|
|
470
|
+
if (type.isIntersectionType()) {
|
|
471
|
+
// `Integer<Min, Max>` is `number` intersected with a marker that carries the bounds.
|
|
472
|
+
const members = type.getTypes();
|
|
473
|
+
const marker = members.map(member => this.checker.getPropertyOfType(member, "__puddingInteger")).find(Boolean);
|
|
474
|
+
if (marker && members.some(member => member.flags & TypeFlags.Number)) {
|
|
475
|
+
const carried = this.checker.getTypeOfSymbol(marker);
|
|
476
|
+
const tuple = (carried?.isUnionType() ? carried.getTypes() : carried ? [carried] : []).find(member => this.checker.isTupleType(member));
|
|
477
|
+
const bound = (member, fallback) => member && member.flags & TypeFlags.NumberLiteral && Number.isSafeInteger(Number(member.value)) ? BigInt(Number(member.value)) : fallback;
|
|
478
|
+
const [low, high] = tuple ? this.checker.getTypeArguments(tuple) : [];
|
|
479
|
+
const range = [bound(low, -ir.MAX_SAFE), bound(high, ir.MAX_SAFE)];
|
|
480
|
+
if (range[0] > range[1])
|
|
481
|
+
throw new Unsupported(`${name()} has a lower bound above its upper bound`, at);
|
|
482
|
+
if (range[1] - range[0] < MAX_ENUMERATED_RANGE) {
|
|
483
|
+
const values = [];
|
|
484
|
+
for (let value = range[0]; value <= range[1]; value++)
|
|
485
|
+
values.push(value);
|
|
486
|
+
return { k: "scalar", ty: "int", num: true, values };
|
|
487
|
+
}
|
|
488
|
+
return { k: "scalar", ty: "int", num: true, range };
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
if (type.isUnionType()) {
|
|
492
|
+
const members = type.getTypes().map(member => this.shapeOf(member, at));
|
|
493
|
+
const first = members[0];
|
|
494
|
+
if (members.every(m => m.k === "scalar" && m.values && m.ty === first.ty && !!m.num === !!first.num)) {
|
|
495
|
+
const values = [...new Set(members.flatMap(m => m.values))];
|
|
496
|
+
return { k: "scalar", ty: first.ty, values, ...(first.num ? { num: true } : {}) };
|
|
497
|
+
}
|
|
498
|
+
if (members.every(m => m.k !== "scalar"))
|
|
499
|
+
return { k: "union", alts: members };
|
|
500
|
+
throw new Unsupported(`the union type ${name()} mixes kinds of values that are not supported together`, at);
|
|
501
|
+
}
|
|
502
|
+
if (this.checker.isTupleType(type)) {
|
|
503
|
+
const elementFlags = (type.getTarget?.().elementFlags ?? type.elementFlags ?? []);
|
|
504
|
+
if (elementFlags.some(flag => flag !== ElementFlags.Required))
|
|
505
|
+
throw new Unsupported("optional and rest tuple elements are not supported", at);
|
|
506
|
+
return { k: "tuple", items: this.checker.getTypeArguments(type).map(item => this.shapeOf(item, at)) };
|
|
507
|
+
}
|
|
508
|
+
if (this.checker.isArrayType(type))
|
|
509
|
+
throw new Unsupported("arrays of unknown length are not supported as inputs; use a tuple", at);
|
|
510
|
+
if (flags & TypeFlags.Object) {
|
|
511
|
+
if (this.checker.getSignaturesOfType(type, SignatureKind.Call).length)
|
|
512
|
+
throw new Unsupported("functions are not supported as inputs", at);
|
|
513
|
+
if (this.checker.getIndexInfosOfType(type).length) {
|
|
514
|
+
throw new Unsupported(`${name()} allows any number of properties, so its values cannot be listed; use an object type with named properties`, at);
|
|
515
|
+
}
|
|
516
|
+
const fields = [];
|
|
517
|
+
for (const property of this.checker.getPropertiesOfType(type)) {
|
|
518
|
+
if (property.flags & SymbolFlags.Optional)
|
|
519
|
+
throw new Unsupported(`optional property \`${property.name}\` is not supported in an input`, at);
|
|
520
|
+
// A property keyed by a symbol has no string name; its compiler name starts like this.
|
|
521
|
+
if (String(property.escapedName).startsWith("__@"))
|
|
522
|
+
throw new Unsupported(`${name()} has a property keyed by a symbol, which is not supported in an input`, at);
|
|
523
|
+
const propertyType = this.checker.getTypeOfSymbol(property);
|
|
524
|
+
if (!propertyType)
|
|
525
|
+
throw new Unsupported(`the type of \`${property.name}\` could not be resolved`, at);
|
|
526
|
+
fields.push([property.name, this.shapeOf(propertyType, at)]);
|
|
527
|
+
}
|
|
528
|
+
return { k: "record", fields };
|
|
529
|
+
}
|
|
530
|
+
throw new Unsupported(`inputs of type ${name()} are not supported`, at);
|
|
531
|
+
}
|
|
532
|
+
/** Split union alternatives so that each result has one fixed structure. */
|
|
533
|
+
expand(shape, at) {
|
|
534
|
+
const product = (parts) => parts.reduce((rows, options) => {
|
|
535
|
+
const next = rows.flatMap(row => options.map(option => [...row, option]));
|
|
536
|
+
if (next.length > MAX_ALTERNATIVES)
|
|
537
|
+
throw new Unsupported(`the input type has more than ${MAX_ALTERNATIVES} union alternatives`, at);
|
|
538
|
+
return next;
|
|
539
|
+
}, [[]]);
|
|
540
|
+
switch (shape.k) {
|
|
541
|
+
case "scalar": return [shape];
|
|
542
|
+
case "union": return shape.alts.flatMap(alt => this.expand(alt, at));
|
|
543
|
+
case "tuple": return product(shape.items.map(item => this.expand(item, at))).map(items => ({ k: "tuple", items }));
|
|
544
|
+
case "record": return product(shape.fields.map(([, field]) => this.expand(field, at)))
|
|
545
|
+
.map(row => ({ k: "record", fields: row.map((field, i) => [shape.fields[i][0], field]) }));
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
instantiate(shape, instance) {
|
|
549
|
+
switch (shape.k) {
|
|
550
|
+
case "scalar": {
|
|
551
|
+
if (shape.values?.length === 1)
|
|
552
|
+
return { k: "const", value: shape.values[0], ...(shape.num ? { num: true } : {}) };
|
|
553
|
+
const name = `x${instance.binders.length}`;
|
|
554
|
+
instance.binders.push({
|
|
555
|
+
name, label: name, ty: shape.ty,
|
|
556
|
+
...(shape.values ? { domain: shape.values } : {}), ...(shape.num ? { num: true } : {}), ...(shape.range ? { range: shape.range } : {}),
|
|
557
|
+
});
|
|
558
|
+
if (shape.range) {
|
|
559
|
+
const input = ir.variable(name, "int");
|
|
560
|
+
instance.assumptions.push(ir.and(ir.le(ir.lit(shape.range[0]), input), ir.le(input, ir.lit(shape.range[1]))));
|
|
561
|
+
}
|
|
562
|
+
return { k: "binder", name };
|
|
563
|
+
}
|
|
564
|
+
case "tuple": return { k: "array", items: shape.items.map(item => this.instantiate(item, instance)) };
|
|
565
|
+
case "record": return { k: "record", fields: shape.fields.map(([key, field]) => [key, this.instantiate(field, instance)]) };
|
|
566
|
+
case "union": throw new Error("unions are expanded before instantiation");
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
valueOf(arg) {
|
|
570
|
+
switch (arg.k) {
|
|
571
|
+
case "binder": {
|
|
572
|
+
const binder = this.instance.binders.find(b => b.name === arg.name);
|
|
573
|
+
return scalar(ir.variable(binder.name, binder.ty), binder.num);
|
|
574
|
+
}
|
|
575
|
+
case "const": return scalar(ir.lit(arg.value), arg.num);
|
|
576
|
+
case "array": return { k: "array", items: arg.items.map(item => this.valueOf(item)) };
|
|
577
|
+
case "record": return { k: "record", fields: new Map(arg.fields.map(([key, field]) => [key, this.valueOf(field)])) };
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
relabel(value, path) {
|
|
581
|
+
if (value.k === "scalar" && value.e.t === "var") {
|
|
582
|
+
const binder = this.instance?.binders.find(b => b.name === value.e.name);
|
|
583
|
+
if (binder)
|
|
584
|
+
binder.label = path;
|
|
585
|
+
}
|
|
586
|
+
else if (value.k === "record")
|
|
587
|
+
for (const [key, field] of value.fields)
|
|
588
|
+
this.relabel(field, `${path}.${key}`);
|
|
589
|
+
else if (value.k === "array")
|
|
590
|
+
value.items.forEach((item, i) => this.relabel(item, `${path}[${i}]`));
|
|
591
|
+
}
|
|
592
|
+
// ------------------------------------------------------------- law bodies
|
|
593
|
+
/** Whether a call is rooted in `expect(...)`, however the chain after it is written. */
|
|
594
|
+
/**
|
|
595
|
+
* Whether a call is to the `expect` this library exports, and not to
|
|
596
|
+
* something else that happens to have its name. Decided by where the name
|
|
597
|
+
* was imported from, since the code being read may be in any module.
|
|
598
|
+
*/
|
|
599
|
+
isExpect(node) {
|
|
600
|
+
return this.isCallTo(node, "expect");
|
|
601
|
+
}
|
|
602
|
+
startsWithExpect(node) {
|
|
603
|
+
let current = node;
|
|
604
|
+
while (current) {
|
|
605
|
+
if (this.isExpect(current))
|
|
606
|
+
return true;
|
|
607
|
+
if (current.kind === K.CallExpression || current.kind === K.PropertyAccessExpression)
|
|
608
|
+
current = current.expression;
|
|
609
|
+
else
|
|
610
|
+
return false;
|
|
611
|
+
}
|
|
612
|
+
return false;
|
|
613
|
+
}
|
|
614
|
+
expectStatement(node, env) {
|
|
615
|
+
const fail = () => new Unsupported("an assertion must be expect(actual).toEqual(expected), .toBe(expected), or the .not form of either", node);
|
|
616
|
+
if (node.kind !== K.CallExpression || node.expression.kind !== K.PropertyAccessExpression || node.arguments.length !== 1)
|
|
617
|
+
throw fail();
|
|
618
|
+
const matcher = node.expression.name.text;
|
|
619
|
+
if (matcher !== "toEqual" && matcher !== "toBe")
|
|
620
|
+
throw fail();
|
|
621
|
+
let target = node.expression.expression;
|
|
622
|
+
let negated = false;
|
|
623
|
+
if (target.kind === K.PropertyAccessExpression && target.name.text === "not") {
|
|
624
|
+
negated = true;
|
|
625
|
+
target = target.expression;
|
|
626
|
+
}
|
|
627
|
+
if (!this.isExpect(target) || target.arguments.length !== 1)
|
|
628
|
+
throw fail();
|
|
629
|
+
const actual = this.evalExpr(target.arguments[0], env);
|
|
630
|
+
const expected = this.evalExpr(node.arguments[0], env);
|
|
631
|
+
const equal = this.equal(actual, expected, node, matcher === "toBe");
|
|
632
|
+
const sides = actual.k === "scalar" && expected.k === "scalar" ? { actual: actual.e, expected: expected.e, negated, num: !!actual.num } : undefined;
|
|
633
|
+
this.emit("expect", negated ? ir.not(equal) : equal, node, sides);
|
|
634
|
+
}
|
|
635
|
+
/** Whether two values are equal as `toEqual` sees it, or as `toBe` does when `identity` is set. */
|
|
636
|
+
equal(a, b, at, identity = false) {
|
|
637
|
+
if (a.k === "bottom" || b.k === "bottom")
|
|
638
|
+
return ir.FALSE;
|
|
639
|
+
if (a.k === "choice")
|
|
640
|
+
return ir.ite(a.cond, this.equal(a.a, b, at, identity), this.equal(a.b, b, at, identity));
|
|
641
|
+
if (b.k === "choice")
|
|
642
|
+
return ir.ite(b.cond, this.equal(a, b.a, at, identity), this.equal(a, b.b, at, identity));
|
|
643
|
+
if (this.isPlain(a) && this.isPlain(b))
|
|
644
|
+
return this.strictEqual(a, b, at);
|
|
645
|
+
if (identity)
|
|
646
|
+
throw new Unsupported("toBe compares identity, which is only modeled for booleans, bigints, numbers and strings; use toEqual", at);
|
|
647
|
+
if (a.k === "array" && b.k === "array") {
|
|
648
|
+
if (a.items.length !== b.items.length)
|
|
649
|
+
return ir.FALSE;
|
|
650
|
+
return ir.all(a.items.map((item, i) => this.equal(item, b.items[i], at)));
|
|
651
|
+
}
|
|
652
|
+
if (a.k === "record" && b.k === "record") {
|
|
653
|
+
if (a.fields.size !== b.fields.size || [...a.fields.keys()].some(key => !b.fields.has(key))) {
|
|
654
|
+
throw new Unsupported("comparing objects that have different property names is not supported", at);
|
|
655
|
+
}
|
|
656
|
+
return ir.all([...a.fields].map(([key, field]) => this.equal(field, b.fields.get(key), at)));
|
|
657
|
+
}
|
|
658
|
+
throw new Unsupported(`cannot compare ${describe(a)} with ${describe(b)}`, at);
|
|
659
|
+
}
|
|
660
|
+
emit(kind, claim, node, sides) {
|
|
661
|
+
const guard = ir.all(this.pc);
|
|
662
|
+
if (guard.t === "lit" && guard.value === false)
|
|
663
|
+
return;
|
|
664
|
+
if (kind !== "expect" && claim.t === "lit" && claim.value === true)
|
|
665
|
+
return;
|
|
666
|
+
if (!this.instance)
|
|
667
|
+
throw new Unsupported("this code can throw while a module is being initialized", node);
|
|
668
|
+
this.instance.obligations.push({ kind, guard, claim, ...locate(node), text: sourceText(node), ...(sides ? { sides } : {}) });
|
|
669
|
+
}
|
|
670
|
+
/**
|
|
671
|
+
* The value of an expression where the translation cannot go on without
|
|
672
|
+
* one. Inputs this instance has fixed are filled in; if that is not enough,
|
|
673
|
+
* the caller's refusal is raised in a form that lets the law be split.
|
|
674
|
+
*/
|
|
675
|
+
settle(e, refusal) {
|
|
676
|
+
const settled = this.instance?.fixed.size ? ir.substitute(e, this.instance.fixed) : e;
|
|
677
|
+
if (settled.t === "lit")
|
|
678
|
+
return settled;
|
|
679
|
+
throw new NeedsValue(ir.freeVariables(settled), refusal());
|
|
680
|
+
}
|
|
681
|
+
under(cond, run) {
|
|
682
|
+
this.pc.push(cond);
|
|
683
|
+
try {
|
|
684
|
+
return run();
|
|
685
|
+
}
|
|
686
|
+
finally {
|
|
687
|
+
this.pc.pop();
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
save() {
|
|
691
|
+
return { values: this.cells.map(cell => cell.value), logged: bindingLog.length, scopes: scopesCreated };
|
|
692
|
+
}
|
|
693
|
+
/** Put variables and bindings back to a saved state, forgetting any declared since. */
|
|
694
|
+
restore(saved) {
|
|
695
|
+
this.cells.length = saved.values.length;
|
|
696
|
+
this.cells.forEach((cell, i) => (cell.value = saved.values[i]));
|
|
697
|
+
while (bindingLog.length > saved.logged) {
|
|
698
|
+
const entry = bindingLog.pop();
|
|
699
|
+
if (entry.env.serial < saved.scopes)
|
|
700
|
+
entry.env.revert(entry.name, entry.previous);
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
/**
|
|
704
|
+
* Evaluate both sides of a condition and merge their results. Each side
|
|
705
|
+
* starts from the same variable state. The state afterwards is the state
|
|
706
|
+
* before: an expression cannot assign, and a statement branch evaluated
|
|
707
|
+
* this way has already run to the end of its function on both sides.
|
|
708
|
+
*/
|
|
709
|
+
branch(cond, whenTrue, whenFalse, control = false) {
|
|
710
|
+
if (cond.t === "lit")
|
|
711
|
+
return cond.value ? whenTrue() : whenFalse();
|
|
712
|
+
// A branch over statements only keeps their effects if both sides run on to
|
|
713
|
+
// the end of the function. Inside a merge they do not, so reaching here
|
|
714
|
+
// would silently drop assignments. Every such construct is meant to merge
|
|
715
|
+
// instead; this is the net under that.
|
|
716
|
+
if (control && this.merging > 0)
|
|
717
|
+
throw new Unsupported("this combination of branches and assignments is not supported", undefined);
|
|
718
|
+
const before = this.save();
|
|
719
|
+
const a = this.under(cond, whenTrue);
|
|
720
|
+
this.restore(before);
|
|
721
|
+
const b = this.under(ir.not(cond), whenFalse);
|
|
722
|
+
this.restore(before);
|
|
723
|
+
return this.merge(cond, a, b);
|
|
724
|
+
}
|
|
725
|
+
/**
|
|
726
|
+
* Run two branches that both continue past the condition, then make every
|
|
727
|
+
* variable hold the value of whichever branch was taken. The code after
|
|
728
|
+
* the condition is then evaluated once, not once per branch.
|
|
729
|
+
*/
|
|
730
|
+
mergeStates(cond, whenTrue, whenFalse) {
|
|
731
|
+
const before = this.save();
|
|
732
|
+
const kept = before.values.length;
|
|
733
|
+
this.merging++;
|
|
734
|
+
let afterTrue;
|
|
735
|
+
let afterFalse;
|
|
736
|
+
try {
|
|
737
|
+
this.under(cond, whenTrue);
|
|
738
|
+
afterTrue = this.cells.slice(0, kept).map(cell => cell.value);
|
|
739
|
+
this.restore(before);
|
|
740
|
+
this.under(ir.not(cond), whenFalse);
|
|
741
|
+
afterFalse = this.cells.slice(0, kept).map(cell => cell.value);
|
|
742
|
+
this.restore(before);
|
|
743
|
+
}
|
|
744
|
+
finally {
|
|
745
|
+
this.merging--;
|
|
746
|
+
}
|
|
747
|
+
this.cells.forEach((cell, i) => {
|
|
748
|
+
const a = afterTrue[i];
|
|
749
|
+
const b = afterFalse[i];
|
|
750
|
+
cell.value = a === b ? a : this.merge(cond, a, b);
|
|
751
|
+
});
|
|
752
|
+
}
|
|
753
|
+
merge(cond, a, b) {
|
|
754
|
+
if (a.k === "bottom")
|
|
755
|
+
return b;
|
|
756
|
+
if (b.k === "bottom")
|
|
757
|
+
return a;
|
|
758
|
+
if (a.k === "scalar" && b.k === "scalar" && a.e.ty === b.e.ty && !!a.num === !!b.num)
|
|
759
|
+
return scalar(ir.ite(cond, a.e, b.e), a.num);
|
|
760
|
+
if (a.k === "array" && b.k === "array" && a.items.length === b.items.length) {
|
|
761
|
+
return { k: "array", items: a.items.map((item, i) => this.merge(cond, item, b.items[i])) };
|
|
762
|
+
}
|
|
763
|
+
if (a.k === "record" && b.k === "record" && a.fields.size === b.fields.size && [...a.fields.keys()].every(key => b.fields.has(key))) {
|
|
764
|
+
return { k: "record", fields: new Map([...a.fields].map(([key, field]) => [key, this.merge(cond, field, b.fields.get(key))])) };
|
|
765
|
+
}
|
|
766
|
+
if (a.k === "closure" && b.k === "closure" && a.node === b.node && a.env === b.env)
|
|
767
|
+
return a;
|
|
768
|
+
if (a.k === "void" && b.k === "void")
|
|
769
|
+
return a;
|
|
770
|
+
return { k: "choice", cond, a, b };
|
|
771
|
+
}
|
|
772
|
+
/** Apply an operation to a value, distributing over conditional values. */
|
|
773
|
+
over(value, apply) {
|
|
774
|
+
value = this.settled(value);
|
|
775
|
+
if (value.k === "choice")
|
|
776
|
+
return this.branch(value.cond, () => this.over(value.a, apply), () => this.over(value.b, apply));
|
|
777
|
+
return apply(value);
|
|
778
|
+
}
|
|
779
|
+
// ------------------------------------------------------------- functions
|
|
780
|
+
/** What a function's body does that affects how it is evaluated, computed once per function. */
|
|
781
|
+
factsOf(fn) {
|
|
782
|
+
let facts = this.facts.get(fn);
|
|
783
|
+
if (facts)
|
|
784
|
+
return facts;
|
|
785
|
+
facts = { assigned: new Set(), mentioned: new Set(), returnsValue: false, usesVar: undefined };
|
|
786
|
+
const isFunction = (node) => node.kind === K.ArrowFunction || node.kind === K.FunctionExpression || node.kind === K.FunctionDeclaration;
|
|
787
|
+
const visit = (node, nested) => {
|
|
788
|
+
if (node.kind === K.Identifier)
|
|
789
|
+
facts.mentioned.add(node.text);
|
|
790
|
+
if (node.kind === K.BinaryExpression && node.operatorToken.kind >= K.FirstAssignment && node.operatorToken.kind <= K.LastAssignment) {
|
|
791
|
+
collectNames(node.left, facts.assigned);
|
|
792
|
+
}
|
|
793
|
+
if ((node.kind === K.PrefixUnaryExpression || node.kind === K.PostfixUnaryExpression) &&
|
|
794
|
+
(node.operator === K.PlusPlusToken || node.operator === K.MinusMinusToken))
|
|
795
|
+
collectNames(node.operand, facts.assigned);
|
|
796
|
+
if (node.kind === K.ReturnStatement && node.expression && !nested)
|
|
797
|
+
facts.returnsValue = true;
|
|
798
|
+
// A `var` belongs to the whole function wherever it is written, even in a block that never runs.
|
|
799
|
+
if (node.kind === K.VariableDeclarationList && !(node.flags & (NodeFlags.Let | NodeFlags.Const)) && !nested)
|
|
800
|
+
facts.usesVar ??= node;
|
|
801
|
+
node.forEachChild((child) => visit(child, nested || isFunction(child)));
|
|
802
|
+
};
|
|
803
|
+
for (const parameter of parametersOf(fn))
|
|
804
|
+
visit(parameter, false);
|
|
805
|
+
if (fn.body)
|
|
806
|
+
visit(fn.body, false);
|
|
807
|
+
this.facts.set(fn, facts);
|
|
808
|
+
return facts;
|
|
809
|
+
}
|
|
810
|
+
declare(statement, env) {
|
|
811
|
+
const list = statement.declarationList ?? statement;
|
|
812
|
+
const reassignable = (list.flags & NodeFlags.Let) !== 0;
|
|
813
|
+
if (!reassignable && !(list.flags & NodeFlags.Const))
|
|
814
|
+
throw new Unsupported("`var` is not supported; use `const` or `let`", statement);
|
|
815
|
+
for (const declaration of list.declarations) {
|
|
816
|
+
if (!declaration.initializer && !reassignable)
|
|
817
|
+
throw new Unsupported("a declaration needs an initializer", declaration);
|
|
818
|
+
// A `let` without an initializer holds undefined until it is assigned.
|
|
819
|
+
this.bind(declaration.name, declaration.initializer ? this.evalExpr(declaration.initializer, env) : VOID, env, false, reassignable);
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
/**
|
|
823
|
+
* Bind the names of a pattern. A name becomes a reassignable variable only
|
|
824
|
+
* if the enclosing function assigns to it somewhere; everything else stays
|
|
825
|
+
* an immutable binding, which keeps closures over it exact.
|
|
826
|
+
*/
|
|
827
|
+
bind(pattern, value, env, label = false, reassignable = false) {
|
|
828
|
+
if (pattern.kind === K.Identifier) {
|
|
829
|
+
const cell = env.set(pattern.text, value, reassignable && this.assigned.at(-1)?.has(pattern.text) === true);
|
|
830
|
+
if (cell.mutable)
|
|
831
|
+
this.cells.push(cell);
|
|
832
|
+
if (label)
|
|
833
|
+
this.relabel(value, pattern.text);
|
|
834
|
+
return;
|
|
835
|
+
}
|
|
836
|
+
if (pattern.kind === K.ArrayBindingPattern) {
|
|
837
|
+
if (value.k !== "array")
|
|
838
|
+
throw new Unsupported(`cannot destructure ${describe(value)} as an array`, pattern);
|
|
839
|
+
pattern.elements.forEach((element, i) => {
|
|
840
|
+
if (element.kind === K.OmittedExpression)
|
|
841
|
+
return;
|
|
842
|
+
if (element.dotDotDotToken || element.initializer)
|
|
843
|
+
throw new Unsupported("rest elements and defaults are not supported in destructuring", element);
|
|
844
|
+
const item = value.items[i];
|
|
845
|
+
if (!item)
|
|
846
|
+
throw new Unsupported("destructuring reads past the end of the array", element);
|
|
847
|
+
this.bind(element.name, item, env, label, reassignable);
|
|
848
|
+
});
|
|
849
|
+
return;
|
|
850
|
+
}
|
|
851
|
+
if (pattern.kind === K.ObjectBindingPattern) {
|
|
852
|
+
if (value.k !== "record")
|
|
853
|
+
throw new Unsupported(`cannot destructure ${describe(value)} as an object`, pattern);
|
|
854
|
+
for (const element of pattern.elements) {
|
|
855
|
+
if (element.dotDotDotToken || element.initializer)
|
|
856
|
+
throw new Unsupported("rest elements and defaults are not supported in destructuring", element);
|
|
857
|
+
const key = element.propertyName ?? element.name;
|
|
858
|
+
if (key.kind !== K.Identifier && key.kind !== K.StringLiteral)
|
|
859
|
+
throw new Unsupported("computed property names are not supported", element);
|
|
860
|
+
const field = value.fields.get(key.text);
|
|
861
|
+
if (!field)
|
|
862
|
+
throw new Unsupported(`property \`${key.text}\` does not exist on this object`, element);
|
|
863
|
+
this.bind(element.name, field, env, label, reassignable);
|
|
864
|
+
}
|
|
865
|
+
return;
|
|
866
|
+
}
|
|
867
|
+
throw new Unsupported("this binding pattern is not supported", pattern);
|
|
868
|
+
}
|
|
869
|
+
call(fn, args, at) {
|
|
870
|
+
if (fn.k === "choice")
|
|
871
|
+
return this.branch(fn.cond, () => this.call(fn.a, args, at), () => this.call(fn.b, args, at));
|
|
872
|
+
if (fn.k !== "closure")
|
|
873
|
+
throw new Unsupported(`cannot call ${describe(fn)}`, at);
|
|
874
|
+
const node = fn.node;
|
|
875
|
+
if (this.stack.includes(node))
|
|
876
|
+
throw new Unsupported("recursive functions are not supported", at);
|
|
877
|
+
if (node.asteriskToken || node.modifiers?.some((m) => m.kind === K.AsyncKeyword))
|
|
878
|
+
throw new Unsupported("async functions and generators are not supported", at);
|
|
879
|
+
if (!node.body)
|
|
880
|
+
throw new Unsupported("this function has no body to translate", at);
|
|
881
|
+
const facts = this.factsOf(node);
|
|
882
|
+
if (facts.usesVar)
|
|
883
|
+
throw new Unsupported("`var` is not supported; use `const` or `let`", facts.usesVar);
|
|
884
|
+
this.noteExpectations(node);
|
|
885
|
+
// A function that reads or writes a variable someone reassigns would need
|
|
886
|
+
// that variable's value at the moment of the call, on every path. That is
|
|
887
|
+
// not tracked, so such closures are refused.
|
|
888
|
+
for (const name of fn.env.mutableNames()) {
|
|
889
|
+
if (facts.mentioned.has(name))
|
|
890
|
+
throw new Unsupported(`this function uses \`${name}\`, a variable that is reassigned outside it; that is not modeled`, at);
|
|
891
|
+
}
|
|
892
|
+
const env = fn.env.child();
|
|
893
|
+
const live = this.cells.length;
|
|
894
|
+
// A call runs to its own end, whatever its caller is in the middle of.
|
|
895
|
+
const merging = this.merging;
|
|
896
|
+
this.merging = 0;
|
|
897
|
+
this.stack.push(node);
|
|
898
|
+
this.assigned.push(facts.assigned);
|
|
899
|
+
try {
|
|
900
|
+
// A function expression with a name can call itself by it, whatever the name means outside.
|
|
901
|
+
if (node.kind === K.FunctionExpression && node.name)
|
|
902
|
+
env.set(node.name.text, fn);
|
|
903
|
+
// Every parameter is in scope, uninitialized, while the defaults before it run.
|
|
904
|
+
const parameters = parametersOf(node);
|
|
905
|
+
for (const parameter of parameters)
|
|
906
|
+
for (const name of boundNames(parameter.name))
|
|
907
|
+
env.set(name, UNINITIALIZED);
|
|
908
|
+
parameters.forEach((parameter, i) => {
|
|
909
|
+
if (parameter.dotDotDotToken)
|
|
910
|
+
throw new Unsupported("rest parameters are not supported", parameter);
|
|
911
|
+
let value = args[i];
|
|
912
|
+
// A default applies when the argument is missing or undefined.
|
|
913
|
+
if (value?.k === "choice" && parameter.initializer)
|
|
914
|
+
throw new Unsupported("an argument that may or may not be undefined, for a parameter with a default, is not supported", at);
|
|
915
|
+
if (!value || value.k === "void") {
|
|
916
|
+
if (parameter.initializer)
|
|
917
|
+
value = this.evalExpr(parameter.initializer, env);
|
|
918
|
+
else if (!value)
|
|
919
|
+
throw new Unsupported("a call must pass every parameter that has no default", at);
|
|
920
|
+
}
|
|
921
|
+
this.bind(parameter.name, value, env, false, true);
|
|
922
|
+
});
|
|
923
|
+
if (node.body.kind !== K.Block)
|
|
924
|
+
return this.evalExpr(node.body, env);
|
|
925
|
+
// Reaching the end of a function that returns values elsewhere yields
|
|
926
|
+
// undefined where a value is expected. Like a throw, that is allowed
|
|
927
|
+
// only where it is proved unreachable.
|
|
928
|
+
// The body has a scope of its own, so a closure made by a default does not see what the body declares.
|
|
929
|
+
return this.block(node.body.statements, env.child(), {
|
|
930
|
+
next: () => {
|
|
931
|
+
if (!facts.returnsValue)
|
|
932
|
+
return VOID;
|
|
933
|
+
this.emit("falloff", ir.FALSE, node);
|
|
934
|
+
return BOTTOM;
|
|
935
|
+
},
|
|
936
|
+
});
|
|
937
|
+
}
|
|
938
|
+
finally {
|
|
939
|
+
this.stack.pop();
|
|
940
|
+
this.assigned.pop();
|
|
941
|
+
this.cells.length = live;
|
|
942
|
+
this.merging = merging;
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
/**
|
|
946
|
+
* Evaluate a block in its own scope. Entering a block makes its function
|
|
947
|
+
* declarations callable at once, and puts its `const` and `let` names in
|
|
948
|
+
* scope before they hold a value, exactly as JavaScript does; reading one
|
|
949
|
+
* early is an error there and is refused here.
|
|
950
|
+
*/
|
|
951
|
+
block(statements, scope, flow) {
|
|
952
|
+
this.enter(statements, scope);
|
|
953
|
+
return this.exec(statements, 0, scope, flow);
|
|
954
|
+
}
|
|
955
|
+
enter(statements, scope) {
|
|
956
|
+
for (const statement of statements) {
|
|
957
|
+
if (statement.kind === K.FunctionDeclaration && statement.name)
|
|
958
|
+
scope.set(statement.name.text, { k: "closure", node: statement, env: scope });
|
|
959
|
+
else if (statement.kind === K.VariableStatement) {
|
|
960
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
961
|
+
for (const name of boundNames(declaration.name))
|
|
962
|
+
scope.set(name, UNINITIALIZED);
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
else if (statement.kind === K.ClassDeclaration && statement.name)
|
|
966
|
+
scope.set(statement.name.text, UNINITIALIZED);
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
/**
|
|
970
|
+
* Evaluate statements from index `i`. `flow.next` continues after the list.
|
|
971
|
+
* A branch that can leave early is evaluated together with everything that
|
|
972
|
+
* follows it; a branch that cannot is evaluated alone and its variables are
|
|
973
|
+
* merged, so straight-line code costs one pass.
|
|
974
|
+
*/
|
|
975
|
+
exec(statements, i, env, flow) {
|
|
976
|
+
if (i >= statements.length)
|
|
977
|
+
return flow.next();
|
|
978
|
+
const statement = statements[i];
|
|
979
|
+
if (++this.steps > MAX_STEPS)
|
|
980
|
+
throw new Unsupported("this code has too many paths to follow", statement);
|
|
981
|
+
const rest = () => this.exec(statements, i + 1, env, flow);
|
|
982
|
+
const after = { ...flow, next: rest };
|
|
983
|
+
const run = (block, to) => block ? this.block(block.kind === K.Block ? block.statements : [block], env.child(), to) : to.next();
|
|
984
|
+
switch (statement.kind) {
|
|
985
|
+
case K.EmptyStatement: return rest();
|
|
986
|
+
case K.VariableStatement:
|
|
987
|
+
this.declare(statement, env);
|
|
988
|
+
return rest();
|
|
989
|
+
case K.FunctionDeclaration:
|
|
990
|
+
// Declared when its block was entered.
|
|
991
|
+
return rest();
|
|
992
|
+
case K.ExpressionStatement:
|
|
993
|
+
this.effect(statement.expression, env);
|
|
994
|
+
return rest();
|
|
995
|
+
case K.ReturnStatement:
|
|
996
|
+
return statement.expression ? this.evalExpr(statement.expression, env) : VOID;
|
|
997
|
+
case K.ThrowStatement:
|
|
998
|
+
this.emit("unreachable", ir.FALSE, statement);
|
|
999
|
+
return BOTTOM;
|
|
1000
|
+
case K.BreakStatement:
|
|
1001
|
+
case K.ContinueStatement: {
|
|
1002
|
+
const target = statement.kind === K.BreakStatement ? flow.brk : flow.cont;
|
|
1003
|
+
if (statement.label || !target)
|
|
1004
|
+
throw new Unsupported("this break or continue is not supported", statement);
|
|
1005
|
+
return target();
|
|
1006
|
+
}
|
|
1007
|
+
case K.Block:
|
|
1008
|
+
return run(statement, after);
|
|
1009
|
+
case K.IfStatement: {
|
|
1010
|
+
const cond = this.bool(statement.expression, env);
|
|
1011
|
+
if (cond.t === "lit")
|
|
1012
|
+
return run(cond.value ? statement.thenStatement : statement.elseStatement, after);
|
|
1013
|
+
if (canExit(statement.thenStatement) || canExit(statement.elseStatement)) {
|
|
1014
|
+
return this.branch(cond, () => run(statement.thenStatement, after), () => run(statement.elseStatement, after), true);
|
|
1015
|
+
}
|
|
1016
|
+
const stop = { next: () => VOID };
|
|
1017
|
+
this.mergeStates(cond, () => run(statement.thenStatement, stop), () => run(statement.elseStatement, stop));
|
|
1018
|
+
return rest();
|
|
1019
|
+
}
|
|
1020
|
+
case K.SwitchStatement: {
|
|
1021
|
+
const subject = this.evalExpr(statement.expression, env);
|
|
1022
|
+
const clauses = statement.caseBlock.clauses;
|
|
1023
|
+
// The whole switch is one block: its declarations exist before any label is evaluated.
|
|
1024
|
+
const scope = env.child();
|
|
1025
|
+
this.enter(clauses.flatMap(clause => clause.statements), scope);
|
|
1026
|
+
// Entering at a clause runs it and every clause below it until a break.
|
|
1027
|
+
const statementsFrom = (start) => clauses.slice(start).flatMap(clause => clause.statements);
|
|
1028
|
+
const matchesAt = (clause) => {
|
|
1029
|
+
const label = this.evalExpr(clause.expression, scope);
|
|
1030
|
+
return this.scalarOf(this.over(subject, value => this.over(label, candidate => scalar(this.strictEqual(value, candidate, clause)))), clause, "bool");
|
|
1031
|
+
};
|
|
1032
|
+
for (const [index, clause] of clauses.entries()) {
|
|
1033
|
+
if (clause.kind === K.DefaultClause && index !== clauses.length - 1)
|
|
1034
|
+
throw new Unsupported("`default` must be the last clause of a switch", clause);
|
|
1035
|
+
}
|
|
1036
|
+
if (!canExit(statement)) {
|
|
1037
|
+
// Nothing leaves the switch early, so each clause is a branch whose assignments are merged.
|
|
1038
|
+
const stop = { next: () => VOID };
|
|
1039
|
+
const settle = (index) => {
|
|
1040
|
+
const clause = clauses[index];
|
|
1041
|
+
if (!clause)
|
|
1042
|
+
return;
|
|
1043
|
+
if (clause.kind === K.DefaultClause)
|
|
1044
|
+
return void this.exec(statementsFrom(index), 0, scope, stop);
|
|
1045
|
+
this.mergeStates(matchesAt(clause), () => void this.exec(statementsFrom(index), 0, scope, stop), () => settle(index + 1));
|
|
1046
|
+
};
|
|
1047
|
+
settle(0);
|
|
1048
|
+
return rest();
|
|
1049
|
+
}
|
|
1050
|
+
const bodyFrom = (start) => this.exec(statementsFrom(start), 0, scope, { ...flow, next: rest, brk: rest });
|
|
1051
|
+
const from = (index) => {
|
|
1052
|
+
const clause = clauses[index];
|
|
1053
|
+
if (!clause)
|
|
1054
|
+
return rest();
|
|
1055
|
+
if (clause.kind === K.DefaultClause)
|
|
1056
|
+
return bodyFrom(index);
|
|
1057
|
+
return this.branch(matchesAt(clause), () => bodyFrom(index), () => from(index + 1), true);
|
|
1058
|
+
};
|
|
1059
|
+
return from(0);
|
|
1060
|
+
}
|
|
1061
|
+
case K.ForOfStatement: {
|
|
1062
|
+
const declarations = statement.initializer;
|
|
1063
|
+
const declared = declarations.kind === K.VariableDeclarationList ? declarations.declarations : [];
|
|
1064
|
+
const reassignable = (declarations.flags & NodeFlags.Let) !== 0;
|
|
1065
|
+
if (statement.awaitModifier || declared.length !== 1 || declared[0].initializer || (!reassignable && !(declarations.flags & NodeFlags.Const))) {
|
|
1066
|
+
throw new Unsupported("a loop must be written `for (const item of items)`", statement);
|
|
1067
|
+
}
|
|
1068
|
+
// The loop is unrolled, so the array must have a length known here.
|
|
1069
|
+
const header = env.child();
|
|
1070
|
+
for (const name of boundNames(declared[0].name))
|
|
1071
|
+
header.set(name, UNINITIALIZED);
|
|
1072
|
+
const body = statement.statement;
|
|
1073
|
+
const loop = (items, after) => {
|
|
1074
|
+
if (items.k === "bottom")
|
|
1075
|
+
return BOTTOM;
|
|
1076
|
+
if (items.k !== "array")
|
|
1077
|
+
throw new Unsupported(`a loop needs an array whose length is known here, but this is ${describe(items)}`, statement.expression);
|
|
1078
|
+
const iterate = (index) => {
|
|
1079
|
+
const item = items.items[index];
|
|
1080
|
+
if (!item)
|
|
1081
|
+
return after();
|
|
1082
|
+
const scope = env.child();
|
|
1083
|
+
this.bind(declared[0].name, item, scope, false, reassignable);
|
|
1084
|
+
const onward = () => iterate(index + 1);
|
|
1085
|
+
return this.block(body.kind === K.Block ? body.statements : [body], scope.child(), { next: onward, cont: onward, brk: after });
|
|
1086
|
+
};
|
|
1087
|
+
return iterate(0);
|
|
1088
|
+
};
|
|
1089
|
+
// The list itself may depend on a condition. If the body cannot leave
|
|
1090
|
+
// the loop, each possible list is run and the variables are merged;
|
|
1091
|
+
// otherwise each runs on to the end of the function.
|
|
1092
|
+
const run = (items) => {
|
|
1093
|
+
items = this.settled(items);
|
|
1094
|
+
if (items.k !== "choice")
|
|
1095
|
+
return loop(items, rest);
|
|
1096
|
+
const choice = items;
|
|
1097
|
+
if (canExit(body))
|
|
1098
|
+
return this.branch(choice.cond, () => run(choice.a), () => run(choice.b), true);
|
|
1099
|
+
const each = (list) => {
|
|
1100
|
+
list = this.settled(list);
|
|
1101
|
+
if (list.k === "choice") {
|
|
1102
|
+
const inner = list;
|
|
1103
|
+
this.mergeStates(inner.cond, () => each(inner.a), () => each(inner.b));
|
|
1104
|
+
}
|
|
1105
|
+
else
|
|
1106
|
+
loop(list, () => VOID);
|
|
1107
|
+
};
|
|
1108
|
+
each(choice);
|
|
1109
|
+
return rest();
|
|
1110
|
+
};
|
|
1111
|
+
return run(this.evalExpr(statement.expression, header));
|
|
1112
|
+
}
|
|
1113
|
+
case K.WhileStatement:
|
|
1114
|
+
case K.DoStatement:
|
|
1115
|
+
case K.ForStatement: {
|
|
1116
|
+
// These loops are unrolled by running them: the condition must come
|
|
1117
|
+
// out as plainly true or false each time round, as it does when it
|
|
1118
|
+
// only depends on a counter and on lengths known here.
|
|
1119
|
+
const scope = env.child();
|
|
1120
|
+
const initializer = statement.kind === K.ForStatement ? statement.initializer : undefined;
|
|
1121
|
+
if (initializer?.kind === K.VariableDeclarationList) {
|
|
1122
|
+
for (const declaration of initializer.declarations)
|
|
1123
|
+
for (const name of boundNames(declaration.name))
|
|
1124
|
+
scope.set(name, UNINITIALIZED);
|
|
1125
|
+
this.declare(initializer, scope);
|
|
1126
|
+
}
|
|
1127
|
+
else if (initializer)
|
|
1128
|
+
this.effect(initializer, scope);
|
|
1129
|
+
const condition = statement.kind === K.ForStatement ? statement.condition : statement.expression;
|
|
1130
|
+
const body = statement.statement;
|
|
1131
|
+
let rounds = 0;
|
|
1132
|
+
const test = () => {
|
|
1133
|
+
const cond = condition ? this.bool(condition, scope) : ir.TRUE;
|
|
1134
|
+
const goes = this.settle(cond, () => new Unsupported("how many times this loop runs depends on a value that is not known here", condition));
|
|
1135
|
+
return goes.value ? round() : rest();
|
|
1136
|
+
};
|
|
1137
|
+
const step = () => {
|
|
1138
|
+
if (statement.kind === K.ForStatement && statement.incrementor)
|
|
1139
|
+
this.effect(statement.incrementor, scope);
|
|
1140
|
+
return test();
|
|
1141
|
+
};
|
|
1142
|
+
const round = () => {
|
|
1143
|
+
if (++rounds > MAX_ITERATIONS)
|
|
1144
|
+
throw new Unsupported(`this loop runs more than ${MAX_ITERATIONS} times, which is too many to unroll`, statement);
|
|
1145
|
+
return this.block(body.kind === K.Block ? body.statements : [body], scope.child(), { next: step, cont: step, brk: rest });
|
|
1146
|
+
};
|
|
1147
|
+
return statement.kind === K.DoStatement ? round() : test();
|
|
1148
|
+
}
|
|
1149
|
+
case K.ForInStatement:
|
|
1150
|
+
throw new Unsupported("for...in loops are not supported", statement);
|
|
1151
|
+
case K.TryStatement:
|
|
1152
|
+
throw new Unsupported("try, catch and finally are not supported", statement);
|
|
1153
|
+
default:
|
|
1154
|
+
throw new Unsupported("this statement is not supported", statement);
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
/** A statement that is an expression: an assignment, an assertion, or a call made for the assertions inside it. */
|
|
1158
|
+
effect(node, env) {
|
|
1159
|
+
if (node.kind === K.ParenthesizedExpression)
|
|
1160
|
+
return this.effect(node.expression, env);
|
|
1161
|
+
if (node.kind === K.BinaryExpression && node.operatorToken.kind >= K.FirstAssignment && node.operatorToken.kind <= K.LastAssignment) {
|
|
1162
|
+
const operator = node.operatorToken.kind;
|
|
1163
|
+
const base = COMPOUND.get(operator);
|
|
1164
|
+
if (operator !== K.EqualsToken && base === undefined)
|
|
1165
|
+
throw new Unsupported("this assignment operator is not supported", node);
|
|
1166
|
+
const cell = this.assignable(node.left, env);
|
|
1167
|
+
// The right-hand side is evaluated first; it cannot change the variable, because closures over it are refused.
|
|
1168
|
+
const right = this.evalExpr(node.right, env);
|
|
1169
|
+
cell.value = base === undefined ? right : this.arithmetic(base, cell.value, right, node);
|
|
1170
|
+
return;
|
|
1171
|
+
}
|
|
1172
|
+
if ((node.kind === K.PrefixUnaryExpression || node.kind === K.PostfixUnaryExpression) &&
|
|
1173
|
+
(node.operator === K.PlusPlusToken || node.operator === K.MinusMinusToken)) {
|
|
1174
|
+
const cell = this.assignable(node.operand, env);
|
|
1175
|
+
const one = scalar(ir.lit(1n), isNumber(cell.value));
|
|
1176
|
+
cell.value = this.arithmetic(node.operator === K.PlusPlusToken ? K.PlusToken : K.MinusToken, cell.value, one, node);
|
|
1177
|
+
return;
|
|
1178
|
+
}
|
|
1179
|
+
if (node.kind === K.CallExpression) {
|
|
1180
|
+
if (this.startsWithExpect(node))
|
|
1181
|
+
return this.expectStatement(node, env);
|
|
1182
|
+
this.evalExpr(node, env);
|
|
1183
|
+
return;
|
|
1184
|
+
}
|
|
1185
|
+
throw new Unsupported("this statement does nothing that is modeled", node);
|
|
1186
|
+
}
|
|
1187
|
+
assignable(target, env) {
|
|
1188
|
+
if (target.kind === K.ParenthesizedExpression)
|
|
1189
|
+
return this.assignable(target.expression, env);
|
|
1190
|
+
if (target.kind === K.PropertyAccessExpression || target.kind === K.ElementAccessExpression) {
|
|
1191
|
+
throw new Unsupported("changing an object or array in place is not modeled, because two names can refer to the same object; build a new value instead", target);
|
|
1192
|
+
}
|
|
1193
|
+
if (target.kind !== K.Identifier)
|
|
1194
|
+
throw new Unsupported("this assignment target is not supported", target);
|
|
1195
|
+
const cell = env.cell(target.text);
|
|
1196
|
+
if (!cell)
|
|
1197
|
+
throw new Unsupported(`\`${target.text}\` is not a local variable, so assigning to it is not supported`, target);
|
|
1198
|
+
if (!cell.mutable)
|
|
1199
|
+
throw new Unsupported(`\`${target.text}\` cannot be reassigned here`, target);
|
|
1200
|
+
return cell;
|
|
1201
|
+
}
|
|
1202
|
+
// ----------------------------------------------------------- expressions
|
|
1203
|
+
scalarOf(value, at, ty) {
|
|
1204
|
+
if (value.k !== "scalar")
|
|
1205
|
+
throw new Unsupported(`expected ${ty ? { bool: "a boolean", int: "a bigint", str: "a string" }[ty] : "a boolean, bigint or string"} here but found ${describe(value)}`, at);
|
|
1206
|
+
if (ty && value.e.ty !== ty)
|
|
1207
|
+
throw new Unsupported(`expected ${{ bool: "a boolean", int: "a bigint", str: "a string" }[ty]} here but found ${describe(value)}`, at);
|
|
1208
|
+
return value.e;
|
|
1209
|
+
}
|
|
1210
|
+
bool(node, env) {
|
|
1211
|
+
const value = this.evalExpr(node, env);
|
|
1212
|
+
if (value.k !== "scalar" || value.e.ty !== "bool")
|
|
1213
|
+
throw new Unsupported(`a condition must be a boolean; JavaScript truthiness of ${describe(value)} is not modeled`, node);
|
|
1214
|
+
return value.e;
|
|
1215
|
+
}
|
|
1216
|
+
wellFormed(text, at) {
|
|
1217
|
+
if (!text.isWellFormed())
|
|
1218
|
+
throw new Unsupported("string literals with unpaired surrogates are not supported", at);
|
|
1219
|
+
return text;
|
|
1220
|
+
}
|
|
1221
|
+
evalExpr(node, env) {
|
|
1222
|
+
switch (node.kind) {
|
|
1223
|
+
case K.ParenthesizedExpression:
|
|
1224
|
+
case K.AsExpression:
|
|
1225
|
+
case K.SatisfiesExpression:
|
|
1226
|
+
case K.NonNullExpression:
|
|
1227
|
+
case K.TypeAssertionExpression:
|
|
1228
|
+
return this.evalExpr(node.expression, env);
|
|
1229
|
+
case K.StringLiteral:
|
|
1230
|
+
case K.NoSubstitutionTemplateLiteral:
|
|
1231
|
+
return this.note(ir.lit(this.wellFormed(node.text, node)));
|
|
1232
|
+
case K.TrueKeyword: return scalar(ir.TRUE);
|
|
1233
|
+
case K.FalseKeyword: return scalar(ir.FALSE);
|
|
1234
|
+
case K.BigIntLiteral: return this.note(ir.lit(BigInt(node.text.replace(/n$/, "").replaceAll("_", ""))));
|
|
1235
|
+
case K.NumericLiteral: {
|
|
1236
|
+
const value = Number(node.text);
|
|
1237
|
+
if (!Number.isSafeInteger(value))
|
|
1238
|
+
throw new Unsupported("only whole numbers up to 2^53 - 1 are modeled; fractions and larger numbers are not", node);
|
|
1239
|
+
return this.note(ir.lit(BigInt(value)), true);
|
|
1240
|
+
}
|
|
1241
|
+
case K.Identifier: return this.read(node, env);
|
|
1242
|
+
case K.ArrowFunction:
|
|
1243
|
+
case K.FunctionExpression:
|
|
1244
|
+
return { k: "closure", node, env };
|
|
1245
|
+
case K.PrefixUnaryExpression: {
|
|
1246
|
+
if (node.operator === K.ExclamationToken)
|
|
1247
|
+
return scalar(ir.not(this.bool(node.operand, env)));
|
|
1248
|
+
if (node.operator === K.MinusToken) {
|
|
1249
|
+
const operand = this.evalExpr(node.operand, env);
|
|
1250
|
+
return scalar(ir.neg(this.scalarOf(operand, node.operand, "int")), isNumber(operand));
|
|
1251
|
+
}
|
|
1252
|
+
throw new Unsupported("this operator is not supported", node);
|
|
1253
|
+
}
|
|
1254
|
+
case K.ConditionalExpression:
|
|
1255
|
+
return this.branch(this.bool(node.condition, env), () => this.evalExpr(node.whenTrue, env), () => this.evalExpr(node.whenFalse, env));
|
|
1256
|
+
case K.BinaryExpression: return this.binary(node, env);
|
|
1257
|
+
case K.TemplateExpression: {
|
|
1258
|
+
let result = ir.lit(this.wellFormed(node.head.text, node));
|
|
1259
|
+
for (const span of node.templateSpans) {
|
|
1260
|
+
const part = this.evalExpr(span.expression, env);
|
|
1261
|
+
if (part.k !== "scalar" || part.e.ty === "bool")
|
|
1262
|
+
throw new Unsupported(`only strings and bigints can be interpolated, but this is ${describe(part)}`, span.expression);
|
|
1263
|
+
const text = part.e.ty === "int" ? ir.toStr(part.e) : part.e;
|
|
1264
|
+
result = ir.concat(ir.concat(result, text), ir.lit(this.wellFormed(span.literal.text, span)));
|
|
1265
|
+
}
|
|
1266
|
+
return scalar(result);
|
|
1267
|
+
}
|
|
1268
|
+
case K.ObjectLiteralExpression: {
|
|
1269
|
+
const fields = new Map();
|
|
1270
|
+
for (const property of node.properties) {
|
|
1271
|
+
if (property.kind === K.SpreadAssignment) {
|
|
1272
|
+
const spread = this.evalExpr(property.expression, env);
|
|
1273
|
+
if (spread.k !== "record")
|
|
1274
|
+
throw new Unsupported(`cannot spread ${describe(spread)} into an object`, property);
|
|
1275
|
+
for (const [key, field] of spread.fields)
|
|
1276
|
+
fields.set(key, field);
|
|
1277
|
+
}
|
|
1278
|
+
else if (property.kind === K.ShorthandPropertyAssignment) {
|
|
1279
|
+
fields.set(property.name.text, this.read(property.name, env, true));
|
|
1280
|
+
}
|
|
1281
|
+
else if (property.kind === K.PropertyAssignment && (property.name.kind === K.Identifier || property.name.kind === K.StringLiteral)) {
|
|
1282
|
+
// In an object literal this name sets the prototype instead of storing a property.
|
|
1283
|
+
if (property.name.text === "__proto__")
|
|
1284
|
+
throw new Unsupported("`__proto__` in an object literal sets the prototype, which is not modeled", property);
|
|
1285
|
+
fields.set(property.name.text, this.evalExpr(property.initializer, env));
|
|
1286
|
+
}
|
|
1287
|
+
else
|
|
1288
|
+
throw new Unsupported("methods, accessors and computed property names are not supported in object literals", property);
|
|
1289
|
+
}
|
|
1290
|
+
return { k: "record", fields };
|
|
1291
|
+
}
|
|
1292
|
+
case K.ArrayLiteralExpression: {
|
|
1293
|
+
const items = [];
|
|
1294
|
+
for (const element of node.elements) {
|
|
1295
|
+
if (element.kind === K.SpreadElement) {
|
|
1296
|
+
const spread = this.evalExpr(element.expression, env);
|
|
1297
|
+
if (spread.k !== "array")
|
|
1298
|
+
throw new Unsupported(`cannot spread ${describe(spread)} into an array`, element);
|
|
1299
|
+
items.push(...spread.items);
|
|
1300
|
+
}
|
|
1301
|
+
else if (element.kind === K.OmittedExpression)
|
|
1302
|
+
throw new Unsupported("array holes are not supported", node);
|
|
1303
|
+
else
|
|
1304
|
+
items.push(this.evalExpr(element, env));
|
|
1305
|
+
}
|
|
1306
|
+
return { k: "array", items };
|
|
1307
|
+
}
|
|
1308
|
+
case K.PropertyAccessExpression: {
|
|
1309
|
+
if (node.questionDotToken)
|
|
1310
|
+
throw new Unsupported("optional chaining is not supported", node);
|
|
1311
|
+
if (this.isNamespace(node.expression, env))
|
|
1312
|
+
return this.global(node.name);
|
|
1313
|
+
const name = node.name.text;
|
|
1314
|
+
if (name === "__proto__")
|
|
1315
|
+
throw new Unsupported("reading `__proto__` is not modeled", node);
|
|
1316
|
+
return this.over(this.evalExpr(node.expression, env), object => {
|
|
1317
|
+
if (object.k === "bottom")
|
|
1318
|
+
return BOTTOM;
|
|
1319
|
+
if (name === "length" && object.k === "array")
|
|
1320
|
+
return scalar(ir.lit(BigInt(object.items.length)), true);
|
|
1321
|
+
if (name === "length" && object.k === "scalar" && object.e.ty === "str") {
|
|
1322
|
+
// JavaScript counts UTF-16 units and Lean counts characters, so only a known string has a length here.
|
|
1323
|
+
if (object.e.t !== "lit")
|
|
1324
|
+
throw new Unsupported("the length of a string that is not known here is not modeled", node);
|
|
1325
|
+
return scalar(ir.lit(BigInt(object.e.value.length)), true);
|
|
1326
|
+
}
|
|
1327
|
+
if (object.k !== "record")
|
|
1328
|
+
throw new Unsupported(`reading \`.${name}\` of ${describe(object)} is not supported`, node);
|
|
1329
|
+
const field = object.fields.get(name);
|
|
1330
|
+
if (!field)
|
|
1331
|
+
throw new Unsupported(`property \`${name}\` does not exist on this object`, node);
|
|
1332
|
+
return field;
|
|
1333
|
+
});
|
|
1334
|
+
}
|
|
1335
|
+
case K.ElementAccessExpression: return this.elementAccess(node, env);
|
|
1336
|
+
case K.CallExpression: return this.callExpression(node, env);
|
|
1337
|
+
default:
|
|
1338
|
+
throw new Unsupported("this expression is not supported", node);
|
|
1339
|
+
}
|
|
1340
|
+
}
|
|
1341
|
+
/** A literal from the source, remembered as a value worth trying as an input. */
|
|
1342
|
+
note(literal, num = false) {
|
|
1343
|
+
if (this.mentioned.length < 256)
|
|
1344
|
+
this.mentioned.push(literal);
|
|
1345
|
+
return scalar(literal, num);
|
|
1346
|
+
}
|
|
1347
|
+
/** The value a name stands for: a local binding, or else a module-level declaration. */
|
|
1348
|
+
read(node, env, shorthand = false) {
|
|
1349
|
+
const local = env.get(node.text);
|
|
1350
|
+
if (local?.k === "uninitialized")
|
|
1351
|
+
throw new Unsupported(`\`${node.text}\` is read before its declaration has run, which throws`, node);
|
|
1352
|
+
if (local)
|
|
1353
|
+
return this.settled(local);
|
|
1354
|
+
if (node.text === "undefined") {
|
|
1355
|
+
const symbol = shorthand ? undefined : this.checker.getSymbolAtLocation(node);
|
|
1356
|
+
if (symbol && this.checker.isUndefinedSymbol(symbol))
|
|
1357
|
+
return VOID;
|
|
1358
|
+
}
|
|
1359
|
+
return this.global(node, shorthand);
|
|
1360
|
+
}
|
|
1361
|
+
/**
|
|
1362
|
+
* A value that depends on a condition, reduced by what is already known on
|
|
1363
|
+
* this path. After `if (x !== undefined)`, a variable that holds something
|
|
1364
|
+
* or undefined depending on that very test holds the something.
|
|
1365
|
+
*/
|
|
1366
|
+
settled(value) {
|
|
1367
|
+
while (value.k === "choice") {
|
|
1368
|
+
const cond = value.cond;
|
|
1369
|
+
if (this.pc.some(known => ir.same(known, cond)))
|
|
1370
|
+
value = value.a;
|
|
1371
|
+
else {
|
|
1372
|
+
const negated = ir.not(cond);
|
|
1373
|
+
if (this.pc.some(known => ir.same(known, negated)))
|
|
1374
|
+
value = value.b;
|
|
1375
|
+
else
|
|
1376
|
+
break;
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
1379
|
+
return value;
|
|
1380
|
+
}
|
|
1381
|
+
/**
|
|
1382
|
+
* `a === b` for two values. Values of different kinds are never equal, and
|
|
1383
|
+
* a number is a different kind from a bigint even when both are whole.
|
|
1384
|
+
*/
|
|
1385
|
+
strictEqual(a, b, at) {
|
|
1386
|
+
if (a.k === "void" || b.k === "void")
|
|
1387
|
+
return a.k === b.k ? ir.TRUE : this.isPlain(a) && this.isPlain(b) ? ir.FALSE : this.refuseEquality(a, b, at);
|
|
1388
|
+
if (a.k !== "scalar" || b.k !== "scalar")
|
|
1389
|
+
return this.refuseEquality(a, b, at);
|
|
1390
|
+
return a.e.ty === b.e.ty && !!a.num === !!b.num ? ir.eq(a.e, b.e) : ir.FALSE;
|
|
1391
|
+
}
|
|
1392
|
+
isPlain(value) {
|
|
1393
|
+
return value.k === "scalar" || value.k === "void";
|
|
1394
|
+
}
|
|
1395
|
+
refuseEquality(a, b, at) {
|
|
1396
|
+
throw new Unsupported(`comparing ${describe(a)} with ${describe(b)} is not modeled; only booleans, bigints, numbers, strings and undefined are compared by ===`, at);
|
|
1397
|
+
}
|
|
1398
|
+
binary(node, env) {
|
|
1399
|
+
const operator = node.operatorToken.kind;
|
|
1400
|
+
if (operator === K.AmpersandAmpersandToken || operator === K.BarBarToken) {
|
|
1401
|
+
const isAnd = operator === K.AmpersandAmpersandToken;
|
|
1402
|
+
const left = this.bool(node.left, env);
|
|
1403
|
+
if (left.t === "lit" && left.value !== isAnd)
|
|
1404
|
+
return scalar(left);
|
|
1405
|
+
const right = this.under(isAnd ? left : ir.not(left), () => this.bool(node.right, env));
|
|
1406
|
+
return scalar(isAnd ? ir.and(left, right) : ir.or(left, right));
|
|
1407
|
+
}
|
|
1408
|
+
const leftValue = this.evalExpr(node.left, env);
|
|
1409
|
+
const rightValue = this.evalExpr(node.right, env);
|
|
1410
|
+
if (operator === K.EqualsEqualsEqualsToken || operator === K.ExclamationEqualsEqualsToken) {
|
|
1411
|
+
const equal = this.over(leftValue, left => this.over(rightValue, right => scalar(this.strictEqual(left, right, node))));
|
|
1412
|
+
const same = this.scalarOf(equal, node, "bool");
|
|
1413
|
+
return scalar(operator === K.EqualsEqualsEqualsToken ? same : ir.not(same));
|
|
1414
|
+
}
|
|
1415
|
+
if (operator === K.EqualsEqualsToken || operator === K.ExclamationEqualsToken)
|
|
1416
|
+
throw new Unsupported("use === and !==; loose equality is not modeled", node);
|
|
1417
|
+
if (operator >= K.FirstAssignment && operator <= K.LastAssignment)
|
|
1418
|
+
throw new Unsupported("an assignment used as a value is not supported; write it as its own statement", node);
|
|
1419
|
+
return this.arithmetic(operator, leftValue, rightValue, node);
|
|
1420
|
+
}
|
|
1421
|
+
/** `+ - * / %` and the comparisons, on values already evaluated. */
|
|
1422
|
+
arithmetic(operator, leftValue, rightValue, node) {
|
|
1423
|
+
if (operator === K.PlusToken && leftValue.k === "scalar" && rightValue.k === "scalar" && leftValue.e.ty === "str" && rightValue.e.ty === "str") {
|
|
1424
|
+
return scalar(ir.concat(leftValue.e, rightValue.e));
|
|
1425
|
+
}
|
|
1426
|
+
const left = this.scalarOf(leftValue, node.left ?? node, "int");
|
|
1427
|
+
const right = this.scalarOf(rightValue, node.right ?? node, "int");
|
|
1428
|
+
if (isNumber(leftValue) !== isNumber(rightValue))
|
|
1429
|
+
throw new Unsupported(`cannot combine ${describe(leftValue)} with ${describe(rightValue)}`, node);
|
|
1430
|
+
if (isNumber(leftValue)) {
|
|
1431
|
+
// A `number` is modeled as the whole number it holds. That is exact for
|
|
1432
|
+
// these operators as long as the result stays within what a double
|
|
1433
|
+
// holds exactly, which each use must prove.
|
|
1434
|
+
const exact = (result) => {
|
|
1435
|
+
this.emit("overflow", ir.isSafe(result), node);
|
|
1436
|
+
return scalar(result, true);
|
|
1437
|
+
};
|
|
1438
|
+
switch (operator) {
|
|
1439
|
+
case K.PlusToken: return exact(ir.add(left, right));
|
|
1440
|
+
case K.MinusToken: return exact(ir.sub(left, right));
|
|
1441
|
+
case K.AsteriskToken: return exact(ir.mul(left, right));
|
|
1442
|
+
case K.PercentToken:
|
|
1443
|
+
this.emit("nan", ir.not(ir.eq(right, ir.lit(0n))), node);
|
|
1444
|
+
return scalar(ir.mod(left, right), true);
|
|
1445
|
+
case K.SlashToken:
|
|
1446
|
+
throw new Unsupported("dividing numbers can give a fraction, which is not modeled; write Math.floor(a / b) or Math.trunc(a / b), or use bigint", node);
|
|
1447
|
+
}
|
|
1448
|
+
}
|
|
1449
|
+
switch (operator) {
|
|
1450
|
+
case K.PlusToken: return scalar(ir.add(left, right));
|
|
1451
|
+
case K.MinusToken: return scalar(ir.sub(left, right));
|
|
1452
|
+
case K.AsteriskToken: return scalar(ir.mul(left, right));
|
|
1453
|
+
case K.SlashToken:
|
|
1454
|
+
case K.PercentToken:
|
|
1455
|
+
this.emit("nothrow", ir.not(ir.eq(right, ir.lit(0n))), node);
|
|
1456
|
+
return scalar(operator === K.SlashToken ? ir.div(left, right) : ir.mod(left, right));
|
|
1457
|
+
case K.LessThanToken: return scalar(ir.lt(left, right));
|
|
1458
|
+
case K.LessThanEqualsToken: return scalar(ir.le(left, right));
|
|
1459
|
+
case K.GreaterThanToken: return scalar(ir.lt(right, left));
|
|
1460
|
+
case K.GreaterThanEqualsToken: return scalar(ir.le(right, left));
|
|
1461
|
+
default: throw new Unsupported("this operator is not supported", node);
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
elementAccess(node, env) {
|
|
1465
|
+
if (node.questionDotToken)
|
|
1466
|
+
throw new Unsupported("optional chaining is not supported", node);
|
|
1467
|
+
const index = node.argumentExpression;
|
|
1468
|
+
return this.over(this.evalExpr(node.expression, env), object => {
|
|
1469
|
+
if (object.k === "bottom")
|
|
1470
|
+
return BOTTOM;
|
|
1471
|
+
if (object.k === "array") {
|
|
1472
|
+
const position = this.evalExpr(index, env);
|
|
1473
|
+
const refusal = () => new Unsupported("an array can only be indexed by a position that is known here", node);
|
|
1474
|
+
if (!isNumber(position) || position.k !== "scalar")
|
|
1475
|
+
throw refusal();
|
|
1476
|
+
const item = object.items[Number(this.settle(position.e, refusal).value)];
|
|
1477
|
+
if (!item)
|
|
1478
|
+
throw new Unsupported("this index is outside the array", node);
|
|
1479
|
+
return item;
|
|
1480
|
+
}
|
|
1481
|
+
if (object.k !== "record")
|
|
1482
|
+
throw new Unsupported(`indexing ${describe(object)} is not supported`, node);
|
|
1483
|
+
const key = this.scalarOf(this.evalExpr(index, env), index, "str");
|
|
1484
|
+
if (key.t === "lit") {
|
|
1485
|
+
const field = object.fields.get(key.value);
|
|
1486
|
+
if (!field || key.value === "__proto__")
|
|
1487
|
+
throw new Unsupported(`property \`${key.value}\` does not exist on this object`, node);
|
|
1488
|
+
return field;
|
|
1489
|
+
}
|
|
1490
|
+
// The key is compared with every property name. A key that matches none
|
|
1491
|
+
// would read `undefined`, which is not modeled, so that case must be
|
|
1492
|
+
// proved impossible. The key's declared type is not trusted for this: a
|
|
1493
|
+
// cast can make it claim anything.
|
|
1494
|
+
const names = [...object.fields.keys()];
|
|
1495
|
+
const pick = (i) => {
|
|
1496
|
+
if (i === names.length) {
|
|
1497
|
+
this.emit("missing", ir.FALSE, node);
|
|
1498
|
+
return BOTTOM;
|
|
1499
|
+
}
|
|
1500
|
+
return this.branch(ir.eq(key, ir.lit(names[i])), () => object.fields.get(names[i]), () => pick(i + 1));
|
|
1501
|
+
};
|
|
1502
|
+
return pick(0);
|
|
1503
|
+
});
|
|
1504
|
+
}
|
|
1505
|
+
callExpression(node, env) {
|
|
1506
|
+
if (node.questionDotToken)
|
|
1507
|
+
throw new Unsupported("optional chaining is not supported", node);
|
|
1508
|
+
const callee = node.expression;
|
|
1509
|
+
const args = () => node.arguments.map(argument => {
|
|
1510
|
+
if (argument.kind === K.SpreadElement)
|
|
1511
|
+
throw new Unsupported("spread arguments are not supported", argument);
|
|
1512
|
+
return this.evalExpr(argument, env);
|
|
1513
|
+
});
|
|
1514
|
+
if (callee.kind === K.Identifier && !env.get(callee.text) && node.arguments.length === 1 && this.isBuiltin(callee)) {
|
|
1515
|
+
this.assertBuiltinsIntact(node);
|
|
1516
|
+
if (callee.text === "String")
|
|
1517
|
+
return this.text(args()[0], node);
|
|
1518
|
+
if (callee.text === "BigInt" || callee.text === "Number") {
|
|
1519
|
+
const [value] = args();
|
|
1520
|
+
const integer = this.scalarOf(value, node, "int");
|
|
1521
|
+
// Every whole number is a bigint, but only some bigints fit a number exactly.
|
|
1522
|
+
if (callee.text === "Number" && !isNumber(value))
|
|
1523
|
+
this.emit("overflow", ir.isSafe(integer), node);
|
|
1524
|
+
return scalar(integer, callee.text === "Number");
|
|
1525
|
+
}
|
|
1526
|
+
}
|
|
1527
|
+
if (callee.kind === K.PropertyAccessExpression && callee.expression.kind === K.Identifier && callee.expression.text === "Math" &&
|
|
1528
|
+
!env.get("Math") && this.isBuiltin(callee.expression))
|
|
1529
|
+
return this.math(callee.name.text, node, env);
|
|
1530
|
+
if (callee.kind === K.PropertyAccessExpression && !this.isNamespace(callee.expression, env)) {
|
|
1531
|
+
const method = callee.name.text;
|
|
1532
|
+
return this.over(this.evalExpr(callee.expression, env), receiver => {
|
|
1533
|
+
if (receiver.k === "bottom")
|
|
1534
|
+
return BOTTOM;
|
|
1535
|
+
if (receiver.k === "scalar" && method === "toString" && node.arguments.length === 0) {
|
|
1536
|
+
this.assertBuiltinsIntact(node);
|
|
1537
|
+
return this.text(receiver, node);
|
|
1538
|
+
}
|
|
1539
|
+
if (receiver.k === "array") {
|
|
1540
|
+
this.assertBuiltinsIntact(node);
|
|
1541
|
+
return this.arrayMethod(receiver.items, method, args(), node);
|
|
1542
|
+
}
|
|
1543
|
+
if (receiver.k === "record" && receiver.fields.has(method))
|
|
1544
|
+
return this.call(receiver.fields.get(method), args(), node);
|
|
1545
|
+
throw new Unsupported(`calling \`.${method}\` on ${describe(receiver)} is not supported`, node);
|
|
1546
|
+
});
|
|
1547
|
+
}
|
|
1548
|
+
return this.call(this.evalExpr(callee, env), args(), node);
|
|
1549
|
+
}
|
|
1550
|
+
/** The `Math` functions that keep whole numbers whole. */
|
|
1551
|
+
/**
|
|
1552
|
+
* Refuse to model a built-in if any file of the program writes to one, as
|
|
1553
|
+
* in `Math.abs = ...` or a patched prototype: the name would no longer mean
|
|
1554
|
+
* what the model assumes. Installed packages are not examined.
|
|
1555
|
+
*/
|
|
1556
|
+
assertBuiltinsIntact(use) {
|
|
1557
|
+
if (this.tampering === null) {
|
|
1558
|
+
this.tampering = undefined;
|
|
1559
|
+
const builtins = new Set(["Math", "Object", "Array", "String", "Number", "BigInt", "Boolean", "JSON", "Reflect", "Function", "Symbol", "globalThis"]);
|
|
1560
|
+
const rootOf = (node) => {
|
|
1561
|
+
while (node.kind === K.PropertyAccessExpression || node.kind === K.ElementAccessExpression || node.kind === K.ParenthesizedExpression ||
|
|
1562
|
+
node.kind === K.AsExpression || node.kind === K.NonNullExpression)
|
|
1563
|
+
node = node.expression;
|
|
1564
|
+
return node;
|
|
1565
|
+
};
|
|
1566
|
+
const visit = (node) => {
|
|
1567
|
+
if (this.tampering)
|
|
1568
|
+
return;
|
|
1569
|
+
const assigns = node.kind === K.BinaryExpression && node.operatorToken.kind >= K.FirstAssignment && node.operatorToken.kind <= K.LastAssignment;
|
|
1570
|
+
const target = assigns ? node.left : node.kind === K.DeleteExpression ? node.expression
|
|
1571
|
+
: (node.kind === K.PrefixUnaryExpression || node.kind === K.PostfixUnaryExpression) && (node.operator === K.PlusPlusToken || node.operator === K.MinusMinusToken) ? node.operand : undefined;
|
|
1572
|
+
const root = target && target.kind !== K.Identifier ? rootOf(target) : undefined;
|
|
1573
|
+
// Also catch a built-in handed to something that writes to it, as in Object.assign(Math, ...) or
|
|
1574
|
+
// Object.defineProperty(Array.prototype, ...). Passing one as a value, as in `.map(String)`, is not a write.
|
|
1575
|
+
const writes = node.kind === K.CallExpression && WRITERS.test(node.expression.getText(node.getSourceFile()));
|
|
1576
|
+
const handed = writes ? node.arguments.slice(0, 1).map(rootOf).find(a => a.kind === K.Identifier && builtins.has(a.text)) : undefined;
|
|
1577
|
+
const culprit = root?.kind === K.Identifier && builtins.has(root.text) ? root : handed;
|
|
1578
|
+
if (culprit && this.isBuiltin(culprit)) {
|
|
1579
|
+
const at = locate(node);
|
|
1580
|
+
this.tampering = { message: `\`${culprit.text}\` is modified at ${at.file}:${at.line}, so built-in behaviour cannot be assumed`, node };
|
|
1581
|
+
return;
|
|
1582
|
+
}
|
|
1583
|
+
node.forEachChild(visit);
|
|
1584
|
+
};
|
|
1585
|
+
for (const name of this.program.getSourceFileNames()) {
|
|
1586
|
+
const file = this.program.getSourceFile(name);
|
|
1587
|
+
if (file && !file.isDeclarationFile && !this.program.isSourceFileFromExternalLibrary(file))
|
|
1588
|
+
visit(file);
|
|
1589
|
+
}
|
|
1590
|
+
}
|
|
1591
|
+
if (this.tampering)
|
|
1592
|
+
throw new Unsupported(this.tampering.message, use);
|
|
1593
|
+
}
|
|
1594
|
+
math(name, node, env) {
|
|
1595
|
+
this.assertBuiltinsIntact(node);
|
|
1596
|
+
const parameters = node.arguments;
|
|
1597
|
+
const number = (argument) => {
|
|
1598
|
+
const value = this.evalExpr(argument, env);
|
|
1599
|
+
if (!isNumber(value))
|
|
1600
|
+
throw new Unsupported(`Math.${name} is modeled for numbers, but this is ${describe(value)}`, argument);
|
|
1601
|
+
return value.e;
|
|
1602
|
+
};
|
|
1603
|
+
const [first] = parameters;
|
|
1604
|
+
if (first && parameters.length === 1 && (name === "floor" || name === "trunc" || name === "ceil" || name === "round")) {
|
|
1605
|
+
let inner = first;
|
|
1606
|
+
while (inner.kind === K.ParenthesizedExpression)
|
|
1607
|
+
inner = inner.expression;
|
|
1608
|
+
if (inner.kind !== K.BinaryExpression || inner.operatorToken.kind !== K.SlashToken)
|
|
1609
|
+
return scalar(number(first), true);
|
|
1610
|
+
// Rounding a quotient of whole numbers. Dividing two exactly held whole
|
|
1611
|
+
// numbers and rounding gives the same integer as exact division; that
|
|
1612
|
+
// does not hold for Math.round, whose halfway cases depend on the fraction.
|
|
1613
|
+
if (name === "round")
|
|
1614
|
+
throw new Unsupported("Math.round of a quotient is not modeled; use Math.floor or Math.trunc", node);
|
|
1615
|
+
const a = number(inner.left);
|
|
1616
|
+
const b = number(inner.right);
|
|
1617
|
+
this.emit("nan", ir.not(ir.eq(b, ir.lit(0n))), inner);
|
|
1618
|
+
if (name === "trunc")
|
|
1619
|
+
return scalar(ir.div(a, b), true);
|
|
1620
|
+
// The ceiling of a quotient is the negated floor of its negation.
|
|
1621
|
+
return scalar(name === "floor" ? ir.fdiv(a, b) : ir.neg(ir.fdiv(ir.neg(a), b)), true);
|
|
1622
|
+
}
|
|
1623
|
+
if (first && parameters.length === 1 && name === "abs") {
|
|
1624
|
+
const value = number(first);
|
|
1625
|
+
return scalar(ir.ite(ir.lt(value, ir.lit(0n)), ir.neg(value), value), true);
|
|
1626
|
+
}
|
|
1627
|
+
if (first && parameters.length === 1 && name === "sign") {
|
|
1628
|
+
const value = number(first);
|
|
1629
|
+
return scalar(ir.ite(ir.lt(value, ir.lit(0n)), ir.lit(-1n), ir.ite(ir.eq(value, ir.lit(0n)), ir.lit(0n), ir.lit(1n))), true);
|
|
1630
|
+
}
|
|
1631
|
+
if (parameters.length >= 1 && (name === "min" || name === "max") && parameters.every(p => p.kind !== K.SpreadElement)) {
|
|
1632
|
+
return scalar(parameters.map(number).reduce((best, value) => ir.ite(name === "min" ? ir.lt(value, best) : ir.lt(best, value), value, best)), true);
|
|
1633
|
+
}
|
|
1634
|
+
throw new Unsupported(`Math.${name} is not supported`, node);
|
|
1635
|
+
}
|
|
1636
|
+
/** `String(x)` and `x.toString()` for the scalars whose text Lean and JavaScript agree on. */
|
|
1637
|
+
text(value, at) {
|
|
1638
|
+
if (value.k === "scalar" && value.e.ty === "str")
|
|
1639
|
+
return value;
|
|
1640
|
+
if (value.k === "scalar" && value.e.ty === "int")
|
|
1641
|
+
return scalar(ir.toStr(value.e));
|
|
1642
|
+
throw new Unsupported(`converting ${describe(value)} to a string is not supported`, at);
|
|
1643
|
+
}
|
|
1644
|
+
/** Whether an identifier refers to a global from TypeScript's own library files. */
|
|
1645
|
+
isBuiltin(node) {
|
|
1646
|
+
const declaration = this.checker.getSymbolAtLocation(node)?.declarations[0]?.resolve();
|
|
1647
|
+
return !!declaration && this.program.isSourceFileDefaultLibrary(declaration.getSourceFile());
|
|
1648
|
+
}
|
|
1649
|
+
arrayMethod(items, method, args, node) {
|
|
1650
|
+
if (ARRAY_MUTATORS.has(method)) {
|
|
1651
|
+
throw new Unsupported("changing an object or array in place is not modeled, because two names can refer to the same object; build a new value instead", node);
|
|
1652
|
+
}
|
|
1653
|
+
if (!["includes", "some", "every", "map", "reduce"].includes(method))
|
|
1654
|
+
throw new Unsupported(`the array method \`.${method}\` is not supported`, node);
|
|
1655
|
+
const [first, second] = args;
|
|
1656
|
+
const expected = method === "reduce" ? 2 : 1;
|
|
1657
|
+
if (!first || args.length !== expected) {
|
|
1658
|
+
throw new Unsupported(method === "reduce" ? "`.reduce` is supported with a callback and an initial value" : `\`.${method}\` is supported with exactly one argument`, node);
|
|
1659
|
+
}
|
|
1660
|
+
// A callback is passed each element and its position. One that declares
|
|
1661
|
+
// more parameters would also receive the array itself, which is refused.
|
|
1662
|
+
const invoke = (fn, values) => {
|
|
1663
|
+
if (fn.k === "choice")
|
|
1664
|
+
return this.branch(fn.cond, () => invoke(fn.a, values), () => invoke(fn.b, values));
|
|
1665
|
+
if (fn.k === "closure" && parametersOf(fn.node).length > values.length)
|
|
1666
|
+
throw new Unsupported("an array callback that takes the array itself is not supported", node);
|
|
1667
|
+
return this.call(fn, values, node);
|
|
1668
|
+
};
|
|
1669
|
+
const callable = (fn) => fn.k === "closure" || (fn.k === "choice" && callable(fn.a) && callable(fn.b));
|
|
1670
|
+
if (method !== "includes" && !callable(first))
|
|
1671
|
+
throw new Unsupported(`\`.${method}\` needs a function, but this is ${describe(first)}`, node);
|
|
1672
|
+
const position = (index) => scalar(ir.lit(BigInt(index)), true);
|
|
1673
|
+
switch (method) {
|
|
1674
|
+
case "reduce":
|
|
1675
|
+
return items.reduce((accumulator, item, index) => invoke(first, [accumulator, item, position(index)]), second);
|
|
1676
|
+
case "includes": {
|
|
1677
|
+
return scalar(items.map(item => this.scalarOf(this.over(item, element => this.over(first, needle => scalar(this.strictEqual(element, needle, node)))), node, "bool"))
|
|
1678
|
+
.reduce(ir.or, ir.FALSE));
|
|
1679
|
+
}
|
|
1680
|
+
case "some":
|
|
1681
|
+
case "every": {
|
|
1682
|
+
const results = items.map((item, index) => this.scalarOf(invoke(first, [item, position(index)]), node, "bool"));
|
|
1683
|
+
return scalar(method === "some" ? results.reduce(ir.or, ir.FALSE) : results.reduce(ir.and, ir.TRUE));
|
|
1684
|
+
}
|
|
1685
|
+
case "map":
|
|
1686
|
+
return { k: "array", items: items.map((item, index) => invoke(first, [item, position(index)])) };
|
|
1687
|
+
default:
|
|
1688
|
+
throw new Unsupported(`the array method \`.${method}\` is not supported`, node);
|
|
1689
|
+
}
|
|
1690
|
+
}
|
|
1691
|
+
// ------------------------------------------------------- module bindings
|
|
1692
|
+
isNamespace(node, env) {
|
|
1693
|
+
if (node.kind !== K.Identifier || env.get(node.text))
|
|
1694
|
+
return false;
|
|
1695
|
+
let symbol = this.checker.getSymbolAtLocation(node);
|
|
1696
|
+
if (symbol && symbol.flags & SymbolFlags.Alias)
|
|
1697
|
+
symbol = this.checker.getAliasedSymbol(symbol);
|
|
1698
|
+
return !!symbol && (symbol.flags & (SymbolFlags.ValueModule | SymbolFlags.NamespaceModule)) !== 0;
|
|
1699
|
+
}
|
|
1700
|
+
/** Resolve a name that is not a local variable to its module-level declaration. */
|
|
1701
|
+
global(node, shorthand = false) {
|
|
1702
|
+
let symbol = shorthand ? this.checker.getShorthandAssignmentValueSymbol(node.parent) : this.checker.getSymbolAtLocation(node);
|
|
1703
|
+
if (symbol && symbol.flags & SymbolFlags.Alias)
|
|
1704
|
+
symbol = this.checker.getAliasedSymbol(symbol);
|
|
1705
|
+
const declaration = symbol?.valueDeclaration?.resolve();
|
|
1706
|
+
if (!symbol || !declaration)
|
|
1707
|
+
throw new Unsupported(`\`${node.text}\` is not a value that can be translated`, node);
|
|
1708
|
+
const file = declaration.getSourceFile();
|
|
1709
|
+
if (file.isDeclarationFile || this.program.isSourceFileFromExternalLibrary(file)) {
|
|
1710
|
+
throw new Unsupported(`\`${node.text}\` comes from a declaration file or a library, so its code cannot be read`, node);
|
|
1711
|
+
}
|
|
1712
|
+
this.reached.add(file.fileName);
|
|
1713
|
+
if (declaration.kind === K.FunctionDeclaration)
|
|
1714
|
+
return { k: "closure", node: declaration, env: new Env() };
|
|
1715
|
+
if (declaration.kind === K.VariableDeclaration) {
|
|
1716
|
+
const list = declaration.parent;
|
|
1717
|
+
const moduleLevel = list.kind === K.VariableDeclarationList && list.parent.kind === K.VariableStatement && list.parent.parent.kind === K.SourceFile;
|
|
1718
|
+
if (!moduleLevel)
|
|
1719
|
+
throw new Unsupported(`\`${node.text}\` is a local variable that is not available here`, node);
|
|
1720
|
+
if (!(list.flags & NodeFlags.Const))
|
|
1721
|
+
throw new Unsupported(`\`${node.text}\` is a mutable module variable`, node);
|
|
1722
|
+
if (declaration.name.kind !== K.Identifier || !declaration.initializer)
|
|
1723
|
+
throw new Unsupported(`the declaration of \`${node.text}\` is not supported`, node);
|
|
1724
|
+
// While a module loads, its constants are initialized in order. Code
|
|
1725
|
+
// that runs during one initializer cannot read a constant declared
|
|
1726
|
+
// further down the same file: JavaScript throws there.
|
|
1727
|
+
const early = this.loading.find(entry => entry.file === file.fileName && declaration.pos > entry.position);
|
|
1728
|
+
if (early)
|
|
1729
|
+
throw new Unsupported(`\`${node.text}\` is read while its module is loading, before its own declaration has run, which throws`, node);
|
|
1730
|
+
const known = this.constants.get(declaration);
|
|
1731
|
+
if (known)
|
|
1732
|
+
return known;
|
|
1733
|
+
const saved = { pc: this.pc, stack: this.stack, instance: this.instance, cells: this.cells, assigned: this.assigned };
|
|
1734
|
+
this.pc = [];
|
|
1735
|
+
this.stack = [];
|
|
1736
|
+
this.instance = undefined;
|
|
1737
|
+
this.cells = [];
|
|
1738
|
+
this.assigned = [];
|
|
1739
|
+
this.loading.push({ file: file.fileName, position: declaration.pos });
|
|
1740
|
+
try {
|
|
1741
|
+
const value = this.evalExpr(declaration.initializer, new Env());
|
|
1742
|
+
if (value.k !== "scalar" && value.k !== "closure")
|
|
1743
|
+
this.assertStable(file, declaration, value, node);
|
|
1744
|
+
this.constants.set(declaration, value);
|
|
1745
|
+
return value;
|
|
1746
|
+
}
|
|
1747
|
+
finally {
|
|
1748
|
+
this.loading.pop();
|
|
1749
|
+
Object.assign(this, saved);
|
|
1750
|
+
}
|
|
1751
|
+
}
|
|
1752
|
+
throw new Unsupported(`\`${node.text}\` is declared in a way that is not supported (only functions and const values are)`, node);
|
|
1753
|
+
}
|
|
1754
|
+
/**
|
|
1755
|
+
* Refuse a module constant whose contents may differ from its initializer
|
|
1756
|
+
* by the time a law runs. Only two kinds of code run before then: the
|
|
1757
|
+
* module's own loading, and whatever the law calls (which is translated,
|
|
1758
|
+
* and refused if it changes anything in place). So the value is stable
|
|
1759
|
+
* unless the file changes it by name, hands it to something while loading,
|
|
1760
|
+
* or runs its own functions while loading.
|
|
1761
|
+
*/
|
|
1762
|
+
assertStable(file, declaration, value, use) {
|
|
1763
|
+
const name = declaration.name.text;
|
|
1764
|
+
const key = `${file.fileName}\0${name}`;
|
|
1765
|
+
if (this.mutationChecked.has(key))
|
|
1766
|
+
return;
|
|
1767
|
+
const refuse = (reason, at) => {
|
|
1768
|
+
throw new Unsupported(`\`${name}\` ${reason} at line ${locate(at).line} of its module, so its initial value cannot be assumed`, use);
|
|
1769
|
+
};
|
|
1770
|
+
this.assertBuiltinsIntact(use);
|
|
1771
|
+
const loose = file.statements.find(statement => !MODULE_DECLARATIONS.has(statement.kind));
|
|
1772
|
+
if (loose)
|
|
1773
|
+
refuse("shares its module with a statement that runs on load", loose);
|
|
1774
|
+
const isFunction = (node) => node.kind === K.ArrowFunction || node.kind === K.FunctionExpression || node.kind === K.FunctionDeclaration ||
|
|
1775
|
+
node.kind === K.MethodDeclaration || node.kind === K.GetAccessor || node.kind === K.SetAccessor || node.kind === K.Constructor;
|
|
1776
|
+
const unwrap = (node) => {
|
|
1777
|
+
while (node.kind === K.ParenthesizedExpression || node.kind === K.AsExpression || node.kind === K.SatisfiesExpression || node.kind === K.NonNullExpression)
|
|
1778
|
+
node = node.expression;
|
|
1779
|
+
return node;
|
|
1780
|
+
};
|
|
1781
|
+
// Functions of this file that its own loading can run.
|
|
1782
|
+
const local = new Set();
|
|
1783
|
+
for (const statement of file.statements) {
|
|
1784
|
+
if (statement.kind === K.FunctionDeclaration && statement.name)
|
|
1785
|
+
local.add(statement.name.text);
|
|
1786
|
+
if (statement.kind === K.VariableStatement) {
|
|
1787
|
+
for (const d of statement.declarationList.declarations) {
|
|
1788
|
+
if (d.name.kind === K.Identifier && d.initializer && isFunction(unwrap(d.initializer)))
|
|
1789
|
+
local.add(d.name.text);
|
|
1790
|
+
}
|
|
1791
|
+
}
|
|
1792
|
+
}
|
|
1793
|
+
const isLocalCode = (node) => {
|
|
1794
|
+
const inner = unwrap(node);
|
|
1795
|
+
return isFunction(inner) || (inner.kind === K.Identifier && local.has(inner.text));
|
|
1796
|
+
};
|
|
1797
|
+
// Names this file imports. Only a function reached through one of them counts as a library.
|
|
1798
|
+
const imported = new Set();
|
|
1799
|
+
for (const statement of file.statements) {
|
|
1800
|
+
const clause = statement.kind === K.ImportDeclaration ? statement.importClause : undefined;
|
|
1801
|
+
if (clause?.name)
|
|
1802
|
+
imported.add(clause.name.text);
|
|
1803
|
+
if (clause?.namedBindings?.kind === K.NamespaceImport)
|
|
1804
|
+
imported.add(clause.namedBindings.name.text);
|
|
1805
|
+
if (clause?.namedBindings?.kind === K.NamedImports)
|
|
1806
|
+
for (const element of clause.namedBindings.elements)
|
|
1807
|
+
imported.add(element.name.text);
|
|
1808
|
+
}
|
|
1809
|
+
const fromPackage = (callee) => {
|
|
1810
|
+
let root = unwrap(callee);
|
|
1811
|
+
while (root.kind === K.PropertyAccessExpression || root.kind === K.ElementAccessExpression || root.kind === K.CallExpression)
|
|
1812
|
+
root = unwrap(root.expression);
|
|
1813
|
+
if (root.kind !== K.Identifier || !imported.has(root.text))
|
|
1814
|
+
return false;
|
|
1815
|
+
let symbol = this.checker.getSymbolAtLocation(root);
|
|
1816
|
+
if (symbol && symbol.flags & SymbolFlags.Alias)
|
|
1817
|
+
symbol = this.checker.getAliasedSymbol(symbol);
|
|
1818
|
+
const source = symbol?.declarations[0]?.resolve()?.getSourceFile();
|
|
1819
|
+
return !!source && this.program.isSourceFileFromExternalLibrary(source);
|
|
1820
|
+
};
|
|
1821
|
+
const shallow = (value) => value?.k === "record" ? [...value.fields.values()].every(field => field.k === "scalar")
|
|
1822
|
+
: value?.k === "array" ? value.items.every(item => item.k === "scalar") : false;
|
|
1823
|
+
// Whether the whole initializer is asserted `as const`, read from the
|
|
1824
|
+
// syntax: the words may also appear on a single field or in a comment,
|
|
1825
|
+
// which says nothing about the table.
|
|
1826
|
+
const declaredConst = (() => {
|
|
1827
|
+
for (let node = declaration.initializer;; node = node.expression) {
|
|
1828
|
+
if (node.kind === K.AsExpression) {
|
|
1829
|
+
const type = node.type;
|
|
1830
|
+
if (type.kind === K.TypeReference && type.typeName.kind === K.Identifier && type.typeName.text === "const" && !type.typeArguments?.length)
|
|
1831
|
+
return true;
|
|
1832
|
+
}
|
|
1833
|
+
else if (node.kind !== K.ParenthesizedExpression && node.kind !== K.SatisfiesExpression && node.kind !== K.NonNullExpression)
|
|
1834
|
+
return false;
|
|
1835
|
+
}
|
|
1836
|
+
})();
|
|
1837
|
+
const handedOver = [];
|
|
1838
|
+
const visit = (node, inFunction) => {
|
|
1839
|
+
if (node.kind === K.Identifier && node.text === name && node !== declaration.name) {
|
|
1840
|
+
// The longest access path that starts at this name, such as `table.rows[0]`.
|
|
1841
|
+
let top = node;
|
|
1842
|
+
const path = [];
|
|
1843
|
+
while ((top.parent.kind === K.PropertyAccessExpression || top.parent.kind === K.ElementAccessExpression) && top.parent.expression === top) {
|
|
1844
|
+
top = top.parent;
|
|
1845
|
+
path.push(top.kind === K.PropertyAccessExpression ? top.name.text : top.argumentExpression.kind === K.StringLiteral || top.argumentExpression.kind === K.NumericLiteral ? top.argumentExpression.text : undefined);
|
|
1846
|
+
}
|
|
1847
|
+
let outer = top;
|
|
1848
|
+
while (outer.parent.kind === K.ParenthesizedExpression || outer.parent.kind === K.AsExpression || outer.parent.kind === K.SatisfiesExpression || outer.parent.kind === K.NonNullExpression)
|
|
1849
|
+
outer = outer.parent;
|
|
1850
|
+
const parent = outer.parent;
|
|
1851
|
+
const assigned = parent.kind === K.BinaryExpression && parent.left === outer &&
|
|
1852
|
+
parent.operatorToken.kind >= K.FirstAssignment && parent.operatorToken.kind <= K.LastAssignment;
|
|
1853
|
+
const updated = (parent.kind === K.PrefixUnaryExpression || parent.kind === K.PostfixUnaryExpression) &&
|
|
1854
|
+
(parent.operator === K.PlusPlusToken || parent.operator === K.MinusMinusToken);
|
|
1855
|
+
const called = parent.kind === K.CallExpression && parent.expression === outer && top.kind === K.PropertyAccessExpression;
|
|
1856
|
+
if (assigned || updated || parent.kind === K.DeleteExpression || (called && ARRAY_MUTATORS.has(top.name.text)))
|
|
1857
|
+
refuse("is modified", parent);
|
|
1858
|
+
// Reading through the value is harmless. What matters is where the
|
|
1859
|
+
// value itself, or an object inside it, is handed to other code.
|
|
1860
|
+
// Everything the path can lead to. A key that is not a literal can pick any child.
|
|
1861
|
+
let reached = [value];
|
|
1862
|
+
for (const step of path.slice(0, called ? -1 : undefined)) {
|
|
1863
|
+
reached = reached.flatMap(part => {
|
|
1864
|
+
// The length of a list is a plain number.
|
|
1865
|
+
if (step === "length" && part.k === "array")
|
|
1866
|
+
return [scalar(ir.lit(BigInt(part.items.length)), true)];
|
|
1867
|
+
const children = part.k === "record" ? [...part.fields] : part.k === "array" ? part.items.map((item, i) => [String(i), item]) : [];
|
|
1868
|
+
return children.filter(([key]) => step === undefined || key === step).map(([, child]) => child);
|
|
1869
|
+
});
|
|
1870
|
+
}
|
|
1871
|
+
const plain = reached.length > 0 && reached.every(part => part.k === "scalar");
|
|
1872
|
+
const flat = reached.length > 0 && reached.every(shallow);
|
|
1873
|
+
// Only uses that are known to read count as reads. A method call does
|
|
1874
|
+
// when it is one of the array methods that change nothing, on a list
|
|
1875
|
+
// of plain values; a method the table defines itself may do anything.
|
|
1876
|
+
// Spreading and iterating copy one level, so they are reads when that
|
|
1877
|
+
// level holds no objects. `a ?? b` and the like return the table itself.
|
|
1878
|
+
const compares = parent.kind === K.BinaryExpression &&
|
|
1879
|
+
[K.EqualsEqualsEqualsToken, K.ExclamationEqualsEqualsToken, K.EqualsEqualsToken, K.ExclamationEqualsToken, K.InKeyword].includes(parent.operatorToken.kind);
|
|
1880
|
+
const reads = (called && READING_METHODS.has(top.name.text) && flat) || (!called && plain) ||
|
|
1881
|
+
parent.kind === K.TypeQuery || parent.kind === K.TypeOfExpression || parent.kind === K.ExportSpecifier || parent.kind === K.ExportAssignment ||
|
|
1882
|
+
((parent.kind === K.SpreadElement || parent.kind === K.SpreadAssignment || (parent.kind === K.ForOfStatement && parent.expression === outer)) && flat) ||
|
|
1883
|
+
compares;
|
|
1884
|
+
// A value declared `as const` may be given to an installed package
|
|
1885
|
+
// while loading: its type forbids changing it, and schema builders are
|
|
1886
|
+
// the common case. A function of the project itself gets no such trust.
|
|
1887
|
+
const toLibrary = declaredConst && parent.kind === K.CallExpression && parent.expression !== outer && fromPackage(parent.expression);
|
|
1888
|
+
// A built-in that only reads may be given the table anywhere.
|
|
1889
|
+
const callee = (parent.kind === K.CallExpression || parent.kind === K.NewExpression) && parent.expression !== outer ? parent.expression.getText(file) : "";
|
|
1890
|
+
const toReader = READERS.test(callee) || (flat && (SHALLOW_READERS.test(callee) || (parent.kind === K.NewExpression && /^(Set|Map)$/.test(callee))));
|
|
1891
|
+
if (!reads && !toLibrary && !toReader)
|
|
1892
|
+
handedOver.push({ at: parent, inFunction });
|
|
1893
|
+
}
|
|
1894
|
+
node.forEachChild((child) => visit(child, inFunction || isFunction(child)));
|
|
1895
|
+
};
|
|
1896
|
+
visit(file, false);
|
|
1897
|
+
const atLoad = handedOver.find(entry => !entry.inFunction);
|
|
1898
|
+
if (atLoad)
|
|
1899
|
+
refuse("is handed to other code while its module loads", atLoad.at);
|
|
1900
|
+
// A function that hands the table on could be run while some module loads,
|
|
1901
|
+
// by this module or by another that imports it, and nothing here can tell.
|
|
1902
|
+
const inCode = handedOver.find(entry => entry.inFunction);
|
|
1903
|
+
if (inCode)
|
|
1904
|
+
refuse("is handed to other code by a function, which may run before the law does,", inCode.at);
|
|
1905
|
+
this.mutationChecked.add(key);
|
|
1906
|
+
}
|
|
1907
|
+
}
|
|
1908
|
+
/** A function's parameters as they exist at run time: TypeScript's `this` parameter is erased. */
|
|
1909
|
+
function parametersOf(fn) {
|
|
1910
|
+
return fn.parameters.filter(parameter => !(parameter.name.kind === K.Identifier && parameter.name.text === "this"));
|
|
1911
|
+
}
|
|
1912
|
+
/** The names a binding pattern declares. */
|
|
1913
|
+
function boundNames(pattern, into = []) {
|
|
1914
|
+
if (pattern.kind === K.Identifier)
|
|
1915
|
+
into.push(pattern.text);
|
|
1916
|
+
else
|
|
1917
|
+
for (const element of (pattern.elements ?? []))
|
|
1918
|
+
if (element.name)
|
|
1919
|
+
boundNames(element.name, into);
|
|
1920
|
+
return into;
|
|
1921
|
+
}
|
|
1922
|
+
/** Whether a statement can leave its enclosing block early: by returning, throwing, breaking or continuing. */
|
|
1923
|
+
function canExit(node) {
|
|
1924
|
+
if (!node)
|
|
1925
|
+
return false;
|
|
1926
|
+
if (node.kind === K.ReturnStatement || node.kind === K.ThrowStatement || node.kind === K.BreakStatement || node.kind === K.ContinueStatement)
|
|
1927
|
+
return true;
|
|
1928
|
+
if (node.kind === K.ArrowFunction || node.kind === K.FunctionExpression || node.kind === K.FunctionDeclaration)
|
|
1929
|
+
return false;
|
|
1930
|
+
return node.forEachChild((child) => canExit(child) || undefined) === true;
|
|
1931
|
+
}
|
|
1932
|
+
/** The plain names an assignment target writes to. Property and element targets write to no name. */
|
|
1933
|
+
function collectNames(target, into) {
|
|
1934
|
+
if (target.kind === K.Identifier)
|
|
1935
|
+
into.add(target.text);
|
|
1936
|
+
else if (target.kind === K.ParenthesizedExpression)
|
|
1937
|
+
collectNames(target.expression, into);
|
|
1938
|
+
}
|