@toiroakr/chisel 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/README.md +114 -10
  2. package/dist/absence.d.ts +1 -0
  3. package/dist/absence.js +39 -1
  4. package/dist/absence.js.map +1 -1
  5. package/dist/behavior.d.ts +5 -10
  6. package/dist/behavior.js +48 -225
  7. package/dist/behavior.js.map +1 -1
  8. package/dist/beside.d.ts +5 -0
  9. package/dist/beside.js +10 -0
  10. package/dist/beside.js.map +1 -1
  11. package/dist/border.d.ts +3 -1
  12. package/dist/border.js +47 -3
  13. package/dist/border.js.map +1 -1
  14. package/dist/bounds.js +4 -3
  15. package/dist/bounds.js.map +1 -1
  16. package/dist/changes.d.ts +23 -0
  17. package/dist/changes.js +355 -0
  18. package/dist/changes.js.map +1 -0
  19. package/dist/checks.d.ts +1 -0
  20. package/dist/checks.js +295 -0
  21. package/dist/checks.js.map +1 -0
  22. package/dist/cli.d.ts +2 -0
  23. package/dist/cli.js +80 -11
  24. package/dist/cli.js.map +1 -1
  25. package/dist/codec.js +9 -3
  26. package/dist/codec.js.map +1 -1
  27. package/dist/codegen.js +2 -0
  28. package/dist/codegen.js.map +1 -1
  29. package/dist/composition.js +5 -4
  30. package/dist/composition.js.map +1 -1
  31. package/dist/conformance.d.ts +24 -0
  32. package/dist/conformance.js +44 -0
  33. package/dist/conformance.js.map +1 -0
  34. package/dist/data.d.ts +2 -2
  35. package/dist/data.js +5 -3
  36. package/dist/data.js.map +1 -1
  37. package/dist/decimal-js.d.ts +2 -0
  38. package/dist/decimal-js.js +5 -0
  39. package/dist/decimal-js.js.map +1 -0
  40. package/dist/decimal.d.ts +2 -0
  41. package/dist/decimal.js +3 -0
  42. package/dist/decimal.js.map +1 -0
  43. package/dist/domain.d.ts +2 -2
  44. package/dist/domain.js +59 -19
  45. package/dist/domain.js.map +1 -1
  46. package/dist/ensures.js +1 -1
  47. package/dist/ensures.js.map +1 -1
  48. package/dist/errors.d.ts +18 -0
  49. package/dist/errors.js +25 -0
  50. package/dist/errors.js.map +1 -0
  51. package/dist/exact.d.ts +13 -1
  52. package/dist/exact.js +52 -3
  53. package/dist/exact.js.map +1 -1
  54. package/dist/feasibility.js +205 -18
  55. package/dist/feasibility.js.map +1 -1
  56. package/dist/guard-borders.d.ts +2 -0
  57. package/dist/guard-borders.js +112 -24
  58. package/dist/guard-borders.js.map +1 -1
  59. package/dist/guard-scope.d.ts +5 -1
  60. package/dist/guard-scope.js +26 -6
  61. package/dist/guard-scope.js.map +1 -1
  62. package/dist/hooks.d.ts +22 -0
  63. package/dist/hooks.js +2 -0
  64. package/dist/hooks.js.map +1 -0
  65. package/dist/index.d.ts +16 -5
  66. package/dist/index.js +12 -4
  67. package/dist/index.js.map +1 -1
  68. package/dist/interval.d.ts +1 -0
  69. package/dist/interval.js +44 -4
  70. package/dist/interval.js.map +1 -1
  71. package/dist/isolated.d.ts +7 -1
  72. package/dist/isolated.js +53 -5
  73. package/dist/isolated.js.map +1 -1
  74. package/dist/kinds/decimal.d.ts +1 -0
  75. package/dist/kinds/decimal.js +16 -0
  76. package/dist/kinds/decimal.js.map +1 -0
  77. package/dist/kinds/rational.d.ts +1 -0
  78. package/dist/kinds/rational.js +13 -0
  79. package/dist/kinds/rational.js.map +1 -0
  80. package/dist/kinds/temporal.d.ts +1 -0
  81. package/dist/kinds/temporal.js +15 -0
  82. package/dist/kinds/temporal.js.map +1 -0
  83. package/dist/lean/behavior.d.ts +29 -0
  84. package/dist/lean/behavior.js +76 -0
  85. package/dist/lean/behavior.js.map +1 -0
  86. package/dist/lean/given.d.ts +10 -0
  87. package/dist/lean/given.js +15 -0
  88. package/dist/lean/given.js.map +1 -0
  89. package/dist/lean/index.d.ts +11 -0
  90. package/dist/lean/index.js +8 -0
  91. package/dist/lean/index.js.map +1 -0
  92. package/dist/lean/model.d.ts +20 -0
  93. package/dist/lean/model.js +133 -0
  94. package/dist/lean/model.js.map +1 -0
  95. package/dist/lean/protocol.d.ts +14 -0
  96. package/dist/lean/protocol.js +34 -0
  97. package/dist/lean/protocol.js.map +1 -0
  98. package/dist/lean/rule.d.ts +54 -0
  99. package/dist/lean/rule.js +149 -0
  100. package/dist/lean/rule.js.map +1 -0
  101. package/dist/lean/schema.d.ts +46 -0
  102. package/dist/lean/schema.js +155 -0
  103. package/dist/lean/schema.js.map +1 -0
  104. package/dist/machine.d.ts +25 -0
  105. package/dist/machine.js +88 -17
  106. package/dist/machine.js.map +1 -1
  107. package/dist/model.d.ts +39 -5
  108. package/dist/model.js +268 -59
  109. package/dist/model.js.map +1 -1
  110. package/dist/off-grid.d.ts +4 -0
  111. package/dist/off-grid.js +92 -0
  112. package/dist/off-grid.js.map +1 -0
  113. package/dist/outcomes.d.ts +9 -1
  114. package/dist/outcomes.js +92 -10
  115. package/dist/outcomes.js.map +1 -1
  116. package/dist/pairs.js +2 -1
  117. package/dist/pairs.js.map +1 -1
  118. package/dist/partition.js +12 -9
  119. package/dist/partition.js.map +1 -1
  120. package/dist/placeholders.d.ts +3 -0
  121. package/dist/placeholders.js +44 -0
  122. package/dist/placeholders.js.map +1 -0
  123. package/dist/proof.js +189 -37
  124. package/dist/proof.js.map +1 -1
  125. package/dist/protocol.d.ts +22 -0
  126. package/dist/protocol.js +12 -0
  127. package/dist/protocol.js.map +1 -0
  128. package/dist/relations.d.ts +30 -0
  129. package/dist/relations.js +235 -0
  130. package/dist/relations.js.map +1 -0
  131. package/dist/rewrites.d.ts +41 -0
  132. package/dist/rewrites.js +180 -0
  133. package/dist/rewrites.js.map +1 -0
  134. package/dist/rule.d.ts +29 -6
  135. package/dist/rule.js +145 -5
  136. package/dist/rule.js.map +1 -1
  137. package/dist/runtime.d.ts +4 -4
  138. package/dist/runtime.js +3 -3
  139. package/dist/runtime.js.map +1 -1
  140. package/dist/schema.d.ts +44 -28
  141. package/dist/schema.js +42 -109
  142. package/dist/schema.js.map +1 -1
  143. package/dist/specification.d.ts +11 -1
  144. package/dist/specification.js +391 -26
  145. package/dist/specification.js.map +1 -1
  146. package/dist/stops.d.ts +20 -0
  147. package/dist/stops.js +221 -0
  148. package/dist/stops.js.map +1 -0
  149. package/dist/temporal.js +5 -5
  150. package/dist/temporal.js.map +1 -1
  151. package/dist/tla-validate.d.ts +31 -0
  152. package/dist/tla-validate.js +151 -0
  153. package/dist/tla-validate.js.map +1 -0
  154. package/dist/tla.d.ts +46 -6
  155. package/dist/tla.js +250 -49
  156. package/dist/tla.js.map +1 -1
  157. package/dist/verification.d.ts +2 -0
  158. package/dist/verification.js +2 -0
  159. package/dist/verification.js.map +1 -1
  160. package/dist/ways.d.ts +4 -1
  161. package/dist/ways.js +23 -8
  162. package/dist/ways.js.map +1 -1
  163. package/dist/world.d.ts +2 -2
  164. package/dist/world.js +13 -17
  165. package/dist/world.js.map +1 -1
  166. package/package.json +23 -7
  167. package/schema/report.schema.json +169 -1
