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
package/dist/tlapm.cjs CHANGED
@@ -6,5 +6,5 @@
6
6
  * This source code is licensed under the MIT license found in the
7
7
  * LICENSE file in the root directory of this source tree.
8
8
  */
9
- const e=require("./worker.cjs");let t=require("node:path"),n=require("node:fs");const r=()=>(process.env.PATH??``).split(t.delimiter).map(e=>(0,t.join)(e,`tlapm`)).filter(e=>(0,n.existsSync)(e)),i=e=>e.split(`@!!BEGIN
10
- `).slice(1).flatMap(e=>{let t=e.indexOf(`@!!END`);if(t===-1)return[];let n=/* @__PURE__ */ new Map;return e.slice(0,t).split(/\n(?=@!!)/).forEach(e=>{let t=e.indexOf(`:`);n.set(e.slice(3,t),e.slice(t+1).replace(/\n$/,``))}),[n]}),a=e=>{let t=e.get(`status`);if(t===`proved`)return{status:t,prover:e.get(`prover`)??``};if(t===`trivial`)return{status:t};if(t===`failed`||t===`interrupted`)return{status:`failed`,reason:e.get(`reason`)||t}},o=async(n,o,s)=>{let c=r()[0];if(c===void 0)throw new e.k(`The tlapm backend needs tlapm on your PATH.`);let l=await import(`node:child_process`),u=await import(`node:fs`),d=await import(`node:os`),f=u.mkdtempSync((0,t.join)(d.tmpdir(),`tla-ts-`));o.forEach((e,n)=>u.writeFileSync((0,t.join)(f,`${n}.tla`),e));let p=/* @__PURE__ */ new Map,m=l.spawn(c,[`--toolbox`,`0`,`0`,`--cache-dir`,(0,t.join)(f,`.tlacache`),`${n}.tla`],{cwd:f,stdio:[`ignore`,`ignore`,`pipe`]}),h=()=>m.kill();s.signal?.addEventListener(`abort`,h);let g={text:``,parsed:0};return m.stderr.on(`data`,e=>{g.text+=e.toString(`utf8`);let t=i(g.text);t.slice(g.parsed).forEach(e=>{let t=a(e),n=Number(e.get(`id`));e.get(`type`)===`obligation`&&t&&(p.set(n,t),s.onResult?.(n,t))}),g.parsed=t.length}),await new Promise(e=>m.on(`close`,e)),s.signal?.removeEventListener(`abort`,h),u.rmSync(f,{recursive:!0,force:!0}),s.signal?.throwIfAborted(),p};exports.getTlapmPaths=r,exports.proveWithTlapm=o;
9
+ const e=require("./worker.cjs"),t=process.getBuiltinModule(`node:child_process`),n=process.getBuiltinModule(`node:fs`),r=process.getBuiltinModule(`node:os`),i=process.getBuiltinModule(`node:path`),a=()=>(process.env.PATH??``).split(i.delimiter).map(e=>i.join(e,`tlapm`)).filter(e=>n.existsSync(e)),o=e=>e.split(`@!!BEGIN
10
+ `).slice(1).flatMap(e=>{let t=e.indexOf(`@!!END`);if(t===-1)return[];let n=/* @__PURE__ */ new Map;return e.slice(0,t).split(/\n(?=@!!)/).forEach(e=>{let t=e.indexOf(`:`);n.set(e.slice(3,t),e.slice(t+1).replace(/\n$/,``))}),[n]}),s=e=>{let t=e.get(`status`);if(t===`proved`)return{status:t,prover:e.get(`prover`)??``};if(t===`trivial`)return{status:t};if(t===`failed`||t===`interrupted`)return{status:`failed`,reason:e.get(`reason`)||t}},c=async(c,l,u)=>{let d=a()[0];if(d===void 0)throw new e.k(`The tlapm backend needs tlapm on your PATH.`);let f=n.mkdtempSync(i.join(r.tmpdir(),`tla-ts-`));l.forEach((e,t)=>n.writeFileSync(i.join(f,`${t}.tla`),e));let p=/* @__PURE__ */ new Map,m=t.spawn(d,[`--toolbox`,`0`,`0`,`--cache-dir`,i.join(f,`.tlacache`),`${c}.tla`],{cwd:f,stdio:[`ignore`,`ignore`,`pipe`]}),h=()=>m.kill();u.signal?.addEventListener(`abort`,h);let g={text:``,parsed:0};return m.stderr.on(`data`,e=>{g.text+=e.toString(`utf8`);let t=o(g.text);t.slice(g.parsed).forEach(e=>{let t=s(e),n=Number(e.get(`id`));e.get(`type`)===`obligation`&&t&&(p.set(n,t),u.onResult?.(n,t))}),g.parsed=t.length}),await new Promise(e=>m.on(`close`,e)),u.signal?.removeEventListener(`abort`,h),n.rmSync(f,{recursive:!0,force:!0}),u.signal?.throwIfAborted(),p};exports.getTlapmPaths=a,exports.proveWithTlapm=c;
package/dist/tlapm.js CHANGED
@@ -6,5 +6,5 @@
6
6
  * This source code is licensed under the MIT license found in the
