tla-ts 0.0.4-dev.8fefa42 → 0.0.4-dev.a11a30a

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 (60) hide show
  1. package/README.md +27 -130
  2. package/dist/deciders.cjs +1 -1
  3. package/dist/deciders.js +1 -1
  4. package/dist/index.cjs +1 -1
  5. package/dist/index.d.cts +1 -3
  6. package/dist/index.d.ts +1 -3
  7. package/dist/index.js +1 -1
  8. package/dist/prove-worker.cjs +1 -1
  9. package/dist/prove-worker.js +1 -1
  10. package/dist/prove.cjs +506 -25
  11. package/dist/prove.js +506 -25
  12. package/dist/run-cli.cjs +35 -28
  13. package/dist/run-cli.js +35 -28
  14. package/dist/tlapm.cjs +2 -2
  15. package/dist/tlapm.js +2 -2
  16. package/package.json +1 -1
  17. package/src/obligations/action.ts +56 -99
  18. package/src/obligations/anon.ts +37 -41
  19. package/src/obligations/deref.ts +49 -90
  20. package/src/obligations/expression.ts +63 -49
  21. package/src/obligations/format.ts +7 -8
  22. package/src/obligations/generate.ts +60 -155
  23. package/src/obligations/index.ts +6 -4
  24. package/src/obligations/levels.ts +20 -32
  25. package/src/obligations/module.ts +93 -127
  26. package/src/obligations/pickle.ts +1 -3
  27. package/src/obligations/pragma.ts +14 -14
  28. package/src/obligations/printer.ts +17 -21
  29. package/src/obligations/proof.ts +0 -1
  30. package/src/obligations/source.ts +72 -73
  31. package/src/obligations/temporal.ts +29 -27
  32. package/src/obligations/tuples.ts +37 -53
  33. package/src/ocaml-marshal.ts +166 -0
  34. package/src/prove/decide-pool.ts +12 -17
  35. package/src/prove/deciders.ts +7 -1
  36. package/src/prove/first-order.ts +78 -0
  37. package/src/prove/isabelle/encode.ts +96 -127
  38. package/src/prove/ocaml.ts +1 -1
  39. package/src/prove/prep/action.ts +39 -51
  40. package/src/prove/prep/defs.ts +19 -13
  41. package/src/prove/prep/elab.ts +1 -1
  42. package/src/prove/prep/level-comparison.ts +15 -38
  43. package/src/prove/prep/pragma.ts +4 -4
  44. package/src/prove/prove-worker.ts +4 -11
  45. package/src/prove/prove.ts +230 -149
  46. package/src/prove/ptl/encode.ts +5 -6
  47. package/src/prove/smt/axioms.ts +78 -79
  48. package/src/prove/smt/data.ts +16 -45
  49. package/src/prove/smt/encode.ts +18 -23
  50. package/src/prove/smt/extensionality.ts +14 -12
  51. package/src/prove/smt/flatten.ts +3 -18
  52. package/src/prove/smt/format.ts +14 -3
  53. package/src/prove/smt/instances.ts +4 -5
  54. package/src/prove/smt/rewrite.ts +36 -48
  55. package/src/prove/smt/simplify.ts +10 -10
  56. package/src/prove/tlapm/tlapm.ts +13 -13
  57. package/src/prove/verdict.ts +5 -0
  58. package/src/prove/zenon/encode.ts +36 -101
  59. package/src/run-cli.ts +264 -115
  60. package/src/tlapm-cache.ts +236 -0