package/dist/tla.js CHANGED
@@ -3,7 +3,8 @@ import { SpecificationError } from "./behavior.js";
3
3
  import { domainOf, integralBounds } from "./domain.js";
4
4
  import { deepEqual } from "./equal.js";
5
5
  import { childrenOf, nodeOf } from "./model.js";
6
- import { positiveLimit } from "./machine.js";
6
+ import { isEffectRecord, positiveLimit } from "./machine.js";
7
+ import { validateTranslation, VALIDATION_PAIR_LIMIT } from "./tla-validate.js";
7
8
  import { schemaAtPath } from "./schema.js";
8
9
  import { isTerm, termData } from "./rule.js";
9
10
  // Compiles the executable expression itself. No sampled transition table is
@@ -30,8 +31,6 @@ export function toTla(specification, options = {}) {
30
31
  throw new SpecificationError("domainLimit must be a positive safe integer");
31
32
  if (!Number.isSafeInteger(maxCommands) || maxCommands < 1)
32
33
  throw new SpecificationError("maxCommands must be a positive safe integer");
33
- if (hasOptional(machine.state))
34
- throw new SpecificationError("TLA+ translation does not support optional state fields");
35
34
  const states = domainOf(machine.state, limit);
36
35
  const commands = domainOf(machine.command, limit);
37
36
  if (!states.exhaustive || !commands.exhaustive) {
@@ -44,19 +43,19 @@ export function toTla(specification, options = {}) {
44
43
  const step = compiler.value(machine.update, new Map([["state", "s"], ["command", "c"]]), true);
45
44
  const properties = machine.invariants.map((invariant, index) => ({
46
45
  name: `Inv${index}`,
47
- formula: compiler.condition(invariant.holds, new Map(), "state"),
46
+ formula: compiler.atTheState(() => compiler.condition(invariant.holds, new Map(), "state")),
48
47
  }));
49
48
  const transitions = machine.transitions.map((transition, index) => ({ name: `Transition${index}`,
50
49
  formula: transition.each
51
50
  ? compiler.paired(transition.holds, transition.each, schemaAtPath(machine.state, transition.each.path)?.kind)
52
51
  : compiler.condition(transition.holds, new Map([["before", "previous"], ["after", "state"]]), "state") }));
53
- const discriminant = machine.command.discriminant === undefined ? "" : identifier(machine.command.discriminant);
52
+ const discriminant = machine.command.discriminant === undefined ? "" : access(machine.command.discriminant);
54
53
  const effectful = hasEffect(machine.update);
55
54
  const preconditions = Object.entries(specification.requires).map(([tag, holds], index) => {
56
55
  const precondition = `(${compiler.condition(holds, new Map([["state", "previous"], ["command", "last"]]), "previous")})`;
57
56
  // A command that stopped (at a failed effect, or by the process dying) may have written nothing yet, so only the other direction holds of it.
58
57
  const agrees = effectful ? `IF stopped THEN (~${precondition} => previous = state) ELSE (${precondition} <=> previous # state)` : `${precondition} <=> previous # state`;
59
- return { name: `Req${index}`, formula: `IF depth = 0 THEN TRUE ELSE IF last.${discriminant} = ${JSON.stringify(tag)} THEN ${agrees} ELSE TRUE` };
58
+ return { name: `Req${index}`, formula: `IF depth = 0 THEN TRUE ELSE IF last${discriminant} = ${JSON.stringify(tag)} THEN ${agrees} ELSE TRUE` };
60
59
  });
61
60
  const last = (command) => preconditions.length > 0 ? ` /\\ last' = ${command}` : "";
62
61
  const next = effectful ? [
@@ -90,6 +89,22 @@ export function toTla(specification, options = {}) {
90
89
  const config = `INIT Init NEXT Next INVARIANT TypeOK ${properties.map(item => `INVARIANT ${item.name}`).join(" ")} ${transitions.map(item => `INVARIANT ${item.name}`).join(" ")} ${preconditions.map(item => `INVARIANT ${item.name}`).join(" ")} INVARIANT Budget CHECK_DEADLOCK FALSE`;
91
90
  return { name, source, config, states: states.values.length, commands: commands.values.length };
92
91
  }
92
+ // What tla-ts says when TLC stops on a value it cannot take, in the terms of the machine.
93
+ function explained(message) {
94
+ if (/can't handle a number this big/.test(message))
95
+ return "a number past what TLC reads (integers from -2147483648 to 2147483647); narrow the range of the field, or check the machine with checkMachine";
96
+ if (/Invalid escape in string/.test(message))
97
+ return "a string holding a character TLA+ has no escape for (a control character other than tab, newline, form feed and carriage return); use a visible character";
98
+ if (/should be an integer/.test(message))
99
+ return "an ordering (<, <=, >, >=) of something that is not an integer: TLA+ orders integers only, so compare enums, booleans and strings with == or !=";
100
+ if (/Attempted to select (the )?(nonexistent )?field|nonexistent field|select field .* from a non-record/.test(message))
101
+ return "a field that may be left out was read where it is absent: TLA+ has no absent field, so write the absence as a case of a sum (a variants schema whose case lacks the field), or do not read it";
102
+ if (/Attempted to compare record:[\s\S]*with non-record/.test(message))
103
+ return "an object whose fields may all be left out has the empty object as a value, which TLA+ writes as {{}} and cannot compare with a record: give the object a field that is always there, or write the absence as a case of a sum (a variants schema whose case lacks the fields)";
104
+ if (/Attempted to check equality/.test(message))
105
+ return "a comparison of values TLC cannot compare (a sequence or a record with null, which is the empty set there, or values of different kinds); compare values of one kind";
106
+ return message;
107
+ }
93
108
  export async function checkMachineTla(machine, options = {}) {
94
109
  let module;
95
110
  try {
@@ -100,25 +115,37 @@ export async function checkMachineTla(machine, options = {}) {
100
115
  return { status: "undetermined", states: 0, generatedStates: 0, reason: error.message };
101
116
  throw error;
102
117
  }
118
+ const limit = positiveLimit(options.validationLimit, VALIDATION_PAIR_LIMIT, "validationLimit");
119
+ const validated = await (options.validate ?? ((specification, built) => validateTranslation(specification, built, { limit, ...(options.domainLimit === undefined ? {} : { domainLimit: options.domainLimit }) })))(machine, module);
120
+ if (validated.kind === "unvalidated")
121
+ return { status: "undetermined", states: 0, generatedStates: 0, reason: explained(validated.reason), module };
122
+ if (validated.kind === "mismatch")
123
+ return { status: "mismatch", states: 0, generatedStates: 0, validation: validated.validation, mismatches: validated.mismatches, module,
124
+ reason: `The TLA+ translation does not agree with the TypeScript evaluation: ${validated.mismatches.map(item => item.what === "step"
125
+ ? `at state ${JSON.stringify(item.state)} and command ${JSON.stringify(item.command)} TypeScript gives ${item.expected}${item.translated === undefined ? "" : ` and the translation ${item.translated}`}`
126
+ : item.what === "accepts what TypeScript refuses"
127
+ ? `at state ${JSON.stringify(item.state)} and command ${JSON.stringify(item.command)} TypeScript refuses the transition and the translation accepts it`
128
+ : `the ${item.what} the translation lists is not the one TypeScript enumerates`).join("; ")}` };
103
129
  let result;
104
130
  try {
105
131
  result = await checkTla({ source: module.source, config: module.config });
106
132
  }
107
133
  catch (error) {
108
134
  return { status: "undetermined", states: 0, generatedStates: 0,
109
- reason: `tla-ts could not complete the check: ${error instanceof Error ? error.message : String(error)}`, module };
135
+ reason: `tla-ts could not complete the check: ${explained(error instanceof Error ? error.message : String(error))}`, module };
110
136
  }
137
+ const validation = validated.validation;
111
138
  if (result.status === "success")
112
- return { status: "held", states: result.distinctStates, generatedStates: result.generatedStates, module };
139
+ return { status: "held", states: result.distinctStates, generatedStates: result.generatedStates, validation, module };
113
140
  if (result.status === "invariant-violation" && result.violation?.name === "Budget")
114
141
  return {
115
- status: "undetermined", states: result.distinctStates, generatedStates: result.generatedStates,
142
+ status: "undetermined", states: result.distinctStates, generatedStates: result.generatedStates, validation,
116
143
  reason: `TLA+ exploration exceeded maxCommands (${options.maxCommands ?? 1000})`, module,
117
144
  };
118
145
  const violated = result.violation?.name ?? "";
119
146
  if (result.status === "invariant-violation")
120
147
  return { status: "broken", states: result.distinctStates,
121
- generatedStates: result.generatedStates,
148
+ generatedStates: result.generatedStates, validation,
122
149
  reason: /^Inv\d+$/.test(violated)
123
150
  ? machine.invariants[Number(violated.slice(3))]?.name ?? violated
124
151
  : /^Req\d+$/.test(violated)
@@ -128,8 +155,8 @@ export async function checkMachineTla(machine, options = {}) {
128
155
  ...(step.action === undefined ? {} : { action: step.action }),
129
156
  state: formatValue(step.state.state), pending: formatValue(step.state.pending),
130
157
  })) }), module };
131
- return { status: "undetermined", states: result.distinctStates, generatedStates: result.generatedStates,
132
- reason: `tla-ts could not complete the check: ${result.status}${result.failure ? `: ${result.failure.message}` : ""}`, module };
158
+ return { status: "undetermined", states: result.distinctStates, generatedStates: result.generatedStates, validation,
159
+ reason: `tla-ts could not complete the check: ${explained(`${result.status}${result.failure ? `: ${result.failure.message}` : ""}`)}`, module };
133
160
  }
134
161
  // Copies of the machine as processes sharing one state (see `checkInterleavings`). Only the
135
162
  // native checker follows the commands a command emits, so a translation that meets one is undetermined.
@@ -182,7 +209,9 @@ export function interleavingsToTla(specification, options) {
182
209
  if (machine.state.kind !== "object")
183
210
  throw new SpecificationError("TLA+ translation of interleavings needs a state that is an object");
184
211
  if (hasOptional(machine.state))
185
- throw new SpecificationError("TLA+ translation does not support optional state fields");
212
+ throw new SpecificationError("TLA+ translation does not support optional state fields: TLA+ has no absent field to compare with. Write the absence as a case of a sum (a variants schema whose case lacks the field)");
213
+ if (hasOptional(machine.command))
214
+ throw new SpecificationError("TLA+ translation does not support optional command fields: TLA+ has no absent field to compare with. Write the absence as a case of a sum (a variants schema whose case lacks the field)");
186
215
  if (options.copies.length === 0)
187
216
  throw new SpecificationError(`Machine ${machine.name} has no copy to run`);
188
217
  const compiler = new Compiler(machine.state, machine.command);
@@ -259,7 +288,7 @@ export async function proveMachine(specification) {
259
288
  const stateOK = compiler.schema(machine.state, "s");
260
289
  const commandOK = compiler.schema(machine.command, "c");
261
290
  const invariants = machine.invariants.map((item, index) => ({ name: `Inv${index}`,
262
- formula: compiler.condition(item.holds, new Map(), "s") }));
291
+ formula: compiler.atTheState(() => compiler.condition(item.holds, new Map(), "s")) }));
263
292
  const assumption = ["StateOK(s)", "CommandOK(c)", ...invariants.map(item => `${item.name}(s)`)].join(" /\\ ");