7
7
  * LICENSE file in the root directory of this source tree.
8
8
  */
9
- import{k as e}from"./worker.js";import{delimiter as t,join as n}from"node:path";import{existsSync as r}from"node:fs";const i=()=>(process.env.PATH??``).split(t).map(e=>n(e,`tlapm`)).filter(e=>r(e)),a=e=>e.split(`@!!BEGIN
10
- `).slice(1).flatMap(e=>{let t=e.indexOf(`@!!END`);if(t===-1)return[];let n=/* @__PURE__ */ new Map;return e.slice(0,t).split(/\n(?=@!!)/).forEach(e=>{let t=e.indexOf(`:`);n.set(e.slice(3,t),e.slice(t+1).replace(/\n$/,``))}),[n]}),o=e=>{let t=e.get(`status`);if(t===`proved`)return{status:t,prover:e.get(`prover`)??``};if(t===`trivial`)return{status:t};if(t===`failed`||t===`interrupted`)return{status:`failed`,reason:e.get(`reason`)||t}},s=async(t,r,s)=>{let c=i()[0];if(c===void 0)throw new e(`The tlapm backend needs tlapm on your PATH.`);let l=await import(`node:child_process`),u=await import(`node:fs`),d=await import(`node:os`),f=u.mkdtempSync(n(d.tmpdir(),`tla-ts-`));r.forEach((e,t)=>u.writeFileSync(n(f,`${t}.tla`),e));let p=/* @__PURE__ */ new Map,m=l.spawn(c,[`--toolbox`,`0`,`0`,`--cache-dir`,n(f,`.tlacache`),`${t}.tla`],{cwd:f,stdio:[`ignore`,`ignore`,`pipe`]}),h=()=>m.kill();s.signal?.addEventListener(`abort`,h);let g={text:``,parsed:0};return m.stderr.on(`data`,e=>{g.text+=e.toString(`utf8`);let t=a(g.text);t.slice(g.parsed).forEach(e=>{let t=o(e),n=Number(e.get(`id`));e.get(`type`)===`obligation`&&t&&(p.set(n,t),s.onResult?.(n,t))}),g.parsed=t.length}),await new Promise(e=>m.on(`close`,e)),s.signal?.removeEventListener(`abort`,h),u.rmSync(f,{recursive:!0,force:!0}),s.signal?.throwIfAborted(),p};export{i as getTlapmPaths,s as proveWithTlapm};
9
+ import{k as e}from"./worker.js";const t=process.getBuiltinModule(`node:child_process`),n=process.getBuiltinModule(`node:fs`),r=process.getBuiltinModule(`node:os`),i=process.getBuiltinModule(`node:path`),a=()=>(process.env.PATH??``).split(i.delimiter).map(e=>i.join(e,`tlapm`)).filter(e=>n.existsSync(e)),o=e=>e.split(`@!!BEGIN
10
+ `).slice(1).flatMap(e=>{let t=e.indexOf(`@!!END`);if(t===-1)return[];let n=/* @__PURE__ */ new Map;return e.slice(0,t).split(/\n(?=@!!)/).forEach(e=>{let t=e.indexOf(`:`);n.set(e.slice(3,t),e.slice(t+1).replace(/\n$/,``))}),[n]}),s=e=>{let t=e.get(`status`);if(t===`proved`)return{status:t,prover:e.get(`prover`)??``};if(t===`trivial`)return{status:t};if(t===`failed`||t===`interrupted`)return{status:`failed`,reason:e.get(`reason`)||t}},c=async(c,l,u)=>{let d=a()[0];if(d===void 0)throw new e(`The tlapm backend needs tlapm on your PATH.`);let f=n.mkdtempSync(i.join(r.tmpdir(),`tla-ts-`));l.forEach((e,t)=>n.writeFileSync(i.join(f,`${t}.tla`),e));let p=/* @__PURE__ */ new Map,m=t.spawn(d,[`--toolbox`,`0`,`0`,`--cache-dir`,i.join(f,`.tlacache`),`${c}.tla`],{cwd:f,stdio:[`ignore`,`ignore`,`pipe`]}),h=()=>m.kill();u.signal?.addEventListener(`abort`,h);let g={text:``,parsed:0};return m.stderr.on(`data`,e=>{g.text+=e.toString(`utf8`);let t=o(g.text);t.slice(g.parsed).forEach(e=>{let t=s(e),n=Number(e.get(`id`));e.get(`type`)===`obligation`&&t&&(p.set(n,t),u.onResult?.(n,t))}),g.parsed=t.length}),await new Promise(e=>m.on(`close`,e)),u.signal?.removeEventListener(`abort`,h),n.rmSync(f,{recursive:!0,force:!0}),u.signal?.throwIfAborted(),p};export{a as getTlapmPaths,c as proveWithTlapm};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tla-ts",
3
- "version": "0.0.4-dev.8fefa42",
3
+ "version": "0.0.4-dev.a11a30a",
4
4
  "description": "A TLA+ interpreter and model checker in TypeScript, 2× faster than TLC",
