tla-ts 0.0.8-dev.d9bffda → 0.0.9-dev.0dd11f695

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.
Files changed (119) hide show
  1. package/README.md +30 -0
  2. package/dist/compile.cjs +23 -0
  3. package/dist/compile.js +23 -0
  4. package/dist/deciders.cjs +15 -15
  5. package/dist/deciders.js +40 -40
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +80 -10
  8. package/dist/index.d.ts +80 -10
  9. package/dist/index.js +1 -1
  10. package/dist/parallel-worker.cjs +1 -1
  11. package/dist/parallel-worker.js +1 -1
  12. package/dist/prove-worker.cjs +1 -1
  13. package/dist/prove-worker.js +1 -1
  14. package/dist/prove.cjs +116 -36
  15. package/dist/prove.js +116 -36
  16. package/dist/run.cjs +143 -31
  17. package/dist/run.js +143 -31
  18. package/dist/tlapm.cjs +2 -2
  19. package/dist/tlapm.js +1 -1
  20. package/dist/transfer.cjs +128 -103
  21. package/dist/transfer.js +128 -103
  22. package/dist/worker.cjs +7 -7
  23. package/dist/worker.js +7 -7
  24. package/package.json +3 -1
  25. package/src/ast.ts +7 -21
  26. package/src/bags.ts +99 -99
  27. package/src/builtins.ts +44 -75
  28. package/src/bundled-modules.ts +1 -8
  29. package/src/check.ts +605 -311
  30. package/src/cli/options.ts +12 -3
  31. package/src/cli/run.ts +2 -2
  32. package/src/cli/runtime-invariants.ts +135 -0
  33. package/src/cli/shared.ts +20 -9
  34. package/src/cli/tlc-arguments.ts +646 -0
  35. package/src/cli/tlc-usage.ts +362 -0
  36. package/src/cli/tlc.ts +571 -185
  37. package/src/cli/typescript.ts +26 -0
  38. package/src/cli/xml-exporter.ts +4 -10
  39. package/src/codegen.ts +190 -46
  40. package/src/config.ts +101 -68
  41. package/src/coverage.ts +855 -0
  42. package/src/dependencies.ts +20 -28
  43. package/src/dfid.ts +636 -0
  44. package/src/environment.ts +266 -98
  45. package/src/errors.ts +142 -45
  46. package/src/evaluate.ts +632 -298
  47. package/src/exit-codes.ts +37 -1
  48. package/src/index.ts +3 -0
  49. package/src/instances.ts +85 -9
  50. package/src/java-overrides.ts +2 -12
  51. package/src/json-reader.ts +456 -0
  52. package/src/json.ts +262 -139
  53. package/src/levels.ts +2 -3
  54. package/src/lexer.ts +17 -26
  55. package/src/liveness-checker.ts +10 -18
  56. package/src/liveness.ts +121 -49
  57. package/src/parallel-worker.ts +14 -10
  58. package/src/parallel.ts +41 -17
  59. package/src/parser.ts +436 -90
  60. package/src/pcal/ast.ts +7 -28
  61. package/src/pcal/parse.ts +11 -39
  62. package/src/pcal/tokenize.ts +4 -20
  63. package/src/pcal/translate.ts +10 -42
  64. package/src/pcal/validate.ts +3 -21
  65. package/src/pretty-print.ts +1 -2
  66. package/src/prover/smt/solver/solver.ts +31 -27
  67. package/src/randomization.ts +84 -35
  68. package/src/resolve.ts +18 -60
  69. package/src/runtime.ts +11 -4
  70. package/src/sany/builtins.ts +3 -4
  71. package/src/sany/generator.ts +128 -176
  72. package/src/sany/levels.ts +6 -30
  73. package/src/sany/lexer.ts +7 -23
  74. package/src/sany/linter.ts +31 -29
  75. package/src/sany/modules.ts +1 -5
  76. package/src/sany/nodes.ts +4 -28
  77. package/src/sany/parse-error.ts +44 -100
  78. package/src/sany/report.ts +25 -40
  79. package/src/sany/selectors.ts +8 -22
  80. package/src/sany/source.ts +8 -15
  81. package/src/sany/xml.ts +11 -42
  82. package/src/search.ts +547 -144
  83. package/src/simulate.ts +694 -0
  84. package/src/spec-description.ts +166 -48
  85. package/src/standard-definitions.ts +2 -3
  86. package/src/standard-modules.ts +264 -68
  87. package/src/state-graph.ts +51 -18
  88. package/src/subexpressions.ts +31 -5
  89. package/src/successors.ts +267 -77
  90. package/src/symmetry.ts +31 -8
  91. package/src/tableau.ts +1 -2
  92. package/src/tlc/fingerprint.ts +183 -61
  93. package/src/tlc/jar-data.ts +113 -6
  94. package/src/tlc/messages.ts +122 -37
  95. package/src/tlc/order.ts +33 -38
  96. package/src/tlc/random.ts +16 -16
  97. package/src/tlc/replay.ts +563 -211
  98. package/src/tlc/summary.ts +2 -4
  99. package/src/tlc/tlc-operators.ts +81 -36
  100. package/src/tlc/tlcext-operators.ts +138 -117
  101. package/src/tlc/trace-spec.ts +273 -0
  102. package/src/tlc/value-stream.ts +143 -0
  103. package/src/tlc/version.ts +2 -4
  104. package/src/typescript/actions.ts +494 -0
  105. package/src/typescript/collections.ts +615 -0
  106. package/src/typescript/compile.ts +70 -0
  107. package/src/typescript/context.ts +106 -0
  108. package/src/typescript/emit.ts +122 -0
  109. package/src/typescript/expressions.ts +508 -0
  110. package/src/typescript/formula.ts +160 -0
  111. package/src/typescript/functions.ts +295 -0
  112. package/src/typescript/model.ts +164 -0
  113. package/src/typescript/names.ts +116 -0
  114. package/src/typescript/program.ts +51 -0
  115. package/src/typescript/properties.ts +148 -0
  116. package/src/typescript/scope.ts +117 -0
  117. package/src/typescript/steps.ts +175 -0
  118. package/src/typescript/types.ts +178 -0
  119. package/src/values.ts +832 -255