264
293
  const effectful = hasEffect(machine.update);
265
294
  const defs = ["Step", ...(effectful ? ["Outcomes"] : []), "StateOK", "CommandOK", ...invariants.map(item => item.name)].join(", ");
@@ -276,7 +305,7 @@ export async function proveMachine(specification) {
276
305
  ...transitions.map(formula => over(`(s = ${output}.state \\/ (${formula}))`)),
277
306
  ...requiredTags.flatMap(tag => {
278
307
  const pre = compiler.condition(specification.requires[tag], new Map([["state", "s"], ["command", "c"]]), "s");
279
- const isTag = `c.${identifier(machine.command.discriminant)} = ${JSON.stringify(tag)}`;
308
+ const isTag = `c${access(machine.command.discriminant)} = ${JSON.stringify(tag)}`;
280
309
  const unchanged = unchangedFormula(machine.state, "s", `${output}.state`);
281
310
  return [over(`(${isTag} => (${unchanged} \\/ (${pre})))`),
282
311
  over(`(${isTag} => (${effectful ? `${output}.stopped \\/ ` : ""}~(${pre}) \\/ ~(${unchanged})))`)];
@@ -334,10 +363,10 @@ function unchangedFormula(schema, before, after) {
334
363
  if (schema.kind !== "object")
335
364
  return `${before} = ${after}`;
336
365
  const fields = Object.entries(schema.shape);
337
- return `(${fields.map(([field, child]) => unchangedFormula(child, `${before}.${identifier(field)}`, `${after}.${identifier(field)}`)).join(" /\\ ") || "TRUE"})`;
366
+ return `(${fields.map(([field, child]) => unchangedFormula(child, `${before}${access(field)}`, `${after}${access(field)}`)).join(" /\\ ") || "TRUE"})`;
338
367
  }
339
368
  function hasEffect(value) {
340
- if (value !== null && typeof value === "object" && value.kind === "effect")
369
+ if (isEffectRecord(value))
341
370
  return true;
342
371
  return childrenOf(value).some(hasEffect);
343
372
  }
@@ -358,7 +387,8 @@ function hasOptional(schema, visited = new Set()) {
358
387
  return hasOptional(schema.element, visited);
359
388
  return false;
360
389
  }
361
- class Compiler {
390
+ // Exported for lean/conformance/generate.ts, which prints rules with it; the package does not re-export it.
391
+ export class Compiler {
362
392
  stateSchema;
363
393
  commandSchema;
364
394
  next = 0;
@@ -367,6 +397,9 @@ class Compiler {
367
397
  this.commandSchema = commandSchema;
368
398
  }
369
399
  value(value, names, result = false) {
400
+ // No value a machine holds is a TLA+ set, so the empty set stands for null apart from every other value.
401
+ if (value === null)
402
+ return "{}";
370
403
  if (isTerm(value))
371
404
  return this.term(termData(value), names);
372
405
  const node = nodeOf(value);
@@ -374,18 +407,28 @@ class Compiler {
374
407
  return `(IF ${this.rule(node.condition, names, names.get("") ?? "s")} THEN ${this.value(node.yes, names, result)} ELSE ${this.value(node.no, names, result)})`;
375
408
  if (node?.kind === "bind") {
376
409
  const data = isTerm(node.value) ? termData(node.value) : undefined;
377
- const source = data?.kind === "position" && data.path.length === 1 ? data.path[0] : undefined;
378
- if ((source !== "state" || node.schema !== this.stateSchema) &&
379
- (source !== "command" || node.schema !== this.commandSchema)) {
410
+ if (data?.kind !== "position" || data.measure !== "value" || this.schemaAt(data.path) !== node.schema || this.mayBeLeftOut(data.path)) {
380
411
  throw new SpecificationError("TLA+ translation cannot preserve bind schema validation");
381
412
  }
382
413
  const local = `local${this.next++}`;
383
- return `(LET ${local} == ${this.value(node.value, names)} IN ${this.value(node.body, new Map([...names, [node.name, local]]), result)})`;
414
+ const bound = this.value(node.value, names);
415
+ // The body reads the local under the schema it was bound under, which is what makes arithmetic on an integer local a whole number.
416
+ const outer = this.locals.get(node.name);
417
+ this.locals.set(node.name, node.schema);
418
+ try {
419
+ return `(LET ${local} == ${bound} IN ${this.value(node.body, new Map([...names, [node.name, local]]), result)})`;
420
+ }
421
+ finally {
422
+ if (outer === undefined)
423
+ this.locals.delete(node.name);
424
+ else
425
+ this.locals.set(node.name, outer);
426
+ }
384
427
  }
385
428
  if (node?.kind === "map") {
386
429
  const data = isTerm(node.values) ? termData(node.values) : undefined;
387
- if (data?.kind !== "position" || data.path.length !== 1 || data.path[0] !== "state" ||
388
- this.stateSchema.kind !== "array" || this.stateSchema.element !== node.element ||
430
+ const array = data?.kind === "position" && data.measure === "value" && !this.mayBeLeftOut(data.path) ? this.schemaAt(data.path) : undefined;
431
+ if (array?.kind !== "array" || array.element !== node.element ||
389
432
  node.element !== node.output || !this.safeMappedBody(node.body, node.element, node.name)) {
390
433
  throw new SpecificationError("TLA+ translation cannot preserve map element and output schema validation");
391
434
  }
@@ -402,23 +445,39 @@ class Compiler {
402
445
  throw new SpecificationError("TLA+ translation cannot preserve invalid constructor");
403
446
  return this.value(parsed.value, names, result);
404
447
  }
405
- if (node?.kind === "operation")
406
- throw new SpecificationError("TLA+ translation cannot preserve intermediate arithmetic validation");
448
+ if (node?.kind === "operation") {
449
+ // Whole numbers only, both of the one kind JavaScript adds without refusing (`arithmeticOf` throws on a number with a bigint),
450
+ // so that TLA+ computes only what TypeScript computes: TLC reads 32 bits, inside the 53 a number holds exactly.
451
+ const symbol = { add: "+", subtract: "-", multiply: "*" }[node.operator];
452
+ if (symbol !== undefined && this.wholeNumber(node.left, names) && this.wholeNumber(node.right, names)) {
453
+ return `(${this.value(node.left, names)} ${symbol} ${this.value(node.right, names)})`;
454
+ }
455
+ throw new SpecificationError(symbol === undefined
456
+ ? `TLA+ translation cannot preserve ${node.operator}: it translates add, subtract and multiply of whole numbers only`
457
+ : `TLA+ translation cannot preserve ${node.operator} of anything but whole numbers: both sides must be integer fields, integers or the length of an array, since TLA+ has one kind of integer and TypeScript refuses a number with a bigint, a decimal or a rational`);
458
+ }
407
459
  if (node)
408
460
  throw new SpecificationError(`TLA+ translation does not support ${node.kind}${"operator" in node ? ` ${node.operator}` : ""}`);
409
- if (typeof value === "string")
410
- return JSON.stringify(value);
461
+ if (typeof value === "string") {
462
+ // TypeScript compares text as NFC (`compareText`), TLC compares what is written: a text not in NFC would be told apart by TLC and not by TypeScript.
463
+ if (value !== value.normalize("NFC"))
464
+ throw new SpecificationError(`TLA+ translation compares text as written, and TypeScript compares it as NFC: write ${JSON.stringify(value)} in NFC (${JSON.stringify(value.normalize("NFC"))})`);
465
+ return tlaString(value);
466
+ }
411
467
  if (typeof value === "boolean")
412
468
  return String(value).toUpperCase();
413
469
  if (typeof value === "bigint")
414
- return value.toString();
470
+ return tlaInteger(value);
471
+ // -0 and 0 are one integer to TLA+, and `deepEqual` tells them apart in an array or a record, so a translation could not keep both.
472
+ if (typeof value === "number" && Object.is(value, -0))
473
+ throw new SpecificationError("TLA+ translation cannot write negative zero: TLA+ has one zero, and TypeScript compares -0 with 0 as different inside an array or a record");
415
474
  if (typeof value === "number" && Number.isSafeInteger(value))
416
- return String(value);
475
+ return tlaInteger(value);
417
476
  if (Array.isArray(value))
418
477
  return `<<${value.map(item => this.value(item, names)).join(", ")}>>`;
419
478
  if (value !== null && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
420
479
  const fields = Object.entries(value);
421
- if (value.kind === "effect") {
480
+ if (isEffectRecord(value)) {
422
481
  const hasFailure = fields.some(([key]) => key === "failure");
423
482
  if (!hasFailure)
424
483
  fields.push(["failure", 0]);
@@ -433,11 +492,79 @@ class Compiler {
433
492
  if (result && !fields.some(([key]) => key === "commands"))
434
493
  fields.push(["commands", []]);
435
494
  if (!fields.length)
436
- throw new SpecificationError("TLA+ translation cannot represent an empty record");
437
- return `[${fields.map(([key, child]) => `${identifier(key)} |-> ${this.value(child, names)}`).join(", ")}]`;
495
+ return "{{}}";
496
+ if (fields.every(([key]) => isIdentifier(key)))
497
+ return `[${fields.map(([key, child]) => `${key} |-> ${this.value(child, names)}`).join(", ")}]`;
498
+ const key = `field${this.next++}`;
499
+ return `[${key} \\in ${set(fields.map(([field]) => JSON.stringify(field)))} |-> CASE ${fields.map(([field, child]) => `${key} = ${JSON.stringify(field)} -> ${this.value(child, names)}`).join(" [] ")}]`;
438
500
  }
439
501
  throw new SpecificationError(`TLA+ translation cannot represent ${String(value)}`);
440
502
  }
503
+ // Whether an operand is a whole number of the kind `number` holds: an integer field or constant, a length, a linear term of
504
+ // integer fields, or arithmetic and a choice of such.
505
+ wholeNumber(operand, names) {
506
+ if (typeof operand === "number")
507
+ return Number.isSafeInteger(operand);
508
+ if (isTerm(operand)) {
509
+ const data = termData(operand);
510
+ if (data.kind === "linear")
511
+ return data.parts.every(part => part.measure === "length" || this.wholeSchema(this.schemaRead(part.path, names)));
512
+ return data.measure === "length" || this.wholeSchema(this.schemaRead(data.path, names));
513
+ }
514
+ const node = nodeOf(operand);
515
+ if (node?.kind === "operation")
516
+ return (node.operator === "add" || node.operator === "subtract" || node.operator === "multiply") && this.wholeNumber(node.left, names) && this.wholeNumber(node.right, names);
517
+ if (node?.kind === "choose")
518
+ return this.wholeNumber(node.yes, names) && this.wholeNumber(node.no, names);
519
+ return false;
520
+ }
521
+ // An integer, or a literal that is a safe whole number.
522
+ wholeSchema(schema) {
523
+ if (schema?.kind === "integer")
524
+ return true;
525
+ return schema?.kind === "literal" && Number.isSafeInteger(schema.value);
526
+ }
527
+ // Whether the field at the path, or an object on the way to it, is optional: a bind of it fails on its absence, which the translation does not model.
528
+ mayBeLeftOut(path) {
529
+ let schema = path[0] === "state" ? this.stateSchema : path[0] === "command" ? this.commandSchema : undefined;
530
+ for (const key of path.slice(1)) {
531
+ if (schema?.kind === "optional")
532
+ return true;
533
+ schema = schema?.kind === "object" ? schema.shape[key] : undefined;
534
+ }
535
+ return schema?.kind === "optional";
536
+ }
537
+ // The schema a term reads in a rule: rooted at `state` or `command` in the update, at the state in an invariant, and unknown inside the elements a paired transition reads.
538
+ schemaRead(path, names) {
539
+ if (this.pairing)
540
+ return undefined;
541
+ const local = path[0] === undefined ? undefined : this.locals.get(path[0]);
542
+ if (local !== undefined && names.has(path[0]))
543
+ return schemaAtPath(local, path.slice(1));
544
+ if ((path[0] === "state" || path[0] === "command") && names.has(path[0]))
545
+ return this.schemaAt(path);
546
+ if (path[0] !== undefined && names.has(path[0]))
547
+ return path[0] === "before" || path[0] === "after" ? this.schemaAt(["state", ...path.slice(1)]) : undefined;
548
+ // Only an invariant of the whole state reads its fields by their names; one of a nested schema reads them from that schema, which this does not know.
549
+ return this.atState ? (path.length === 0 ? this.stateSchema : this.schemaAt(["state", ...path])) : undefined;
550
+ }
551
+ locals = new Map();
552
+ pairing = false;
553
+ atState = false;
554
+ // Compiles what reads the state by its field names: the invariants of the machine.
555
+ atTheState(compile) {
556
+ this.atState = true;
557
+ try {
558
+ return compile();
559
+ }
560
+ finally {
561
+ this.atState = false;
562
+ }
563
+ }
564
+ schemaAt(path) {
565
+ const root = path[0] === "state" ? this.stateSchema : path[0] === "command" ? this.commandSchema : undefined;
566
+ return root && schemaAtPath(root, path.slice(1));
567
+ }
441
568
  safeMappedBody(value, schema, element) {
442
569
  const node = nodeOf(value);
443
570
  if (node?.kind === "choose")
@@ -453,13 +580,22 @@ class Compiler {
453
580
  }
454
581
  condition(value, names, self) {
455
582
  if (value !== null && typeof value === "object" && "kind" in value &&
456
- ["compare", "all", "any", "and", "or", "not"].includes(String(value.kind)))
583
+ ["compare", "relation", "all", "any", "and", "or", "not"].includes(String(value.kind)))
457
584
  return this.rule(value, names, self);
458
585
  return this.value(value, new Map([...names, ["", self]]));
459
586
  }
460
587
  paired(condition, each, kind, beforeRoot = "previous", afterRoot = "state") {
461
- const before = each.path.reduce((root, field) => `${root}.${identifier(field)}`, `(${beforeRoot})`);
462
- const after = each.path.reduce((root, field) => `${root}.${identifier(field)}`, `(${afterRoot})`);
588
+ this.pairing = true;
589
+ try {
590
+ return this.pairedIn(condition, each, kind, beforeRoot, afterRoot);
591
+ }
592
+ finally {
593
+ this.pairing = false;
594
+ }
595
+ }
596
+ pairedIn(condition, each, kind, beforeRoot, afterRoot) {
597
+ const before = each.path.reduce((root, field) => `${root}${access(field)}`, `(${beforeRoot})`);
598
+ const after = each.path.reduce((root, field) => `${root}${access(field)}`, `(${afterRoot})`);
463
599
  if (kind === "record") {
464
600
  const earlier = `${before}[key]`, later = `${after}[key]`;
465
601
  const rule = this.condition(condition, new Map([["before", earlier], ["after", later]]), later);
@@ -467,11 +603,11 @@ class Compiler {
467
603
  }
468
604
  if (kind !== "array" || each.by === undefined)
469
605
  throw new SpecificationError("TLA+ translation cannot pair this collection");
470
- const key = identifier(each.by);
606
+ const key = access(each.by);
471
607
  const bi = `${before}[i]`, aj = `${after}[j]`;
472
608
  const rule = this.condition(condition, new Map([["before", bi], ["after", aj]]), aj);
473
- const unique = (collection) => `(\\A x, y \\in 1..Len(${collection}): x = y \\/ ${collection}[x].${key} # ${collection}[y].${key})`;
474
- return `(${unique(before)} /\\ ${unique(after)} /\\ \\A i \\in 1..Len(${before}): \\A j \\in 1..Len(${after}): ${bi}.${key} # ${aj}.${key} \\/ ${bi} = ${aj} \\/ (${rule}))`;
609
+ const unique = (collection) => `(\\A x, y \\in 1..Len(${collection}): x = y \\/ ${collection}[x]${key} # ${collection}[y]${key})`;
610
+ return `(${unique(before)} /\\ ${unique(after)} /\\ \\A i \\in 1..Len(${before}): \\A j \\in 1..Len(${after}): ${bi}${key} # ${aj}${key} \\/ ${bi} = ${aj} \\/ (${rule}))`;
475
611
  }
476
612
  schema(schema, value) {
477
613
  let type;
@@ -496,14 +632,14 @@ class Compiler {
496
632
  break;
497
633
  case "object": {
498
634
  const fields = Object.entries(schema.shape);
499
- type = `(DOMAIN ${value} = ${set(fields.map(([field]) => JSON.stringify(field)))} /\\ ${fields.map(([field, child]) => this.schema(child, `${value}.${identifier(field)}`)).join(" /\\ ") || "TRUE"})`;
635
+ type = fields.length === 0 ? `${value} = {{}}` : `(DOMAIN ${value} = ${set(fields.map(([field]) => JSON.stringify(field)))} /\\ ${fields.map(([field, child]) => this.schema(child, `${value}${access(field)}`)).join(" /\\ ")})`;
500
636
  break;
501
637
  }
502
638
  case "variants": {
503
639
  const sum = schema;
504
640
  type = `(${sum.variantTags.map(tag => {
505
641
  const fields = sum.variants[tag].shape;
506
- return `(${value}.${identifier(sum.discriminant)} = ${JSON.stringify(tag)} /\\ DOMAIN ${value} = ${set([sum.discriminant, ...Object.keys(fields)].map(field => JSON.stringify(field)))}${Object.entries(fields).map(([field, child]) => ` /\\ ${this.schema(child, `${value}.${identifier(field)}`)}`).join("")})`;
642
+ return `(${value}${access(sum.discriminant)} = ${JSON.stringify(tag)} /\\ DOMAIN ${value} = ${set([sum.discriminant, ...Object.keys(fields)].map(field => JSON.stringify(field)))}${Object.entries(fields).map(([field, child]) => ` /\\ ${this.schema(child, `${value}${access(field)}`)}`).join("")})`;
507
643
  }).join(" \\/ ")})`;
508
644
  break;
509
645
  }
@@ -533,10 +669,23 @@ class Compiler {
533
669
  }
534
670
  rule(rule, names, self = "s") {
535
671
  if (rule.kind === "compare") {
672
+ this.comparable(rule, names);
536
673
  const operands = new Map([...names, ["", self]]);
537
674
  const operator = rule.operator === "==" ? "=" : rule.operator === "!=" ? "#" : rule.operator;
538
675
  return `(${this.value(rule.left, operands)} ${operator} ${this.value(rule.right, operands)})`;
539
676
  }
677
+ if (rule.kind === "relation") {
678
+ const operands = new Map([...names, ["", self]]);
679
+ const subject = this.value(rule.subject, operands), other = this.value(rule.other, operands);
680
+ if (rule.relation === "hasKey")
681
+ return `(${other} \\in DOMAIN ${subject})`;
682
+ if (rule.relation === "includes") {
683
+ // A fresh index: an enclosing quantifier of a paired transition may already bind i.
684
+ const index = `element${this.next++}`;
685
+ return `(\\E ${index} \\in 1..Len(${subject}): ${subject}[${index}] = ${other})`;
686
+ }
687
+ throw new SpecificationError(`TLA+ translation does not read ${rule.relation}: strings are no sequences there`);
688
+ }
540
689
  if (rule.kind === "not")
541
690
  return `~(${this.rule(rule.rule, names, self)})`;
542
691
  if (rule.kind === "and" || rule.kind === "or")
@@ -547,33 +696,85 @@ class Compiler {
547
696
  const elements = new Map([...names, [rule.element, `${bound}[${variable}]`]]);
548
697
  return `(\\${rule.kind === "all" ? "A" : "E"} ${variable} \\in ${collection}: ${this.rule(rule.each, elements, self)})`;
549
698
  }
699
+ // What TLC can compare: integers order, and a sequence or a record is never compared with null, which is the empty set there.
700
+ comparable(rule, names) {
701
+ const kindOf = (operand) => {
702
+ if (operand === null)
703
+ return "null";
704
+ if (isTerm(operand)) {
705
+ const data = termData(operand);
706
+ if (data.kind !== "position")
707
+ return undefined;
708
+ if (data.measure === "length")
709
+ return "integer";
710
+ const schema = this.schemaRead(data.path, names);
711
+ if (schema === undefined)
712
+ return undefined;
713
+ if (schema.kind === "literal" && schema.value === null)
714
+ return "null";
715
+ if (schema.kind === "object" && Object.keys(schema.shape).length === 0)
716
+ return "empty object";
717
+ return schema.kind === "int64" ? "integer" : schema.kind;
718
+ }
719
+ return typeof operand === "number" || typeof operand === "bigint" ? "integer" : typeof operand === "string" ? "string" : typeof operand === "boolean" ? "boolean" : Array.isArray(operand) ? "array" : undefined;
720
+ };
721
+ const left = kindOf(rule.left), right = kindOf(rule.right);
722
+ if (rule.operator !== "==" && rule.operator !== "!=") {
723
+ const other = [left, right].find(kind => kind !== undefined && kind !== "integer");
724
+ if (other !== undefined)
725
+ throw new SpecificationError(`TLA+ translation cannot order ${other === "enum" ? "an enum" : `a ${other}`} with ${rule.operator}: TLA+ orders integers only. Compare with == or !=, or check the machine with checkMachine`);
726
+ }
727
+ const sequenceOrRecord = (kind) => kind === "array" || kind === "object" || kind === "variants";
728
+ if ((left === "null" && sequenceOrRecord(right)) || (right === "null" && sequenceOrRecord(left))) {
729
+ throw new SpecificationError("TLA+ translation cannot compare a sequence or a record with null: null is the empty set there, and TLC refuses to compare a set with them. Compare with a case of a sum instead");
730
+ }
731
+ }
550
732
  term(data, names) {
551
733
  if (data.kind === "linear") {
552
734
  if (!Number.isSafeInteger(data.constant))
553
735
  throw new SpecificationError("TLA+ translation requires integer arithmetic");
736
+ const constant = tlaInteger(data.constant);
554
737
  const parts = data.parts.map(part => {
555
738
  if (!Number.isSafeInteger(part.coefficient))
556
739
  throw new SpecificationError("TLA+ translation requires integer coefficients");
557
740
  const value = this.position(part.path, part.measure, names);
558
- return part.coefficient === 1 ? value : `(${part.coefficient} * ${value})`;
741
+ return part.coefficient === 1 ? value : `(${tlaInteger(part.coefficient)} * ${value})`;
559
742
  });
560
- return `(${[...parts, String(data.constant)].join(" + ")})`;
743
+ return `(${[...parts, constant].join(" + ")})`;
561
744
  }
562
745
  return this.position(data.path, data.measure, names);
563
746
  }
564
747
  position(path, measure, names) {
565
- if (measure !== "value")
748
+ if (measure !== "value" && measure !== "length")
566
749
  throw new SpecificationError(`TLA+ translation does not support measure ${measure}`);
567
750
  const named = names.get(path[0] ?? "");
568
751
  const root = named ?? names.get("");
569
752
  if (root === undefined)
570
753
  throw new SpecificationError(`TLA+ translation cannot resolve term ${path.join(".")}`);
571
- return path.slice(named === undefined ? 0 : 1).reduce((current, part) => `${current}.${identifier(part)}`, root);
754
+ const read = path.slice(named === undefined ? 0 : 1).reduce((current, part) => `${current}${access(part)}`, root);
755
+ return measure === "length" ? `Len(${read})` : read;
572
756
  }
573
757
  }
574
- function identifier(value) {
575
- if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(value))
576
- throw new SpecificationError(`TLA+ translation cannot represent field ${value}`);
577
- return value;
758
+ // TLC reads integers of 32 bits only.
759
+ function tlaInteger(value) {
760
+ if (value >= 2147483648 || value <= -2147483649)
761
+ throw new SpecificationError(`TLA+ translation cannot represent the integer ${value}: TLC reads integers from -2147483648 to 2147483647. Narrow the range of the field, or check the machine with checkMachine`);
762
+ return String(value);
763
+ }
764
+ // A TLA+ string escapes only \", \\, \t, \n, \f and \r, and holds no lone surrogate; JSON.stringify writes every other control character as \uXXXX, which TLC refuses to read.
765
+ function tlaString(value) {
766
+ const found = /[\u0000-\u0008\u000b\u000e-\u001f]/.exec(value);
767
+ if (found !== null)
768
+ throw new SpecificationError(`TLA+ translation cannot write the string ${JSON.stringify(value)}: the control character U+${found[0].charCodeAt(0).toString(16).padStart(4, "0").toUpperCase()} has no TLA+ escape. Use a visible character, or check the machine with checkMachine`);
769
+ if (!value.isWellFormed())
770
+ throw new SpecificationError(`TLA+ translation cannot write the string ${JSON.stringify(value)}: it holds an unpaired surrogate`);
771
+ return JSON.stringify(value);
772
+ }
773
+ function isIdentifier(value) {
774
+ return /^[A-Za-z][A-Za-z0-9_]*$/.test(value);
775
+ }
776
+ // A record is a function on its field names, so a field TLA+ cannot name is read by its name as a string.
777
+ function access(field) {
778
+ return isIdentifier(field) ? `.${field}` : `[${JSON.stringify(field)}]`;
578
779
  }
579
780
  //# sourceMappingURL=tla.js.map