tla-ts 0.0.10-dev.a4b81b6d0 → 0.0.10-dev.a5705bfbf

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 (76) hide show
  1. package/dist/deciders.cjs +31 -31
  2. package/dist/deciders.js +2 -2
  3. package/dist/index.cjs +1 -1
  4. package/dist/index.d.cts +7 -1
  5. package/dist/index.d.ts +7 -1
  6. package/dist/index.js +1 -1
  7. package/dist/parallel-worker.cjs +1 -1
  8. package/dist/parallel-worker.js +1 -1
  9. package/dist/prove.cjs +42 -42
  10. package/dist/prove.js +30 -30
  11. package/dist/run.cjs +42 -42
  12. package/dist/run.js +42 -42
  13. package/dist/transfer.cjs +31 -29
  14. package/dist/transfer.js +43 -41
  15. package/dist/worker.cjs +4 -4
  16. package/dist/worker.js +4 -4
  17. package/package.json +1 -1
  18. package/src/ast.ts +10 -1
  19. package/src/check-failure.ts +5 -6
  20. package/src/check-trace.ts +4 -4
  21. package/src/check.ts +78 -90
  22. package/src/cli/tlc-output.ts +16 -2
  23. package/src/cli/tlc.ts +2 -2
  24. package/src/codegen.ts +10 -16
  25. package/src/coverage.ts +190 -1
  26. package/src/dependencies.ts +14 -2
  27. package/src/dfid.ts +80 -27
  28. package/src/environment.ts +30 -1
  29. package/src/evaluate.ts +223 -47
  30. package/src/exit-codes.ts +3 -4
  31. package/src/instances.ts +11 -1
  32. package/src/levels.ts +48 -7
  33. package/src/liveness-checker.ts +123 -70
  34. package/src/liveness.ts +4 -1
  35. package/src/obligations/source.ts +2 -0
  36. package/src/parser.ts +3 -0
  37. package/src/prover/smt/solver/card2bv.ts +7 -4
  38. package/src/prover/smt/solver/context.ts +20 -4
  39. package/src/prover/smt/solver/dependent-expr-state.ts +18 -12
  40. package/src/prover/smt/solver/dt2bv-tactic.ts +36 -20
  41. package/src/prover/smt/solver/fd-solver.ts +146 -39
  42. package/src/prover/smt/solver/maxcore.ts +2 -1
  43. package/src/prover/smt/solver/maxsmt-base.ts +1 -0
  44. package/src/prover/smt/solver/model-checker.ts +1 -1
  45. package/src/prover/smt/solver/muz/dl-context.ts +12 -40
  46. package/src/prover/smt/solver/muz/dl-mk-coi-filter.ts +1 -1
  47. package/src/prover/smt/solver/muz/dl-rule.ts +6 -7
  48. package/src/prover/smt/solver/muz/hnf.ts +2 -2
  49. package/src/prover/smt/solver/muz/horn-tactic.ts +14 -1
  50. package/src/prover/smt/solver/muz/rule-properties.ts +22 -0
  51. package/src/prover/smt/solver/muz/spacer-prop-solver.ts +1 -1
  52. package/src/prover/smt/solver/opt-context.ts +1 -0
  53. package/src/prover/smt/solver/opt-solver.ts +1 -1
  54. package/src/prover/smt/solver/parallel-tactic.ts +1 -1
  55. package/src/prover/smt/solver/qsat.ts +7 -2
  56. package/src/prover/smt/solver/rewriter-tpl.ts +7 -6
  57. package/src/prover/smt/solver/sat/inc-sat-solver.ts +45 -26
  58. package/src/prover/smt/solver/sat/sat-tactic.ts +4 -2
  59. package/src/prover/smt/solver/sat/sat2goal.ts +10 -7
  60. package/src/prover/smt/solver/smt-consequences.ts +1 -1
  61. package/src/prover/smt/solver/smt-kernel.ts +9 -2
  62. package/src/prover/smt/solver/smtlib-parser.ts +6 -2
  63. package/src/prover/smt/solver/smtlib-script.ts +197 -73
  64. package/src/prover/smt/solver/tactic.ts +64 -37
  65. package/src/resolve.ts +143 -39
  66. package/src/sany/generator-expressions.ts +2 -0
  67. package/src/sany/generator-proofs.ts +1 -0
  68. package/src/search.ts +109 -23
  69. package/src/simulate.ts +114 -124
  70. package/src/spec-description.ts +3 -0
  71. package/src/subexpressions.ts +168 -63
  72. package/src/successors.ts +30 -10
  73. package/src/tlc/replay.ts +45 -29
  74. package/src/trace-liveness.ts +529 -0
  75. package/src/typed-tier.ts +14 -4
  76. package/src/values.ts +15 -1
package/src/evaluate.ts CHANGED
@@ -22,7 +22,19 @@ import {
22
22
  } from "./errors";