@@ -31,6 +31,7 @@ import {
31
31
  FUN_APP,
32
32
  FUN_EXCEPT,
33
33
  FUN_SET,
34
+ getBinders,
34
35
  INT_LTEQ,
35
36
  INT_SET,
36
37
  MEM,
@@ -64,7 +65,7 @@ export interface EncodingSession {
64
65
 
65
66
  export interface Mode {
66
67
  // Whether the text encodes a fact that tlapm leaves out, which may declare operators.
67
- isOmitted?: boolean;
68
+ isOmitted: boolean;
68
69
  polarity: Polarity;
69
70
  at: string | undefined;
70
71
  depth: number;
@@ -82,6 +83,14 @@ export interface Env {
82
83
  rest: Env | undefined;
83
84
  }
84
85
 
86
+ // A nested ASSUME's declarations and facts so far: each wraps the goal in a quantifier or an
87
+ // implication.
88
+ interface NestedContext {
89
+ env: Env | undefined;
90
+ mode: Mode;
91
+ wrappers: ((body: string) => string)[];
92
+ }
93
+
85
94
  export const createEncoder = (session: EncodingSession) => {
86
95
  const flattener = createFlattener();
87
96
  const flatten = flattener.flatten;
@@ -174,9 +183,6 @@ export const createEncoder = (session: EncodingSession) => {
174
183
  return { variables, env: inner, mode: { ...mode, depth: mode.depth + names.length } };
175
184
  };
176
185
 
177
- const binders = (variables: string[]) =>
178
- variables.map((variable) => `(${variable} Idv)`).join(" ");
179
-
180
186
  const encodeQuantifier = (
181
187
  expression: Extract<Expr, { kind: "Quant" }>,
182
188
  env: Env | undefined,
@@ -193,8 +199,8 @@ export const createEncoder = (session: EncodingSession) => {
193
199
  domains[index] === undefined ? [] : [`(${MEM} ${variable} ${domains[index]})`],
194
200
  );
195
201
  return expression.quantifier === "Forall"
196
- ? `(forall (${binders(bound.variables)}) ${guards.length === 0 ? body : `(=> ${conjoin(guards)} ${body})`})`
197
- : `(exists (${binders(bound.variables)}) ${conjoin([...guards, body])})`;
202
+ ? `(forall (${getBinders(bound.variables)}) ${guards.length === 0 ? body : `(=> ${conjoin(guards)} ${body})`})`
203
+ : `(exists (${getBinders(bound.variables)}) ${conjoin([...guards, body])})`;
198
204
  };
199
205
 
200
206
  const encodeSetSt = (
@@ -297,21 +303,15 @@ export const createEncoder = (session: EncodingSession) => {
297
303
  return idv(call(symbol, free));
298
304
  };
299
305
 
300
- // Standardize.set_extensionality_visitor: an equality of sets where it may need proving
301
- // triggers the extensionality axiom.
302
- const encodeEquality = (
303
- left: Expr,
304
- right: Expr,
305
- env: Env | undefined,
306
- mode: Mode,
307
- isNegated: boolean,
308
- ) => {
309
- // Type.Synthesize compares values of the same sort only above type level 1, so two formulas
310
- // are compared as values.
311
- const leftText = encodeIdv(left, env, mode);
312
- const rightText = encodeIdv(right, env, mode);
313
- return getEquality(leftText, rightText, mode.polarity, isNegated);
314
- };
306
+ // Type.Synthesize compares values of the same sort only above type level 1, so two formulas are
307
+ // compared as values.
308
+ const encodeEquality = (args: Expr[], env: Env | undefined, mode: Mode, isNegated: boolean) =>
309
+ getEquality(
310
+ encodeIdv(args[0], env, mode),
311
+ encodeIdv(args[1], env, mode),
312
+ mode.polarity,
313
+ isNegated,
314
+ );
315
315
 
316
316
  // Type.Synthesize: SelectSeq's test becomes the predicate LAMBDA x1 : Test(x1), its body the
317
317
  // text Flatten compares.
@@ -351,9 +351,9 @@ export const createEncoder = (session: EncodingSession) => {
351
351
  case "Neg":
352
352
  return bool(`(not ${encodeBool(args[0], env, invert(mode))})`);
353
353
  case "Eq":
354
- return bool(encodeEquality(args[0], args[1], env, mode, false));
354
+ return bool(encodeEquality(args, env, mode, false));
355
355
  case "Neq":
356
- return bool(encodeEquality(args[0], args[1], env, mode, true));
356
+ return bool(encodeEquality(args, env, mode, true));
357
357
  case "Mem":
358
358
  return bool(call(MEM, idvs()));
359
359
  // Rewrite.elim_notmem: a \notin S is ~(a \in S).
@@ -405,12 +405,10 @@ export const createEncoder = (session: EncodingSession) => {
405
405
  ): Term => {
406
406
  switch (binding.kind) {
407
407
  case "constant":
408
- if (args.length > 0) throw new TlaUnsupportedError("an applied constant");
409
- return idv(binding.symbol);
410
408
  case "variable":
411
- if (args.length > 0) throw new TlaUnsupportedError("an applied variable");
409
+ if (args.length > 0) throw new TlaUnsupportedError(`an applied ${binding.kind}`);
412
410
  return idv(binding.symbol);
413
- case "operator": {
411
+ case "operator":
414
412
  if (args.length !== binding.arity)
415
413
  throw new TlaUnsupportedError("an operator applied to the wrong number of arguments");
416
414
  return idv(
@@ -419,7 +417,6 @@ export const createEncoder = (session: EncodingSession) => {
419
417
  args.map((arg) => encodeIdv(arg, env, mode)),
420
418
  ),
421
419
  );
422
- }
423
420
  // Flatten: an application of a second-order operator, which has no axioms, is a fresh
424
421
  // operator of its first-order arguments and the bound variables its others use.
425
422
  case "secondOrder": {
@@ -559,11 +556,7 @@ export const createEncoder = (session: EncodingSession) => {
559
556
  };
560
557
 
561
558
  const encodeSequent = (sequent: Sequent, env: Env | undefined, mode: Mode): string => {
562
- const steps = sequent.context.reduce<{
563
- env: Env | undefined;
564
- mode: Mode;
565
- wrappers: ((body: string) => string)[];
566
- }>(
559
+ const steps = sequent.context.reduce<NestedContext>(
567
560
  (state, hyp) => {
568
561
  switch (hyp.kind) {
569
562
  case "Fresh": {
@@ -573,10 +566,7 @@ export const createEncoder = (session: EncodingSession) => {
573
566
  return {
574
567
  env: push(state.env, { kind: "operator", symbol: variable, arity: hyp.shape }),
575
568
  mode: { ...state.mode, depth: state.mode.depth + 1 },
576
- wrappers: [
577
- ...state.wrappers,
578
- (body: string) => `(forall ((${variable} Idv)) ${body})`,
579
- ],
569
+ wrappers: [...state.wrappers, (body) => `(forall ((${variable} Idv)) ${body})`],
580
570
  };
581
571
  }
582
572
  if (hyp.level !== "Constant")
@@ -590,8 +580,7 @@ export const createEncoder = (session: EncodingSession) => {
590
580
  mode: bound.mode,
591
581
  wrappers: [
592
582
  ...state.wrappers,
593
- (body: string) =>
594
- `(forall ((${variable} Idv)) ${guard ? `(=> ${guard} ${body})` : body})`,
583
+ (body) => `(forall ((${variable} Idv)) ${guard ? `(=> ${guard} ${body})` : body})`,
595
584
  ],
596
585
  };
597
586
  }
@@ -604,7 +593,7 @@ export const createEncoder = (session: EncodingSession) => {
604
593
  env: push(state.env, { kind: "unsupported", reason: "a reference to a fact" }),
605
594
  mode: state.mode,
606
595
  wrappers: fact
607
- ? [...state.wrappers, (body: string) => `(=> ${fact} ${body})`]
596
+ ? [...state.wrappers, (body) => `(=> ${fact} ${body})`]
608
597
  : state.wrappers,
609
598
  };
610
599
  }
@@ -650,7 +639,7 @@ export const createEncoder = (session: EncodingSession) => {
650
639
  if (operator.kind === "Opaque")
651
640
  return encodeOpaque(operator.name, expression.args, env, mode);
652
641
  if (operator.kind === "Lambda")
653
- return encode({ ...normalizeApply(operator, expression.args) }, env, mode);
642
+ return encode(normalizeApply(operator, expression.args), env, mode);
654
643
  throw new TlaUnsupportedError(`an application of ${operator.kind}`);
655
644
  }
656
645
  case "Sequent":
@@ -723,15 +712,14 @@ export const createEncoder = (session: EncodingSession) => {
723
712
  );
724
713
  case "Record":
725
714
  case "Rect": {
726
- const fields = expression.fields;
727
- const names = fields.map((field) => field.name);
728
- recordFields.set(`Record_${names.join("_")}`, names);
729
- recordFields.set(`RecordSet_${names.join("_")}`, names);
730
- const name = `${expression.kind === "Record" ? "Record" : "RecordSet"}_${names.join("_")}`;
715
+ const names = expression.fields.map((field) => field.name);
716
+ const suffix = names.join("_");
717
+ recordFields.set(`Record_${suffix}`, names);
718
+ recordFields.set(`RecordSet_${suffix}`, names);
731
719
  return idv(
732
720
  call(
733
- tla(name),
734
- fields.map((field) => encodeIdv(field.value, env, mode)),
721
+ tla(`${expression.kind === "Record" ? "Record" : "RecordSet"}_${suffix}`),
722
+ expression.fields.map((field) => encodeIdv(field.value, env, mode)),
735
723
  ),
736
724
  );
737
725
  }
@@ -34,16 +34,16 @@ const decompose = (left: Expr, right: Expr, from: Expr): Expr => {
34
34
  // the equalities of their fields, paired by name.
35
35
  export const simplifyRecordEqualities = (expression: Expr): Expr => {
36
36
  const inner = mapChildren(expression, simplifyRecordEqualities);
37
- const isRecordEquality =
38
- inner.kind === "Apply" &&
39
- inner.operator.kind === "Internal" &&
40
- inner.operator.builtin === "Eq" &&
41
- inner.args.length === 2 &&
42
- inner.args[0].kind === "Record" &&
43
- inner.args[1].kind === "Record";
44
- return isRecordEquality && inner.kind === "Apply"
45
- ? at(decompose(inner.args[0], inner.args[1], inner), inner)
46
- : inner;
37
+ if (
38
+ inner.kind !== "Apply" ||
39
+ inner.operator.kind !== "Internal" ||
40
+ inner.operator.builtin !== "Eq" ||
41
+ inner.args.length !== 2 ||
42
+ inner.args[0].kind !== "Record" ||
43
+ inner.args[1].kind !== "Record"
44
+ )
45
+ return inner;
46
+ return at(decompose(inner.args[0], inner.args[1], inner), inner);
47
47
  };
48
48
 
49
49
  // sort_recfields: a record's or a record set's fields in order. Like tlapm, it doesn't visit the
@@ -1,26 +1,29 @@
1
1
  // The tlapm backend: runs tlapm on a module and reads each obligation's result from its Toolbox
2
2
  // messages.
3
3
 
4
- import { existsSync } from "node:fs";
5
- import { delimiter, join } from "node:path";
6
4
  import { TlaUnsupportedError } from "../../errors";
7
5
 
6
+ // Loaded at runtime so browser bundles leave them out. prove loads this module only in Node and Bun.
7
+ const childProcess = process.getBuiltinModule("node:child_process");
8
+ const fs = process.getBuiltinModule("node:fs");
9
+ const os = process.getBuiltinModule("node:os");
10
+ const path = process.getBuiltinModule("node:path");
11
+
8
12
  export type TlapmResult =
9
13
  | { status: "proved"; prover: string }
10
14
  | { status: "trivial" }
11
15
  | { status: "failed"; reason: string };
12
16
 
13
- export interface TlapmOptions {
17
+ interface TlapmOptions {
14
18
  signal?: AbortSignal;
15
19
  onResult?: (id: number, result: TlapmResult) => void;
16
20
  }
17
21
 
18
- // Each tlapm on the PATH, first to last.
19
22
  export const getTlapmPaths = () =>
20
23
  (process.env.PATH ?? "")
21
- .split(delimiter)
22
- .map((directory) => join(directory, "tlapm"))
23
- .filter((path) => existsSync(path));
24
+ .split(path.delimiter)
25
+ .map((directory) => path.join(directory, "tlapm"))
26
+ .filter((tlapm) => fs.existsSync(tlapm));
24
27
 
25
28
  // tlapm's Toolbox protocol: each message is @!!BEGIN, then @!!name:value lines, then @!!END.
26
29
  const parseToolboxMessages = (text: string) =>
@@ -60,17 +63,14 @@ export const proveWithTlapm = async (
60
63
  const tlapm = getTlapmPaths()[0];
61
64
  if (tlapm === undefined)
62
65
  throw new TlaUnsupportedError("The tlapm backend needs tlapm on your PATH.");
63
- const childProcess = await import("node:child_process");
64
- const fs = await import("node:fs");
65
- const os = await import("node:os");
66
- const directory = fs.mkdtempSync(join(os.tmpdir(), "tla-ts-"));
66
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), "tla-ts-"));
67
67
  modules.forEach((source, moduleName) =>
68
- fs.writeFileSync(join(directory, `${moduleName}.tla`), source),
68
+ fs.writeFileSync(path.join(directory, `${moduleName}.tla`), source),
69
69
  );
70
70
  const results = new Map<number, TlapmResult>();
71
71
  const child = childProcess.spawn(
72
72
  tlapm,
73
- ["--toolbox", "0", "0", "--cache-dir", join(directory, ".tlacache"), `${name}.tla`],
73
+ ["--toolbox", "0", "0", "--cache-dir", path.join(directory, ".tlacache"), `${name}.tla`],
74
74
  { cwd: directory, stdio: ["ignore", "ignore", "pipe"] },
75
75
  );
76
76
  const kill = () => child.kill();
@@ -2,6 +2,11 @@
2
2
  // proves it.
3
3
  export type Verdict = "unsat" | "sat" | "unknown";
4
4
 
5
+ export interface Decision {
6
+ verdict: Verdict;
7
+ timeUsedMs: number;
8
+ }
9
+
5
10
  export interface DecideOptions {
6
11
  timeLimitMs: number;
7
12
  signal?: AbortSignal;
@@ -3,16 +3,10 @@
3
3
 
4
4
  import { TlapmBugError, TlaProverError, TlaUnsupportedError } from "../../errors";
5
5
  import { createContext, getBoundName, popNames, pushName } from "../../obligations/ctx";
6
- import {
7
- shiftExpr,
8
- type Bound,
9
- type Builtin,
10
- type Expr,
11
- type Hyp,
12
- type Sequent,
13
- } from "../../obligations/expression";
6
+ import type { Bound, Builtin, Expr, Hyp, Sequent } from "../../obligations/expression";
14
7
  import { format, formatDelimited, renderDoc, text, type Doc } from "../../obligations/format";
15
8
  import { pickle } from "../../obligations/pickle";
9
+ import { getUnprintableError, printFact, splitFirstBound } from "../first-order";
16
10
 
17
11
  const SPACE = format("@ ");
18
12
 
@@ -76,21 +70,6 @@ const OPERATORS: Partial<Record<Builtin, [string, number]>> = {
76
70
  ToString: ["TLA.ToString", 1],
77
71
  };
78
72
 
79
- // The temporal operators Zenon has no counterpart for, by the name tlapm reports.
80
- const TEMPORAL_OPERATORS: Partial<Record<Builtin, [string, number]>> = {
81
- Leadsto: ["Leadsto", 2],
82
- ENABLED: ["ENABLED", 1],
83
- Cdot: ["\\cdot", 2],
84
- Actplus: ["-+->", 2],
85
- BoxTrue: ["[]", 1],
86
- BoxFalse: ["[]", 1],
87
- Diamond: ["<>", 1],
88
- };
89
-
90
- const unsupported = (message: string): never => {
91
- throw new TlaUnsupportedError(message);
92
- };
93
-
94
73
  const getSuccessors = (integer: string) => {
95
74
  const count = Number.parseInt(integer, 10);
96
75
  return `${"(TLA.fapply TLA.Succ ".repeat(count)}0${")".repeat(count)}`;
@@ -108,9 +87,9 @@ export const encodeZenon = (id: number, sequent: Sequent) => {
108
87
  const nonatomic = (name: string, args: Expr[]) => format("(%s %a)", name, delimited(args));
109
88
 
110
89
  // A binder's name binds in the body, and what comes before prints outside it.
111
- const printBinder = (name: string, before: Doc, body: Expr, after: string) => {
90
+ const printBinder = (name: string, before: Doc, body: Expr) => {
112
91
  const bound = adjoin(name);
113
- const doc = format("%a((%s) %a)%s", before, bound, printExpr(body), after);
92
+ const doc = format("%a((%s) %a))", before, bound, printExpr(body));
114
93
  popNames(context, 1);
115
94
  return doc;
116
95
  };
@@ -120,7 +99,6 @@ export const encodeZenon = (id: number, sequent: Sequent) => {
120
99
  if (atom !== undefined && args.length === 0) return text(atom);
121
100
  const operator = OPERATORS[builtin];
122
101
  if (operator && operator[1] === args.length) return nonatomic(operator[0], args);
123
- const [first, second] = args;
124
102
  if (args.length === 2) {
125
103
  switch (builtin) {
126
104
  case "Neq":
@@ -129,28 +107,22 @@ export const encodeZenon = (id: number, sequent: Sequent) => {
129
107
  return format("(-. %a)", nonatomic("TLA.in", args));
130
108
  case "Minus":
131
109
  return nonatomic("arith.add", [
132
- first,
110
+ args[0],
133
111
  {
134
112
  kind: "Apply",
135
- operator: { kind: "Internal", builtin: "Uminus", location: second.location },
136
- args: [second],
137
- location: second.location,
113
+ operator: { kind: "Internal", builtin: "Uminus", location: args[1].location },
114
+ args: [args[1]],
115
+ location: args[1].location,
138
116
  },
139
117
  ]);
140
118
  case "Gteq":
141
- return nonatomic("arith.le", [second, first]);
119
+ return nonatomic("arith.le", args.toReversed());
142
120
  case "Gt":
143
- return nonatomic("arith.lt", [second, first]);
121
+ return nonatomic("arith.lt", args.toReversed());
144
122
  }
145
123
  }
146
- if (builtin === "Unprimable" && args.length === 1) return printExpr(first);
147
- const isFrontend = builtin === "Prime" || builtin === "StrongPrime" || builtin === "UNCHANGED";
148
- if (isFrontend && args.length === 1) throw new TlapmBugError();
149
- const temporal = TEMPORAL_OPERATORS[builtin];
150
- if (temporal && temporal[1] === args.length) {
151
- throw new TlaProverError(`Unsupported operator \`${temporal[0]}\`.\n`);
152
- }
153
- throw new TlaProverError("Backend.Zenon.fmt_apply");
124
+ if (builtin === "Unprimable" && args.length === 1) return printExpr(args[0]);
125
+ throw getUnprintableError(builtin, args.length, "Backend.Zenon.fmt_apply");
154
126
  };
155
127
 
156
128
  const printApply = (operator: Expr, args: Expr[]): Doc => {
@@ -177,63 +149,39 @@ export const encodeZenon = (id: number, sequent: Sequent) => {
177
149
  }
178
150
  };
179
151
 
180
- // The first bound binds around a quantifier over the others, which move under it.
181
152
  const printQuant = (quantifier: "Forall" | "Exists", bounds: Bound[], body: Expr): Doc => {
182
- const [bound, ...rest] = bounds;
183
- if (!bound) return printExpr(body);
184
- const undittoed =
185
- rest[0]?.domain.kind === "Ditto"
186
- ? [{ ...rest[0], domain: bound.domain }, ...rest.slice(1)]
187
- : rest;
188
- const inner: Expr =
189
- undittoed.length === 0
190
- ? body
191
- : {
192
- kind: "Quant",
193
- quantifier,
194
- bounds: undittoed.map((other) =>
195
- other.domain.kind === "Domain"
196
- ? {
197
- ...other,
198
- domain: { kind: "Domain", expression: shiftExpr(1, other.domain.expression) },
199
- }
200
- : other,
201
- ),
202
- body,
203
- location: body.location,
204
- };
153
+ if (bounds.length === 0) return printExpr(body);
154
+ const split = splitFirstBound(quantifier, bounds, body);
205
155
  const isForall = quantifier === "Forall";
206
- if (bound.domain.kind === "NoDomain") {
207
- return printBinder(bound.name, text(isForall ? "(A. " : "(E. "), inner, ")");
208
- }
209
- if (bound.domain.kind !== "Domain") throw new TlapmBugError();
210
- const domain = printExpr(bound.domain.expression);
156
+ if (split.first.domain.kind === "NoDomain")
157
+ return printBinder(split.first.name, text(isForall ? "(A. " : "(E. "), split.inner);
158
+ if (split.first.domain.kind !== "Domain") throw new TlapmBugError();
159
+ const domain = printExpr(split.first.domain.expression);
211
160
  return printBinder(
212
- bound.name,
161
+ split.first.name,
213
162
  format("(%s %a ", isForall ? "TLA.bAll" : "TLA.bEx", domain),
214
- inner,
215
- ")",
163
+ split.inner,
216
164
  );
217
165
  };
218
166
 
219
167
  // SetOf and Fcn take one bound, whose domain prints outside it.
220
168
  const printOneBound = (name: string, bounds: Bound[], body: Expr, what: string) => {
221
- if (bounds.length !== 1) return unsupported(`${what} (multiple declared constants)`);
169
+ if (bounds.length !== 1) throw new TlaUnsupportedError(`${what} (multiple declared constants)`);
222
170
  const bound = bounds[0];
223
171
  if (bound.domain.kind !== "Domain") throw new TlapmBugError();
224
172
  return printBinder(
225
173
  bound.name,
226
174
  format("(%s %a ", name, printExpr(bound.domain.expression)),
227
175
  body,
228
- ")",
229
176
  );
230
177
  };
231
178
 
232
179
  // A sequent inside an expression, as an implication under quantifiers.
233
180
  const printNestedSequent = (sequent: Sequent): Doc => {
234
- const [hyp, ...rest] = sequent.context;
235
- if (!hyp) return printExpr(sequent.active);
236
- const printRest = () => printNestedSequent({ context: rest, active: sequent.active });
181
+ if (sequent.context.length === 0) return printExpr(sequent.active);
182
+ const hyp = sequent.context[0];
183
+ const printRest = () =>
184
+ printNestedSequent({ context: sequent.context.slice(1), active: sequent.active });
237
185
  if (hyp.kind === "Fact") {
238
186
  const fact = hyp.visibility === "Visible" ? printExpr(hyp.expression) : undefined;
239
187
  bump();
@@ -281,9 +229,8 @@ export const encodeZenon = (id: number, sequent: Sequent) => {
281
229
  case "List":
282
230
  if (expression.bullet === "Refs" && expression.items.length === 0)
283
231
  throw new TlapmBugError();
284
- if (expression.bullet === "Refs" && expression.items.length === 1) {
232
+ if (expression.bullet === "Refs" && expression.items.length === 1)
285
233
  return printExpr(expression.items[0]);
286
- }
287
234
  return format(
288
235
  "(%s %a)",
289
236
  expression.bullet === "Or" ? "\\/" : "/\\",
@@ -292,22 +239,20 @@ export const encodeZenon = (id: number, sequent: Sequent) => {
292
239
  case "Quant":
293
240
  return printQuant(expression.quantifier, expression.bounds, expression.body);
294
241
  case "Tquant":
295
- return unsupported("\\AA or \\EE");
242
+ throw new TlaUnsupportedError("\\AA or \\EE");
296
243
  case "Choose":
297
244
  return expression.domain
298
245
  ? printBinder(
299
246
  expression.name,
300
247
  format("(TLA.bChoice %a ", printExpr(expression.domain)),
301
248
  expression.body,
302
- ")",
303
249
  )
304
- : printBinder(expression.name, text("(t. "), expression.body, ")");
250
+ : printBinder(expression.name, text("(t. "), expression.body);
305
251
  case "SetSt":
306
252
  return printBinder(
307
253
  expression.name,
308
254
  format("(TLA.subsetOf %a ", printExpr(expression.domain)),
309
255
  expression.body,
310
- ")",
311
256
  );
312
257
  case "SetOf":
313
258
  return printOneBound("TLA.setOfAll", expression.bounds, expression.element, "Setof");
@@ -342,7 +287,7 @@ export const encodeZenon = (id: number, sequent: Sequent) => {
342
287
  case "Except": {
343
288
  const spec = expression.specs[0];
344
289
  if (expression.specs.length !== 1 || spec.trail.length !== 1)
345
- return unsupported("complex EXCEPT");
290
+ throw new TlaUnsupportedError("complex EXCEPT");
346
291
  const point = spec.trail[0];
347
292
  const argument =
348
293
  point.kind === "Dot" ? text(`"${point.field}"`) : printExpr(point.expression);
@@ -368,7 +313,7 @@ export const encodeZenon = (id: number, sequent: Sequent) => {
368
313
  case "Sub":
369
314
  case "Tsub":
370
315
  case "Fair":
371
- return unsupported(expression.kind);
316
+ throw new TlaUnsupportedError(expression.kind);
372
317
  case "Case": {
373
318
  const arms = formatDelimited(
374
319
  expression.arms,
@@ -382,7 +327,7 @@ export const encodeZenon = (id: number, sequent: Sequent) => {
382
327
  case "String":
383
328
  return format('"%s"', expression.value);
384
329
  case "Num":
385
- if (expression.fraction !== "") return unsupported("Real number constants");
330
+ if (expression.fraction !== "") throw new TlaUnsupportedError("Real number constants");
386
331
  return text(getSuccessors(expression.integer));
387
332
  case "Bang":
388
333
  case "Let":
@@ -391,18 +336,6 @@ export const encodeZenon = (id: number, sequent: Sequent) => {
391
336
  }
392
337
  };
393
338
 
394
- // tlapm prints a fact to a formatter that drops its output first, to omit an unsupported one.
395
- const getFactDoc = (expression: Expr) => {
396
- const depth = context.stack.length;
397
- try {
398
- return printExpr(expression);
399
- } catch (error) {
400
- if (!(error instanceof TlaUnsupportedError)) throw error;
401
- popNames(context, context.stack.length - depth);
402
- return error;
403
- }
404
- };
405
-
406
339
  const printHyp = (hyp: Hyp): Doc => {
407
340
  switch (hyp.kind) {
408
341
  case "Fresh": {
@@ -422,11 +355,13 @@ export const encodeZenon = (id: number, sequent: Sequent) => {
422
355
  }
423
356
  case "Fact": {
424
357
  const count = String(context.stack.length);
425
- const fact = hyp.visibility === "Visible" ? getFactDoc(hyp.expression) : undefined;
358
+ const fact =
359
+ hyp.visibility === "Visible"
360
+ ? printFact(context, () => printExpr(hyp.expression))
361
+ : undefined;
426
362
  bump();
427
- if (fact instanceof TlaUnsupportedError) {
363
+ if (fact instanceof TlaUnsupportedError)
428
364
  return format("; omitted temporal assumption : %s @.", fact.message);
429
- }
430
365
  return fact ? format('$hyp "v\'%s" %a@\n', count, fact) : [];
431
366
  }
432
367
  }