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
@@ -3,14 +3,9 @@
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 Sequent,
12
- } from "../../obligations/expression";
6
+ import type { Bound, Builtin, Expr, Sequent } from "../../obligations/expression";
13
7
  import { pickle } from "../../obligations/pickle";
8
+ import { getUnprintableError, printFact, splitFirstBound } from "../first-order";
14
9
 
15
10
  const cook = (name: string) => `is${pickle(name)}`;
16
11
 
@@ -85,17 +80,6 @@ const NONFIX: Partial<Record<Builtin, [string, number]>> = {
85
80
  ToString: ["ToString", 1],
86
81
  };
87
82
 
88
- // The temporal operators Isabelle/TLA+ has no counterpart for, by the name tlapm reports.
89
- const TEMPORAL: Partial<Record<Builtin, [string, number]>> = {
90
- Leadsto: ["Leadsto", 2],
91
- ENABLED: ["ENABLED", 1],
92
- Cdot: ["\\cdot", 2],
93
- Actplus: ["-+->", 2],
94
- BoxTrue: ["[]", 1],
95
- BoxFalse: ["[]", 1],
96
- Diamond: ["<>", 1],
97
- };
98
-
99
83
  // thy_header's tdoms_table: the operators the theory declares, with their arities.
100
84
  const DECLARED: [string, number][] = [
101
85
  ["Real", 0],
@@ -111,35 +95,30 @@ const DECLARED: [string, number][] = [
111
95
  const HEADER = [
112
96
  "consts",
113
97
  ...DECLARED.map(
114
- ([name, arity]) =>
115
- ` "${cook(name)}" :: ${arity === 0 ? "c" : `"[${Array(arity).fill("c").join(",")}] => c"`}`,
98
+ (declared) =>
99
+ ` "${cook(declared[0])}" :: ${declared[1] === 0 ? "c" : `"[${Array(declared[1]).fill("c").join(",")}] => c"`}`,
116
100
  ),
117
101
  "",
118
102
  ].join("\n");
119
103
 
120
- // tlapm raises Unsupported for what Isabelle/TLA+ can't express, which omits a fact and fails the
121
- // obligation anywhere else.
122
- const unsupported = (message: string): never => {
123
- throw new TlaUnsupportedError(message);
124
- };
125
-
126
104
  const getSuccessors = (integer: string) => {
127
105
  const count = Number.parseInt(integer, 10);
128
106
  return `${"succ[".repeat(count)}0${"]".repeat(count)}`;
129
107
  };
130
108
 
131
- // thy_temp: the theory tlapm writes for Isabelle to prove obligation id, after Backend.Prep has
132
- // shipped it, with the tactic of the method that selects Isabelle.
133
- export const encodeIsabelle = (
134
- id: number,
135
- sequent: Sequent,
136
- tactic: string,
137
- theoryName: string,
138
- ): string => {
109
+ // thy_header.
110
+ const getTheoryHeader = (name: string, isVerbose: boolean) => [
111
+ "(* automatically generated -- do not edit manually *)",
112
+ `theory ${name} imports Constant Zenon begin`,
113
+ ...(isVerbose ? ['ML_command \\<open> writeln ("*** TLAPS PARSED\\n"); \\<close>'] : []),
114
+ HEADER,
115
+ ];
116
+
117
+ // pp_print_expr on an obligation after Backend.Prep has shipped it.
118
+ const printLemma = (sequent: Sequent) => {
139
119
  const context = createContext();
140
120
  const adjoin = (name: string) => pushName(context, pickle(name));
141
121
  const bump = () => pushName(context, "");
142
- const state = { isAssumed: false };
143
122
 
144
123
  // A binder's name binds in what prints inside it.
145
124
  const withBound = (name: string, print: (bound: string) => string) => {
@@ -165,13 +144,8 @@ export const encodeIsabelle = (
165
144
  if (operator && operator[1] === args.length) return nonfix(operator[0], args);
166
145
  if (builtin === "Unprimable" && args.length === 1) return printExpr(args[0]);
167
146
  // tlapm prints an irregular expression as the hash of its TLA+ text, but never makes one.
168
- if (builtin === "Irregular" && args.length === 1) return unsupported("Irregular");
169
- const isFrontend = builtin === "Prime" || builtin === "StrongPrime" || builtin === "UNCHANGED";
170
- if (isFrontend && args.length === 1) throw new TlapmBugError();
171
- const temporal = TEMPORAL[builtin];
172
- if (temporal && temporal[1] === args.length)
173
- throw new TlaProverError(`Unsupported operator \`${temporal[0]}\`.\n`);
174
- throw new TlaProverError("Backend.Isabelle.pp_apply");
147
+ if (builtin === "Irregular" && args.length === 1) throw new TlaUnsupportedError("Irregular");
148
+ throw getUnprintableError(builtin, args.length, "Backend.Isabelle.pp_apply");
175
149
  };
176
150
 
177
151
  const printApply = (operator: Expr, args: Expr[]): string => {
@@ -199,47 +173,26 @@ export const encodeIsabelle = (
199
173
  }
200
174
  };
201
175
 
202
- // The first bound binds around a quantifier over the others, which move under it.
203
176
  const printQuant = (quantifier: "Forall" | "Exists", bounds: Bound[], body: Expr): string => {
204
- const [bound, ...rest] = bounds;
205
- if (!bound) return formatExpr(body);
206
- const undittoed =
207
- rest[0]?.domain.kind === "Ditto"
208
- ? [{ ...rest[0], domain: bound.domain }, ...rest.slice(1)]
209
- : rest;
210
- const inner: Expr =
211
- undittoed.length === 0
212
- ? body
213
- : {
214
- kind: "Quant",
215
- quantifier,
216
- bounds: undittoed.map((other) =>
217
- other.domain.kind === "Domain"
218
- ? {
219
- ...other,
220
- domain: { kind: "Domain", expression: shiftExpr(1, other.domain.expression) },
221
- }
222
- : other,
223
- ),
224
- body,
225
- location: body.location,
226
- };
177
+ if (bounds.length === 0) return formatExpr(body);
178
+ const split = splitFirstBound(quantifier, bounds, body);
227
179
  const symbol = quantifier === "Forall" ? "\\<forall>" : "\\<exists>";
228
- if (bound.domain.kind === "NoDomain")
229
- return withBound(bound.name, (name) => `${symbol}${name} : ${printExpr(inner)}`);
230
- if (bound.domain.kind !== "Domain") throw new TlapmBugError();
231
- const domain = printExpr(bound.domain.expression);
180
+ if (split.first.domain.kind === "NoDomain")
181
+ return withBound(split.first.name, (name) => `${symbol}${name} : ${printExpr(split.inner)}`);
182
+ if (split.first.domain.kind !== "Domain") throw new TlapmBugError();
183
+ const domain = printExpr(split.first.domain.expression);
232
184
  return withBound(
233
- bound.name,
234
- (name) => `${symbol} ${name} \\<in> ${domain} : ${printExpr(inner)}`,
185
+ split.first.name,
186
+ (name) => `${symbol} ${name} \\<in> ${domain} : ${printExpr(split.inner)}`,
235
187
  );
236
188
  };
237
189
 
238
190
  // pp_print_sequent_inner: a sequent inside an expression, as a meta-level implication.
239
191
  const printNestedSequent = (sequent: Sequent): string => {
240
- const [hyp, ...rest] = sequent.context;
241
- if (!hyp) return printExpr(sequent.active);
242
- const printRest = () => printNestedSequent({ context: rest, active: sequent.active });
192
+ if (sequent.context.length === 0) return printExpr(sequent.active);
193
+ const hyp = sequent.context[0];
194
+ const printRest = () =>
195
+ printNestedSequent({ context: sequent.context.slice(1), active: sequent.active });
243
196
  switch (hyp.kind) {
244
197
  case "Flex":
245
198
  return withBound(hyp.name, (name) => `(\\<And> ${name} ${name}'.${printRest()})`);
@@ -263,7 +216,7 @@ export const encodeIsabelle = (
263
216
  return doc;
264
217
  }
265
218
  case "Defn":
266
- return unsupported("Inner definition");
219
+ throw new TlaUnsupportedError("Inner definition");
267
220
  }
268
221
  };
269
222
 
@@ -284,7 +237,7 @@ export const encodeIsabelle = (
284
237
  case "Parens":
285
238
  return formatExpr(expression.expression);
286
239
  case "Let":
287
- return unsupported("LET");
240
+ throw new TlaUnsupportedError("LET");
288
241
  case "List":
289
242
  if (expression.bullet === "Refs" && expression.items.length === 0) return "TRUE";
290
243
  if (expression.bullet === "Refs" && expression.items.length === 1)
@@ -295,50 +248,49 @@ export const encodeIsabelle = (
295
248
  case "Quant":
296
249
  return printQuant(expression.quantifier, expression.bounds, expression.body);
297
250
  case "Tquant":
298
- return unsupported(expression.quantifier === "Forall" ? "\\\\AA" : "\\\\EE");
251
+ throw new TlaUnsupportedError(expression.quantifier === "Forall" ? "\\\\AA" : "\\\\EE");
299
252
  case "Choose": {
300
- const body = expression.body;
301
253
  if (!expression.domain)
302
- return withBound(expression.name, (name) => `Choice(%${name}. ${printExpr(body)})`);
254
+ return withBound(
255
+ expression.name,
256
+ (name) => `Choice(%${name}. ${printExpr(expression.body)})`,
257
+ );
303
258
  const domain = printExpr(expression.domain);
304
259
  return withBound(
305
260
  expression.name,
306
- (name) => `bChoice(${domain}, %${name}. ${printExpr(body)})`,
261
+ (name) => `bChoice(${domain}, %${name}. ${printExpr(expression.body)})`,
307
262
  );
308
263
  }
309
264
  case "SetSt": {
310
- const body = expression.body;
311
265
  const domain = printExpr(expression.domain);
312
266
  return withBound(
313
267
  expression.name,
314
- (name) => `subsetOf(${domain}, %${name}. ${printExpr(body)})`,
268
+ (name) => `subsetOf(${domain}, %${name}. ${printExpr(expression.body)})`,
315
269
  );
316
270
  }
317
271
  case "SetOf": {
318
- const element = expression.element;
319
- const [bound] = expression.bounds;
320
- if (!bound) throw new TlapmBugError();
272
+ if (expression.bounds.length === 0) throw new TlapmBugError();
273
+ const bound = expression.bounds[0];
321
274
  if (expression.bounds.length !== 1 || bound.domain.kind !== "Domain")
322
- return unsupported("SetOf (multiple declared constants)");
275
+ throw new TlaUnsupportedError("SetOf (multiple declared constants)");
323
276
  const domain = printExpr(bound.domain.expression);
324
277
  return withBound(
325
278
  bound.name,
326
- (name) => `setOfAll(${domain}, %${name}. ${printExpr(element)})`,
279
+ (name) => `setOfAll(${domain}, %${name}. ${printExpr(expression.element)})`,
327
280
  );
328
281
  }
329
282
  case "SetEnum":
330
283
  return `{${delimited(expression.elements)}}`;
331
284
  case "Fcn": {
332
- const body = expression.body;
333
- const [bound] = expression.bounds;
334
- if (!bound || expression.bounds.length !== 1)
335
- return unsupported("function (multiple declared constants)");
285
+ const bound = expression.bounds[0];
286
+ if (expression.bounds.length !== 1)
287
+ throw new TlaUnsupportedError("function (multiple declared constants)");
336
288
  if (bound.domain.kind === "Ditto") throw new TlapmBugError();
337
289
  const domain =
338
290
  bound.domain.kind === "Domain" ? printExpr(bound.domain.expression) : undefined;
339
291
  return withBound(bound.name, (name) => {
340
292
  const printed = domain === undefined ? name : ` ${name} \\<in> ${domain} `;
341
- return `[${printed} \\<mapsto> ${printExpr(body)}]`;
293
+ return `[${printed} \\<mapsto> ${printExpr(expression.body)}]`;
342
294
  });
343
295
  }
344
296
  case "FcnApp": {
@@ -390,28 +342,16 @@ export const encodeIsabelle = (
390
342
  case "String":
391
343
  return `''${expression.value}''`;
392
344
  case "Num":
393
- if (expression.fraction !== "") return unsupported("real constants");
345
+ if (expression.fraction !== "") throw new TlaUnsupportedError("real constants");
394
346
  return `(${getSuccessors(expression.integer)})`;
395
347
  case "At":
396
348
  throw new TlapmBugError();
397
349
  }
398
350
  };
399
351
 
400
- // tlapm prints a fact to a formatter that drops its output first, to omit an unsupported one.
401
- const getFact = (expression: Expr) => {
402
- const depth = context.stack.length;
403
- try {
404
- return printExpr(expression);
405
- } catch (error) {
406
- if (!(error instanceof TlaUnsupportedError)) throw error;
407
- popNames(context, context.stack.length - depth);
408
- return error;
409
- }
410
- };
411
-
412
- // pp_print_sequent_outer: the obligation's sequent as the fixes, assumes and shows of a lemma. A
413
- // pragma's definition ends it, without the goal.
414
- const printLemma = (sequent: Sequent) => {
352
+ // pp_print_sequent_outer: the obligation's sequent as the lines of a lemma's fixes, assumes and
353
+ // shows. A pragma's definition ends it with an empty line in place of the goal.
354
+ const printSequent = (sequent: Sequent) => {
415
355
  const lines: string[] = [];
416
356
  for (const hyp of sequent.context) {
417
357
  switch (hyp.kind) {
@@ -426,52 +366,81 @@ export const encodeIsabelle = (
426
366
  const name = adjoin(hyp.name);
427
367
  lines.push(`fixes ${name}`);
428
368
  if (domain === undefined) break;
429
- state.isAssumed = true;
430
369
  lines.push(`assumes ${name}_in : "(${name} \\<in> ${domain})"`);
431
370
  break;
432
371
  }
433
372
  case "Fact": {
434
373
  const count = context.stack.length;
435
- const fact = hyp.visibility === "Visible" ? getFact(hyp.expression) : undefined;
374
+ const fact =
375
+ hyp.visibility === "Visible"
376
+ ? printFact(context, () => printExpr(hyp.expression))
377
+ : undefined;
436
378
  bump();
437
379
  if (fact instanceof TlaUnsupportedError) {
438
380
  lines.push(`(* omitted temporal assumption : ${fact.message} *)`);
439
381
  break;
440
382
  }
441
383
  if (fact === undefined) break;
442
- state.isAssumed = true;
443
384
  lines.push(`assumes v'${count}: "${fact}"`);
444
385
  break;
445
386
  }
446
387
  case "Defn":
447
- if (hyp.definition.kind === "Bpragma") return lines.map((line) => `${line}\n`).join("");
388
+ if (hyp.definition.kind === "Bpragma") return [...lines, ""];
448
389
  lines.push(`(* usable definition ${hyp.definition.name} suppressed *)`);
449
390
  adjoin(hyp.definition.name);
450
391
  break;
451
392
  }
452
393
  }
453
- return [...lines, `shows "${printExpr(sequent.active)}"`].join("\n");
394
+ return [...lines, `shows "${printExpr(sequent.active)}"`];
454
395
  };
455
396
 
456
- const lemma = (() => {
457
- try {
458
- return printLemma(sequent);
459
- } catch (error) {
460
- if (!(error instanceof TlaUnsupportedError)) throw error;
461
- throw new TlaProverError(`isabelle : unsupported operator ${error.message}`);
462
- }
463
- })();
397
+ try {
398
+ const lines = printSequent(sequent);
399
+ return {
400
+ text: lines.join("\n"),
401
+ isAssumed: lines.some((line) => line.startsWith("assumes ")),
402
+ };
403
+ } catch (error) {
404
+ if (!(error instanceof TlaUnsupportedError)) throw error;
405
+ throw new TlaProverError(`isabelle : unsupported operator ${error.message}`);
406
+ }
407
+ };
408
+
409
+ // thy_temp: the theory tlapm writes for Isabelle to prove obligation id.
410
+ export const encodeIsabelle = (id: number, sequent: Sequent, tactic: string): string => {
411
+ const lemma = printLemma(sequent);
464
412
  return [
465
- "(* automatically generated -- do not edit manually *)",
466
- `theory ${theoryName} imports Constant Zenon begin`,
467
- HEADER,
413
+ ...getTheoryHeader(`tlapm_${id}`, false),
468
414
  `lemma ob'${id}:`,
469
- `${lemma}(is "PROP ?ob'${id}")`,
415
+ `${lemma.text}(is "PROP ?ob'${id}")`,
470
416
  "proof -",
471
417
  `show "PROP ?ob'${id}"`,
472
- `${state.isAssumed ? "using assms " : ""}by ${tactic}`,
418
+ `${lemma.isAssumed ? "using assms " : ""}by ${tactic}`,
473
419
  "qed",
474
420
  "end",
475
421
  "",
476
422
  ].join("\n");
477
423
  };
424
+
425
+ interface IsabelleProof {
426
+ id: number;
427
+ sequent: Sequent;
428
+ tactic: string;
429
+ }
430
+
431
+ // Isabelle.thy_init, thy_write and thy_close.
432
+ export const encodeIsabelleTheory = (name: string, proofs: IsabelleProof[]) =>
433
+ [
434
+ ...getTheoryHeader(name, true),
435
+ ...proofs.flatMap((proof) => [
436
+ `lemma ob'${proof.id}:`,
437
+ `${printLemma(proof.sequent).text}(is "PROP ?ob'${proof.id}")`,
438
+ "proof -",
439
+ `ML_command \\<open> writeln "*** TLAPS ENTER ${proof.id}"; \\<close>`,
440
+ `show "PROP ?ob'${proof.id}"`,
441
+ `using assms by ${proof.tactic}`,
442
+ `ML_command \\<open> writeln "*** TLAPS EXIT ${proof.id}"; \\<close> qed`,
443
+ ]),
444
+ "end",
445
+ "",
446
+ ].join("\n");
@@ -1,6 +1,6 @@
1
1
  // The parts of OCaml's standard library whose exact order steers what tlapm prints.
2
2
 
3
- export type OcamlValue = number | string | OcamlValue[];
3
+ type OcamlValue = number | string | OcamlValue[];
4
4
 
5
5
  // String.compare: byte by byte, on the UTF-8 bytes. Code units order the same way for the ASCII
6
6
  // names tlapm compares.
@@ -3,14 +3,18 @@
3
3
  // down to the variables (Symbol_commute), and what remains modal becomes opaque (Coalesce).
4
4
 
5
5
  import { TlapmBugError } from "../../errors";
6
- import { rewriteUnchanged } from "../../obligations/action";
6
+ import { rewriteUnchanged } from "../../obligations/temporal";
7
7
  import {
8
8
  adjoin,
9
+ adjoinAll,
9
10
  applyBuiltin,
10
11
  at,
11
12
  createContextMap,
12
13
  getBoundedFresh,
14
+ getBoundFresh,
13
15
  getFresh,
16
+ getLocalDefn,
17
+ getParamFresh,
14
18
  getScopeAt,
15
19
  getScopeHyps,
16
20
  mapAccumulate,
@@ -29,7 +33,7 @@ import { getLevelInfo } from "../../obligations/levels";
29
33
  import { printExpression } from "../../obligations/printer";
30
34
  import { getMd5 } from "./md5";
31
35
 
32
- type Map = (scope: Scope | undefined, expression: Expr) => Expr;
36
+ type Rewrite = (scope: Scope | undefined, expression: Expr) => Expr;
33
37
 
34
38
  const getHyp = (scope: Scope | undefined, index: number) => {
35
39
  const hyp = getScopeAt(scope, index - 1)?.hyp;
@@ -47,7 +51,7 @@ const isBuiltin = (expression: Expr, builtins: Builtin[]) =>
47
51
 
48
52
  // Visit.map over a sequent: each hypothesis maps in the scope before it, hidden ones too if hyps
49
53
  // is "all". The context maps by the obligation's own hypotheses, from which it derives.
50
- const createSequentMap = (map: Map, hyps: "visible" | "all") => {
54
+ const createSequentMap = (map: Rewrite, hyps: "visible" | "all") => {
51
55
  const mapContext = createContextMap<Scope | undefined>(undefined, (scope, hyp) => {
52
56
  const mapped = mapHyp(hyp, (inner) => map(scope, inner), hyps);
53
57
  return [adjoin(scope, mapped), mapped];
@@ -59,7 +63,7 @@ const createSequentMap = (map: Map, hyps: "visible" | "all") => {
59
63
  };
60
64
 
61
65
  // Expr.Tla_norm.expand_action, then expand_unchanged.
62
- const expandAction: Map = (scope, expression) => {
66
+ const expandAction: Rewrite = (scope, expression) => {
63
67
  if (expression.kind === "Sub" || expression.kind === "Tsub") {
64
68
  const action = expandAction(scope, expression.action);
65
69
  const subscript = expandAction(scope, expression.subscript);
@@ -74,7 +78,7 @@ const expandAction: Map = (scope, expression) => {
74
78
  return mapScoped(scope, expression, expandAction, adjoin, "all");
75
79
  };
76
80
 
77
- const expandUnchanged: Map = (scope, expression) =>
81
+ const expandUnchanged: Rewrite = (scope, expression) =>
78
82
  expression.kind === "Apply" &&
79
83
  isBuiltin(expression, ["UNCHANGED"]) &&
80
84
  expression.args.length === 1
@@ -85,7 +89,7 @@ const getModal = (builtin: Builtin, expression: Expr) =>
85
89
  applyBuiltin(builtin, [expression], expression);
86
90
 
87
91
  // prime_commuter: a prime distributes down to the declarations that are not constant.
88
- const commutePrime: Map = (scope, expression) => {
92
+ const commutePrime: Rewrite = (scope, expression) => {
89
93
  if (expression.kind === "Ix") {
90
94
  const hyp = getHyp(scope, expression.index);
91
95
  if (hyp.kind === "Fresh" && hyp.level === "Constant") return expression;
@@ -125,10 +129,10 @@ const commutePrime: Map = (scope, expression) => {
125
129
 
126
130
  // box_commuter and dia_commuter: [] distributes over /\ and \A, and <> over \/ and \E, and both
127
131
  // vanish on a constant.
128
- const getModalCommuter = (builtin: "BoxTrue" | "Diamond"): Map => {
132
+ const getModalCommuter = (builtin: "BoxTrue" | "Diamond"): Rewrite => {
129
133
  const connective: Builtin = builtin === "BoxTrue" ? "Conj" : "Disj";
130
134
  const quantifier = builtin === "BoxTrue" ? "Forall" : "Exists";
131
- const commute: Map = (scope, expression) => {
135
+ const commute: Rewrite = (scope, expression) => {
132
136
  if (getLevel(scope, expression) === 0) return expression;
133
137
  const isDistributed =
134
138
  isBuiltin(expression, [connective]) ||
@@ -141,14 +145,14 @@ const getModalCommuter = (builtin: "BoxTrue" | "Diamond"): Map => {
141
145
  return commute;
142
146
  };
143
147
 
144
- const COMMUTERS: Partial<Record<Builtin, Map>> = {
148
+ const COMMUTERS: Partial<Record<Builtin, Rewrite>> = {
145
149
  Prime: commutePrime,
146
150
  BoxTrue: getModalCommuter("BoxTrue"),
147
151
  Diamond: getModalCommuter("Diamond"),
148
152
  };
149
153
 
150
154
  // symbol_commute: each prime, [] and <> commutes down its operand.
151
- const commuteSymbols: Map = (scope, expression) => {
155
+ const commuteSymbols: Rewrite = (scope, expression) => {
152
156
  if (expression.kind === "Apply" && expression.operator.kind === "Internal") {
153
157
  const commuter = COMMUTERS[expression.operator.builtin];
154
158
  if (commuter) {
@@ -256,23 +260,20 @@ const renameSequent = (scope: Scope | undefined, sequent: Sequent): Sequent => {
256
260
  return { context, active: rename(inner, sequent.active) };
257
261
  };
258
262
 
259
- const rename: Map = (scope, expression) => {
263
+ const rename: Rewrite = (scope, expression) => {
260
264
  switch (expression.kind) {
261
265
  case "Lambda": {
262
266
  const params = expression.params.map((param) => ({
263
267
  ...param,
264
268
  name: getRenamed("Unknown", param.name),
265
269
  }));
266
- const inner = params.reduce(
267
- (current, param) => adjoin(current, getFresh(param.name, "Unknown", param.shape)),
268
- scope,
269
- );
270
+ const inner = adjoinAll(scope, params.map(getParamFresh));
270
271
  return { ...expression, params, body: rename(inner, expression.body) };
271
272
  }
272
273
  case "Tquant": {
273
- const inner = expression.names.reduce(
274
- (current, name) => adjoin(current, { kind: "Flex", name: getRenamed("VARIABLE", name) }),
274
+ const inner = adjoinAll(
275
275
  scope,
276
+ expression.names.map((name) => ({ kind: "Flex", name: getRenamed("VARIABLE", name) })),
276
277
  );
277
278
  return { ...expression, body: rename(inner, expression.body) };
278
279
  }
@@ -299,10 +300,7 @@ const rename: Map = (scope, expression) => {
299
300
  ? { kind: "Domain" as const, expression: rename(scope, bound.domain.expression) }
300
301
  : bound.domain,
301
302
  }));
302
- const inner = bounds.reduce(
303
- (current, bound) => adjoin(current, getFresh(bound.name, bound.level)),
304
- scope,
305
- );
303
+ const inner = adjoinAll(scope, bounds.map(getBoundFresh));
306
304
  return expression.kind === "SetOf"
307
305
  ? { ...expression, bounds, element: rename(inner, expression.element) }
308
306
  : { ...expression, bounds, body: rename(inner, expression.body) };
@@ -313,14 +311,7 @@ const rename: Map = (scope, expression) => {
313
311
  expression.definitions,
314
312
  (current, definition) => {
315
313
  const renamed = renameDefn(current, definition);
316
- const hyp: Hyp = {
317
- kind: "Defn",
318
- definition: renamed,
319
- whereDefined: "User",
320
- visibility: "Visible",
321
- isLocal: true,
322
- };
323
- return [adjoin(current, hyp), renamed];
314
+ return [adjoin(current, getLocalDefn(renamed)), renamed];
324
315
  },
325
316
  );
326
317
  return { ...expression, definitions, body: rename(inner, expression.body) };
@@ -341,10 +332,7 @@ const getSubstitutiveArgs = (scope: Scope | undefined, definition: Defn): boolea
341
332
  if (cached) return cached;
342
333
  const body = definition.kind === "Operator" ? definition.body : undefined;
343
334
  if (body?.kind !== "Lambda") return [];
344
- const inner = body.params.reduce(
345
- (current, param) => adjoin(current, getFresh(param.name, "Unknown", param.shape)),
346
- scope,
347
- );
335
+ const inner = adjoinAll(scope, body.params.map(getParamFresh));
348
336
  const result = body.params.map((_param, index) =>
349
337
  isSubstitutive(inner, body.body, index + 1, true),
350
338
  );
@@ -352,6 +340,18 @@ const getSubstitutiveArgs = (scope: Scope | undefined, definition: Defn): boolea
352
340
  return result;
353
341
  };
354
342
 
343
+ const UNARY_MODALS: Builtin[] = [
344
+ "Prime",
345
+ "StrongPrime",
346
+ "BoxTrue",
347
+ "BoxFalse",
348
+ "Diamond",
349
+ "ENABLED",
350
+ "UNCHANGED",
351
+ ];
352
+
353
+ const BINARY_MODALS: Builtin[] = ["Leadsto", "Actplus", "Cdot"];
354
+
355
355
  // compute_substitutivity_array: whether the parameter at index occurs only where scope holds.
356
356
  const isSubstitutive = (
357
357
  scope: Scope | undefined,
@@ -362,19 +362,9 @@ const isSubstitutive = (
362
362
  if (expression.kind === "Ix") return isInScope || expression.index !== index;
363
363
  if (expression.kind === "Apply" && expression.operator.kind === "Internal") {
364
364
  const builtin = expression.operator.builtin;
365
- const isUnary = [
366
- "Prime",
367
- "StrongPrime",
368
- "BoxTrue",
369
- "BoxFalse",
370
- "Diamond",
371
- "ENABLED",
372
- "UNCHANGED",
373
- ];
374
- const isBinary = ["Leadsto", "Actplus", "Cdot"];
375
365
  if (
376
- (isUnary.includes(builtin) && expression.args.length === 1) ||
377
- (isBinary.includes(builtin) && expression.args.length === 2)
366
+ (UNARY_MODALS.includes(builtin) && expression.args.length === 1) ||
367
+ (BINARY_MODALS.includes(builtin) && expression.args.length === 2)
378
368
  ) {
379
369
  return expression.args.every((arg) => isSubstitutive(scope, arg, index, false));
380
370
  }
@@ -396,20 +386,18 @@ const isSubstitutive = (
396
386
  });
397
387
  }
398
388
  }
399
- let isSubstitutiveHere = true;
389
+ const found = { isSubstitutive: true };
400
390
  mapScoped(
401
391
  { scope, index },
402
392
  expression,
403
393
  (state, inner) => {
404
- if (isSubstitutiveHere && !isSubstitutive(state.scope, inner, state.index, isInScope)) {
405
- isSubstitutiveHere = false;
406
- }
394
+ found.isSubstitutive &&= isSubstitutive(state.scope, inner, state.index, isInScope);
407
395
  return inner;
408
396
  },
409
397
  (state, hyp) => ({ scope: adjoin(state.scope, hyp), index: state.index + 1 }),
410
398
  "all",
411
399
  );
412
- return isSubstitutiveHere;
400
+ return found.isSubstitutive;
413
401
  };
414
402
 
415
403
  // Coalesce.crypthash: h and the first five hexadecimal digits of the MD5 of the expression as
@@ -457,7 +445,7 @@ const MODAL_BUILTINS: Builtin[] = [
457
445
  // modal expression an opaque name. tlapm means to apply that name to the expression's free
458
446
  // variables, but compute_vars collects them into an instance variable and returns its own empty
459
447
  // set, so the name always stands alone.
460
- const coalesceModal: Map = (scope, expression) => {
448
+ const coalesceModal: Rewrite = (scope, expression) => {
461
449
  if (expression.kind !== "Apply") return mapScoped(scope, expression, coalesceModal, adjoin);
462
450
  const operator = expression.operator;
463
451
  const [arg] = expression.args;
@@ -8,20 +8,26 @@ import {
8
8
  type Sequent,
9
9
  } from "../../obligations/expression";
10
10
 
11
- const expandContext = createContextMap(shift(0), (current, hyp) => {
12
- if (
13
- hyp.kind === "Defn" &&
14
- (hyp.definition.kind === "Bpragma" ||
15
- (hyp.definition.kind === "Operator" && hyp.visibility === "Visible"))
16
- ) {
17
- return [consSubstitution(substituteExpr(current, hyp.definition.body), current), undefined];
18
- }
19
- return [bumpBy(1, current), substituteHyp(current, hyp)];
20
- });
11
+ const createExpander = (isPragmaExpanded: boolean) =>
12
+ createContextMap(shift(0), (current, hyp) => {
13
+ if (
14
+ hyp.kind === "Defn" &&
15
+ ((isPragmaExpanded && hyp.definition.kind === "Bpragma") ||
16
+ (hyp.definition.kind === "Operator" && hyp.visibility === "Visible"))
17
+ ) {
18
+ return [consSubstitution(substituteExpr(current, hyp.definition.body), current), undefined];
19
+ }
20
+ return [bumpBy(1, current), substituteHyp(current, hyp)];
21
+ });
22
+
23
+ const expandWithPragmas = createExpander(true);
24
+
25
+ const expandOperators = createExpander(false);
21
26
 
22
27
  // expand_defs: each visible operator definition and each pragma, whatever its visibility,
23
- // substitutes into the rest of the obligation and leaves the context.
24
- export const expandDefs = (sequent: Sequent): Sequent => {
25
- const expanded = expandContext(sequent.context);
28
+ // substitutes into the rest of the obligation and leaves the context. Toolbox.expand_defs leaves
29
+ // the pragmas.
30
+ export const expandDefs = (sequent: Sequent, isPragmaExpanded = true): Sequent => {
31
+ const expanded = (isPragmaExpanded ? expandWithPragmas : expandOperators)(sequent.context);
26
32
  return { context: expanded.context, active: substituteExpr(expanded.state, sequent.active) };
27
33
  };
@@ -44,7 +44,7 @@ const getVisitedExprs = (hyp: Hyp): Expr[] => {
44
44
  };
45
45
 
46
46
  // non_temporal: no temporal operator, but in hidden hypotheses.
47
- export const isNonTemporal = (expression: Expr): boolean => {
47
+ const isNonTemporal = (expression: Expr): boolean => {
48
48
  if (expression.kind === "Tsub" || expression.kind === "Fair") return false;
49
49
  if (
50
50
  expression.kind === "Apply" &&