@@ -0,0 +1,26 @@
1
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { basename, dirname, join } from "node:path";
3
+ import { TlaTypeScriptError } from "../errors";
4
+
5
+ // Compiles a TypeScript file to the TLA+ spec and config of its module, beside it, and returns the
6
+ // spec's path. A file there that tla-ts didn't generate is left alone.
7
+ export const writeTypeScriptSpec = async (path: string) => {
8
+ // The TypeScript compiler takes a while to load, so only a TypeScript input loads it.
9
+ const compiled = (await import("../typescript/compile")).compile(
10
+ readFileSync(path, "utf8"),
11
+ path,
12
+ );
13
+ const header = `\\* Generated by tla-ts from ${basename(path)}. Edit ${basename(path)} instead.`;
14
+ const specPath = join(dirname(path), `${compiled.name}.tla`);
15
+ const configPath = join(dirname(path), `${compiled.name}.cfg`);
16
+ for (const outputPath of [specPath, configPath]) {
17
+ if (existsSync(outputPath) && !readFileSync(outputPath, "utf8").startsWith(header)) {
18
+ throw new TlaTypeScriptError(
19
+ `${outputPath} already exists, and tla-ts didn't generate it from ${path}`,
20
+ );
21
+ }
22
+ }
23
+ writeFileSync(specPath, `${header}\n${compiled.source}\n`);
24
+ writeFileSync(configPath, `${header}\n${compiled.config}\n`);
25
+ return specPath;
26
+ };
@@ -14,7 +14,6 @@ import {
14
14
  toLibraryPath,
15
15
  } from "./shared";
16
16
 
