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
@@ -16,13 +16,25 @@ import {
16
16
  SEQ,
17
17
  tla,
18
18
  } from "./format";
19
- import { axiom, TYPED_SYMBOLS, type Axiom, type AxiomArgument } from "./table";
19
+ import { axiom, TYPED_SYMBOLS, type AxiomArgument } from "./table";
20
20
 
21
- export const getTyping = (name: string, operator: string, arity: number, isGuarded = false) => {
22
- const symbol = tla(name);
23
- const variables = arity === 1 ? ["x1"] : isGuarded ? ["x", "y"] : ["x1", "x2"];
21
+ // The arithmetic symbols with a Typing axiom: each one's SMT-LIB operator and arity.
22
+ export const TYPED_OPERATORS: Record<string, [string, number]> = {
23
+ IntPlus: ["+", 2],
24
+ IntMinus: ["-", 2],
25
+ IntTimes: ["*", 2],
26
+ IntUminus: ["-", 1],
27
+ IntQuotient: ["div", 2],
28
+ IntRemainder: ["mod", 2],
29
+ IntLteq: ["<=", 2],
30
+ };
31
+
32
+ export const getTyping = (name: string) => {
33
+ const operator = TYPED_OPERATORS[name][0];
34
+ const isGuarded = operator === "div" || operator === "mod";
35
+ const variables = TYPED_OPERATORS[name][1] === 1 ? ["x1"] : isGuarded ? ["x", "y"] : ["x1", "x2"];
24
36
  const left = call(
25
- symbol,
37
+ tla(name),
26
38
  variables.map((variable) => `(${CAST_INT} ${variable})`),
27
39
  );
28
40
  const right =
@@ -38,16 +50,6 @@ export const getTyping = (name: string, operator: string, arity: number, isGuard
38
50
  );
39
51
  };
40
52
 
41
- export const TYPINGS: Record<string, () => Axiom> = {
42
- IntPlus: () => getTyping("IntPlus", "+", 2),
43
- IntMinus: () => getTyping("IntMinus", "-", 2),
44
- IntTimes: () => getTyping("IntTimes", "*", 2),
45
- IntUminus: () => getTyping("IntUminus", "-", 1),
46
- IntQuotient: () => getTyping("IntQuotient", "div", 2, true),
47
- IntRemainder: () => getTyping("IntRemainder", "mod", 2, true),
48
- IntLteq: () => getTyping("IntLteq", "<=", 2),
49
- };
50
-
51
53
  export const getEnumeration = (count: number) => {
52
54
  const symbol = tla(`SetEnum_${count}`);
53
55
  const elements = getNames("a", count);
@@ -75,53 +77,76 @@ export const getEnumeration = (count: number) => {
75
77
  export const getIntegers = (count: number) =>
76
78
  Array.from({ length: count }, (_value, index) => `(${CAST_INT} ${index + 1})`);
77
79
 
80
+ export const getFieldKeys = (fields: string[]) => fields.map((field) => tla(`StrLit_${field}`));
81
+
78
82
  // TupExcept and RecExcept: updating one component of a tuple or record.
79
- export const getComponentExcept = (
80
- name: string,
83
+ const getComponentExcepts = (
84
+ prefix: string,
81
85
  args: AxiomArgument[],
82
86
  symbol: string,
83
87
  keys: string[],
84
- index: number,
85
88
  ) => {
86
89
  const elements = getNames("x", keys.length);
87
- const updated = `(${FUN_EXCEPT} ${call(symbol, elements)} ${keys[index]} x)`;
88
- const replaced = elements.map((element, position) => (position === index ? "x" : element));
89
- return axiom(
90
- name,
91
- [...args, index + 1],
92
- forall([...elements, "x"], `(= ${updated} ${call(symbol, replaced)})`, [[updated]]),
90
+ return keys.map((key, index) => {
91
+ const updated = `(${FUN_EXCEPT} ${call(symbol, elements)} ${key} x)`;
92
+ const replaced = elements.map((element, position) => (position === index ? "x" : element));
93
+ return axiom(
94
+ `${prefix}Except`,
95
+ [...args, index + 1],
96
+ forall([...elements, "x"], `(= ${updated} ${call(symbol, replaced)})`, [[updated]]),
97
+ );
98
+ });
99
+ };
100
+
101
+ export const getTupleExcepts = (count: number) =>
102
+ getComponentExcepts("Tup", [count], tla(`Tuple_${count}`), getIntegers(count));
103
+
104
+ export const getRecordExcepts = (fields: string[]) =>
105
+ getComponentExcepts("Rec", [fields], tla(`Record_${fields.join("_")}`), getFieldKeys(fields));
106
+
107
+ // TupIsafcn, TupDomDef and TupAppDef, or their Rec counterparts: a tuple or record is the
108
+ // function from its keys to its components. The empty tuple has no domain or components to define.
109
+ const getComponentFunction = (
110
+ prefix: string,
111
+ args: AxiomArgument[],
112
+ symbol: string,
113
+ keys: string[],
114
+ ) => {
115
+ const elements = getNames("x", keys.length);
116
+ const value = call(symbol, elements);
117
+ const isafcn = axiom(
118
+ `${prefix}Isafcn`,
119
+ args,
120
+ forall(elements, `(${FUN_ISAFCN} ${value})`, [[value]]),
93
121
  );
122
+ if (keys.length === 0) return [isafcn];
123
+ return [
124
+ isafcn,
125
+ axiom(
126
+ `${prefix}DomDef`,
127
+ args,
128
+ forall(elements, `(= (${FUN_DOM} ${value}) ${call(tla(`SetEnum_${keys.length}`), keys)})`, [
129
+ [value],
130
+ ]),
131
+ ),
132
+ axiom(
133
+ `${prefix}AppDef`,
134
+ args,
135
+ forall(
136
+ elements,
137
+ conjoin(keys.map((key, index) => `(= (${FUN_APP} ${value} ${key}) ${elements[index]})`)),
138
+ [[value]],
139
+ ),
140
+ ),
141
+ ];
94
142
  };
95
143
 
96
144
  export const getTupleAxioms = (count: number, isExcept: boolean) => {
97
145
  const symbol = tla(`Tuple_${count}`);
98
146
  const elements = getNames("x", count);
99
147
  const value = call(symbol, elements);
100
- const keys = getIntegers(count);
101
148
  return [
102
- axiom("TupIsafcn", [count], forall(elements, `(${FUN_ISAFCN} ${value})`, [[value]])),
103
- ...(count === 0
104
- ? []
105
- : [
106
- axiom(
107
- "TupDomDef",
108
- [count],
109
- forall(elements, `(= (${FUN_DOM} ${value}) ${call(tla(`SetEnum_${count}`), keys)})`, [
110
- [value],
111
- ]),
112
- ),
113
- axiom(
114
- "TupAppDef",
115
- [count],
116
- forall(
117
- elements,
118
- conjoin(
119
- keys.map((key, index) => `(= (${FUN_APP} ${value} ${key}) ${elements[index]})`),
120
- ),
121
- [[value]],
122
- ),
123
- ),
124
- ]),
149
+ ...getComponentFunction("Tup", [count], symbol, getIntegers(count)),
125
150
  axiom(
126
151
  "SeqTupTyping",
127
152
  [count],
@@ -138,40 +163,14 @@ export const getTupleAxioms = (count: number, isExcept: boolean) => {
138
163
  [count],
139
164
  forall(elements, `(= (${LEN} ${value}) (${CAST_INT} ${count}))`, [[value]]),
140
165
  ),
141
- ...(isExcept
142
- ? keys.map((_key, index) => getComponentExcept("TupExcept", [count], symbol, keys, index))
143
- : []),
166
+ ...(isExcept ? getTupleExcepts(count) : []),
144
167
  ];
145
168
  };
146
169
 
147
- export const getRecordAxioms = (fields: string[], isExcept: boolean) => {
148
- const symbol = tla(`Record_${fields.join("_")}`);
149
- const keys = fields.map((field) => tla(`StrLit_${field}`));
150
- const elements = getNames("x", fields.length);
151
- const value = call(symbol, elements);
152
- return [
153
- axiom("RecIsafcn", [fields], forall(elements, `(${FUN_ISAFCN} ${value})`, [[value]])),
154
- axiom(
155
- "RecDomDef",
156
- [fields],
157
- forall(elements, `(= (${FUN_DOM} ${value}) ${call(tla(`SetEnum_${fields.length}`), keys)})`, [
158
- [value],
159
- ]),
160
- ),
161
- axiom(
162
- "RecAppDef",
163
- [fields],
164
- forall(
165
- elements,
166
- conjoin(keys.map((key, index) => `(= (${FUN_APP} ${value} ${key}) ${elements[index]})`)),
167
- [[value]],
168
- ),
169
- ),
170
- ...(isExcept
171
- ? keys.map((_key, index) => getComponentExcept("RecExcept", [fields], symbol, keys, index))
172
- : []),
173
- ];
174
- };
170
+ export const getRecordAxioms = (fields: string[], isExcept: boolean) => [
171
+ ...getComponentFunction("Rec", [fields], tla(`Record_${fields.join("_")}`), getFieldKeys(fields)),
172
+ ...(isExcept ? getRecordExcepts(fields) : []),
173
+ ];
175
174
 
176
175
  // The set of tuples or records whose components are in the given sets.
177
176
  export const getComponentSet = (
@@ -3,13 +3,16 @@
3
3
 
4
4
  import { TlaUnsupportedError } from "../../errors";
5
5
  import {
6
- TYPINGS,
6
+ getComponentSet,
7
7
  getEnumeration,
8
+ getFieldKeys,
8
9
  getIntegers,
9
- getTupleAxioms,
10
10
  getRecordAxioms,
11
- getComponentExcept,
12
- getComponentSet,
11
+ getRecordExcepts,
12
+ getTupleAxioms,
13
+ getTupleExcepts,
14
+ getTyping,
15
+ TYPED_OPERATORS,
13
16
  } from "./axioms";
14
17
  import {
15
18
  APPEND,
@@ -19,7 +22,6 @@ import {
19
22
  CAST_INT,
20
23
  CAT,
21
24
  declare,
22
- formatName,
23
25
  forall,
24
26
  FUN_APP,
25
27
  FUN_DOM,
@@ -77,7 +79,7 @@ export const getSymbolSpec = (name: string, state: CollectState): SymbolSpec =>
77
79
  deps,
78
80
  axioms,
79
81
  });
80
- const symbol = formatName(`TLA__${name}`);
82
+ const symbol = tla(name);
81
83
  const fixed = (arity: number, deps: string[], axioms: Axiom[], sort = "Idv") =>
82
84
  spec(declare(symbol, arity, sort), deps, axioms);
83
85
  const enumeration = /^SetEnum_(\d+)$/.exec(name);
@@ -154,26 +156,14 @@ export const getSymbolSpec = (name: string, state: CollectState): SymbolSpec =>
154
156
  return fixed(
155
157
  fields.length,
156
158
  ["Mem", record, "FunApp", ...fields.map((field) => `StrLit_${field}`)],
157
- getComponentSet(
158
- "RecSet",
159
- [fields],
160
- symbol,
161
- tla(record),
162
- fields.map((field) => tla(`StrLit_${field}`)),
163
- "r",
164
- ),
159
+ getComponentSet("RecSet", [fields], symbol, tla(record), getFieldKeys(fields), "r"),
165
160
  );
166
161
  }
167
162
  const anonymous = state.anonymous.get(name);
168
163
  if (anonymous !== undefined) return fixed(anonymous, [], []);
169
- const typing = TYPINGS[name];
170
- if (typing)
171
- return fixed(
172
- name === "IntUminus" ? 1 : 2,
173
- ["Cast_Int"],
174
- [typing()],
175
- name === "IntLteq" ? "Bool" : "Idv",
176
- );
164
+ const typed = TYPED_OPERATORS[name];
165
+ if (typed)
166
+ return fixed(typed[1], ["Cast_Int"], [getTyping(name)], name === "IntLteq" ? "Bool" : "Idv");
177
167
  switch (name) {
178
168
  // SMT-LIB has no exponentiation, so IntExp keeps only its typing.
179
169
  case "IntExp":
@@ -409,31 +399,12 @@ export const getSymbolSpec = (name: string, state: CollectState): SymbolSpec =>
409
399
  [],
410
400
  `(forall ((f Idv) (x Idv) (y Idv) (z Idv)) (! (=> (${MEM} z (${FUN_DOM} f)) (and (=> (= z x) (= (${FUN_APP} ${updated} z) y)) (=> (distinct z x) (= (${FUN_APP} ${updated} z) (${FUN_APP} f z))))) :pattern ((${FUN_APP} ${updated} z)) :pattern (${updated} (${FUN_APP} f z))))`,
411
401
  ),
412
- ...state.tuples.flatMap((count) =>
413
- getIntegers(count).map((_key, index) =>
414
- getComponentExcept(
415
- "TupExcept",
416
- [count],
417
- tla(`Tuple_${count}`),
418
- getIntegers(count),
419
- index,
420
- ),
421
- ),
422
- ),
423
- ...state.records.flatMap((recordFields) =>
424
- recordFields.map((_field, index) =>
425
- getComponentExcept(
426
- "RecExcept",
427
- [recordFields],
428
- tla(`Record_${recordFields.join("_")}`),
429
- recordFields.map((field) => tla(`StrLit_${field}`)),
430
- index,
431
- ),
432
- ),
433
- ),
402
+ ...state.tuples.flatMap(getTupleExcepts),
403
+ ...state.records.flatMap(getRecordExcepts),
434
404
  ],
435
405
  );
436
406
  }
407
+ // tlapm labels SeqSetElim1 and SeqSetElim2 SetSetElim1 and SetSetElim2.
437
408
  case "Seq":
438
409
  return fixed(
439
410
  1,
@@ -656,7 +627,7 @@ export const getSymbolSpec = (name: string, state: CollectState): SymbolSpec =>
656
627
  case "Tt_Idv":
657
628
  return fixed(0, [], []);
658
629
  case "TIntLteq":
659
- return spec(undefined, ["IntLteq"], [TYPINGS.IntLteq()]);
630
+ return spec(undefined, ["IntLteq"], [getTyping("IntLteq")]);
660
631
  default:
661
632
  // The rest are numerals, which SMT-LIB has natively.
662
633
  if (name.startsWith("TIntLit_")) return spec(undefined, [], []);
@@ -2,13 +2,7 @@
2
2
  // backend/smtlib.ml): TLA+ values share one sort Idv, set membership is the predicate TLA__Mem,
3
3
  // and each symbol the obligation uses brings the symbols and axioms encode/n_data.ml lists for it.
4
4
 
5
- import {
6
- adjoin,
7
- type Expr,
8
- type Hyp,
9
- type Scope,
10
- type Sequent,
11
- } from "../../obligations/expression";
5
+ import type { Expr, Hyp, Sequent } from "../../obligations/expression";
12
6
  import { compareStrings } from "../ocaml";
13
7
  import { collectSymbols } from "./axiomatize";
14
8
  import { createPrinter } from "./context";
@@ -20,7 +14,7 @@ import { compareAxioms } from "./table";
20
14
 
21
15
  type Encoder = ReturnType<typeof createEncoder>;
22
16
 
23
- const HYPOTHESIS: Mode = { polarity: "Negative", at: undefined, depth: 0 };
17
+ const HYPOTHESIS: Mode = { isOmitted: false, polarity: "Negative", at: undefined, depth: 0 };
24
18
 
25
19
  // Prep.expand_defs substitutes visible definitions and pragmas, so they declare nothing.
26
20
  const isExpanded = (hyp: Extract<Hyp, { kind: "Defn" }>) =>
@@ -32,14 +26,17 @@ const isSecondOrder = (expression: Expr) =>
32
26
  expression.kind === "Sequent" &&
33
27
  expression.sequent.context.some((hyp) => hyp.kind === "Fresh" && hyp.shape > 0);
34
28
 
29
+ interface EncodedContext {
30
+ env: Env | undefined;
31
+ entries: Entry[];
32
+ }
33
+
35
34
  // Declares each hypothesis's names and asserts its facts, in order, as Smtlib.pp_print_obligation.
36
- // Visible definitions and TLAPS's pragmas are expanded, so they declare nothing.
37
35
  const encodeContext = (context: Hyp[], encoder: Encoder) =>
38
- context.reduce<{ env: Env | undefined; scope: Scope | undefined; entries: Entry[] }>(
36
+ context.reduce<EncodedContext>(
39
37
  (state, hyp) => {
40
38
  const next = (binding: Binding, entries: Entry[] = []) => ({
41
39
  env: encoder.push(state.env, binding),
42
- scope: adjoin(state.scope, hyp),
43
40
  entries: [...state.entries, ...entries],
44
41
  });
45
42
  switch (hyp.kind) {
@@ -50,10 +47,9 @@ const encodeContext = (context: Hyp[], encoder: Encoder) =>
50
47
  ? { kind: "constant", symbol }
51
48
  : { kind: "operator", symbol, arity: hyp.shape };
52
49
  const declaration = declare(symbol, hyp.shape);
53
- const domain = hyp.domain;
54
- if (!domain || hyp.domainVisibility === "Hidden") return next(binding, [declaration]);
50
+ if (!hyp.domain || hyp.domainVisibility === "Hidden") return next(binding, [declaration]);
55
51
  // Rewrite.elim_bounds: NEW x \in S is NEW x and the fact x \in S.
56
- const fact = `(assert (${MEM} ${symbol} ${encoder.encodeIdv(domain, state.env, HYPOTHESIS)}))`;
52
+ const fact = `(assert (${MEM} ${symbol} ${encoder.encodeIdv(hyp.domain, state.env, HYPOTHESIS)}))`;
57
53
  return next(binding, [declaration, ...encoder.getEntries(fact)]);
58
54
  }
59
55
  // Rewrite.elim_flex: a variable is two constants, the second for its primed value.
@@ -95,21 +91,20 @@ const encodeContext = (context: Hyp[], encoder: Encoder) =>
95
91
  case "Fact": {
96
92
  const binding: Binding = { kind: "unsupported", reason: "a reference to a fact" };
97
93
  if (hyp.visibility === "Hidden") return next(binding);
98
- if (!isSecondOrder(hyp.expression)) {
99
- const fact = `(assert ${encoder.encodeBool(hyp.expression, state.env, HYPOTHESIS)})`;
100
- return next(binding, encoder.getEntries(fact));
101
- }
102
- const fact = `(assert ${encoder.encodeBool(hyp.expression, state.env, { ...HYPOTHESIS, isOmitted: true })})`;
94
+ const isOmitted = isSecondOrder(hyp.expression);
95
+ const entries = encoder.getEntries(
96
+ `(assert ${encoder.encodeBool(hyp.expression, state.env, { ...HYPOTHESIS, isOmitted })})`,
97
+ );
103
98
  return next(
104
99
  binding,
105
- encoder
106
- .getEntries(fact)
107
- .map((entry) => (typeof entry === "string" ? { omitted: entry } : entry)),
100
+ isOmitted
101
+ ? entries.map((entry) => (typeof entry === "string" ? { omitted: entry } : entry))
102
+ : entries,
108
103
  );
109
104
  }
110
105
  }
111
106
  },
112
- { env: undefined, scope: undefined, entries: [] },
107
+ { env: undefined, entries: [] },
113
108
  );
114
109
 
115
110
  // Smtlib.pp_print_obligation: the logic, the sort, the builtin symbols by name, their axioms,
@@ -1,7 +1,18 @@
1
1
  // Standardize.set_extensionality_visitor: an equality of sets where it may need proving triggers
2
2
  // the set extensionality axiom, through TrigEq.
3
3
 
4
- import { CAP, CUP, FUN_SET, INT_RANGE, SEQ, SET_MINUS, SUBSET, TRIG_EQ, UNION } from "./format";
4
+ import {
5
+ CAP,
6
+ CUP,
7
+ FUN_SET,
8
+ getClosing,
9
+ INT_RANGE,
10
+ SEQ,
11
+ SET_MINUS,
12
+ SUBSET,
13
+ TRIG_EQ,
14
+ UNION,
15
+ } from "./format";
5
16
 
6
17
  export type Polarity = "Positive" | "Negative" | "Neither";
7
18
 
@@ -27,18 +38,9 @@ const isSetTerm = (text: string) => {
27
38
  export const resolveTriggers = (text: string, isTriggered: boolean): string => {
28
39
  const start = text.indexOf(`(${UNRESOLVED_TRIGGER} `);
29
40
  if (start === -1) return text;
30
- const getEnd = (from: number) => {
31
- const end = { depth: 0, index: from };
32
- for (; end.index < text.length; end.index++) {
33
- if (text[end.index] === "(") end.depth++;
34
- if (text[end.index] === ")") end.depth--;
35
- if (end.depth === 0) return end.index + 1;
36
- }
37
- return text.length;
38
- };
39
41
  const triggeredStart = start + UNRESOLVED_TRIGGER.length + 2;
40
- const triggeredEnd = getEnd(triggeredStart);
41
- const keptEnd = getEnd(triggeredEnd + 1);
42
+ const triggeredEnd = getClosing(text, triggeredStart) + 1;
43
+ const keptEnd = getClosing(text, triggeredEnd + 1) + 1;
42
44
  const chosen = isTriggered
43
45
  ? text.slice(triggeredStart, triggeredEnd)
44
46
  : text.slice(triggeredEnd + 1, keptEnd);
@@ -1,7 +1,7 @@
1
1
  // encode/n_flatten.ml: each application of a second-order construct becomes a fresh first-order
2
2
  // symbol, declared with its axioms before the fact that uses it.
3
3
 
4
- import { declare, formatName } from "./format";
4
+ import { declare, formatName, getClosing } from "./format";
5
5
  import type { Axiom } from "./table";
6
6
 
7
7
  // A symbol that Flatten introduces, with the text tlapm's collect pass visits for its
@@ -14,7 +14,7 @@ export interface Flattened {
14
14
  }
15
15
 
16
16
  // A fact that tlapm encodes, so its symbols bring their axioms, but leaves out of the text.
17
- export interface OmittedFact {
17
+ interface OmittedFact {
18
18
  omitted: string;
19
19
  }
20
20
 
@@ -29,20 +29,6 @@ export const getDepth = (variable: string) => Number(variable.slice(variable.las
29
29
  // (?unprimable term). Flatten.compare_expr tells it apart, and the printed text drops it.
30
30
  export const UNPRIMABLE = "?unprimable";
31
31
 
32
- const getClosing = (text: string, from: number) => {
33
- const state = { depth: 0 };
34
- for (const index of Array.from(
35
- { length: text.length - from },
36
- (_value, offset) => from + offset,
37
- )) {
38
- if (text[index] === "(") state.depth++;
39
- if (text[index] === ")") state.depth--;
40
- if (state.depth === 0) return index;
41
- }
42
- return text.length;
43
- };
44
-
45
- // The text with each Unprimable mark dropped.
46
32
  export const removeUnprimable = (text: string): string => {
47
33
  const start = text.indexOf(`(${UNPRIMABLE} `);
48
34
  if (start === -1) return text;
@@ -68,7 +54,7 @@ const getFlatKey = (text: string, depth: number) =>
68
54
  // Smtlib leaves out, which Flatten doesn't enter.
69
55
  interface Site {
70
56
  depth: number;
71
- isOmitted?: boolean;
57
+ isOmitted: boolean;
72
58
  }
73
59
 
74
60
  // The state of Flatten.main over one obligation: its blueprint count, which init_bp_count resets
@@ -120,7 +106,6 @@ export const createFlattener = () => {
120
106
  return symbol;
121
107
  };
122
108
 
123
- // The symbols introduced since the last call, in order.
124
109
  const takeIntroduced = () => introduced.splice(0);
125
110
 
126
111
  return { flattened, flatten, takeIntroduced };
@@ -110,8 +110,8 @@ export const BUILTIN_SYMBOLS: Partial<Record<Builtin, string>> = {
110
110
  export const getNames = (prefix: string, count: number) =>
111
111
  Array.from({ length: count }, (_value, index) => `${prefix}${index + 1}`);
112
112
 
113
- const getSortedBinders = (variables: [string, string][]) =>
114
- variables.map((variable) => `(${variable[0]} ${variable[1]})`).join(" ");
113
+ export const getBinders = (variables: string[], sort = "Idv") =>
114
+ variables.map((variable) => `(${variable} ${sort})`).join(" ");
115
115
 
116
116
  export const forall = (
117
117
  variables: string[],
@@ -121,7 +121,7 @@ export const forall = (
121
121
  ) =>
122
122
  variables.length === 0
123
123
  ? body
124
- : `(forall (${getSortedBinders(variables.map((variable) => [variable, sort]))}) ${
124
+ : `(forall (${getBinders(variables, sort)}) ${
125
125
  patterns.length === 0
126
126
  ? body
127
127
  : `(! ${body} ${patterns.map((pattern) => `:pattern (${pattern.join(" ")})`).join(" ")})`
@@ -139,5 +139,16 @@ export const call = (symbol: string, args: string[]) =>
139
139
  export const declare = (symbol: string, arity: number, sort = "Idv", argSort = "Idv") =>
140
140
  `(declare-fun ${symbol} (${Array.from({ length: arity }, () => argSort).join(" ")}) ${sort})`;
141
141
 
142
+ // The index of the parenthesis that closes the one at from.
143
+ export const getClosing = (text: string, from: number) => {
144
+ const state = { depth: 0, index: from };
145
+ for (; state.index < text.length; state.index++) {
146
+ if (text[state.index] === "(") state.depth++;
147
+ if (text[state.index] === ")") state.depth--;
148
+ if (state.depth === 0) return state.index;
149
+ }
150
+ return text.length;
151
+ };
152
+
142
153
  export const replaceToken = (text: string, token: string, replacement: string) =>
143
154
  text.replace(/[^\s()]+/g, (found) => (found === token ? replacement : found));
@@ -11,6 +11,7 @@ import {
11
11
  FUN_DOM,
12
12
  FUN_ISAFCN,
13
13
  FUN_SET,
14
+ getBinders,
14
15
  getNames,
15
16
  IS_SET_OF,
16
17
  LEN,
@@ -50,9 +51,9 @@ export const getSetOfAxioms = (name: string, free: string[], element: string, bo
50
51
  );
51
52
  const set = call(name, [...sets, ...free]);
52
53
  const guards = variables.map((variable, index) => `(${MEM} ${variable} ${sets[index]})`);
53
- const binders = variables.map((variable) => `(${variable} Idv)`).join(" ");
54
54
  // N_axioms.assert_issetof names its one set a.
55
55
  const single = count === 1 ? ["a"] : sets;
56
+ const asserted = call(name, [...single, ...free]);
56
57
  return [
57
58
  axiom(
58
59
  "SetOfIntro",
@@ -67,16 +68,14 @@ export const getSetOfAxioms = (name: string, free: string[], element: string, bo
67
68
  [count],
68
69
  forall(
69
70
  [...free, ...sets, "x"],
70
- `(=> (${MEM} x ${set}) (exists (${binders}) ${conjoin([...guards, `(= x ${value})`])}))`,
71
+ `(=> (${MEM} x ${set}) (exists (${getBinders(variables)}) ${conjoin([...guards, `(= x ${value})`])}))`,
71
72
  [[`(${MEM} x ${set})`]],
72
73
  ),
73
74
  ),
74
75
  axiom(
75
76
  "AssertIsSetOf",
76
77
  [count],
77
- forall([...free, ...single], `(${IS_SET_OF} ${call(name, [...single, ...free])})`, [
78
- [call(name, [...single, ...free])],
79
- ]),
78
+ forall([...free, ...single], `(${IS_SET_OF} ${asserted})`, [[asserted]]),
80
79
  ),
81
80
  ];
82
81
  };