tla-ts 0.0.10-dev.a17d6d9fa → 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 (78) 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 +12 -2
  5. package/dist/index.d.ts +12 -2
  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 +64 -64
  10. package/dist/prove.js +76 -76
  11. package/dist/run.cjs +42 -42
  12. package/dist/run.js +44 -44
  13. package/dist/transfer.cjs +37 -35
  14. package/dist/transfer.js +43 -41
  15. package/dist/worker.cjs +7 -7
  16. package/dist/worker.js +7 -7
  17. package/package.json +1 -1
  18. package/src/ast.ts +10 -1
  19. package/src/check-failure.ts +12 -10
  20. package/src/check-trace.ts +36 -23
  21. package/src/check.ts +182 -135
  22. package/src/cli/tlc-output.ts +17 -2
  23. package/src/cli/tlc.ts +2 -2
  24. package/src/codegen.ts +15 -19
  25. package/src/coverage.ts +190 -1
  26. package/src/dependencies.ts +19 -6
  27. package/src/dfid.ts +80 -27
  28. package/src/environment.ts +30 -1
  29. package/src/evaluate.ts +254 -59
  30. package/src/exit-codes.ts +25 -13
  31. package/src/instances.ts +11 -1
  32. package/src/levels.ts +48 -7
  33. package/src/liveness-checker.ts +98 -27
  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 +156 -37
  69. package/src/simulate.ts +143 -150
  70. package/src/spec-description.ts +3 -0
  71. package/src/standard-modules.ts +41 -16
  72. package/src/subexpressions.ts +168 -63
  73. package/src/successors.ts +33 -11
  74. package/src/symmetry.ts +1 -0
  75. package/src/tlc/replay.ts +64 -41
  76. package/src/trace-liveness.ts +529 -0
  77. package/src/typed-tier.ts +20 -6
  78. package/src/values.ts +15 -1
@@ -9,6 +9,7 @@ import {
9
9
  type Instance,
10
10
  type Module,
11
11
  type OperatorParam,
12
+ type Proof,
12
13
  type SourceLocation,
13
14
  } from "./ast";
14
15
  import type { ModuleOperator } from "./check";
@@ -236,6 +237,19 @@ const getSubstitutions = (instances: Instance[]) =>
236
237
  instance.substitutions.map((substitution) => substitution.expression),
237
238
  );
238
239
 
240
+ const getProofInstances = (proof: Proof | undefined): Instance[] =>
241
+ proof?.kind === "Steps"
242
+ ? proof.steps.flatMap((step) => [
243
+ ...(step.body.kind === "Instance" ? [step.body] : []),
244
+ ...(step.body.kind === "Define"
245
+ ? step.body.definitions.flatMap((definition) =>
246
+ definition.kind === "Instance" ? [definition] : [],
247
+ )
248
+ : []),
249
+ ...getProofInstances(step.proof),
250
+ ])
251
+ : [];
252
+
239
253
  const rejectLiterals = (expressions: Expression[]): void =>
