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

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.
package/src/check.ts CHANGED
@@ -272,6 +272,11 @@ export interface Postcondition {
272
272
  counts?: string;
273
273
  }
274
274
 
275
+ export interface TraceFailure extends FailureMessage {
276
+ /** What the spec prints as TLC rebuilds the step it then fails to print. */
277
+ output: OutputLine[];
278
+ }
279
+
275
280
  /** An evaluation that failed during the search, with the behavior up to the state TLC was working on. */
276
281
  export interface EvaluationFailure {
277
282
  code: number;
@@ -288,7 +293,7 @@ export interface EvaluationFailure {
288
293
  /** The FingerprintException the replay raises, which TLC reports in place of the call stack. */
289
294
  fingerprint?: FingerprintFailure;
290
295
  /** How TLC reports failing again as it prints the trace, since it can't fingerprint the state. */
291
- traceFailure?: FailureMessage;
296
+ traceFailure?: TraceFailure;
292
297
  /** A POSTCONDITION that is false or fails after the trace, which TLC checks as it prints one. */
293
298
  postcondition?: Postcondition;
294
299
  /** Whether TLC stops before it prints the statistics, as it does for an illegal initial state. */
@@ -346,13 +351,15 @@ const toUnexpectedError = (error: TlaEvaluationError) =>
346
351
  `${isEvalException(error) ? UNEXPECTED_EVAL_EXCEPTION : UNEXPECTED_EXCEPTION}${error.message}`,
347
352
  );
348
353
 
349
- const getTraceFailure = (error: TlaEvaluationError) =>
350
- getFailureMessage(
354
+ const getTraceFailure = (error: TlaEvaluationError, output: OutputLine[]): TraceFailure => ({
355
+ ...getFailureMessage(
351
356
  isEvalException(error)
352
357
  ? new TlaEvaluationError(`${UNEXPECTED_EVAL_EXCEPTION}${error.message}`)
353
358
  : error,
354
359
  true,
355
- );
360
+ ),
361
+ output,
362
+ });
356
363
 
357
364
  const STOP_REPLAY = new Error("The replay stopped");
358
365
  const STOP_WALK = new Error("The walk stopped");
@@ -623,6 +630,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
623
630
  onState(successor);
624
631
  },
625
632
  (partial) => {
633
+ if (coverage) coverage.primary[action.node]++;
626
634
  const missing = environment.variables.filter(
627
635
  (_variable, index) => partial[index] === undefined,
628
636
  );
@@ -634,6 +642,23 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
634
642
  );
635
643
  },
636
644
  );