5
5
  "keywords": [
6
6
  "formal verification",
@@ -1,7 +1,6 @@
1
- // A port of tlapm's Expr.Action. Instantiation lambdifies each definition and theorem: each
2
- // ENABLED and \cdot takes a LAMBDA over the variables it binds, after expanding the definitions
3
- // in its scope that soundness needs expanded. The ExpandENABLED and ExpandCdot frontends then
4
- // replace each LAMBDA with an existential quantifier.
1
+ // A port of tlapm's Expr.Action. Lambdifying gives each ENABLED and \cdot a LAMBDA over the
2
+ // variables it binds, after expanding the definitions soundness needs expanded. The ExpandENABLED
3
+ // and ExpandCdot frontends then replace each LAMBDA with an existential quantifier.
5
4
 
6
5
  import { TlaProofError, TlapmBugError, TlaProverError } from "../errors";
7
6
  import type { Anonymizer } from "./anon";
@@ -13,25 +12,27 @@ import {
13
12
  bumpBy,
14
13
  getAtPrefix,
15
14
  getErrorNote,
16
- getFresh,
17
- getLocusText,
15
+ getLocationText,
16
+ getParamFresh,
18
17
  getScopeAt,
18
+ isBuiltinApply,
19
19
  mapScoped,
20
20
  normalizeApply,
21
21
  shift,
22
22
  stripProps,
23
23
  substituteExpr,
24
24
  type Expr,
25
- type ObligationWarning,
25
+ type Warn,
26
26
  type Param,
27
27
  type Scope,
28
28
  type Substitution,
29
29
  } from "./expression";
30
30
  import { getLevelInfo, LEVEL_NUMBERS } from "./levels";
31
+ import { rewriteUnchanged } from "./temporal";
31
32
 
32
33
  // Which of ENABLED and \cdot a pass handles, and whether it may expand the definitions that
33
34
  // soundness needs expanded, as the AutoUSE directive allows.
34
- export interface ActionOptions {
35
+ interface ActionOptions {
35
36
  isEnabled: boolean;
36
37
  isCdot: boolean;
37
38
  isAutoUse: boolean;
@@ -42,8 +43,6 @@ interface FreshNames {
42
43
  depth: number;
43
44
  }
44
45
 
45
- type Warn = (warning: ObligationWarning) => void;
46
-
47
46
  const ENABLED_WRAPPER = "EnabledWrapper";
48
47
  const CDOT_WRAPPER = "CdotWrapper";
49
48
 
@@ -53,11 +52,17 @@ const NESTED_ENABLED =
53
52
  const NESTED_CDOT =
54
53
  "Nested occurrence of the operator `\\cdot` found in scope of `ENABLED` when expanding `ENABLED`. Using the proof directive `ExpandCdot` from the module `TLAPS` is expected to avoid this error.";
55
54
 
56
- // Util.eprintf ~at:from "%s" printed, then failwith failure, which keeps a backend from running.
57
- const fail = (onWarning: Warn, from: Expr, printed: string, failure = printed): never => {
58
- onWarning(getErrorNote(from.location, printed));
59
- throw new TlaProverError(failure);
60
- };
55
+ // Unlike auto_expansion_of_defs, tlapm puts a space before "For example" here.
56
+ const NESTED_CDOT_SPACED = `${NESTED_CDOT} For example, writing \`BY ExpandCdot\`.`;
57
+
58
+ // Visit.map_visible_hyp with no state.
59
+ const mapVisibleChildren = (expression: Expr, map: (child: Expr) => Expr) =>
60
+ mapScoped(
61
+ undefined,
62
+ expression,
63
+ (_state, child) => map(child),
64
+ () => undefined,
65
+ );
61
66
 
62
67
  const getHyp = (scope: Scope | undefined, index: number) => {
63
68
  const hyp = getScopeAt(scope, index - 1)?.hyp;
@@ -81,11 +86,6 @@ const isLambdified = (expression: Expr) =>
81
86
  expression.args[0].kind === "Lambda" &&
82
87
  (isActionOperator(expression.operator) || isWrapper(expression.operator));
83
88
 
84
- const isBuiltinApply = (expression: Expr, builtin: "ENABLED" | "Cdot") =>
85
- expression.kind === "Apply" &&
86
- expression.operator.kind === "Internal" &&
87
- expression.operator.builtin === builtin;
88
-
89
89
  const getInitialLevel = (level: number | undefined) =>
90
90
  level === undefined ? 2 : Math.min(2, level);
91
91
 
@@ -116,12 +116,13 @@ const expandDefinitions = (
116
116
  const [first, second] = expression.args;
117
117
  if (builtin === "Cdot" && expression.args.length === 2) {
118
118
  if (level !== undefined && !options.isCdot) {
119
- fail(
120
- onWarning,
121
- expression,
122
- `${NESTED_CDOT}For example, writing \`BY ExpandCdot\`.`,
123
- "Expr.Action",
119
+ onWarning(
120
+ getErrorNote(
121
+ expression.location,
122
+ `${NESTED_CDOT}For example, writing \`BY ExpandCdot\`.`,
123
+ ),
124
124
  );
125
+ throw new TlaProverError("Expr.Action");
125
126
  }
126
127
  return {
127
128
  ...expression,
@@ -132,7 +133,8 @@ const expandDefinitions = (
132
133
  }
133
134
  if (builtin === "ENABLED" && expression.args.length === 1) {
134
135
  if (level !== undefined && !options.isEnabled) {
135
- fail(onWarning, expression, NESTED_ENABLED, "Expr.Action");
136
+ onWarning(getErrorNote(expression.location, NESTED_ENABLED));
137
+ throw new TlaProverError("Expr.Action");
136
138
  }
137
139
  return {
138
140
  ...expression,
@@ -159,7 +161,7 @@ const expandDefinitions = (
159
161
  const expressionLevel = getLevelInfo(scope, expression).level;
160
162
  const hyp = getHyp(scope, head.index);
161
163
  const getDeclaration = (name: string) =>
162
- `The operator \`${name}\` is declared at:\n${hyp.location ? getLocusText(hyp.location) : "<unknown location>"}`;
164
+ `The operator \`${name}\` is declared at:\n${getLocationText(hyp.location)}`;
163
165
  if (hyp.kind === "Fresh" && hyp.level === "Unknown") {
164
166
  onWarning(
165
167
  getErrorNote(
@@ -197,13 +199,9 @@ const expandDefinitions = (
197
199
  ? ["the operator `ENABLED`", "`ExpandENABLED` proof directive"]
198
200
  : ["the operator `\\cdot`", "`ExpandCdot` proof directive"];
199
201
  const body = definition.body.kind === "Lambda" ? definition.body.body : definition.body;
200
- const getAt = (from: Expr) =>
201
- from.location ? getLocusText(from.location) : "<unknown location>";
202
- fail(
203
- onWarning,
204
- expression,
205
- `Hidden definition of operator \`${definition.name}\` needs expansion for soundly expanding ${names[0]} (using rigid quantification).\nThe expansion of ${names[0]} has been activated with the ${names[1]} from the module \`TLAPS\`.\nThe operator \`${definition.name}\` is defined at: \n\t${getAt(body)}\nand the operator \`${definition.name}\` occurs at: \n\t${getAt(expression)}\nUsing the proof directive \`AutoUSE\` from the module \`TLAPS\`, or \`BY DEF ${definition.name}\` is expected to avoid this error.\n`,
206
- );
202
+ const message = `Hidden definition of operator \`${definition.name}\` needs expansion for soundly expanding ${names[0]} (using rigid quantification).\nThe expansion of ${names[0]} has been activated with the ${names[1]} from the module \`TLAPS\`.\nThe operator \`${definition.name}\` is defined at: \n\t${getLocationText(body.location)}\nand the operator \`${definition.name}\` occurs at: \n\t${getLocationText(expression.location)}\nUsing the proof directive \`AutoUSE\` from the module \`TLAPS\`, or \`BY DEF ${definition.name}\` is expected to avoid this error.\n`;
203
+ onWarning(getErrorNote(expression.location, message));
204
+ throw new TlaProverError(message);
207
205
  }
208
206
  onWarning({
209
207
  text: `${getAtPrefix(expression.location)}[INFO]: Auto-expanding the definition of operator: ${definition.name}\n`,
@@ -215,19 +213,6 @@ const expandDefinitions = (
215
213
  );
216
214
  };
217
215
 
218
- const getEquality = (expression: Expr): Expr =>
219
- applyBuiltin("Eq", [applyBuiltin("Prime", [expression], expression), expression], expression);
220
-
221
- // E_tla_norm.rewrite_unch: UNCHANGED <<x, <<y>>>> as x' = x /\ y' = y.
222
- export const rewriteUnchanged = (expression: Expr): Expr => {
223
- const flatten = (inner: Expr): Expr[] =>
224
- inner.kind === "Tuple" ? inner.elements.flatMap(flatten) : [inner];
225
- const items = flatten(expression);
226
- if (items.length === 0) return at({ kind: "Internal", builtin: "TRUE" }, expression);
227
- if (items.length === 1) return getEquality(items[0]);
228
- return at({ kind: "List", bullet: "And", items: items.map(getEquality) }, expression);
229
- };
230
-
231
216
  // expand_propositional_action_operators: UNCHANGED v, [A]_v and <<A>>_v in terms of primes.
232
217
  const expandPropositional = (expression: Expr): Expr => {
233
218
  if (expression.kind === "Apply" && expression.args.length === 1) {
@@ -330,15 +315,13 @@ const bindVariables = (
330
315
  ) {
331
316
  return lambdifyOperator(expression.operator, expression.args);
332
317
  }
333
- if (builtin === "ENABLED" && isInScope)
334
- fail(onWarning, expression, NESTED_ENABLED, "Expr.Action");
318
+ if (builtin === "ENABLED" && isInScope) {
319
+ onWarning(getErrorNote(expression.location, NESTED_ENABLED));
320
+ throw new TlaProverError("Expr.Action");
321
+ }
335
322
  if (builtin === "Cdot" && isInScope) {
336
- fail(
337
- onWarning,
338
- expression,
339
- `${NESTED_CDOT} For example, writing \`BY ExpandCdot\`.`,
340
- "Expr.Action",
341
- );
323
+ onWarning(getErrorNote(expression.location, NESTED_CDOT_SPACED));
324
+ throw new TlaProverError("Expr.Action");
342
325
  }
343
326
  if (builtin === "Prime" && expression.args.length === 1) {
344
327
  const arg = bindVariables(options, onWarning, primed, undefined, scope, expression.args[0]);
@@ -408,8 +391,7 @@ const shiftIndices = (substitution: Substitution, expression: Expr): Expr => {
408
391
  return mapScoped(substitution, expression, shiftIndices, (current) => bumpBy(1, current));
409
392
  };
410
393
 
411
- // normalize_lambda_param_names: the parameters keep their names or become r#0, r#1, ..., and the
412
- // operator becomes EnabledWrapper or CdotWrapper.
394
+ // normalize_lambda_param_names.
413
395
  const renameParams = (isKeepingNames: boolean, expression: Expr): Expr => {
414
396
  if (expression.kind === "Apply" && isActionOperator(expression.operator)) {
415
397
  const [lambda] = expression.args;
@@ -432,32 +414,22 @@ const renameParams = (isKeepingNames: boolean, expression: Expr): Expr => {
432
414
  ],
433
415
  };
434
416
  }
435
- return mapScoped(
436
- undefined,
437
- expression,
438
- (_state, child) => renameParams(isKeepingNames, child),
439
- () => undefined,
440
- );
417
+ return mapVisibleChildren(expression, (child) => renameParams(isKeepingNames, child));
441
418
  };
442
419
 
443
- // check_arity: no \cdot keeps a single argument that is not a LAMBDA.
420
+ // check_arity.
444
421
  const checkArity = (expression: Expr): Expr => {
445
- const isInvalid =
446
- expression.kind === "Apply" &&
447
- expression.operator.kind === "Internal" &&
448
- expression.operator.builtin === "Cdot" &&
422
+ if (
423
+ isBuiltinApply(expression, "Cdot") &&
449
424
  expression.args.length === 1 &&
450
- expression.args[0].kind !== "Lambda";
451
- if (isInvalid) throw new TlapmBugError();
452
- return mapScoped(
453
- undefined,
454
- expression,
455
- (_state, child) => checkArity(child),
456
- () => undefined,
457
- );
425
+ expression.args[0].kind !== "Lambda"
426
+ ) {
427
+ throw new TlapmBugError();
428
+ }
429
+ return mapVisibleChildren(expression, checkArity);
458
430
  };
459
431
 
460
- // lambdify_action_operators#expand: binding, shifting, anonymizing the bound names, and renaming.
432
+ // lambdify_action_operators#expand.
461
433
  const lambdifyOperators = (
462
434
  anonymizer: Anonymizer,
463
435
  onWarning: Warn,
@@ -503,10 +475,7 @@ const replaceWithQuantifiers = (
503
475
  body: replaceWithQuantifiers(
504
476
  options,
505
477
  onWarning,
506
- adjoinAll(
507
- scope,
508
- params.map((param) => getFresh(param.name, "Unknown", param.shape)),
509
- ),
478
+ adjoinAll(scope, params.map(getParamFresh)),
510
479
  body,
511
480
  true,
512
481
  ),
@@ -541,15 +510,12 @@ const replaceWithQuantifiers = (
541
510
  }
542
511
  }
543
512
  if (isBuiltinApply(expression, "ENABLED") && isInScope) {
544
- fail(onWarning, expression, NESTED_ENABLED, "Expr.Action");
513
+ onWarning(getErrorNote(expression.location, NESTED_ENABLED));
514
+ throw new TlaProverError("Expr.Action");
545
515
  }
546
516
  if (isBuiltinApply(expression, "Cdot") && isInScope) {
547
- fail(
548
- onWarning,
549
- expression,
550
- `${NESTED_CDOT} For example, writing \`BY ExpandCdot\`.`,
551
- "Expr.Action",
552
- );
517
+ onWarning(getErrorNote(expression.location, NESTED_CDOT_SPACED));
518
+ throw new TlaProverError("Expr.Action");
553
519
  }
554
520
  return mapScoped(
555
521
  scope,
@@ -569,11 +535,7 @@ const commuteExistsDisjunction = (expression: Expr): Expr => {
569
535
  items: body.items.map((item) => ({ ...expression, body: item })),
570
536
  });
571
537
  }
572
- if (
573
- body.kind === "Apply" &&
574
- body.operator.kind === "Internal" &&
575
- body.operator.builtin === "Disj"
576
- ) {
538
+ if (isBuiltinApply(body, "Disj")) {
577
539
  if (body.args.length !== 2) throw new TlapmBugError();
578
540
  return commuteExistsDisjunction({
579
541
  ...body,
@@ -581,12 +543,7 @@ const commuteExistsDisjunction = (expression: Expr): Expr => {
581
543
  });
582
544
  }
583
545
  }
584
- return mapScoped(
585
- undefined,
586
- expression,
587
- (_state, child) => commuteExistsDisjunction(child),
588
- () => undefined,
589
- );
546
+ return mapVisibleChildren(expression, commuteExistsDisjunction);
590
547
  };
591
548
 
592
549
  // expand_action_operators, the ExpandENABLED and ExpandCdot frontends.
@@ -10,8 +10,10 @@ import {
10
10
  consSubstitution,
11
11
  exprifySequent,
12
12
  findNamed,
13
+ getBoundFresh,
13
14
  getErrorNote,
14
15
  getFresh,
16
+ getLocalDefn,
15
17
  getLocusPrefix,
16
18
  getScopeAt,
17
19
  isEqualExpr,
@@ -29,7 +31,7 @@ import {
29
31
  type Expr,
30
32
  type ExprCore,
31
33
  type Hyp,
32
- type ObligationWarning,
34
+ type Warn,
33
35
  type ParenForm,
34
36
  type Scope,
35
37
  type Selector,
@@ -63,7 +65,7 @@ const ANON_SELECTOR_FAILURES = {
63
65
  Instance: "1INST",
64
66
  Left: "1",
65
67
  Right: "1",
66
- } as const;
68
+ };
67
69
 
68
70
  const BAD_EXPRESSION: Expr = { kind: "Opaque", name: "$badexp" };
69
71
 
@@ -78,11 +80,13 @@ export const createAnonymizer = (
78
80
  scope: Scope | undefined,
79
81
  definition: Extract<Defn, { kind: "Instance" }>,
80
82
  ) => Defn[],
81
- onWarning: (warning: ObligationWarning) => void,
83
+ onWarning: Warn,
82
84
  ) => {
83
85
  // Elab.desugar's current_at: the value @ stands for inside an EXCEPT, and the context size there.
84
86
  let currentAt: { expression: Expr; size: number } | undefined;
85
87
 
88
+ const getContext = (scope: Scope | undefined): AnonContext => ({ warnedSteps: [], scope });
89
+
86
90
  const getSize = (context: AnonContext) => context.scope?.size ?? 0;
87
91
 
88
92
  const expr = (context: AnonContext, expression: Expr): Expr => {
@@ -219,7 +223,7 @@ export const createAnonymizer = (
219
223
  mapSelectorArgs(selector, (arg) => expr(context, arg)),
220
224
  );
221
225
  const args = inner.args.map((arg) => expr(context, arg));
222
- const bangContext = { warnedSteps: [], scope: context.scope };
226
+ const bangContext = getContext(context.scope);
223
227
  return resolveBang(bangContext, inner.operator.name, args, selectors, false, expression);
224
228
  }
225
229
  return expr(context, {
@@ -275,13 +279,12 @@ export const createAnonymizer = (
275
279
  const adjoinContext = (context: AnonContext, hyp: Hyp) =>
276
280
  withScope(context, adjoin(context.scope, hyp));
277
281
 
282
+ const adjoinBounds = (context: AnonContext, items: Bound[]) =>
283
+ withScope(context, adjoinAll(context.scope, items.map(getBoundFresh)));
284
+
278
285
  const bounds = (context: AnonContext, items: Bound[]): [AnonContext, Bound[]] => {
279
286
  const mapped = mapBoundDomains(items, (domain) => expr(context, domain));
280
- const inner = mapped.reduce(
281
- (current, bound) => adjoinContext(current, getFresh(bound.name, bound.level)),
282
- context,
283
- );
284
- return [inner, mapped];
287
+ return [adjoinBounds(context, mapped), mapped];
285
288
  };
286
289
 
287
290
  // Visit.map, apart from the definitions an ASSUME or a LET binds.
@@ -327,14 +330,7 @@ export const createAnonymizer = (
327
330
  continue;
328
331
  }
329
332
  const result = defn(current, definition);
330
- current = adjoinContext(current, {
331
- kind: "Defn",
332
- definition: result,
333
- whereDefined: "User",
334
- visibility: "Visible",
335
- isLocal: true,
336
- isConstnessUnset: true,
337
- });
333
+ current = adjoinContext(current, { ...getLocalDefn(result), isConstnessUnset: true });
338
334
  mapped.push(result);
339
335
  }
340
336
  return [current, mapped];
@@ -368,7 +364,7 @@ export const createAnonymizer = (
368
364
  scope: context.scope,
369
365
  });
370
366
 
371
- const adjStep = (context: AnonContext, step: StepNumber, body: Expr, from: Step) =>
367
+ const adjoinStep = (context: AnonContext, step: StepNumber, body: Expr, from: Step) =>
372
368
  adjoinContext(context, {
373
369
  kind: "Defn",
374
370
  definition: { kind: "Operator", name: getStepName(step), body, location: from.location },
@@ -464,22 +460,22 @@ export const createAnonymizer = (
464
460
  const [, mapped] = sequent(context, item.sequent);
465
461
  const assumptions = mapped.context.reduce(adjoinContext, context);
466
462
  const withTuple = bumpContext(
467
- adjStep(bumpContext(assumptions, 1), number, at(tupleForm(mapped), item), item),
463
+ adjoinStep(bumpContext(assumptions, 1), number, at(tupleForm(mapped), item), item),
468
464
  1,
469
465
  );
470
466
  const inner = mapped.context.length === 0 ? pushWarnedStep(withTuple, number) : withTuple;
471
467
  const result: Step = { ...item, sequent: mapped, proof: proof(inner, item.proof) };
472
468
  return [
473
- bumpContext(adjStep(context, number, at(exprifySequent(mapped), item), item), 1),
469
+ bumpContext(adjoinStep(context, number, at(exprifySequent(mapped), item), item), 1),
474
470
  result,
475
471
  ];
476
472
  }
477
473
  case "Pcase": {
478
474
  const expression = expr(context, item.expression);
479
475
  const tuple = at({ kind: "Tuple", elements: [shiftExpr(2, expression)] }, item);
480
- const inner = bumpContext(adjStep(bumpContext(context, 2), number, tuple, item), 1);
476
+ const inner = bumpContext(adjoinStep(bumpContext(context, 2), number, tuple, item), 1);
481
477
  const result: Step = { ...item, expression, proof: proof(inner, item.proof) };
482
- const after = adjStep(
478
+ const after = adjoinStep(
483
479
  context,
484
480
  number,
485
481
  at({ kind: "Tuple", elements: [expression] }, item),
@@ -490,17 +486,20 @@ export const createAnonymizer = (
490
486
  case "Suffices": {
491
487
  const [, mapped] = sequent(context, item.sequent);
492
488
  const fact = at({ kind: "Tuple", elements: [at(exprifySequent(mapped), item)] }, item);
493
- const inner = bumpContext(adjStep(context, number, fact, item), 1);
489
+ const inner = bumpContext(adjoinStep(context, number, fact, item), 1);
494
490
  const result: Step = { ...item, sequent: mapped, proof: proof(inner, item.proof) };
495
491
  const assumptions = mapped.context.reduce(adjoinContext, context);
496
492
  const tuple = at({ kind: "Tuple", elements: [at(tupleForm(mapped), item)] }, item);
497
- return [bumpContext(adjStep(bumpContext(assumptions, 1), number, tuple, item), 1), result];
493
+ return [
494
+ bumpContext(adjoinStep(bumpContext(assumptions, 1), number, tuple, item), 1),
495
+ result,
496
+ ];
498
497
  }
499
498
  case "Have": {
500
499
  const expression = expr(context, item.expression);
501
500
  const tuple = at({ kind: "Tuple", elements: [shiftExpr(2, expression)] }, item);
502
501
  return [
503
- bumpContext(adjStep(bumpContext(context, 2), number, tuple, item), 1),
502
+ bumpContext(adjoinStep(bumpContext(context, 2), number, tuple, item), 1),
504
503
  { ...item, expression },
505
504
  ];
506
505
  }
@@ -511,7 +510,7 @@ export const createAnonymizer = (
511
510
  item,
512
511
  );
513
512
  return [
514
- bumpContext(adjStep(bumpContext(inner, 1), number, universal, item), 1),
513
+ bumpContext(adjoinStep(bumpContext(inner, 1), number, universal, item), 1),
515
514
  { ...item, bounds: mapped },
516
515
  ];
517
516
  }
@@ -519,7 +518,7 @@ export const createAnonymizer = (
519
518
  const expressions = item.expressions.map((expression) => expr(context, expression));
520
519
  const tuple = at({ kind: "Tuple", elements: expressions }, item);
521
520
  return [
522
- bumpContext(adjStep(bumpContext(context, 1), number, tuple, item), 1),
521
+ bumpContext(adjoinStep(bumpContext(context, 1), number, tuple, item), 1),
523
522
  { ...item, expressions },
524
523
  ];
525
524
  }
@@ -531,7 +530,7 @@ export const createAnonymizer = (
531
530
  item,
532
531
  );
533
532
  const inner = pushWarnedStep(
534
- bumpContext(adjStep(bumpContext(context, 1), number, existential, item), 1),
533
+ bumpContext(adjoinStep(bumpContext(context, 1), number, existential, item), 1),
535
534
  number,
536
535
  );
537
536
  const result: Step = {
@@ -540,12 +539,12 @@ export const createAnonymizer = (
540
539
  expression,
541
540
  proof: proof(inner, item.proof),
542
541
  };
543
- const declared = mapped.reduce(
544
- (current, bound) => adjoinContext(current, getFresh(bound.name, bound.level)),
545
- bumpContext(context, 2),
546
- );
542
+ const declared = adjoinBounds(bumpContext(context, 2), mapped);
547
543
  const shifted = shiftExpr(4 + mapped.length, existential);
548
- return [bumpContext(adjStep(bumpContext(declared, 2), number, shifted, item), 1), result];
544
+ return [
545
+ bumpContext(adjoinStep(bumpContext(declared, 2), number, shifted, item), 1),
546
+ result,
547
+ ];
549
548
  }
550
549
  case "Use": {
551
550
  const mapped = usable(context, item.usable);
@@ -563,14 +562,11 @@ export const createAnonymizer = (
563
562
  };
564
563
 
565
564
  return {
566
- expr: (scope: Scope | undefined, expression: Expr) =>
567
- expr({ warnedSteps: [], scope }, expression),
568
- defn: (scope: Scope | undefined, definition: Defn) =>
569
- defn({ warnedSteps: [], scope }, definition),
570
- sequent: (scope: Scope | undefined, item: Sequent) =>
571
- sequent({ warnedSteps: [], scope }, item)[1],
572
- usable: (scope: Scope | undefined, item: Usable) => usable({ warnedSteps: [], scope }, item),
573
- proof: (scope: Scope | undefined, item: Proof) => proof({ warnedSteps: [], scope }, item),
565
+ expr: (scope: Scope | undefined, expression: Expr) => expr(getContext(scope), expression),
566
+ defn: (scope: Scope | undefined, definition: Defn) => defn(getContext(scope), definition),
567
+ sequent: (scope: Scope | undefined, item: Sequent) => sequent(getContext(scope), item)[1],
568
+ usable: (scope: Scope | undefined, item: Usable) => usable(getContext(scope), item),
569
+ proof: (scope: Scope | undefined, item: Proof) => proof(getContext(scope), item),
574
570
  };
575
571
  };
576
572