23
23
  import { EXIT_STATUS, setExitCode } from "./exit-codes";
24
24
  import { generateEvaluator } from "./codegen";
25
- import { countCoverage, getCoverageNode, runAtCoverageNode, type Coverage } from "./coverage";
25
+ import {
26
+ chargeContexts,
27
+ chargeFunctionConstruction,
28
+ chargeSetOperation,
29
+ costCoverage,
30
+ countCoverage,
31
+ createChargedEnumerator,
32
+ createProductSetEnumerator,
33
+ getCoverageNode,
34
+ runAtCoverageNode,
35
+ tagSubset,
36
+ type Coverage,
37
+ } from "./coverage";
26
38
  import { MESSAGE_CODE } from "./tlc/messages";
27
39
  import type { CheckerRuntime } from "./runtime";
28
40
  import {
@@ -30,6 +42,7 @@ import {
30
42
  isExpressionImpure,
31
43
  isImpureDefinition,
32
44
  isNonconstant,
45
+ isTlcEvalReached,
33
46
  type DefinitionFacts,
34
47
  } from "./dependencies";
35
48
  import { contextualApplications, substitutionFrames } from "./instances";
@@ -561,6 +574,31 @@ export const forEachBinding = (
561
574
  visit: (scope: Scope | undefined) => boolean,
562
575
  ) => forEachBoundElement(bounds, getBoundElements(bounds, context), context.scope, visit);
563
576
 
577
+ const forEachChargedBinding = (
578
+ bounds: Bound[],
579
+ context: Context,
580
+ coverage: Coverage,
581
+ visit: (scope: Scope | undefined) => boolean,
582
+ ) => {
583
+ const bounded = mapBoundSets(bounds, (set) => {
584
+ const value = evaluate(set, context);
585
+ return {
586
+ value,
587
+ elements: getQuantifierElements(value, set, context.environment.runtime.version),
588
+ };
589
+ });
590
+ const sets = bounded.map((item) => item.elements);
591
+ const charge = chargeContexts(
592
+ coverage,
593
+ bounded.map((item) => item.value),
594
+ sets,
595
+ );
596
+ return forEachBoundElement(bounds, sets, context.scope, (scope) => {
597
+ charge();
598
+ return visit(scope);
599
+ });
600
+ };
601
+
564
602
  const getBoundsDomain = (bounds: Bound[], context: Context): Value => {
565
603
  const sets = mapBoundSets(bounds, (set) => evaluate(set, context));
566
604
  return sets.length === 1 ? sets[0] : { kind: "ProductSet", factors: sets };
@@ -801,14 +839,27 @@ const compileDefinitionBody = (definition: Definition, environment: Environment)
801
839
  return getEntryEvaluator(getDefinitionSource(definition), environment);
802
840
  };
803
841
 
842
+ const CALLER_SCOPE: Scope = {
843
+ name: "",
844
+ binding: { kind: "Value", value: false },
845
+ parent: undefined,
846
+ };
847
+
804
848
  const getDefinitionEvaluator = (definition: Definition, environment: Environment): Evaluator => {
805
849
  const compiled = environment.definitionEvaluators.get(definition);
806
850
  if (compiled) return compiled;
807
851
  const body = compileDefinitionBody(definition, environment);
808
852
  const definitionId = environment.facts.ids.get(definition);
809
853
  const startupValues = environment.startupValues;
810
- const evaluator: Evaluator =
811
- definitionId === undefined
854
+ const isInCallerContext =
855
+ definition.kind === "Operator" &&
856
+ definition.params.length === 0 &&
857
+ isTlcEvalReached(definition.body, environment);
858
+ const evaluator: Evaluator = isInCallerContext
859
+ ? (context) =>
860
+ (definitionId === undefined ? undefined : startupValues[definitionId]) ??
861
+ body(withScope(context, isTlcContextEmpty(context.scope) ? undefined : CALLER_SCOPE))
862
+ : definitionId === undefined
812
863
  ? (context) => body(withScope(context, undefined))
813
864
  : (context) => startupValues[definitionId] ?? body(withScope(context, undefined));
814
865
  environment.definitionEvaluators.set(definition, evaluator);
@@ -1122,7 +1173,15 @@ export const bindDefinitions = (
1122
1173
  node.parent = parent;
1123
1174
  return node;
1124
1175
  }, context.scope);
1125
- definitions.forEach((definition, index) => {
1176
+ let isRecursiveAtOrAfter = false;
1177
+ for (let index = definitions.length - 1; index >= 0; index--) {
1178
+ const definition = definitions[index];
1179
+ isRecursiveAtOrAfter ||= definition.isRecursive;
1180
+ // TLC's LET evaluates an operator without parameters in the context before it, which TLCEval#tlcEval tells from an empty one.
1181
+ const ownScope =
1182
+ definition.kind === "Operator" && definition.params.length === 0 && !isRecursiveAtOrAfter
1183
+ ? nodes[index].parent
1184
+ : scope;
1126
1185
  nodes[index].binding =
1127
1186
  definition.kind === "Function"
1128
1187
  ? {
@@ -1142,19 +1201,19 @@ export const bindDefinitions = (
1142
1201
  name: definition.name,
1143
1202
  params: definition.params,
1144
1203
  body: definition.body,
1145
- scope,
1204
+ scope: ownScope,
1146
1205
  },
1147
1206
  }
1148
1207
  : {
1149
1208
  kind: "Thunk",
1150
1209
  expression: definition.body,
1151
- scope,
1210
+ scope: ownScope,
1152
1211
  state: context.state,
1153
1212
  next: context.next,
1154
1213
  cache: undefined,
1155
1214
  isStreamed: reevaluated?.streamed.has(definition) ?? false,
1156
1215
  };
1157
- });
1216
+ }
1158
1217
  const coverage = context.environment.coverage;
1159
1218
  if (coverage && coverage.current !== -1) {
1160
1219
  nodes.forEach((node) => {
@@ -1184,7 +1243,9 @@ const evaluateLocalIdentifier = (name: string, expression: Expression, context:
1184
1243
  if (global?.kind === "Definition") {
1185
1244
  return getDefinitionEvaluator(global.definition, context.environment)(context);
1186
1245
  }
1187
- const builtin = context.environment.builtins.get(name);
1246
+ const builtin = context.environment.builtins.get(
1247
+ context.environment.substitutions.get(name) ?? name,
1248
+ );
1188
1249
  if (builtin?.arity === 0) return builtin.evaluate([], context);
1189
1250
  throw new TlaEvaluationError(
1190
1251
  `In evaluation, the identifier ${name} is either undefined or not an operator.\n${describeRange(expression)}`,
@@ -1195,7 +1256,9 @@ export const getReevaluatedDefinitions = (
1195
1256
  definitions: Definition[],
1196
1257
  environment: Environment,
1197
1258
  ): ReevaluatedDefinitions => ({
1198
- impure: new Set(definitions.filter((definition) => isImpureDefinition(definition, environment))),
1259
+ impure: new Set(
1260
+ definitions.filter((definition) => isImpureDefinition(definition, environment, "varying")),
1261
+ ),
1199
1262
  streamed: new Set(
1200
1263
  definitions.filter((definition) => isImpureDefinition(definition, environment, "streamed")),
1201
1264
  ),
@@ -1401,9 +1464,21 @@ const countEvaluator =
1401
1464
  coverage.current = node;
1402
1465
  try {
1403
1466
  const value = evaluator(context);
1404
- if (typeof value === "object" && expression.kind === "SetEnumeration") {
1405
- coverage.values.set(value, node);
1406
- }
1467
+ const isTagged =
1468
+ expression.kind === "SetEnumeration" ||
1469
+ ((expression.kind === "SetFilter" || expression.kind === "SetMap") &&
1470
+ isReducibleSet(value)) ||
1471
+ (expression.kind === "SetFilter" &&
1472
+ typeof value === "object" &&
1473
+ value.kind === "FilteredSet") ||
1474
+ ((expression.kind === "FunctionSet" || expression.kind === "RecordSet") &&
1475
+ typeof value === "object" &&
1476
+ value.kind === expression.kind) ||
1477
+ (expression.kind === "Apply" &&
1478
+ expression.operator === "SUBSET" &&
1479
+ typeof value === "object" &&
1480
+ value.kind === "Subset");
1481
+ if (typeof value === "object" && isTagged) coverage.values.set(value, node);
1407
1482
  return value;
1408
1483
  } finally {
1409
1484
  coverage.current = outer;
@@ -1553,6 +1628,26 @@ const compileClosureCall = (
1553
1628
  };
1554
1629
  };
1555
1630
 
1631
+ // TLC's LET conses only its arity-0 definitions onto the context that TLCEval#tlcEval caches under when it is empty.
1632
+ const isTlcContextEmpty = (scope: Scope | undefined) => {
1633
+ for (let node = scope; node !== undefined; node = node.parent) {
1634
+ const binding = node.binding;
1635
+ if (
1636
+ binding.kind !== "Operator" ||
1637
+ binding.operator.kind !== "Closure" ||
1638
+ binding.operator.params.length === 0
1639
+ ) {
1640
+ return false;
1641
+ }
1642
+ let letScope = binding.operator.scope;
1643
+ while (letScope !== undefined && letScope !== node) letScope = letScope.parent;
1644
+ if (letScope !== node) return false;
1645
+ }
1646
+ return true;
1647
+ };
1648
+
1649
+ const SET_OPERATORS = new Set(["\\cup", "\\cap", "\\"]);
1650
+
1556
1651
  const compileApply = (
1557
1652
  expression: Expression & { kind: "Apply" },
1558
1653
  environment: Environment,
@@ -1597,7 +1692,7 @@ const compileApply = (
1597
1692
  !contextualApplications.has(expression) && !isNonconstant(args[0], environment);
1598
1693
  const tlcEvalValues = environment.tlcEvalValues;
1599
1694
  return (context) => {
1600
- if (!isCached || context.scope !== undefined) {
1695
+ if (!isCached || !isTlcContextEmpty(context.scope)) {
1601
1696
  return global.evaluate(getLazyArguments(args, context), context);
1602
1697
  }
1603
1698
  const cached = tlcEvalValues.get(expression);
@@ -1616,7 +1711,39 @@ const compileApply = (
1616
1711
  const left = getEvaluator(args[0], environment);
1617
1712
  const right = getEvaluator(args[1], environment);
1618
1713
  const subset = getSubsetOperator(expression, global.evaluateBinary);
1619
- return (context) => subset(left(context), right(context));
1714
+ const coverage = environment.coverage;
1715
+ if (!coverage) return (context) => subset(left(context), right(context));
1716
+ return (context) => {
1717
+ const leftValue = left(context);
1718
+ const rightValue = right(context);
1719
+ if (
1720
+ typeof leftValue !== "object" ||
1721
+ leftValue.kind !== "Set" ||
1722
+ !coverage.values.has(leftValue)
1723
+ ) {
1724
+ return subset(leftValue, rightValue);
1725
+ }
1726
+ const missing = leftValue.elements.findIndex((element) => !isElementOf(element, rightValue));
1727
+ costCoverage(coverage, leftValue, (missing === -1 ? leftValue.elements.length : missing) + 1);
1728
+ return missing === -1;
1729
+ };
1730
+ }
1731
+ const coverage = environment.coverage;
1732
+ const combine = global?.kind === "Builtin" ? global.evaluateBinary : undefined;
1733
+ if (coverage && combine && SET_OPERATORS.has(expression.operator) && args.length === 2) {
1734
+ const left = getEvaluator(args[0], environment);
1735
+ const right = getEvaluator(args[1], environment);
1736
+ return (context) => {
1737
+ const leftValue = left(context);
1738
+ const rightValue = right(context);
1739
+ return chargeSetOperation(
1740
+ coverage,
1741
+ expression.operator,
1742
+ leftValue,
1743
+ rightValue,
1744
+ combine(leftValue, rightValue),
1745
+ );
1746
+ };
1620
1747
  }
1621
1748
  if (global?.kind === "Builtin") return compileBuiltinCall(global, args, environment);
1622
1749
  if (expression.operator === "\\cdot" && args.length === 2) {
@@ -1649,6 +1776,18 @@ const compileQuantifier = (
1649
1776
  const isForall = expression.kind === "Forall";
1650
1777
  const body = getEvaluator(expression.body, environment);
1651
1778
  const bound = expression.bounds[0];
1779
+ const coverage = environment.coverage;
1780
+ if (coverage) {
1781
+ return (context) => {
1782
+ const isFound = forEachChargedBinding(
1783
+ expression.bounds,
1784
+ context,
1785
+ coverage,
1786
+ (scope) => expectBooleanBody(body(withScope(context, scope)), expression) !== isForall,
1787
+ );
1788
+ return isFound ? !isForall : isForall;
1789
+ };
1790
+ }
1652
1791
  if (expression.bounds.length === 1 && bound.pattern.kind === "Name") {
1653
1792
  const name = bound.pattern.name;
1654
1793
  const set = getEvaluator(bound.set, environment);
@@ -1796,13 +1935,22 @@ export const getFunctionBuilder = (
1796
1935
  const template = getLazyFunctionTemplate(bounds, expression.body);
1797
1936
  const boundTupleLengths = getBoundTupleLengths(bounds);
1798
1937
  const bodyNames = getScopeNames(expression.body);
1938
+ const coverage = environment.coverage;
1799
1939
  const createLazy = (domain: Value, context: Context) => {
1800
1940
  const scope = trimScope(context.scope, bodyNames);
1801
1941
  const lambdaContext = withScope(context, scope);
1942
+ const compute = (argument: Value) =>
1943
+ body(withScope(lambdaContext, bindArgument(bounds, scope, argument)));
1944
+ const node = coverage && !environment.callStack ? coverage.current : -1;
1802
1945
  const functionValue = keepLambda({
1803
1946
  value: createLazyFunction(
1804
1947
  domain,
1805
- (argument) => body(withScope(lambdaContext, bindArgument(bounds, scope, argument))),
1948
+ coverage
1949
+ ? (argument) =>
1950
+ coverage.current === -1
1951
+ ? compute(argument)
1952
+ : runAtCoverageNode(coverage, node, () => compute(argument))
1953
+ : compute,
1806
1954
  getLazyFunctionSource(template, bounds, domain),
1807
1955
  boundTupleLengths,
1808
1956
  ),
@@ -1854,6 +2002,23 @@ const compileFunctionConstruction = (
1854
2002
  ): Evaluator => {
1855
2003
  const build = getFunctionBuilder(expression, environment).build;
1856
2004
  const bounds = expression.bounds;
2005
+ const coverage = environment.coverage;
2006
+ if (coverage) {
2007
+ return (context) => {
2008
+ const domain = getBoundsDomain(bounds, context);
2009
+ const value = build(domain, context);
2010
+ const sets =
2011
+ bounds.length === 1 || typeof domain !== "object" || domain.kind !== "ProductSet"
2012
+ ? [domain]
2013
+ : domain.factors;
2014
+ const isConverted =
2015
+ (typeof value !== "object" || value.kind !== "LazyFunction") && sets.every(isReducibleSet);
2016
+ if (isConverted && coverage.current !== -1 && coverage.covered.has(expression)) {
2017
+ chargeFunctionConstruction(coverage, coverage.current, sets);
2018
+ }
2019
+ return value;
2020
+ };
2021
+ }
1857
2022
  if (bounds.length === 1 && bounds[0].pattern.kind === "Name") {
1858
2023
  const set = getEvaluator(bounds[0].set, environment);
1859
2024
  return (context) => build(set(context), context);
@@ -1933,22 +2098,13 @@ export const getLazyFilter = (
1933
2098
  predicate: predicateNode,
1934
2099
  };
1935
2100
  const coverage = environment.coverage;
1936
- const testCovered = (node: number, isMember: boolean, test: () => Value) => {
1937
- if (!coverage || node === -1) return test();
1938
- if (!isMember) coverage.secondary[node]++;
1939
- const value = runAtCoverageNode(coverage, isMember ? -1 : node, test);
1940
- if (!isMember && value === true) coverage.secondary[node]++;
1941
- return value;
1942
- };
1943
2101
  const createFiltered = (
1944
2102
  base: Value,
1945
2103
  context: Context,
1946
2104
  evaluator: Evaluator,
1947
2105
  node: number,
1948
- ): RebindableFilteredSet => ({
1949
- kind: "FilteredSet",
1950
- base,
1951
- test: (element, isMember) => {
2106
+ ): RebindableFilteredSet => {
2107
+ const test = (element: Value, isMember: boolean) => {
1952
2108
  if (
1953
2109
  pattern.kind === "Tuple" &&
1954
2110
  getSequenceElements(element)?.length !== pattern.names.length
@@ -1957,25 +2113,42 @@ export const getLazyFilter = (
1957
2113
  `Attempted to check if the value:\n${prettyPrint(formatValue(element))}\nis an element of a set of ${pattern.names.length}-tuples.`,
1958
2114
  );
1959
2115
  }
1960
- const value = testCovered(node, isMember, () =>
1961
- evaluator(withScope(context, bindPattern(context.scope, pattern, element))),
1962
- );
2116
+ const value = evaluator(withScope(context, bindPattern(context.scope, pattern, element)));
1963
2117
  if (typeof value !== "boolean") {
1964
2118
  throw new TlaEvaluationError(
1965
2119
  `${isMember ? "The evaluation of predicate" : "Evaluating predicate"} ${predicateNode} yielded non-Boolean value.`,
1966
2120
  );
1967
2121
  }
1968
2122
  return value;
1969
- },
1970
- source,
1971
- rebind: (tracing) =>
2123
+ };
2124
+ const rebind = (tracing: Environment) =>
1972
2125
  createFiltered(
1973
2126
  base,
1974
2127
  { ...context, environment: tracing },
1975
2128
  getEvaluator(expression.predicate, tracing),
1976
2129
  -1,
1977
- ),
1978
- });
2130
+ );
2131
+ if (!coverage || node === -1) return { kind: "FilteredSet", base, test, source, rebind };
2132
+ return {
2133
+ kind: "FilteredSet",
2134
+ base,
2135
+ test: (element, isMember) =>
2136
+ runAtCoverageNode(coverage, isMember ? -1 : node, () => test(element, isMember)),
2137
+ startPass: (isMaterialized) => {
2138
+ const draws = createProductSetEnumerator(coverage, base);
2139
+ return (element) => {
2140
+ draws?.next();
2141
+ tagSubset(coverage, base, element);
2142
+ coverage.secondary[node]++;
2143
+ const value = runAtCoverageNode(coverage, node, () => test(element, false));
2144
+ if (isMaterialized && value) coverage.secondary[node]++;
2145
+ return value;
2146
+ };
2147
+ },
2148
+ source,
2149
+ rebind,
2150
+ };
2151
+ };
1979
2152
  return (base: Value, context: Context, node = -1) =>
1980
2153
  createFiltered(base, context, predicate, node);
1981
2154
  };
@@ -2049,20 +2222,21 @@ const compileSetComprehension = (
2049
2222
  if (expectFilterPredicate(value, expression)) addBoundedElement(kept, element);
2050
2223
  else if (isUniform) break;
2051
2224
  }
2052
- if (coverage && coverage.current !== -1) {
2053
- coverage.secondary[coverage.current] += size + kept.length;
2054
- }
2225
+ if (coverage) costCoverage(coverage, base, size + 1);
2055
2226
  return createNormalizedSet(kept);
2056
2227
  };
2057
2228
  }
2058
2229
  if (expression.kind === "SetMap") {
2059
2230
  const mapped = getEvaluator(expression.expression, environment);
2231
+ const coverage = environment.coverage;
2060
2232
  return (context) => {
2061
2233
  const elements: Value[] = [];
2062
- forEachBinding(expression.bounds, context, (scope) => {
2234
+ const add = (scope: Scope | undefined) => {
2063
2235
  addBoundedElement(elements, mapped(withScope(context, scope)));
2064
2236
  return false;
2065
- });
2237
+ };
2238
+ if (coverage) forEachChargedBinding(expression.bounds, context, coverage, add);
2239
+ else forEachBinding(expression.bounds, context, add);
2066
2240
  return createEnumeratedSet(elements);
2067
2241
  };
2068
2242
  }
@@ -2076,16 +2250,15 @@ const compileSetComprehension = (
2076
2250
  }
2077
2251
  const body = getEvaluator(expression.body, environment);
2078
2252
  const evaluateSet = getEvaluator(set, environment);
2253
+ const coverage = environment.coverage;
2079
2254
  return (context) => {
2080
- const elements = getChoiceElements(
2081
- evaluateSet(context),
2082
- expression,
2083
- set,
2084
- context.environment.runtime.version,
2085
- );
2255
+ const base = evaluateSet(context);
2256
+ const elements = getChoiceElements(base, expression, set, context.environment.runtime.version);
2257
+ const enumerator = coverage && createChargedEnumerator(coverage, base, elements, true);
2086
2258
  let chosen: Value | undefined;
2087
2259
  const pattern = expression.pattern;
2088
2260
  someElement(elements, (element) => {
2261
+ enumerator?.next();
2089
2262
  if (
2090
2263
  pattern.kind === "Tuple" &&
2091
2264
  getSequenceElements(element)?.length !== pattern.names.length
@@ -2099,8 +2272,9 @@ const compileSetComprehension = (
2099
2272
  chosen = getBoundValue(pattern, scope);
2100
2273
  return true;
2101
2274
  });
2102
- if (chosen === undefined) throw createNoChoiceError(expression);
2103
- return chosen;
2275
+ if (chosen !== undefined) return chosen;
2276
+ enumerator?.next();
2277
+ throw createNoChoiceError(expression);
2104
2278
  };
2105
2279
  };
2106
2280
 
@@ -2365,6 +2539,8 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
2365
2539
  }
2366
2540
  case "Label":
2367
2541
  return getChildEvaluator(expression.body);
2542
+ case "Selection":
2543
+ return getChildEvaluator(expression.expression);
2368
2544
  case "Subexpression":
2369
2545
  return () => {
2370
2546
  throw new TlaEvaluationError(
package/src/exit-codes.ts CHANGED
@@ -73,8 +73,7 @@ const withErrorExitCode = <Result>(run: () => Result) => {
73
73
  const withCheckerExitCode = (checker: LivenessChecker): LivenessChecker => ({
74
74
  branches: checker.branches,
75
75
  solutions: checker.solutions,
76
- addInitialState: (index, state, tracing) =>
77
- withErrorExitCode(() => checker.addInitialState(index, state, tracing)),
76
+ addInitialState: checker.addInitialState,
78
77
  addState: (index, state, successors, tracing) =>
79
78
  withErrorExitCode(() => checker.addState(index, state, successors, tracing)),
80
79
  storeState: checker.storeState,
@@ -98,8 +97,8 @@ export const withLivenessChecksExitCode = (
98
97
  return (
99
98
  checks && {
100
99
  solutions: checks.solutions,
101
- createChecker: (search, solutions) =>
102
- withCheckerExitCode(checks.createChecker(search, solutions)),
100
+ findTraceViolation: (trace, fingerprints) =>
101
+ withErrorExitCode(() => checks.findTraceViolation(trace, fingerprints)),
103
102
  }
104
103
  );
105
104
  };
package/src/instances.ts CHANGED
@@ -219,6 +219,8 @@ export const mapChildren = (
219
219
  };
220
220
  case "Label":
221
221
  return { ...expression, body: mapUnbound(expression.body) };
222
+ case "Selection":
223
+ return { ...expression, expression: mapUnbound(expression.expression) };
222
224
  case "Subexpression":
223
225
  return {
224
226
  ...expression,
@@ -262,6 +264,7 @@ interface Rewrite {
262
264
  mode: RewriteMode;
263
265
  modes: Map<RewriteMode, Rewrite>;
264
266
  bindings?: Map<string, Expression>;
267
+ selections: Map<Expression, Expression>;
265
268
  }
266
269
 
267
270
  const getSubstitutionName = (name: string) => `${name}@SUBSTITUTION`;
@@ -548,6 +551,12 @@ const substitute = (
548
551
  bound: Map<string, string>,
549
552
  ): Expression => {
550
553
  const recurse = (node: Expression) => substitute(node, rewrite, bound);
554
+ if (expression.kind === "Selection" && [...bound].every((entry) => entry[0] === entry[1])) {
555
+ const selected = expression.expression;
556
+ const substituted = rewrite.selections.get(selected) ?? recurse(selected);
557
+ rewrite.selections.set(selected, substituted);
558
+ return { ...expression, expression: substituted };
559
+ }
551
560
  const instantiation = rewrite.instantiation;
552
561
  const params = instantiation.params;
553
562
  const isFree = (name: string) => !bound.has(name) && !isLocallyResolved(expression);
@@ -731,7 +740,7 @@ const copyDefinition = (rewrite: Rewrite, key: string): string => {
731
740
  const bindings = new Map<string, Expression>();
732
741
  const bodyRewrite =
733
742
  definition.kind === "Operator" && rewrite.mode === "Normal"
734
- ? { ...rewrite, bindings }
743
+ ? { ...rewrite, bindings, selections: new Map<Expression, Expression>() }
735
744
  : rewrite;
736
745
  const mapped = renameParams(
737
746
  mapDefinition(definition, (child, bound) =>
@@ -777,6 +786,7 @@ export const createInstantiation = (instantiation: Instantiation) => {
777
786
  copies: new Map<string, string>(),
778
787
  mode,
779
788
  modes,
789
+ selections: new Map<Expression, Expression>(),
780
790
  };
781
791
  modes.set(mode, created);
782
792
  return created;
package/src/levels.ts CHANGED
@@ -5,6 +5,7 @@ import {
5
5
  type Definition,
6
6
  type Expression,
7
7
  type Module,
8
+ type NewSymbol,
8
9
  type OperatorParam,
9
10
  type Proof,
10
11
  type ProofStep,
@@ -48,7 +49,7 @@ interface LevelContext {
48
49
  }
49
50
 
50
51
  type ScopeEntry =
51
- | { kind: "Formal"; arity: number }
52
+ | { kind: "Formal"; arity: number; level: number }
52
53
  | { kind: "Let"; definition: Definition; scope: Scope };
53
54
 
54
55
  export type Scope = Map<string, ScopeEntry>;
@@ -67,6 +68,14 @@ export const VARIABLE_LEVEL = 1;
67
68
  export const ACTION_LEVEL = 2;
68
69
  export const TEMPORAL_LEVEL = 3;
69
70
 
71
+ const NEW_SYMBOL_LEVELS = {
72
+ Constant: CONSTANT_LEVEL,
73
+ Variable: VARIABLE_LEVEL,
74
+ State: VARIABLE_LEVEL,
75
+ Action: ACTION_LEVEL,
76
+ Temporal: TEMPORAL_LEVEL,
77
+ } satisfies Record<NewSymbol["level"], number>;
78
+
70
79
  const SEPARATOR = "\u0000";
71
80
 
72
81
  export const getArgumentKey = (operator: string, index: number) =>
@@ -208,7 +217,7 @@ const bindFormals = (scope: Scope, formals: OperatorParam[]) =>
208
217
  ...scope,
209
218
  ...formals.map((formal): [string, ScopeEntry] => [
210
219
  formal.name,
211
- { kind: "Formal", arity: formal.arity },
220
+ { kind: "Formal", arity: formal.arity, level: CONSTANT_LEVEL },
212
221
  ]),
213
222
  ]);
214
223
 
@@ -228,11 +237,12 @@ const isOperatorApplication = (expression: Expression) =>
228
237
 
229
238
  export const createLevelAnalyzer = (context: LevelContext) => {
230
239
  const definitionLevels = new Map<Definition, OperatorLevels>();
240
+ const selectionLevels = new Map<Expression, LevelData>();
231
241
 
232
242
  const resolve = (name: string, scope: Scope): Resolved => {
233
243
  const entry = scope.get(name);
234
244
  if (entry?.kind === "Formal") {
235
- return { kind: "Declared", name, level: 0, arity: entry.arity };
245
+ return { kind: "Declared", name, level: entry.level, arity: entry.arity };
236
246
  }
237
247
  if (entry?.kind === "Let") {
238
248
  return { kind: "Defined", levels: analyzeDefinition(entry.definition, entry.scope) };
@@ -739,6 +749,14 @@ export const createLevelAnalyzer = (context: LevelContext) => {
739
749
  );
740
750
  case "Label":
741
751
  return analyze(expression.body, scope);
752
+ case "Selection": {
753
+ const selected = expression.expression;
754
+ const known = selectionLevels.get(selected);
755
+ if (known) return known;
756
+ const data = analyze(selected, scope);
757
+ selectionLevels.set(selected, data);
758
+ return data;
759
+ }
742
760
  case "Subexpression":
743
761
  return createData();
744
762
  }
@@ -772,6 +790,7 @@ export const createLevelAnalyzer = (context: LevelContext) => {
772
790
  return names;
773
791
  case "Lambda":
774
792
  case "Let":
793
+ case "Selection":
775
794
  return names;
776
795
  case "Prime":
777
796
  case "Unchanged":
@@ -808,7 +827,10 @@ export const createLevelAnalyzer = (context: LevelContext) => {
808
827
  const inner = bindFormals(scope, formals);
809
828
  const data = analyze(body, inner);
810
829
  const isFormal = (param: string) => formals.some((formal) => formal.name === param);
811
- const nonLeibnizNames = getNonLeibnizNames(body, inner);
830
+ const nonLeibnizNames = getNonLeibnizNames(
831
+ body.kind === "Selection" ? body.expression : body,
832
+ inner,
833
+ );
812
834
  const levels: OperatorLevels = {
813
835
  ...createData(data.level),
814
836
  name,
@@ -889,17 +911,29 @@ export const analyzeAssumeProve = (
889
911
  assumeProve: AssumeProve,
890
912
  scope: Scope,
891
913
  analyzer: ReturnType<typeof createLevelAnalyzer>,
914
+ errors: SanyError[] = [],
892
915
  ): LevelData => {
893
916
  const inner = new Map(scope);
894
917
  const parts = assumeProve.assumptions.flatMap((assumption) => {
895
918
  if (assumption.kind === "NewSymbol") {
896
919
  const set = assumption.set && analyzer.analyze(assumption.set, inner);
897
- inner.set(assumption.name, { kind: "Formal", arity: assumption.arity });
920
+ const range = assumption.location.range;
921
+ if (set?.level === TEMPORAL_LEVEL && range) {
922
+ errors.push({
923
+ location: formatRange(range),
924
+ message: "Level error:\nTemporal formula used as set.",
925
+ });
926
+ }
927
+ inner.set(assumption.name, {
928
+ kind: "Formal",
929
+ arity: assumption.arity,
930
+ level: NEW_SYMBOL_LEVELS[assumption.level],
931
+ });
898
932
  return set ? [set] : [];
899
933
  }
900
934
  return [
901
935
  assumption.kind === "AssumeProve"
902
- ? analyzeAssumeProve(assumption, inner, analyzer)
936
+ ? analyzeAssumeProve(assumption, inner, analyzer, errors)
903
937
  : analyzer.analyze(assumption, inner),
904
938
  ];
905
939
  });
@@ -964,6 +998,10 @@ export const checkModuleLevels = (
964
998
  ? []
965
999
  : proof.steps.flatMap((step) => {
966
1000
  const body = step.body;
1001
+ const newSymbolErrors: SanyError[] = [];
1002
+ if (body.kind === "Assert" && body.statement.kind === "AssumeProve") {
1003
+ analyzeAssumeProve(body.statement, new Map(), analyzer, newSymbolErrors);
1004
+ }
967
1005
  const isTemporal = () => getStepLevel(step) === TEMPORAL_LEVEL;
968
1006
  const pickErrors =
969
1007
  body.kind === "Pick" && body.bounds.length > 0 && isTemporal()
@@ -981,6 +1019,7 @@ export const checkModuleLevels = (
981
1019
  )
982
1020
  : [];
983
1021
  return [
1022
+ ...newSymbolErrors,
984
1023
  ...checkProof(step.proof),
985
1024
  ...pickErrors,
986
1025
  ...(step.proof?.kind === "Steps" && isTemporal() ? checkTemporalGoal(step.proof) : []),
@@ -1010,11 +1049,13 @@ export const checkModuleLevels = (
1010
1049
  ...module.theorems.map((theorem) => ({
1011
1050
  location: theorem.location,
1012
1051
  check: () => {
1052
+ const newSymbolErrors: SanyError[] = [];
1013
1053
  const data =
1014
1054
  theorem.statement.kind === "AssumeProve"
1015
- ? analyzeAssumeProve(theorem.statement, new Map(), analyzer)
1055
+ ? analyzeAssumeProve(theorem.statement, new Map(), analyzer, newSymbolErrors)
1016
1056
  : analyzer.analyze(theorem.statement, new Map());
1017
1057
  const errors = [
1058
+ ...newSymbolErrors,
1018
1059
  ...checkProof(theorem.proof),
1019
1060
  ...(data.level === TEMPORAL_LEVEL ? checkTemporalGoal(theorem.proof) : []),
1020
1061
  ];