645
+ const hasCoveredIncompleteSuccessor = (action: CoveredAction, state: Value[]) => {
646
+ let complete = 0;
647
+ let incomplete = 0;
648
+ walkSuccessors(
649
+ action,
650
+ action.node,
651
+ state,
652
+ environment,
653
+ () => complete++,
654
+ () => {
655
+ incomplete++;
656
+ return true;
657
+ },
658
+ );
659
+ if (coverage) coverage.primary[action.node] += complete + incomplete;
660
+ return incomplete > 0;
661
+ };
637
662
  const getCoveredSuccessors = (action: CoveredAction, state: Value[]) => {
638
663
  const successors: Successor[] = [];
639
664
  walkCoveredSuccessors(action, state, (successor) =>
@@ -686,7 +711,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
686
711
  const deferred: unknown[] = [];
687
712
  const addReplayed = createReplayedStates();
688
713
  return getReplayFailure(environment, (tracing) => {
689
- replayInitialStates(getDescription().inits, tracing, (state) => {
714
+ replayInitialStates(coverage ? coverageInits : getDescription().inits, tracing, (state) => {
690
715
  reportInitialStatesProgress(replayedCount, (progress) => capturedLines?.push(progress));
691
716
  replayedCount++;
692
717
  runtime.generatedStates = replayedCount;
@@ -723,7 +748,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
723
748
  const state = states[index];
724
749
  const source = stateWriter && getGraphState(state, depths[index]);
725
750
  const addReplayed = createReplayedStates();
726
- replaySuccessors(nextActions, state, tracing, (next, action) => {
751
+ replaySuccessors(coverage ? coverageActions : nextActions, state, tracing, (next, action) => {
727
752
  const addFingerprint = () => {
728
753
  const isUnseen = addReplayed(next, tracing.callStack);
729
754
  if (source) {
@@ -834,10 +859,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
834
859
  const canonicalizeState = createCanonicalizer();
835
860
 
836
861
  const toRecord = search.toRecord;
837
- const getSpecInitialStates = () => {
838
- if (coverage) return getCoveredInitialStates();
839
- return spec.init === undefined ? [] : getInitialStates(spec.init, environment, spec.scope);
840
- };
862
+ const getUncoveredInitialStates = () =>
863
+ spec.init === undefined ? [] : getInitialStates(spec.init, environment, spec.scope);
864
+ const getSpecInitialStates = () =>
865
+ coverage ? getCoveredInitialStates() : getUncoveredInitialStates();
841
866
  const isUnfingerprintable = (state: Value[]) => {
842
867
  try {
843
868
  return getFingerprintState(state).some((value) => getFingerprintError(value) !== undefined);
@@ -846,19 +871,27 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
846
871
  return true;
847
872
  }
848
873
  };
874
+ const checkFailedTrace = (behavior: Behavior, counterExample?: CounterExampleOptions) => {
875
+ if (!counterExample) return { behavior, postcondition: undefined };
876
+ const checked = checkTracePostconditions(
877
+ behavior.trace,
878
+ undefined,
879
+ getStepAlias,
880
+ counterExample.isConsole,
881
+ );
882
+ return {
883
+ behavior: appendTraceOutput(behavior, checked.lines),
884
+ postcondition: checked.unwitnessed ?? checked.postcondition,
885
+ };
886
+ };
849
887
  const createFailureResult = (
850
888
  failed: unknown,
851
889
  behavior: Behavior,
852
890
  failureOptions: FailureOptions = {},
853
- counterExample?: CounterExampleOptions,
891
+ postcondition?: Postcondition,
854
892
  ) => {
855
893
  const error = isStackOverflow(failed) ? new TlaStackOverflowError() : failed;
856
894
  if (!(error instanceof TlaEvaluationError)) throw error;
857
- const checked =
858
- counterExample &&
859
- checkTracePostconditions(behavior.trace, undefined, getStepAlias, counterExample.isConsole);
860
- const postcondition = checked?.unwitnessed ?? checked?.postcondition;
861
- const traceOutput = [...(behavior.traceOutput ?? []), ...(checked?.lines ?? [])];
862
895
  return {
863
896
  ...createResult("error", undefined, {
864
897
  ...getFailureMessage(
@@ -866,7 +899,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
866
899
  failureOptions.phase !== undefined && failureOptions.phase !== "initial",
867
900
  ),
868
901
  ...behavior,
869
- ...(traceOutput.length > 0 && { traceOutput }),
870
902
  ...(postcondition && { postcondition }),
871
903
  initialState:
872
904
  failureOptions.initialState && !(error instanceof TlaModuleError)
@@ -891,18 +923,20 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
891
923
  const found = captureOutput(() => {
892
924
  try {
893
925
  return {
894
- action: nextActions.find((item) =>
895
- hasIncompleteSuccessor(item.expression, states[index], environment, item.scope),
896
- ),
897
- traceFailure: undefined,
926
+ action: coverage
927
+ ? coverageActions.find((item) => hasCoveredIncompleteSuccessor(item, states[index]))
928
+ : nextActions.find((item) =>
929
+ hasIncompleteSuccessor(item.expression, states[index], environment, item.scope),
930
+ ),
931
+ failed: undefined,
898
932
  };
899
933
  } catch (failed) {
900
934
  if (!(failed instanceof TlaEvaluationError)) throw failed;
901
- return { action: undefined, traceFailure: getTraceFailure(failed) };
935
+ return { action: undefined, failed };
902
936
  }
903
937
  });
904
938
  const action = found.result.action;
905
- const traceFailure = found.result.traceFailure;
939
+ const traceFailure = found.result.failed && getTraceFailure(found.result.failed, found.lines);
906
940
  const message = getIncompleteSuccessorMessage(
907
941
  error.variables,
908
942
  error.action,
@@ -910,9 +944,8 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
910
944
  options.version,
911
945
  );
912
946
  const live = captureOutput(() => addFailedLiveState(index, liveSuccessors));
913
- const trace = traces.getStateTrace(index, error.state).trace;
914
- const failure = createFailureResult(
915
- error,
947
+ const trace = traces.getStateTrace(index, { incomplete: error.state, isFailed: true }).trace;
948
+ const checked = checkFailedTrace(
916
949
  appendTraceOutput(
917
950
  {
918
951
  trace: traceFailure
@@ -933,9 +966,14 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
933
966
  },
934
967
  live.lines,
935
968
  ),
936
- { callStack: live.result, traceFailure },
937
969
  { isConsole: true },
938
970
  );
971
+ const failure = createFailureResult(
972
+ error,
973
+ checked.behavior,
974
+ { callStack: live.result, traceFailure },
975
+ checked.postcondition,
976
+ );
939
977
  return withOutDegrees({
940
978
  ...failure,
941
979
  failure: failure.failure && {
@@ -996,6 +1034,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
996
1034
  tracedSteps,
997
1035
  captureOutput,
998
1036
  getInitialStates: getSpecInitialStates,
1037
+ getUncoveredInitialStates,
999
1038
  findSuccessorAction,
1000
1039
  });
1001
1040
  const getPath = (index: number): Value[][] =>
@@ -1059,14 +1098,15 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1059
1098
  });
1060
1099
 
1061
1100
  const visitInitialState = (state: Value[]) => {
1062
- canonicalizeState(state);
1063
1101
  runtime.generatedStates++;
1064
1102
  runtime.initialStates++;
1065
1103
  current.candidate = state;
1066
1104
  current.candidateLevel = 1;
1067
- const fingerprintState = getFingerprintState(state);
1068
- const hash = getStateHash(fingerprintState);
1069
1105
  const isInModel = search.satisfiesConstraints(state);
1106
+ // TLC fingerprints only a state in the model, which sorts its records in place.
1107
+ if (isInModel) canonicalizeState(state);
1108
+ const fingerprintState = isInModel ? getFingerprintState(state) : state;
1109
+ const hash = isInModel ? getStateHash(fingerprintState) : 0;
1070
1110
  if (isInModel) {
1071
1111
  search.trackStatePossible(state);
1072
1112
  fingerprintModelState(fingerprintState);
@@ -1113,18 +1153,17 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1113
1153
  // Looks a successor up, where the constraints keep it in the model, as the search does before it
1114
1154
  // checks the successor.
1115
1155
  const lookUpSuccessor = (state: Value[], successor: Successor) => {
1116
- const fingerprintState = getFingerprintState(successor.state);
1117
- const hash = getStateHash(fingerprintState);
1118
- const foundIndex = findStateIndex(seenStates, hash, fingerprintState);
1119
1156
  const isStateInModel = search.satisfiesConstraints(successor.state, state);
1120
1157
  if (isStateInModel) search.trackStatePossible(successor.state);
1121
1158
  const isInModel = isStateInModel && search.satisfiesActionConstraints(state, successor.state);
1159
+ const fingerprintState = isInModel ? getFingerprintState(successor.state) : successor.state;
1160
+ const hash = isInModel ? getStateHash(fingerprintState) : 0;
1122
1161
  if (isInModel) {
1123
1162
  search.trackActionPossible(state, successor.state);
1124
1163
  fingerprintModelState(fingerprintState);
1125
1164
  successor.state.forEach(markFingerprinted);
1126
1165
  }
1127
- const existing = isInModel ? foundIndex : -1;
1166
+ const existing = isInModel ? findStateIndex(seenStates, hash, fingerprintState) : -1;
1128
1167
  return {
1129
1168
  fingerprintState,
1130
1169
  hash,
@@ -1196,10 +1235,11 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1196
1235
  if (violation) reportContinuedViolation("invariant-violation", violation);
1197
1236
  } catch (error) {
1198
1237
  if (isStackOverflow(error)) throw error;
1238
+ const behavior = traces.getTrace(index, successor, { isFailed: true });
1199
1239
  const replay = captureOutput(() => replayNext(index));
1200
1240
  return createFailureResult(
1201
1241
  error,
1202
- appendTraceOutput(traces.getFailedTrace(index, successor), replay.lines),
1242
+ appendTraceOutput(behavior, replay.lines),
1203
1243
  replay.result ?? { outDegrees: getFailureOutDegrees() },
1204
1244
  );
1205
1245
  }
@@ -1464,19 +1504,21 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1464
1504
  return { result, lines: live.lines };
1465
1505
  }
1466
1506
  const replay = captureOutput(() => replayNext(index));
1467
- return { result: replay.result, lines: [...live.lines, ...replay.lines] };
1468
- };
1469
- const getNextFailureTrace = (index: number, counterExample?: CounterExampleOptions) => {
1470
- const behavior = traces.getStateTrace(index);
1471
- return counterExample ? behavior : { trace: behavior.trace };
1507
+ const result: FailureOptions =
1508
+ replay.result ?? (is174 ? {} : { outDegrees: getFailureOutDegrees() });
1509
+ return { result, lines: [...live.lines, ...replay.lines] };
1472
1510
  };
1473
- const reportNextStateOverflow = (index: number, counterExample?: CounterExampleOptions) =>
1474
- createFailureResult(
1511
+ const getNextFailureTrace = (index: number, counterExample?: CounterExampleOptions) =>
1512
+ checkFailedTrace(traces.getStateTrace(index, { isFailed: !counterExample }), counterExample);
1513
+ const reportNextStateOverflow = (index: number, counterExample?: CounterExampleOptions) => {
1514
+ const checked = getNextFailureTrace(index, counterExample);
1515
+ return createFailureResult(
1475
1516
  createStackOverflowError(),
1476
- getNextFailureTrace(index, counterExample),
1517
+ checked.behavior,
1477
1518
  { phase: "next" },
1478
- counterExample,
1519
+ checked.postcondition,
1479
1520
  );
1521
+ };
1480
1522
  // Deviation from TLC: under -continue, TLC's Worker reports a state whose next-state relation failed as deadlocked, or else reports the failure twice as its replay fails again.
1481
1523
  const reportNextStateFailure = (
1482
1524
  error: unknown,
@@ -1490,12 +1532,13 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1490
1532
  ? { isConsole: false }
1491
1533
  : undefined;
1492
1534
  if (isStackOverflow(error)) return reportNextStateOverflow(index, counterExample);
1535
+ const checked = getNextFailureTrace(index, counterExample);
1493
1536
  const replay = replayFailedNext(index, liveSuccessors);
1494
1537
  return createFailureResult(
1495
1538
  withNextStateExitCode(error),
1496
- appendTraceOutput(getNextFailureTrace(index, counterExample), replay.lines),
1539
+ appendTraceOutput(checked.behavior, replay.lines),
1497
1540
  { phase: "next", ...replay.result },
1498
- counterExample,
1541
+ checked.postcondition,
1499
1542
  );
1500
1543
  };
1501
1544
  const addLiveState = (
@@ -1563,10 +1606,8 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1563
1606
  outcome = reportNextStateOverflow(index);
1564
1607
  return true;
1565
1608
  }
1566
- const replay = is174
1567
- ? captureOutput(() => replayNext(index))
1568
- : replayFailedNext(index, liveSuccessors);
1569
1609
  if (is174 && error instanceof TlaEvaluationError && !isHeadedError(error)) {
1610
+ const replay = captureOutput(() => replayNext(index));
1570
1611
  outcome = createFailureResult(
1571
1612
  new TlaEvaluationError(`${getWrappedException(error)}${error.message}`, error),
1572
1613
  appendTraceOutput({ trace: [] }, replay.lines),
@@ -1574,17 +1615,33 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1574
1615
  );
1575
1616
  return true;
1576
1617
  }
1577
- const isTraceFailed = isUnfingerprintable(successor.state);
1618
+ const traceError =
1619
+ error instanceof TlaEvaluationError && isUnfingerprintable(successor.state)
1620
+ ? error
1621
+ : undefined;
1622
+ const behavior = traceError
1623
+ ? traces.getStateTrace(index, { isFailed: true })
1624
+ : traces.getTrace(index, successor, { isFailed: true });
1578
1625
  const traceFailure =
1579
- isTraceFailed && error instanceof TlaEvaluationError ? getTraceFailure(error) : undefined;
1580
- outcome = createFailureResult(
1581
- error,
1582
- appendTraceOutput(
1583
- traceFailure ? traces.getStateTrace(index) : traces.getFailedTrace(index, successor),
1584
- replay.lines,
1585
- ),
1586
- { phase: "next", ...replay.result, traceFailure },
1587
- );
1626
+ traceError &&
1627
+ getTraceFailure(
1628
+ traceError,
1629
+ captureOutput(() => {
1630
+ try {
1631
+ traces.findStepAction(index, state, successor.state, true);
1632
+ } catch (failed) {
1633
+ if (!(failed instanceof TlaEvaluationError)) throw failed;
1634
+ }
1635
+ }).lines,
1636
+ );
1637
+ const replay = is174
1638
+ ? captureOutput(() => replayNext(index))
1639
+ : replayFailedNext(index, liveSuccessors);
1640
+ outcome = createFailureResult(error, appendTraceOutput(behavior, replay.lines), {
1641
+ phase: "next",
1642
+ ...replay.result,
1643
+ traceFailure,
1644
+ });
1588
1645
  }
1589
1646
  return outcome !== undefined;
1590
1647
  });
@@ -1632,7 +1689,9 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1632
1689
  const replay = getReplayFailure(environment, (tracing) =>
1633
1690
  liveness?.addState(index, state, liveSuccessors, tracing),
1634
1691
  );
1635
- return createFailureResult(error, traces.getStateTrace(index), {
1692
+ const behavior = traces.getStateTrace(index, { isFailed: true });
1693
+ const replayed = captureOutput(() => replayNext(index));
1694
+ return createFailureResult(error, appendTraceOutput(behavior, replayed.lines), {
1636
1695
  outDegrees: getFailureOutDegrees(),
1637
1696
  callStack: replay?.callStack.length ? replay.callStack : undefined,
1638
1697
  phase: "liveness",
@@ -548,6 +548,7 @@ export const printResult = (result: CheckResult, printer: MessagePrinter, timing
548
548
  printTrace(printer, failure.trace, "error-trace");
549
549
  const traceFailure = failure.traceFailure;
550
550
  if (traceFailure) {
551
+ printTraceOutput(printer, traceFailure.output);
551
552
  print(
552
553
  traceFailure.code,
553
554
  MESSAGE_LEVEL.error,
package/src/codegen.ts CHANGED
@@ -14,6 +14,7 @@ import {
14
14
  getFunctionBuilder,
15
15
  getLazyFilter,
16
16
  isKeptLazy,
17
+ isUniformPredicate,
17
18
  getDomainOperator,
18
19
  getSubsetOperator,
19
20
  getEvaluator,
@@ -279,7 +280,8 @@ const generateSetFilter = (
279
280
  const lazy = `if (!isReducible(${base})) return ${filterLazily}(${base}, ${getDelegateContext(generator, expression, bodyFrame)});`;
280
281
  const set = generateExpression(generator, expression.bound.set, bodyFrame);
281
282
  bodyFrame.locals.set(name, element);
282
- const test = `if (filterPredicate(${generateExpression(generator, expression.predicate, bodyFrame)}, ${node})) addBounded(${kept}, ${element});`;
283
+ const stop = isUniformPredicate(expression, generator.environment) ? " else break;" : "";
284
+ const test = `if (filterPredicate(${generateExpression(generator, expression.predicate, bodyFrame)}, ${node})) addBounded(${kept}, ${element});${stop}`;
283
285
  return `const ${base} = ${set}; ${lazy} const ${list} = ${base}.kind === "Interval" ? ${base} : finiteElements(${base}); const ${kept} = []; ${generateLoop(generator, list, element, test)} return normalizedSet(${kept});`;
284
286
  });
285
287
 
@@ -332,8 +334,8 @@ const generateApply = (
332
334
  }
333
335
  // TLC caches a constant TLCEval only where no name is bound, so the delegate sees every local.
334
336
  if (builtin.name === "TLCEval") return generateDelegate(generator, expression, frame, true);
335
- if (builtin.name === "\\subseteq" && args.length === 2) {
336
- const subset = addReference(generator, getSubsetOperator(expression, builtin));
337
+ if (builtin.name === "\\subseteq" && builtin.evaluateBinary && args.length === 2) {
338
+ const subset = addReference(generator, getSubsetOperator(expression, builtin.evaluateBinary));
337
339
  return `${subset}(${generateExpression(generator, args[0], frame)}, ${generateExpression(generator, args[1], frame)})`;
338
340
  }
339
341
  const environment = generator.environment;
@@ -156,11 +156,11 @@ const collectLocalFacts = (
156
156
  definition.params.length > 0),
157
157
  });
158
158
  } else {
159
- if (isImpureBuiltin(name, environment)) {
160
- row[0] |= IMPURE | (name === "Assert" ? 0 : REPEATED_EFFECT);
159
+ if (isImpureBuiltin(target, environment)) {
160
+ row[0] |= IMPURE | (target === "Assert" ? 0 : REPEATED_EFFECT);
161
161
  }
162
- if (STREAMED_BUILTINS.has(name)) row[0] |= STREAMED;
163
- if (RANDOM_BUILTINS.has(name)) row[0] |= RANDOM;
162
+ if (STREAMED_BUILTINS.has(target)) row[0] |= STREAMED;
163
+ if (RANDOM_BUILTINS.has(target)) row[0] |= RANDOM;
164
164
  if (!isOverridden && isImpureBuiltin(target, environment)) row[0] |= READS_IMPURE;
165
165
  const builtin = environment.builtins.get(target);
166
166
  if (
@@ -348,6 +348,7 @@ const EFFECT_FLAGS = {
348
348
  streamed: STREAMED,
349
349
  // What a second evaluation shows: output again, or other random draws.
350
350
  replayed: REPEATED_EFFECT | RANDOM,
351
+ varying: IMPURE | RANDOM,
351
352
  };
352
353
 
353
354
  export const isExpressionImpure = (
package/src/evaluate.ts CHANGED
@@ -27,6 +27,7 @@ import { MESSAGE_CODE } from "./tlc/messages";
27
27
  import type { CheckerRuntime } from "./runtime";
28
28
  import {
29
29
  isEvaluatedAtStartup,
30
+ isExpressionImpure,
30
31
  isImpureDefinition,
31
32
  isNonconstant,
32
33
  type DefinitionFacts,
@@ -321,15 +322,14 @@ export const getDomainOperator = (expression: Expression) => (value: Value) => {
321
322
  };
322
323
 
323
324
  export const getSubsetOperator =
324
- (expression: Expression, builtin: Builtin) => (left: Value, right: Value) => {
325
+ (expression: Expression, subset: (left: Value, right: Value) => Value) =>
326
+ (left: Value, right: Value) => {
325
327
  if (!isSetValue(left) || isOverriddenSet(left)) {
326
328
  throw new TlaEvaluationError(
327
329
  `Attempted to evaluate an expression of form S \\subseteq T, but S was not enumerable.\n${describeRange(expression)}`,
328
330
  );
329
331
  }
330
- return builtin.evaluateBinary
331
- ? builtin.evaluateBinary(left, right)
332
- : builtin.evaluate([left, right]);
332
+ return subset(left, right);
333
333
  };
334
334
 
335
335
  export const createRealNumberError = (expression: DecimalExpression) =>
@@ -1327,7 +1327,6 @@ const headFingerprint = (callStack: CallStack, source: Expression, error: unknow
1327
1327
 
1328
1328
  export const createTracingEnvironment = (environment: Environment): Environment => ({
1329
1329
  ...environment,
1330
- coverage: undefined,
1331
1330
  evaluators: new WeakMap(),
1332
1331
  entryEvaluators: new WeakMap(),
1333
1332
  definitionEvaluators: new WeakMap(),
@@ -1608,10 +1607,15 @@ const compileApply = (
1608
1607
  return value;
1609
1608
  };
1610
1609
  }
1611
- if (global?.kind === "Builtin" && global.name === "\\subseteq" && args.length === 2) {
1610
+ if (
1611
+ global?.kind === "Builtin" &&
1612
+ global.name === "\\subseteq" &&
1613
+ global.evaluateBinary &&
1614
+ args.length === 2
1615
+ ) {
1612
1616
  const left = getEvaluator(args[0], environment);
1613
1617
  const right = getEvaluator(args[1], environment);
1614
- const subset = getSubsetOperator(expression, global);
1618
+ const subset = getSubsetOperator(expression, global.evaluateBinary);
1615
1619
  return (context) => subset(left(context), right(context));
1616
1620
  }
1617
1621
  if (global?.kind === "Builtin") return compileBuiltinCall(global, args, environment);
@@ -1976,6 +1980,20 @@ export const getLazyFilter = (
1976
1980
  createFiltered(base, context, predicate, node);
1977
1981
  };
1978
1982
 
1983
+ const hasLocalName = (expression: Expression): boolean =>
1984
+ isLocallyResolved(expression) ||
1985
+ expression.kind === "OperatorReference" ||
1986
+ getChildren(expression).some(hasLocalName);
1987
+
1988
+ export const isUniformPredicate = (
1989
+ expression: Expression & { kind: "SetFilter" },
1990
+ environment: Environment,
1991
+ ) =>
1992
+ expression.bound.pattern.kind === "Name" &&
1993
+ !environment.coverage &&
1994
+ !hasLocalName(expression.predicate) &&
1995
+ !isExpressionImpure([expression.predicate], environment, "varying");
1996
+
1979
1997
  export const expectFilterPredicate = (
1980
1998
  value: Value,
1981
1999
  expression: Expression & { kind: "SetFilter" },
@@ -2018,20 +2036,21 @@ const compileSetComprehension = (
2018
2036
  const filterLazily = getLazyFilter(expression, environment);
2019
2037
  const pattern = expression.bound.pattern;
2020
2038
  const coverage = environment.coverage;
2039
+ const isUniform = isUniformPredicate(expression, environment);
2021
2040
  return (context) => {
2022
2041
  const base = set(context);
2023
2042
  if (!isReducibleSet(base)) return filterLazily(base, context, coverage?.current);
2024
2043
  const kept: Value[] = [];
2025
- const visit = (element: Value) => {
2044
+ const elements = base.kind === "Interval" ? base : toFiniteSet(base).elements;
2045
+ const size = Array.isArray(elements) ? elements.length : elements.high - elements.low + 1;
2046
+ for (let position = 0; position < size; position++) {
2047
+ const element = Array.isArray(elements) ? elements[position] : elements.low + position;
2026
2048
  const value = predicate(withScope(context, bindPattern(context.scope, pattern, element)));
2027
2049
  if (expectFilterPredicate(value, expression)) addBoundedElement(kept, element);
2028
- };
2029
- const elements = base.kind === "Interval" ? base : toFiniteSet(base).elements;
2030
- forEachElement(elements, visit);
2050
+ else if (isUniform) break;
2051
+ }
2031
2052
  if (coverage && coverage.current !== -1) {
2032
- coverage.secondary[coverage.current] +=
2033
- (Array.isArray(elements) ? elements.length : elements.high - elements.low + 1) +
2034
- kept.length;
2053
+ coverage.secondary[coverage.current] += size + kept.length;
2035
2054
  }
2036
2055
  return createNormalizedSet(kept);
2037
2056
  };
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,36 @@ 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: (index, state, tracing) =>
77
+ withErrorExitCode(() => checker.addInitialState(index, state, tracing)),
78
+ addState: (index, state, successors, tracing) =>
79
+ withErrorExitCode(() => checker.addState(index, state, successors, tracing)),
80
+ storeState: checker.storeState,
81
+ getStateCounts: checker.getStateCounts,
82
+ findViolation: () => withErrorExitCode(() => checker.findViolation()),
83
+ getViolatedProperties: (path, cycleStart) =>
84
+ withErrorExitCode(() => checker.getViolatedProperties(path, cycleStart)),
85
+ });
86
+
73
87
  export const withLivenessExitCode = (
74
88
  create: () => LivenessChecker | undefined,
75
89
  ): LivenessChecker | undefined => {
76
90
  const checker = withErrorExitCode(create);
91
+ return checker && withCheckerExitCode(checker);
92
+ };
93
+
94
+ export const withLivenessChecksExitCode = (
95
+ create: () => LivenessChecks | undefined,
96
+ ): LivenessChecks | undefined => {
97
+ const checks = withErrorExitCode(create);
77
98
  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)),
99
+ checks && {
100
+ solutions: checks.solutions,
101
+ createChecker: (search, solutions) =>
102
+ withCheckerExitCode(checks.createChecker(search, solutions)),
90
103
  }
91
104
  );
92
105
  };