240
254
  expressions.forEach((expression) => {
241
255
  if (expression.kind === "Decimal") throw createRealNumberError(expression);
@@ -275,9 +289,10 @@ export const createEnvironment = (
275
289
  const dependencies = new Map<string, Set<string>>();
276
290
  const loading: Set<string>[] = [];
277
291
  const linking: string[] = [];
292
+ const usedModules = new Set<string>();
278
293
 
279
294
  const useModule = (name: string, used: Iterable<string>) =>
280
- loading.forEach((closure) => {
295
+ [usedModules, ...loading].forEach((closure) => {
281
296
  closure.add(name);
282
297
  [...used].forEach((dependency) => closure.add(dependency));
283
298
  });
@@ -896,6 +911,13 @@ export const createEnvironment = (
896
911
  module.definitions.toReversed().map((definition) => [definition.name, definition]),
897
912
  ),
898
913
  getKey,
914
+ isModuleKnown: (name, location) =>
915
+ name === parsed.name ||
916
+ usedModules.has(name) ||
917
+ scope.modules.has(name) ||
918
+ parsed.modules.some(
919
+ (nested) => nested.name === name && isBefore(nested.location, location),
920
+ ),
899
921
  instanced,
900
922
  facts,
901
923
  reports,
@@ -972,6 +994,13 @@ export const createEnvironment = (
972
994
  ),
973
995
  getAvailableDefinitions(visible),
974
996
  );
997
+ parsed.theorems
998
+ .flatMap((theorem) => getProofInstances(theorem.proof))
999
+ .filter((instance) => !getVisibleModules().has(instance.module))
1000
+ .forEach(
1001
+ (instance) =>
1002
+ getStandardSymbols(instance.module) ?? getLinkedModule(instance.module, parsed.name),
1003
+ );
975
1004
  scope.errors.push(...resolveModule(module, getUnit(module)));
976
1005
  module.definitions.forEach((definition) => {
977
1006
  const key = getKey(definition);
package/src/evaluate.ts CHANGED
@@ -22,13 +22,27 @@ 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 {
29
41
  isEvaluatedAtStartup,
42
+ isExpressionImpure,
30
43
  isImpureDefinition,
31
44
  isNonconstant,
45
+ isTlcEvalReached,
32
46
  type DefinitionFacts,
33
47
  } from "./dependencies";
34
48
  import { contextualApplications, substitutionFrames } from "./instances";
@@ -321,15 +335,14 @@ export const getDomainOperator = (expression: Expression) => (value: Value) => {
321
335
  };
322
336
 
323
337
  export const getSubsetOperator =
324
- (expression: Expression, builtin: Builtin) => (left: Value, right: Value) => {
338
+ (expression: Expression, subset: (left: Value, right: Value) => Value) =>
339
+ (left: Value, right: Value) => {
325
340
  if (!isSetValue(left) || isOverriddenSet(left)) {
326
341
  throw new TlaEvaluationError(
327
342
  `Attempted to evaluate an expression of form S \\subseteq T, but S was not enumerable.\n${describeRange(expression)}`,
328
343
  );
329
344
  }
330
- return builtin.evaluateBinary
331
- ? builtin.evaluateBinary(left, right)
332
- : builtin.evaluate([left, right]);
345
+ return subset(left, right);
333
346
  };
334
347
 
335
348
  export const createRealNumberError = (expression: DecimalExpression) =>
@@ -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
  ),
@@ -1327,7 +1390,6 @@ const headFingerprint = (callStack: CallStack, source: Expression, error: unknow
1327
1390
 
1328
1391
  export const createTracingEnvironment = (environment: Environment): Environment => ({
1329
1392
  ...environment,
1330
- coverage: undefined,
1331
1393
  evaluators: new WeakMap(),
1332
1394
  entryEvaluators: new WeakMap(),
1333
1395
  definitionEvaluators: new WeakMap(),
@@ -1402,9 +1464,21 @@ const countEvaluator =
1402
1464
  coverage.current = node;
1403
1465
  try {
1404
1466
  const value = evaluator(context);
1405
- if (typeof value === "object" && expression.kind === "SetEnumeration") {
1406
- coverage.values.set(value, node);
1407
- }
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);
1408
1482
  return value;
1409
1483
  } finally {
1410
1484
  coverage.current = outer;
@@ -1554,6 +1628,26 @@ const compileClosureCall = (
1554
1628
  };
1555
1629
  };
1556
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
+
1557
1651
  const compileApply = (
1558
1652
  expression: Expression & { kind: "Apply" },
1559
1653
  environment: Environment,
@@ -1598,7 +1692,7 @@ const compileApply = (
1598
1692
  !contextualApplications.has(expression) && !isNonconstant(args[0], environment);
1599
1693
  const tlcEvalValues = environment.tlcEvalValues;
1600
1694
  return (context) => {
1601
- if (!isCached || context.scope !== undefined) {
1695
+ if (!isCached || !isTlcContextEmpty(context.scope)) {
1602
1696
  return global.evaluate(getLazyArguments(args, context), context);
1603
1697
  }
1604
1698
  const cached = tlcEvalValues.get(expression);
@@ -1608,11 +1702,48 @@ const compileApply = (
1608
1702
  return value;
1609
1703
  };
1610
1704
  }
1611
- if (global?.kind === "Builtin" && global.name === "\\subseteq" && args.length === 2) {
1705
+ if (
1706
+ global?.kind === "Builtin" &&
1707
+ global.name === "\\subseteq" &&
1708
+ global.evaluateBinary &&
1709
+ args.length === 2
1710
+ ) {
1612
1711
  const left = getEvaluator(args[0], environment);
1613
1712
  const right = getEvaluator(args[1], environment);
1614
- const subset = getSubsetOperator(expression, global);
1615
- return (context) => subset(left(context), right(context));
1713
+ const subset = getSubsetOperator(expression, global.evaluateBinary);
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
+ };
1616
1747
  }
1617
1748
  if (global?.kind === "Builtin") return compileBuiltinCall(global, args, environment);
1618
1749
  if (expression.operator === "\\cdot" && args.length === 2) {
@@ -1645,6 +1776,18 @@ const compileQuantifier = (
1645
1776
  const isForall = expression.kind === "Forall";
1646
1777
  const body = getEvaluator(expression.body, environment);
1647
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
+ }
1648
1791
  if (expression.bounds.length === 1 && bound.pattern.kind === "Name") {
1649
1792
  const name = bound.pattern.name;
1650
1793
  const set = getEvaluator(bound.set, environment);
@@ -1792,13 +1935,22 @@ export const getFunctionBuilder = (
1792
1935
  const template = getLazyFunctionTemplate(bounds, expression.body);
1793
1936
  const boundTupleLengths = getBoundTupleLengths(bounds);
1794
1937
  const bodyNames = getScopeNames(expression.body);
1938
+ const coverage = environment.coverage;
1795
1939
  const createLazy = (domain: Value, context: Context) => {
1796
1940
  const scope = trimScope(context.scope, bodyNames);
1797
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;
1798
1945
  const functionValue = keepLambda({
1799
1946
  value: createLazyFunction(
1800
1947
  domain,
1801
- (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,
1802
1954
  getLazyFunctionSource(template, bounds, domain),
1803
1955
  boundTupleLengths,
1804
1956
  ),
@@ -1850,6 +2002,23 @@ const compileFunctionConstruction = (
1850
2002
  ): Evaluator => {
1851
2003
  const build = getFunctionBuilder(expression, environment).build;
1852
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
+ }
1853
2022
  if (bounds.length === 1 && bounds[0].pattern.kind === "Name") {
1854
2023
  const set = getEvaluator(bounds[0].set, environment);
1855
2024
  return (context) => build(set(context), context);
@@ -1929,22 +2098,13 @@ export const getLazyFilter = (
1929
2098
  predicate: predicateNode,
1930
2099
  };
1931
2100
  const coverage = environment.coverage;
1932
- const testCovered = (node: number, isMember: boolean, test: () => Value) => {
1933
- if (!coverage || node === -1) return test();
1934
- if (!isMember) coverage.secondary[node]++;
1935
- const value = runAtCoverageNode(coverage, isMember ? -1 : node, test);
1936
- if (!isMember && value === true) coverage.secondary[node]++;
1937
- return value;
1938
- };
1939
2101
  const createFiltered = (
1940
2102
  base: Value,
1941
2103
  context: Context,
1942
2104
  evaluator: Evaluator,
1943
2105
  node: number,
1944
- ): RebindableFilteredSet => ({
1945
- kind: "FilteredSet",
1946
- base,
1947
- test: (element, isMember) => {
2106
+ ): RebindableFilteredSet => {
2107
+ const test = (element: Value, isMember: boolean) => {
1948
2108
  if (
1949
2109
  pattern.kind === "Tuple" &&
1950
2110
  getSequenceElements(element)?.length !== pattern.names.length
@@ -1953,29 +2113,60 @@ export const getLazyFilter = (
1953
2113
  `Attempted to check if the value:\n${prettyPrint(formatValue(element))}\nis an element of a set of ${pattern.names.length}-tuples.`,
1954
2114
  );
1955
2115
  }
1956
- const value = testCovered(node, isMember, () =>
1957
- evaluator(withScope(context, bindPattern(context.scope, pattern, element))),
1958
- );
2116
+ const value = evaluator(withScope(context, bindPattern(context.scope, pattern, element)));
1959
2117
  if (typeof value !== "boolean") {
1960
2118
  throw new TlaEvaluationError(
1961
2119
  `${isMember ? "The evaluation of predicate" : "Evaluating predicate"} ${predicateNode} yielded non-Boolean value.`,
1962
2120
  );
1963
2121
  }
1964
2122
  return value;
1965
- },
1966
- source,
1967
- rebind: (tracing) =>
2123
+ };
2124
+ const rebind = (tracing: Environment) =>
1968
2125
  createFiltered(
1969
2126
  base,
1970
2127
  { ...context, environment: tracing },
1971
2128
  getEvaluator(expression.predicate, tracing),
1972
2129
  -1,
1973
- ),
1974
- });
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
+ };
1975
2152
  return (base: Value, context: Context, node = -1) =>
1976
2153
  createFiltered(base, context, predicate, node);
1977
2154
  };
1978
2155
 
2156
+ const hasLocalName = (expression: Expression): boolean =>
2157
+ isLocallyResolved(expression) ||
2158
+ expression.kind === "OperatorReference" ||
2159
+ getChildren(expression).some(hasLocalName);
2160
+
2161
+ export const isUniformPredicate = (
2162
+ expression: Expression & { kind: "SetFilter" },
2163
+ environment: Environment,
2164
+ ) =>
2165
+ expression.bound.pattern.kind === "Name" &&
2166
+ !environment.coverage &&
2167
+ !hasLocalName(expression.predicate) &&
2168
+ !isExpressionImpure([expression.predicate], environment, "varying");
2169
+
1979
2170
  export const expectFilterPredicate = (
1980
2171
  value: Value,
1981
2172
  expression: Expression & { kind: "SetFilter" },
@@ -2018,32 +2209,34 @@ const compileSetComprehension = (
2018
2209
  const filterLazily = getLazyFilter(expression, environment);
2019
2210
  const pattern = expression.bound.pattern;
2020
2211
  const coverage = environment.coverage;
2212
+ const isUniform = isUniformPredicate(expression, environment);
2021
2213
  return (context) => {
2022
2214
  const base = set(context);
2023
2215
  if (!isReducibleSet(base)) return filterLazily(base, context, coverage?.current);
2024
2216
  const kept: Value[] = [];
2025
- const visit = (element: Value) => {
2217
+ const elements = base.kind === "Interval" ? base : toFiniteSet(base).elements;
2218
+ const size = Array.isArray(elements) ? elements.length : elements.high - elements.low + 1;
2219
+ for (let position = 0; position < size; position++) {
2220
+ const element = Array.isArray(elements) ? elements[position] : elements.low + position;
2026
2221
  const value = predicate(withScope(context, bindPattern(context.scope, pattern, element)));
2027
2222
  if (expectFilterPredicate(value, expression)) addBoundedElement(kept, element);
2028
- };
2029
- const elements = base.kind === "Interval" ? base : toFiniteSet(base).elements;
2030
- forEachElement(elements, visit);
2031
- if (coverage && coverage.current !== -1) {
2032
- coverage.secondary[coverage.current] +=
2033
- (Array.isArray(elements) ? elements.length : elements.high - elements.low + 1) +
2034
- kept.length;
2223
+ else if (isUniform) break;
2035
2224
  }
2225
+ if (coverage) costCoverage(coverage, base, size + 1);
2036
2226
  return createNormalizedSet(kept);
2037
2227
  };
2038
2228
  }
2039
2229
  if (expression.kind === "SetMap") {
2040
2230
  const mapped = getEvaluator(expression.expression, environment);
2231
+ const coverage = environment.coverage;
2041
2232
  return (context) => {
2042
2233
  const elements: Value[] = [];
2043
- forEachBinding(expression.bounds, context, (scope) => {
2234
+ const add = (scope: Scope | undefined) => {
2044
2235
  addBoundedElement(elements, mapped(withScope(context, scope)));
2045
2236
  return false;
2046
- });
2237
+ };
2238
+ if (coverage) forEachChargedBinding(expression.bounds, context, coverage, add);
2239
+ else forEachBinding(expression.bounds, context, add);
2047
2240
  return createEnumeratedSet(elements);
2048
2241
  };
2049
2242
  }
@@ -2057,16 +2250,15 @@ const compileSetComprehension = (
2057
2250
  }
2058
2251
  const body = getEvaluator(expression.body, environment);
2059
2252
  const evaluateSet = getEvaluator(set, environment);
2253
+ const coverage = environment.coverage;
2060
2254
  return (context) => {
2061
- const elements = getChoiceElements(
2062
- evaluateSet(context),
2063
- expression,
2064
- set,
2065
- context.environment.runtime.version,
2066
- );
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);
2067
2258
  let chosen: Value | undefined;
2068
2259
  const pattern = expression.pattern;
2069
2260
  someElement(elements, (element) => {
2261
+ enumerator?.next();
2070
2262
  if (
2071
2263
  pattern.kind === "Tuple" &&
2072
2264
  getSequenceElements(element)?.length !== pattern.names.length
@@ -2080,8 +2272,9 @@ const compileSetComprehension = (
2080
2272
  chosen = getBoundValue(pattern, scope);
2081
2273
  return true;
2082
2274
  });
2083
- if (chosen === undefined) throw createNoChoiceError(expression);
2084
- return chosen;
2275
+ if (chosen !== undefined) return chosen;
2276
+ enumerator?.next();
2277
+ throw createNoChoiceError(expression);
2085
2278
  };
2086
2279
  };
2087
2280
 
@@ -2346,6 +2539,8 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
2346
2539
  }
2347
2540
  case "Label":
2348
2541
  return getChildEvaluator(expression.body);
2542
+ case "Selection":
2543
+ return getChildEvaluator(expression.expression);
2349
2544
  case "Subexpression":
2350
2545
  return () => {
2351
2546
  throw new TlaEvaluationError(
package/src/exit-codes.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { LivenessChecker } from "./liveness-checker";
1
+ import type { LivenessChecker, LivenessChecks } from "./liveness-checker";
2
2
 
3
3
  export const EXIT_STATUS = {
4
4
  success: 0,
@@ -70,23 +70,35 @@ const withErrorExitCode = <Result>(run: () => Result) => {
70
70
  }
71
71
  };
72
72
 
73
+ const withCheckerExitCode = (checker: LivenessChecker): LivenessChecker => ({
74
+ branches: checker.branches,
75
+ solutions: checker.solutions,
76
+ addInitialState: checker.addInitialState,
77
+ addState: (index, state, successors, tracing) =>
78
+ withErrorExitCode(() => checker.addState(index, state, successors, tracing)),
79
+ storeState: checker.storeState,
80
+ getStateCounts: checker.getStateCounts,
81
+ findViolation: () => withErrorExitCode(() => checker.findViolation()),
82
+ getViolatedProperties: (path, cycleStart) =>
83
+ withErrorExitCode(() => checker.getViolatedProperties(path, cycleStart)),
84
+ });
85
+
73
86
  export const withLivenessExitCode = (
74
87
  create: () => LivenessChecker | undefined,
75
88
  ): LivenessChecker | undefined => {
76
89
  const checker = withErrorExitCode(create);
90
+ return checker && withCheckerExitCode(checker);
91
+ };
92
+
93
+ export const withLivenessChecksExitCode = (
94
+ create: () => LivenessChecks | undefined,
95
+ ): LivenessChecks | undefined => {
96
+ const checks = withErrorExitCode(create);
77
97
  return (
78
- checker && {
79
- branches: checker.branches,
80
- solutions: checker.solutions,
81
- addInitialState: (index, state, tracing) =>
82
- withErrorExitCode(() => checker.addInitialState(index, state, tracing)),
83
- addState: (index, state, successors, tracing) =>
84
- withErrorExitCode(() => checker.addState(index, state, successors, tracing)),
85
- storeState: checker.storeState,
86
- getStateCounts: checker.getStateCounts,
87
- findViolation: () => withErrorExitCode(() => checker.findViolation()),
88
- getViolatedProperties: (path, cycleStart) =>
89
- withErrorExitCode(() => checker.getViolatedProperties(path, cycleStart)),
98
+ checks && {
99
+ solutions: checks.solutions,
100
+ findTraceViolation: (trace, fingerprints) =>
101
+ withErrorExitCode(() => checks.findTraceViolation(trace, fingerprints)),
90
102
  }
91
103
  );
92
104
  };