17
- // The usage that XMLExporter.printUsage prints with UsageGenerator.
18
17
  const XML_EXPORT_USAGE = (() => {
19
18
  const bold = (text: string) => `\x1b[1m${text}\x1b[0m`;
20
19
  const options = [
@@ -67,7 +66,6 @@ const printXmlExportUsageError = (message: string) => {
67
66
  return XML_EXPORT_EXIT_CODE.argsParsingFailure;
68
67
  };
69
68
 
70
- // XMLExporter.run.
71
69
  const writeXml = (specification: SanySpecification, options: XmlExportOptions) => {
72
70
  try {
73
71
  process.stdout.write(exportSanyXml(specification, options));
@@ -128,8 +126,7 @@ export const exportXml = (args: string[]) => {
128
126
  return EXIT_STATUS.success;
129
127
  }
130
128
  const fileName = name.endsWith(".tla") ? name : `${name}.tla`;
131
- // SANY looks for each module in the working directory, then in the -I directories, which
132
- // XMLExporter passes in place of TLA-Library, then among its standard modules.
129
+ // XMLExporter passes the -I directories in place of TLA-Library.
133
130
  const directories = [".", ...parsed.includes];
134
131
  const path = directories.map((directory) => resolve(directory, fileName)).find(existsSync);
135
132
  if (path === undefined && !SANY_STANDARD_MODULES.has(fileName.slice(0, -".tla".length))) {
@@ -152,8 +149,6 @@ export const exportXml = (args: string[]) => {
152
149
  });
153
150
  };
154
151
 
155
- // TLC 1.7.4's XMLExporter.main throws an exception for an argument it can't take or a
156
- // specification without a root module.
157
152
  const printXmlExporterException = (exception: string, line: number) => {
158
153
  console.error(
159
154
  `Exception in thread "main" ${exception}\n\tat tla2sany.xml.XMLExporter.main(XMLExporter.java:${line})`,
@@ -161,8 +156,8 @@ const printXmlExporterException = (exception: string, line: number) => {
161
156
  return XML_EXPORT_EXIT_CODE.uncaughtException;
162
157
  };
163
158
 
164
- // TLC 1.7.4's XMLExporter.main, which takes only -o, as it can't validate the XML without
165
- // fetching its schema, and -I, and exports a specification that SANY finds errors in.
159
+ // TLC 1.7.4's XMLExporter takes only -o, as it can't validate the XML without fetching its
160
+ // schema, and -I, and exports a specification that SANY finds errors in.
166
161
  export const exportXml174 = (args: string[], jar: string | undefined) => {
167
162
  if (args.length === 0) {
168
163
  return printXmlExporterException(
@@ -185,8 +180,7 @@ export const exportXml174 = (args: string[], jar: string | undefined) => {
185
180
  }
186
181
  const name = args[args.length - 1];
187
182
  const fileName = `${name.replace(/\.tla$/i, "")}.tla`;
188
- // SimpleFilenameToStream looks for a module in the working directory, then in the -I
189
- // directories, or the root directory when there are none, then among the standard modules.
183
+ // With no -I directories, SimpleFilenameToStream looks in the root directory.
190
184
  const libraries = (parsed.includes.length === 0 ? ["/"] : parsed.includes).map(toLibraryPath);
191
185
  const directories = [".", ...libraries];
192
186
  const printMissingFile = (moduleFileName: string) =>
package/src/codegen.ts CHANGED
@@ -1,10 +1,19 @@
1
1
  import { getChildren, isLocallyResolved, type Expression } from "./ast";
2
2
  import {
3
3
  bindValue,
4
- expectBoolean,
4
+ expectBooleanBody,
5
+ expectImplication,
6
+ isEquivalent,
7
+ negate,
5
8
  findGlobalName,
6
9
  createConditionError,
7
10
  createJunctionError,
11
+ createNoChoiceError,
12
+ expectFilterPredicate,
13
+ getChoiceElements,
14
+ getFunctionBuilder,
15
+ getLazyFilter,
16
+ isKeptLazy,
8
17
  getDomainOperator,
9
18
  getSubsetOperator,
10
19
  getEvaluator,
@@ -16,7 +25,6 @@ import {
16
25
  resolveGlobalOperator,
17
26
  expectFunction,
18
27
  toKeepLazyContext,
19
- createPrimeOutsideActionError,
20
28
  createUnassignedError,
21
29
  getSortedFields,
22
30
  hasDuplicateFields,
@@ -25,12 +33,20 @@ import {
25
33
  type Evaluator,
26
34
  } from "./evaluate";
27
35
  import {
36
+ addBoundedElement,
28
37
  applyFunction,
29
38
  createEnumeratedSet,
39
+ createNormalizedSet,
40
+ createSortedFunction,
30
41
  createSortedRecord,
31
42
  createTuple,
32
43
  createWrittenRecord,
44
+ getCardinality,
45
+ getFunctionDomain,
46
+ isBeyondSetBound,
47
+ isReducibleSet,
33
48
  isTlcInteger,
49
+ toFiniteSet,
34
50
  valuesEqual,
35
51
  type Value,
36
52
  } from "./values";
@@ -64,10 +80,16 @@ const GENERATED_KINDS = new Set([
64
80
  "Unchanged",
65
81
  "Forall",
66
82
  "Exists",
83
+ "Choose",
84
+ "SetFilter",
85
+ "FunctionConstruction",
67
86
  ]);
68
87
 
69
88
  const createGeneratedHelpers = () => ({
70
- bool: expectBoolean,
89
+ implication: expectImplication,
90
+ negate,
91
+ equivalent: isEquivalent,
92
+ body: expectBooleanBody,
71
93
  condition: (value: Value, expression: Expression) => {
72
94
  if (typeof value !== "boolean") throw createConditionError(expression, value);
73
95
  return value;
@@ -84,12 +106,22 @@ const createGeneratedHelpers = () => ({
84
106
  writtenRecord: createWrittenRecord,
85
107
  equal: valuesEqual,
86
108
  enumerate: getQuantifierElements,
109
+ choiceElements: getChoiceElements,
110
+ noChoice: (expression: Expression & { kind: "Choose" }): never => {
111
+ throw createNoChoiceError(expression);
112
+ },
113
+ filterPredicate: expectFilterPredicate,
114
+ isReducible: isReducibleSet,
115
+ finiteElements: (set: Value) => toFiniteSet(set).elements,
116
+ addBounded: addBoundedElement,
117
+ normalizedSet: createNormalizedSet,
118
+ isBeyondBound: isBeyondSetBound,
119
+ cardinality: getCardinality,
120
+ functionDomain: getFunctionDomain,
121
+ sortedFunction: createSortedFunction,
87
122
  unassigned: (name: string, expression: Expression): never => {
88
123
  throw createUnassignedError(name, expression);
89
124
  },
90
- primeOutsideAction: (expression: Expression): never => {
91
- throw createPrimeOutsideActionError(expression);
92
- },
93
125
  prime: (context: Context): Context => ({
94
126
  environment: context.environment,
95
127
  scope: context.scope,
@@ -140,26 +172,28 @@ const getFreeNames = (expression: Expression, names = new Set<string>()) => {
140
172
  return names;
141
173
  };
142
174
 
143
- const generateDelegate = (generator: Generator, expression: Expression, frame: Frame) => {
144
- const evaluator = addReference(generator, getEvaluator(expression, generator.environment));
175
+ const getDelegateContext = (generator: Generator, expression: Expression, frame: Frame) => {
145
176
  const freeNames = getFreeNames(expression);
146
177
  const captured = [...frame.locals].filter(([name]) => freeNames.has(name));
147
- if (captured.length === 0) return `${evaluator}(${frame.context})`;
178
+ if (captured.length === 0) return frame.context;
148
179
  const names = addReference(
149
180
  generator,
150
181
  captured.map(([name]) => name),
151
182
  );
152
- return `${evaluator}(extend(${frame.context}, ${names}, [${captured.map(([, local]) => local).join(", ")}]))`;
183
+ return `extend(${frame.context}, ${names}, [${captured.map(([, local]) => local).join(", ")}])`;
153
184
  };
154
185
 
155
- const generateQuantifier = (
186
+ const generateDelegate = (generator: Generator, expression: Expression, frame: Frame) =>
187
+ `${addReference(generator, getEvaluator(expression, generator.environment))}(${getDelegateContext(generator, expression, frame)})`;
188
+
189
+ // A helper function gets the frame's locals as parameters, so a loop in it binds its element to a
190
+ // local too.
191
+ const generateHelper = (
156
192
  generator: Generator,
157
- expression: Expression & { kind: "Forall" | "Exists" },
158
193
  frame: Frame,
194
+ build: (bodyFrame: Frame) => string,
159
195
  ) => {
160
- const isForall = expression.kind === "Forall";
161
- const description = JSON.stringify(isForall ? "the body of \\A" : "the body of \\E");
162
- const name = `quantifier${generator.counter++}`;
196
+ const name = `helper${generator.counter++}`;
163
197
  const outerLocals = [...frame.locals.values()];
164
198
  const bodyFrame = {
165
199
  context: "context",
@@ -168,32 +202,109 @@ const generateQuantifier = (
168
202
  isPrimed: false,
169
203
  locals: new Map(frame.locals),
170
204
  };
171
- const lists = expression.bounds.map(() => createLocal(generator));
172
- const declarations = expression.bounds.map(
173
- (bound, index) =>
174
- `const ${lists[index]} = enumerate(${generateExpression(generator, bound.set, bodyFrame)}, ${addReference(generator, bound.set)}, ${JSON.stringify(generator.environment.runtime.version)});`,
175
- );
176
- const elements = expression.bounds.map((bound) => {
177
- const local = createLocal(generator);
178
- if (bound.pattern.kind === "Name") bodyFrame.locals.set(bound.pattern.name, local);
179
- return local;
180
- });
181
- const test = `if (bool(${generateExpression(generator, expression.body, bodyFrame)}, ${description}) !== ${isForall}) return ${!isForall};`;
182
- // enumerate returns an array, or an interval, which has a low end, to step through.
183
- const loops = elements.reduce((code, element, index) => {
184
- const position = createLocal(generator);
185
- const low = createLocal(generator);
186
- const size = createLocal(generator);
187
- const list = lists[index];
188
- return `for (let ${position} = 0, ${low} = ${list}.low, ${size} = ${low} === undefined ? ${list}.length : ${list}.high - ${low} + 1; ${position} < ${size}; ${position}++) { const ${element} = ${low} === undefined ? ${list}[${position}] : ${low} + ${position}; ${code} }`;
189
- }, test);
190
205
  const parameters = outerLocals.map((local) => `, ${local}`).join("");
191
206
  generator.helpers.push(
192
- `function ${name}(context, state, next${parameters}) { let primed; let applied; ${declarations.join(" ")} ${loops} return ${isForall}; }`,
207
+ `function ${name}(context, state, next${parameters}) { let primed; let applied; ${build(bodyFrame)} }`,
193
208
  );
194
209
  return `${name}(${frame.context}, ${frame.state}, ${frame.isPrimed ? "undefined" : frame.next}${parameters})`;
195
210
  };
196
211
 
212
+ // The list is an array, or an interval, which has a low end, to step through.
213
+ const generateLoop = (generator: Generator, list: string, element: string, code: string) => {
214
+ const position = createLocal(generator);
215
+ const low = createLocal(generator);
216
+ const size = createLocal(generator);
217
+ return `for (let ${position} = 0, ${low} = ${list}.low, ${size} = ${low} === undefined ? ${list}.length : ${list}.high - ${low} + 1; ${position} < ${size}; ${position}++) { const ${element} = ${low} === undefined ? ${list}[${position}] : ${low} + ${position}; ${code} }`;
218
+ };
219
+
220
+ const generateQuantifier = (
221
+ generator: Generator,
222
+ expression: Expression & { kind: "Forall" | "Exists" },
223
+ frame: Frame,
224
+ ) => {
225
+ const isForall = expression.kind === "Forall";
226
+ return generateHelper(generator, frame, (bodyFrame) => {
227
+ const lists = expression.bounds.map(() => createLocal(generator));
228
+ const declarations = expression.bounds.map((bound, index) =>
229
+ index > 0 && expression.bounds[index - 1].set === bound.set
230
+ ? `const ${lists[index]} = ${lists[index - 1]};`
231
+ : `const ${lists[index]} = enumerate(${generateExpression(generator, bound.set, bodyFrame)}, ${addReference(generator, bound.set)}, ${JSON.stringify(generator.environment.runtime.version)});`,
232
+ );
233
+ const elements = expression.bounds.map((bound) => {
234
+ const local = createLocal(generator);
235
+ if (bound.pattern.kind === "Name") bodyFrame.locals.set(bound.pattern.name, local);
236
+ return local;
237
+ });
238
+ const test = `if (body(${generateExpression(generator, expression.body, bodyFrame)}, ${addReference(generator, expression)}) !== ${isForall}) return ${!isForall};`;
239
+ const loops = elements.reduce(
240
+ (code, element, index) => generateLoop(generator, lists[index], element, code),
241
+ test,
242
+ );
243
+ return `${declarations.join(" ")} ${loops} return ${isForall};`;
244
+ });
245
+ };
246
+
247
+ const generateChoose = (
248
+ generator: Generator,
249
+ expression: Expression & { kind: "Choose" },
250
+ set: Expression,
251
+ name: string,
252
+ frame: Frame,
253
+ ) =>
254
+ generateHelper(generator, frame, (bodyFrame) => {
255
+ const list = createLocal(generator);
256
+ const element = createLocal(generator);
257
+ const node = addReference(generator, expression);
258
+ const elements = `choiceElements(${generateExpression(generator, set, bodyFrame)}, ${node}, ${addReference(generator, set)}, ${JSON.stringify(generator.environment.runtime.version)})`;
259
+ bodyFrame.locals.set(name, element);
260
+ const test = `if (body(${generateExpression(generator, expression.body, bodyFrame)}, ${node})) return ${element};`;
261
+ return `const ${list} = ${elements}; ${generateLoop(generator, list, element, test)} return noChoice(${node});`;
262
+ });
263
+
264
+ const generateSetFilter = (
265
+ generator: Generator,
266
+ expression: Expression & { kind: "SetFilter" },
267
+ name: string,
268
+ frame: Frame,
269
+ ) =>
270
+ generateHelper(generator, frame, (bodyFrame) => {
271
+ const base = createLocal(generator);
272
+ const list = createLocal(generator);
273
+ const kept = createLocal(generator);
274
+ const element = createLocal(generator);
275
+ const node = addReference(generator, expression);
276
+ const filterLazily = addReference(generator, getLazyFilter(expression, generator.environment));
277
+ const lazy = `if (!isReducible(${base})) return ${filterLazily}(${base}, ${getDelegateContext(generator, expression, bodyFrame)});`;
278
+ const set = generateExpression(generator, expression.bound.set, bodyFrame);
279
+ bodyFrame.locals.set(name, element);
280
+ const test = `if (filterPredicate(${generateExpression(generator, expression.predicate, bodyFrame)}, ${node})) addBounded(${kept}, ${element});`;
281
+ return `const ${base} = ${set}; ${lazy} const ${list} = ${base}.kind === "Interval" ? ${base} : finiteElements(${base}); const ${kept} = []; ${generateLoop(generator, list, element, test)} return normalizedSet(${kept});`;
282
+ });
283
+
284
+ // TLC builds a function with a reducible domain by sizing it, then evaluating its body at each
285
+ // element. A domain too large to hold the values keeps the function lazy once the body is evaluated.
286
+ const generateFunctionConstruction = (
287
+ generator: Generator,
288
+ expression: Expression & { kind: "FunctionConstruction" },
289
+ name: string,
290
+ frame: Frame,
291
+ ) =>
292
+ generateHelper(generator, frame, (bodyFrame) => {
293
+ const domain = createLocal(generator);
294
+ const isBeyond = createLocal(generator);
295
+ const keys = createLocal(generator);
296
+ const values = createLocal(generator);
297
+ const element = createLocal(generator);
298
+ const value = createLocal(generator);
299
+ const builder = addReference(generator, getFunctionBuilder(expression, generator.environment));
300
+ const builtContext = getDelegateContext(generator, expression, bodyFrame);
301
+ const built = `if (context.isKeepLazy || !isReducible(${domain})) return ${builder}.build(${domain}, ${builtContext});`;
302
+ const set = generateExpression(generator, expression.bounds[0].set, bodyFrame);
303
+ bodyFrame.locals.set(name, element);
304
+ const store = `const ${value} = ${generateExpression(generator, expression.body, bodyFrame)}; if (!${isBeyond}) ${values}.push(${value});`;
305
+ return `const ${domain} = ${set}; ${built} const ${isBeyond} = isBeyondBound(${domain}); const ${keys} = ${isBeyond} ? ${domain} : functionDomain(${domain}); if (${isBeyond}) cardinality(${domain}); const ${values} = []; ${generateLoop(generator, keys, element, store)} return ${isBeyond} ? ${builder}.createLazy(${domain}, ${builtContext}) : sortedFunction(${keys}, ${values});`;
306
+ });
307
+
197
308
  const generateApply = (
198
309
  generator: Generator,
199
310
  expression: Expression & { kind: "Apply" },
@@ -203,7 +314,14 @@ const generateApply = (
203
314
  if (expression.operator === "=>") {
204
315
  const left = generateExpression(generator, args[0], frame);
205
316
  const right = generateExpression(generator, args[1], frame);
206
- return `(bool(${left}, "the left side of =>") ? bool(${right}, "the right side of =>") : true)`;
317
+ const reference = addReference(generator, expression);
318
+ return `(implication(${left}, ${reference}, "P") ? implication(${right}, ${reference}, "Q") : true)`;
319
+ }
320
+ if (expression.operator === "~" && args.length === 1) {
321
+ return `negate(${generateExpression(generator, args[0], frame)}, ${addReference(generator, expression)})`;
322
+ }
323
+ if (expression.operator === "<=>") {
324
+ return `equivalent(${generateExpression(generator, args[0], frame)}, ${generateExpression(generator, args[1], frame)}, ${addReference(generator, expression)})`;
207
325
  }
208
326
  if (isLocallyResolved(expression)) return generateDelegate(generator, expression, frame);
209
327
  const builtin = resolveGlobalOperator(expression.operator, generator.environment);
@@ -233,7 +351,6 @@ const generateApply = (
233
351
  return generateDelegate(generator, expression, frame);
234
352
  };
235
353
 
236
- // Whether an expression only reads values, so that it constructs no function whatever the control.
237
354
  const isConstructionFree = (
238
355
  expression: Expression,
239
356
  frame: Frame,
@@ -259,8 +376,7 @@ const isConstructionFree = (
259
376
  }
260
377
  };
261
378
 
262
- // Whether the generated code evaluates an expression only in the context its frame names. A primed
263
- // expression doesn't, since it shares the generated function's primed context.
379
+ // A primed expression shares the generated function's primed context, so it isn't read-only.
264
380
  const isReadOnly = (expression: Expression): boolean => {
265
381
  switch (expression.kind) {
266
382
  case "Identifier":
@@ -304,6 +420,8 @@ const generateExpression = (generator: Generator, expression: Expression, frame:
304
420
  return generateApply(generator, expression, frame);
305
421
  case "And":
306
422
  case "Or": {
423
+ // UNCHANGED <<>> is an empty conjunction.
424
+ if (expression.operands.length === 0) return String(expression.kind === "And");
307
425
  const node = addReference(generator, expression);
308
426
  const operator = expression.kind === "And" ? " && " : " || ";
309
427
  return `(${expression.operands.map((operand, index) => `junct(${generate(operand)}, ${node}, ${index})`).join(operator)})`;
@@ -323,8 +441,8 @@ const generateExpression = (generator: Generator, expression: Expression, frame:
323
441
  : isReadOnly(expression.function)
324
442
  ? generate(expression.function, keepLazyFrame)
325
443
  : generateDelegate(generator, expression.function, keepLazyFrame);
326
- // Tool#evalAppl checks that it applies a function before it evaluates the argument. The check
327
- // is written out, as calling expectFunction for each application costs more.
444
+ // Tool#evalAppl checks that it applies a function before it evaluates the argument. The check is
445
+ // written out, as calling expectFunction for each application costs more.
328
446
  const functionCode = `(applied = ${evaluatedFunction}, typeof applied === "object" && (applied.kind === "Function" || applied.kind === "LazyFunction") ? applied : expectFunction(applied, ${addReference(generator, expression)}))`;
329
447
  const describeMissing = getMissingArgumentDescriber(generator.environment.runtime.version);
330
448
  const error = describeMissing ? `, ${addReference(generator, describeMissing)}` : "";
@@ -353,16 +471,14 @@ const generateExpression = (generator: Generator, expression: Expression, frame:
353
471
  case "SetEnumeration":
354
472
  return `set([${expression.elements.map((element) => generate(element)).join(", ")}])`;
355
473
  case "Prime": {
356
- const node = addReference(generator, expression);
357
- if (frame.isPrimed) return `primeOutsideAction(${node})`;
358
- const primed = {
474
+ if (frame.isPrimed) return generateDelegate(generator, expression, frame);
475
+ return generate(expression.expression, {
359
476
  context: `(primed ??= prime(${frame.context}))`,
360
477
  state: frame.next,
361
478
  next: "undefined",
362
479
  isPrimed: true,
363
480
  locals: frame.locals,
364
- };
365
- return `(${frame.next} === undefined ? primeOutsideAction(${node}) : ${generate(expression.expression, primed)})`;
481
+ });
366
482
  }
367
483
  case "Unchanged": {
368
484
  const primed = generate({
@@ -378,6 +494,34 @@ const generateExpression = (generator: Generator, expression: Expression, frame:
378
494
  return generateQuantifier(generator, expression, frame);
379
495
  }
380
496
  return generateDelegate(generator, expression, frame);
497
+ case "Choose":
498
+ if (expression.set && expression.pattern.kind === "Name") {
499
+ return generateChoose(
500
+ generator,
501
+ expression,
502
+ expression.set,
503
+ expression.pattern.name,
504
+ frame,
505
+ );
506
+ }
507
+ return generateDelegate(generator, expression, frame);
508
+ case "FunctionConstruction": {
509
+ const bound = expression.bounds[0];
510
+ if (
511
+ expression.bounds.length === 1 &&
512
+ bound.pattern.kind === "Name" &&
513
+ !expression.isRecursive &&
514
+ !isKeptLazy(expression)
515
+ ) {
516
+ return generateFunctionConstruction(generator, expression, bound.pattern.name, frame);
517
+ }
518
+ return generateDelegate(generator, expression, frame);
519
+ }
520
+ case "SetFilter":
521
+ if (expression.bound.pattern.kind === "Name") {
522
+ return generateSetFilter(generator, expression, expression.bound.pattern.name, frame);
523
+ }
524
+ return generateDelegate(generator, expression, frame);
381
525
  default:
382
526
  return generateDelegate(generator, expression, frame);
383
527
  }