tla-ts 0.0.8-dev.d9bffda → 0.0.9-dev.0dd11f695

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 (119) hide show
  1. package/README.md +30 -0
  2. package/dist/compile.cjs +23 -0
  3. package/dist/compile.js +23 -0
  4. package/dist/deciders.cjs +15 -15
  5. package/dist/deciders.js +40 -40
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +80 -10
  8. package/dist/index.d.ts +80 -10
  9. package/dist/index.js +1 -1
  10. package/dist/parallel-worker.cjs +1 -1
  11. package/dist/parallel-worker.js +1 -1
  12. package/dist/prove-worker.cjs +1 -1
  13. package/dist/prove-worker.js +1 -1
  14. package/dist/prove.cjs +116 -36
  15. package/dist/prove.js +116 -36
  16. package/dist/run.cjs +143 -31
  17. package/dist/run.js +143 -31
  18. package/dist/tlapm.cjs +2 -2
  19. package/dist/tlapm.js +1 -1
  20. package/dist/transfer.cjs +128 -103
  21. package/dist/transfer.js +128 -103
  22. package/dist/worker.cjs +7 -7
  23. package/dist/worker.js +7 -7
  24. package/package.json +3 -1
  25. package/src/ast.ts +7 -21
  26. package/src/bags.ts +99 -99
  27. package/src/builtins.ts +44 -75
  28. package/src/bundled-modules.ts +1 -8
  29. package/src/check.ts +605 -311
  30. package/src/cli/options.ts +12 -3
  31. package/src/cli/run.ts +2 -2
  32. package/src/cli/runtime-invariants.ts +135 -0
  33. package/src/cli/shared.ts +20 -9
  34. package/src/cli/tlc-arguments.ts +646 -0
  35. package/src/cli/tlc-usage.ts +362 -0
  36. package/src/cli/tlc.ts +571 -185
  37. package/src/cli/typescript.ts +26 -0
  38. package/src/cli/xml-exporter.ts +4 -10
  39. package/src/codegen.ts +190 -46
  40. package/src/config.ts +101 -68
  41. package/src/coverage.ts +855 -0
  42. package/src/dependencies.ts +20 -28
  43. package/src/dfid.ts +636 -0
  44. package/src/environment.ts +266 -98
  45. package/src/errors.ts +142 -45
  46. package/src/evaluate.ts +632 -298
  47. package/src/exit-codes.ts +37 -1
  48. package/src/index.ts +3 -0
  49. package/src/instances.ts +85 -9
  50. package/src/java-overrides.ts +2 -12
  51. package/src/json-reader.ts +456 -0
  52. package/src/json.ts +262 -139
  53. package/src/levels.ts +2 -3
  54. package/src/lexer.ts +17 -26
  55. package/src/liveness-checker.ts +10 -18
  56. package/src/liveness.ts +121 -49
  57. package/src/parallel-worker.ts +14 -10
  58. package/src/parallel.ts +41 -17
  59. package/src/parser.ts +436 -90
  60. package/src/pcal/ast.ts +7 -28
  61. package/src/pcal/parse.ts +11 -39
  62. package/src/pcal/tokenize.ts +4 -20
  63. package/src/pcal/translate.ts +10 -42
  64. package/src/pcal/validate.ts +3 -21
  65. package/src/pretty-print.ts +1 -2
  66. package/src/prover/smt/solver/solver.ts +31 -27
  67. package/src/randomization.ts +84 -35
  68. package/src/resolve.ts +18 -60
  69. package/src/runtime.ts +11 -4
  70. package/src/sany/builtins.ts +3 -4
  71. package/src/sany/generator.ts +128 -176
  72. package/src/sany/levels.ts +6 -30
  73. package/src/sany/lexer.ts +7 -23
  74. package/src/sany/linter.ts +31 -29
  75. package/src/sany/modules.ts +1 -5
  76. package/src/sany/nodes.ts +4 -28
  77. package/src/sany/parse-error.ts +44 -100
  78. package/src/sany/report.ts +25 -40
  79. package/src/sany/selectors.ts +8 -22
  80. package/src/sany/source.ts +8 -15
  81. package/src/sany/xml.ts +11 -42
  82. package/src/search.ts +547 -144
  83. package/src/simulate.ts +694 -0
  84. package/src/spec-description.ts +166 -48
  85. package/src/standard-definitions.ts +2 -3
  86. package/src/standard-modules.ts +264 -68
  87. package/src/state-graph.ts +51 -18
  88. package/src/subexpressions.ts +31 -5
  89. package/src/successors.ts +267 -77
  90. package/src/symmetry.ts +31 -8
  91. package/src/tableau.ts +1 -2
  92. package/src/tlc/fingerprint.ts +183 -61
  93. package/src/tlc/jar-data.ts +113 -6
  94. package/src/tlc/messages.ts +122 -37
  95. package/src/tlc/order.ts +33 -38
  96. package/src/tlc/random.ts +16 -16
  97. package/src/tlc/replay.ts +563 -211
  98. package/src/tlc/summary.ts +2 -4
  99. package/src/tlc/tlc-operators.ts +81 -36
  100. package/src/tlc/tlcext-operators.ts +138 -117
  101. package/src/tlc/trace-spec.ts +273 -0
  102. package/src/tlc/value-stream.ts +143 -0
  103. package/src/tlc/version.ts +2 -4
  104. package/src/typescript/actions.ts +494 -0
  105. package/src/typescript/collections.ts +615 -0
  106. package/src/typescript/compile.ts +70 -0
  107. package/src/typescript/context.ts +106 -0
  108. package/src/typescript/emit.ts +122 -0
  109. package/src/typescript/expressions.ts +508 -0
  110. package/src/typescript/formula.ts +160 -0
  111. package/src/typescript/functions.ts +295 -0
  112. package/src/typescript/model.ts +164 -0
  113. package/src/typescript/names.ts +116 -0
  114. package/src/typescript/program.ts +51 -0
  115. package/src/typescript/properties.ts +148 -0
  116. package/src/typescript/scope.ts +117 -0
  117. package/src/typescript/steps.ts +175 -0
  118. package/src/typescript/types.ts +178 -0
  119. package/src/values.ts +832 -255
package/src/search.ts CHANGED
@@ -10,11 +10,20 @@ import type {
10
10
  CheckOptions,
11
11
  InitialStatesProgress,
12
12
  InitialStateViolation,
13
+ ModuleOperator,
13
14
  Postcondition,
14
15
  Violation,
15
16
  } from "./check";
16
- import type { ConfigValue, ModelConfig } from "./config";
17
+ import { parseConfig, type ConfigValue, type ModelConfig } from "./config";
18
+ import {
19
+ addCoverageRelation,
20
+ getCoverageLabel,
21
+ runAtCoverageNode,
22
+ type Coverage,
23
+ type CoverageKind,
24
+ } from "./coverage";
17
25
  import { getReadVariables, isConstantLevel } from "./dependencies";
26
+ import { createEnvironment, type ResolvedModuleOperator } from "./environment";
18
27
  import {
19
28
  isStackOverflow,
20
29
  TlaConfigError,
@@ -29,6 +38,7 @@ import {
29
38
  evaluateStartupDefinitions,
30
39
  getStartupValue,
31
40
  expectBoolean,
41
+ expectBooleanBody,
32
42
  formatRange,
33
43
  getDefinition,
34
44
  type Context,
@@ -47,10 +57,30 @@ import {
47
57
  import { expandTemporal, getLevel, type ScopedExpression, type TemporalProperty } from "./liveness";
48
58
  import { prettyPrint } from "./pretty-print";
49
59
  import { getPossibleCounts, type CheckerRuntime } from "./runtime";
60
+ import { getSpecificationValue, getSubscriptVariables } from "./spec-description";
50
61
  import { getRepresentative, getSymmetryGroup } from "./symmetry";
51
- import { MESSAGE_CODE, MISSING_INIT_174, withHeadline } from "./tlc/messages";
52
- import { getTlcFingerprint, getTlcFingerprints } from "./tlc/fingerprint";
53
- import { formatValue, isUpdatedElementOf, type Value } from "./values";
62
+ import {
63
+ formatInnerMessage,
64
+ formatNestedMessage,
65
+ MESSAGE_CODE,
66
+ MISSING_INIT_174,
67
+ withHeadline,
68
+ } from "./tlc/messages";
69
+ import { createTlcOrder } from "./tlc/order";
70
+ import { getTlcFingerprint, getTlcFingerprints, setFingerprintPolynomial } from "./tlc/fingerprint";
71
+ import type { TlcVersion } from "./tlc/version";
72
+ import {
73
+ formatValue,
74
+ getWrittenPairs,
75
+ isFunctionValue,
76
+ isUpdatedElementOf,
77
+ setAliasName,
78
+ setStringOrder,
79
+ setValueOptions,
80
+ setViewText,
81
+ toFiniteFunction,
82
+ type Value,
83
+ } from "./values";
54
84
 
55
85
  interface NamedExpression {
56
86
  name: string;
@@ -58,10 +88,16 @@ interface NamedExpression {
58
88
  scope: Scope | undefined;
59
89
  }
60
90
 
91
+ interface CoveredCheck {
92
+ expression: Expression;
93
+ scope: Scope | undefined;
94
+ node: number;
95
+ }
96
+
61
97
  interface StateCheck extends NamedExpression {
62
98
  variables: number[] | undefined;
63
99
  membership: Membership | undefined;
64
- // The whole predicate that TLC evaluates for the check, of which the expression is a conjunct.
100
+ // The whole predicate TLC evaluates, of which the expression is a conjunct.
65
101
  predicate: Expression;
66
102
  }
67
103
 
@@ -84,6 +120,8 @@ interface Specification {
84
120
  next: Expression | undefined;
85
121
  scope: Scope | undefined;
86
122
  temporals: ScopedExpression[];
123
+ // Whether TLC takes every temporal formula of the spec for a part of its only property.
124
+ isPropertyFairness: boolean;
87
125
  }
88
126
 
89
127
  interface Properties {
@@ -121,11 +159,14 @@ const getConfigOperator = (kind: string, name: string, environment: Environment)
121
159
  return definition;
122
160
  };
123
161
 
124
- // TLC evaluates every constant definition before it reads the configuration. It keeps a literal
125
- // number or string, and a definition that fails to evaluate, as an operator.
162
+ const isLiteralDefinition = (definition: Definition) =>
163
+ definition.body.kind === "Number" || definition.body.kind === "String";
164
+
165
+ // TLC keeps a literal number or string, and a definition that fails to evaluate, as an operator.
126
166
  const getConstantValue = (name: string, definition: Definition, environment: Environment) => {
127
- if (!isConstantLevel(definition, environment)) return undefined;
128
- if (definition.body.kind === "Number" || definition.body.kind === "String") return undefined;
167
+ if (environment.constants.has(name)) return environment.constants.get(name);
168
+ if (!isConstantLevel(definition, environment) || isLiteralDefinition(definition))
169
+ return undefined;
129
170
  try {
130
171
  return evaluate(createIdentifier(name), getContext(environment, undefined, undefined));
131
172
  } catch (error) {
@@ -137,6 +178,9 @@ const getConstantValue = (name: string, definition: Definition, environment: Env
137
178
 
138
179
  // TLC takes for an operator only a definition it hasn't replaced with its value.
139
180
  export const getConfigDefinition = (kind: string, name: string, environment: Environment) => {
181
+ if (environment.constants.has(name)) {
182
+ throw new TlaConfigError(`The ${kind} ${name} cannot be a constant.`);
183
+ }
140
184
  const definition = getConfigOperator(kind, name, environment);
141
185
  if (getConstantValue(name, definition, environment) !== undefined) {
142
186
  throw new TlaConfigError(`The ${kind} ${name} cannot be a constant.`);
@@ -167,8 +211,7 @@ export const reportInitialStatesProgress = (
167
211
  }
168
212
  };
169
213
 
170
- // After SANY, TLC computes the constant definitions and warns once about each invariant that is a
171
- // true constant formula, which it doesn't check.
214
+ // TLC warns once about each invariant that is a true constant formula, which it doesn't check.
172
215
  export const reportStartup = (
173
216
  specification: {
174
217
  environment: Environment;
@@ -179,12 +222,7 @@ export const reportStartup = (
179
222
  onProgress: CheckOptions["onProgress"],
180
223
  ) => {
181
224
  const environment = specification.environment;
182
- const warned = new Set<string>();
183
- environment.runtime.warn = (code, text) => {
184
- if (warned.has(text)) return;
185
- warned.add(text);
186
- onProgress?.({ kind: "warning", code, text });
187
- };
225
+ environment.runtime.warn = (code, text) => onProgress?.({ kind: "warning", code, text });
188
226
  onProgress?.({ kind: "parsed" });
189
227
  // TLC loads the classes of the modules before it computes the constant definitions.
190
228
  specification.javaOverrides.forEach((override) =>
@@ -198,11 +236,12 @@ export const reportStartup = (
198
236
  });
199
237
  };
200
238
 
239
+ // TLC reads the invariant's level from SANY, which doesn't see the configuration's substitutions.
201
240
  const getInvariants = (names: string[], environment: Environment) => {
202
241
  const analyzer = createLevelAnalyzer({
203
242
  constants: new Set(environment.constants.keys()),
204
243
  variables: new Set(environment.variables),
205
- getDefinition: (name) => getDefinition(name, environment),
244
+ getDefinition: (name) => environment.definitions.get(name),
206
245
  });
207
246
  return names.flatMap((name) => {
208
247
  const definition = getConfigPredicate("invariant", name, environment);
@@ -229,9 +268,12 @@ const getConjuncts = (expression: Expression, environment: Environment): Express
229
268
  return expression.operands.flatMap((operand) => getConjuncts(operand, environment));
230
269
  if (expression.kind === "Identifier" && !environment.constants.has(expression.name)) {
231
270
  const definition = getDefinition(expression.name, environment);
232
- if (definition?.kind === "Operator" && definition.params.length === 0) {
233
- return getConjuncts(definition.body, environment);
234
- }
271
+ // A definition that TLC computed when it started stays its value.
272
+ const isUnfolded =
273
+ definition?.kind === "Operator" &&
274
+ definition.params.length === 0 &&
275
+ getStartupValue(definition, environment) === undefined;
276
+ if (isUnfolded) return getConjuncts(definition.body, environment);
235
277
  }
236
278
  return [expression];
237
279
  };
@@ -256,7 +298,13 @@ const isConstantTrue = (item: ScopedExpression, environment: Environment, usage:
256
298
  return true;
257
299
  };
258
300
 
259
- const getSpecification = (config: ModelConfig, environment: Environment): Specification => {
301
+ const getSpecification = (
302
+ config: ModelConfig,
303
+ environment: Environment,
304
+ variableLocations: SourceLocation[],
305
+ getVariableOrder: () => string[],
306
+ onProgress: CheckOptions["onProgress"],
307
+ ): Specification => {
260
308
  if (config.specification === undefined) {
261
309
  const getOperator = (name: string | undefined, description: string) => {
262
310
  if (name === undefined) return undefined;
@@ -268,6 +316,7 @@ const getSpecification = (config: ModelConfig, environment: Environment): Specif
268
316
  next: getOperator(config.next, "next state action"),
269
317
  scope: undefined,
270
318
  temporals: [],
319
+ isPropertyFairness: false,
271
320
  };
272
321
  }
273
322
  if (config.init !== undefined || config.next !== undefined) {
@@ -278,16 +327,36 @@ const getSpecification = (config: ModelConfig, environment: Environment): Specif
278
327
  const initConjuncts: ScopedExpression[] = [];
279
328
  const nextActions: ScopedExpression[] = [];
280
329
  const temporals: ScopedExpression[] = [];
281
- const definition = getConfigOperator("name", config.specification, environment);
282
- const value = getConstantValue(config.specification, definition, environment);
330
+ const value = environment.constants.has(config.specification)
331
+ ? environment.constants.get(config.specification)
332
+ : getConstantValue(
333
+ config.specification,
334
+ getConfigOperator("name", config.specification, environment),
335
+ environment,
336
+ );
283
337
  if (value !== undefined) {
284
338
  throw new TlaConfigError(
285
339
  `The value of ${config.specification} is equal to ${formatValue(value)}`,
286
340
  );
287
341
  }
342
+ const definition = getConfigOperator("name", config.specification, environment);
343
+ // TLC tags a temporal formula as part of a property it reached through the property's name.
344
+ const property = config.properties.length === 1 ? config.properties[0] : undefined;
345
+ const untagged = { isFound: false };
288
346
  expandTemporal(definition.body, undefined, environment, false).forEach((item) => {
289
347
  const conjunct = item.expression;
290
348
  if (isConstantTrue(item, environment, "spec")) return;
349
+ const variableIndex =
350
+ conjunct.kind === "Identifier" && !isLocallyResolved(conjunct)
351
+ ? environment.variableIndex.get(conjunct.name)
352
+ : undefined;
353
+ // TLC looks a variable up as it does an operator, and finds its declaration.
354
+ if (conjunct.kind === "Identifier" && variableIndex !== undefined) {
355
+ const range = variableLocations[variableIndex].range;
356
+ throw new TlaConfigError(
357
+ `The operator ${conjunct.name}, which equals ${range ? formatRange(range) : conjunct.name},\ncannot be used as a spec`,
358
+ );
359
+ }
291
360
  if (conjunct.kind === "UnboundedQuantifier" && conjunct.isTemporal) {
292
361
  throw setExitCode(
293
362
  new TlaConfigError(
@@ -297,11 +366,40 @@ const getSpecification = (config: ModelConfig, environment: Environment): Specif
297
366
  );
298
367
  }
299
368
  if (conjunct.kind === "Always" && conjunct.expression.kind === "BoxAction") {
369
+ const variables = getSubscriptVariables(
370
+ conjunct.expression.subscript,
371
+ item.scope,
372
+ environment,
373
+ );
374
+ if (variables === undefined) {
375
+ onProgress?.({
376
+ kind: "warning",
377
+ code: MESSAGE_CODE.subscriptUndetermined,
378
+ text: "TLC could not determine if the subscript of the next-state relation contains\nall state variables. Proceed with fingers crossed.",
379
+ });
380
+ }
381
+ getVariableOrder()
382
+ .filter((name) => variables !== undefined && !variables.includes(name))
383
+ .forEach((name) =>
384
+ onProgress?.({
385
+ kind: "warning",
386
+ code: MESSAGE_CODE.subscriptMissingVariable,
387
+ text: `The subscript of the next-state relation specified by the specification\ndoes not seem to contain the state variable ${name}`,
388
+ }),
389
+ );
390
+ if (nextActions.length > 0) {
391
+ throw new TlaConfigError(
392
+ "The specification contains more than one conjunct of the form [][Next]_v,\nbut TLC can handle only specifications with one next-state relation.",
393
+ );
394
+ }
300
395
  nextActions.push({ expression: conjunct.expression.action, scope: item.scope });
301
396
  return;
302
397
  }
398
+ // TLC rejects []S for a state-level S applying an operator, but not for a LET or a label.
303
399
  if (
304
400
  conjunct.kind === "Always" &&
401
+ conjunct.expression.kind !== "Let" &&
402
+ conjunct.expression.kind !== "Label" &&
305
403
  getLevel(conjunct.expression, item.scope, environment) < ACTION_LEVEL
306
404
  ) {
307
405
  // TLC accepts the spec and fails when it builds the tableau of the temporal formulas.
@@ -314,21 +412,17 @@ const getSpecification = (config: ModelConfig, environment: Environment): Specif
314
412
  }
315
413
  const level = getLevel(conjunct, item.scope, environment);
316
414
  if (level === TEMPORAL_LEVEL) {
415
+ if (property === undefined || !item.path.includes(property)) untagged.isFound = true;
317
416
  temporals.push(item);
318
417
  return;
319
418
  }
320
419
  if (level === ACTION_LEVEL) {
321
420
  throw new TlaConfigError(
322
- `TLC cannot handle the action-level conjunct of the specification ${config.specification}`,
421
+ `TLC cannot handle this conjunct of the spec:\n${describeRange(conjunct)}`,
323
422
  );
324
423
  }
325
424
  initConjuncts.push(item);
326
425
  });
327
- if (nextActions.length > 1) {
328
- throw new TlaConfigError(
329
- `The specification ${config.specification} must contain at most one [][Next]_vars`,
330
- );
331
- }
332
426
  const items = [...initConjuncts, ...nextActions];
333
427
  const getName = (index: number) => `$specification${index}`;
334
428
  const scope = items.reduce<Scope | undefined>(
@@ -367,6 +461,7 @@ const getSpecification = (config: ModelConfig, environment: Environment): Specif
367
461
  next: nextActions.length === 0 ? undefined : getReference(nextActions[0], initConjuncts.length),
368
462
  scope,
369
463
  temporals,
464
+ isPropertyFairness: temporals.length > 0 && !untagged.isFound,
370
465
  };
371
466
  };
372
467
 
@@ -384,13 +479,11 @@ const getProperties = (
384
479
  config.properties.forEach((name) => {
385
480
  const definition = getConfigPredicate("property", name, environment);
386
481
  if (!definition) return;
387
- // TLC checks a property that is a state formula only on the initial states, so it warns about
388
- // one as it processes the property, before the constraints.
482
+ // TLC checks a state-formula property only on initial states, and warns before the constraints.
389
483
  if (getLevel(definition.body, undefined, environment) === VARIABLE_LEVEL) {
390
484
  onProgress?.({ kind: "state-level-property", name });
391
485
  }
392
- // TLC 1.7.4 expands a property as it does a specification, so it doesn't unroll one that
393
- // quantifies over a constant set.
486
+ // TLC 1.7.4 expands a property as a specification, without unrolling \A over a constant set.
394
487
  const isProperty = environment.runtime.version !== "1.7.4";
395
488
  expandTemporal(definition.body, undefined, environment, isProperty).forEach((item) => {
396
489
  const conjunct = item.expression;
@@ -410,9 +503,9 @@ const getProperties = (
410
503
  conjunct.kind === "Always" &&
411
504
  getLevel(conjunct.expression, item.scope, environment) <= VARIABLE_LEVEL
412
505
  ) {
413
- // TLC names the invariant by the operator the property asserts always holds, when it
414
- // applies the operator to no arguments. The name of an operator another module defines
415
- // resolves to its key, so the name comes from its definition.
506
+ // TLC names the invariant by the operator a property asserts always holds, when it applies
507
+ // it to no arguments. Another module's operator resolves to its key, so the name comes
508
+ // from its definition.
416
509
  const body = conjunct.expression;
417
510
  const operator =
418
511
  body.kind === "Identifier" && !isLocallyResolved(body)
@@ -435,7 +528,17 @@ const getProperties = (
435
528
  return;
436
529
  }
437
530
  if (level === ACTION_LEVEL) {
438
- throw new TlaConfigError(`The property ${name} is an action-level formula`);
531
+ const location = describeRange(conjunct);
532
+ const book = "Specifying Systems at https://lamport.azurewebsites.net/tla/book.html";
533
+ const advice =
534
+ conjunct.kind === "BoxAction"
535
+ ? `To check that action ${partName} holds in *every* step of the behavior, define a temporal property by applying the "always" temporal operator ([]) to the formula at ${location} (compare page 90 of ${book}).`
536
+ : conjunct.kind === "AngleAction"
537
+ ? `To check that infinitely many ${partName} steps occur, define a temporal property by applying the "always eventually" temporal operator combination ([]<>) to the formula at ${location} (compare page 91 of ${book}).`
538
+ : `To check that action ${partName} holds in *every* step of the behavior, define a temporal property: Let A be the formula at ${location}; rewrite A as [][A]_v, where v is a state function (typically the tuple of variables) (compare page 90 of ${book}).`;
539
+ throw new TlaConfigError(
540
+ `The formula ${partName} at ${location} is an action-level formula (i.e., it contains no temporal operators). Only temporal-level (or state-level) formulas are allowed under PROPERTY or PROPERTIES. ${advice}`,
541
+ );
439
542
  }
440
543
  properties.liveness.push({ name, expression: conjunct, scope: item.scope });
441
544
  });
@@ -488,7 +591,6 @@ const getMembership = (
488
591
  : undefined;
489
592
  };
490
593
 
491
- // TLC evaluates the body of an invariant that the configuration names.
492
594
  const getPredicate = (expression: Expression, environment: Environment) => {
493
595
  if (expression.kind !== "Identifier" || environment.constants.has(expression.name)) {
494
596
  return expression;
@@ -555,6 +657,13 @@ const hasWideString = (config: ModelConfig, environment: Environment) =>
555
657
 
556
658
  interface Search {
557
659
  properties: Properties;
660
+ toRecord: (state: Value[]) => Record<string, Value>;
661
+ evaluateAlias: (
662
+ alias: string,
663
+ state: Value[],
664
+ next: Value[] | undefined,
665
+ isTool: boolean,
666
+ ) => Record<string, Value>;
558
667
  spec: Specification;
559
668
  getFingerprintState: (state: Value[]) => Value[];
560
669
  getStoredFingerprints: (states: Value[][], fingerprintStates: Value[][]) => BigInt64Array;
@@ -563,9 +672,10 @@ interface Search {
563
672
  // TLC drops a constraint that is a true constant formula.
564
673
  isConstrained: boolean;
565
674
  findViolatedInvariant: (state: Value[], parent?: Value[]) => StateCheck | undefined;
566
- // The checks of a state that TLC evaluates when it replays the computation of the initial states
567
- // or of the successors of a state, with an environment that records the call stack. The first
568
- // returns the check that stops the replay, and the second false where TLC stops it.
675
+ // Every invariant an initial state violates, which TLC reports with -continue.
676
+ getViolatedInvariants: (state: Value[]) => StateCheck[];
677
+ // TLC evaluates these as it replays the initial states or successors with a call stack. The
678
+ // first returns the check that stops the replay, and the second false where TLC stops it.
569
679
  // TLC fingerprints a replayed state that satisfies the constraints before it checks the rest.
570
680
  checkReplayedInitialState: (
571
681
  state: Value[],
@@ -583,13 +693,35 @@ interface Search {
583
693
  findFailedInitialPredicate: (state: Value[]) => NamedExpression | undefined;
584
694
  findViolatedActionProperty: (state: Value[], next: Value[]) => ActionProperty | undefined;
585
695
  satisfiesActionConstraints: (state: Value[], next: Value[]) => boolean;
696
+ getExcludingConstraints: (state: Value[], next: Value[]) => string[];
586
697
  trackStatePossible: (state: Value[]) => void;
587
698
  trackActionPossible: (state: Value[], next: Value[]) => void;
588
699
  findUnwitnessedPossible: () => Postcondition | undefined;
700
+ getReward: (state: Value[] | undefined, next: Value[], fallback: number) => number;
589
701
  // After a counterexample, TLC skips the postconditions when one of them is constant.
590
702
  findPostconditionViolation: (isAfterViolation?: boolean) => Postcondition | undefined;
591
703
  }
592
704
 
705
+ // TLC prints the alias's record in the order it was written, unless it sorted the record.
706
+ const toAliasRecord = (value: Value) => {
707
+ if (!isFunctionValue(value)) return undefined;
708
+ const pairs = getWrittenPairs(toFiniteFunction(value));
709
+ if (!pairs.every((pair) => typeof pair[0] === "string")) return undefined;
710
+ return Object.fromEntries(pairs.map((pair) => [String(pair[0]), pair[1]]));
711
+ };
712
+
713
+ export const getIncompleteSuccessorMessage = (
714
+ missing: string[],
715
+ action: string | undefined,
716
+ actionCount: number,
717
+ version: TlcVersion | undefined,
718
+ ) => {
719
+ const subject =
720
+ actionCount === 1 ? "the next-state action" : `action ${action} of the next-state relation`;
721
+ const verb = version === "1.7.4" ? "assigned" : "defined";
722
+ return `Successor state is not completely specified by ${subject}. The following variable${missing.length > 1 ? "s are" : " is"} not ${verb}: ${missing.join(", ")}.\n`;
723
+ };
724
+
593
725
  export const getContext = (
594
726
  environment: Environment,
595
727
  state: Value[] | undefined,
@@ -613,17 +745,19 @@ const holdsLikeTlc = (
613
745
  return value;
614
746
  };
615
747
 
616
- const getExpectedBoolean = (expression: Expression, environment: Environment) => {
748
+ const getExpectedValue = (kind: string, expression: Expression, environment: Environment) => {
617
749
  const definition =
618
750
  expression.kind === "Identifier" ? getDefinition(expression.name, environment) : undefined;
619
751
  const body = definition?.kind === "Operator" ? definition.body : expression;
620
752
  const range = definition?.kind === "Operator" ? definition.bodyRange : undefined;
621
753
  const location = range && body.kind !== "Number" ? formatRange(range) : describeNode(body);
622
- return `TLC expected a boolean value, but did not find one. ${location}`;
754
+ return `TLC expected a ${kind} value, but did not find one. ${location}`;
623
755
  };
624
756
 
625
- // TLC evaluates the whole predicate of a check, which fails at a conjunct that isn't a boolean as
626
- // the conjunction does.
757
+ const getExpectedBoolean = (expression: Expression, environment: Environment) =>
758
+ getExpectedValue("boolean", expression, environment);
759
+
760
+ // TLC evaluates the whole predicate, which fails at a non-boolean conjunct as the conjunction does.
627
761
  const holdsAsConjunct = (check: StateCheck, context: Context) =>
628
762
  holdsLikeTlc(check.expression, context, (expression, environment) => {
629
763
  holdsLikeTlc(check.predicate, context);
@@ -639,13 +773,9 @@ const trackPossible = (items: NamedExpression[], runtime: CheckerRuntime, contex
639
773
  runtime.possibleCounts.set(item.name, isWitnessed ? count + 1 : count);
640
774
  });
641
775
 
642
- const getConstantFailure = (
643
- expression: Expression,
644
- environment: Environment,
645
- description: string,
646
- ) => {
776
+ const getConstantFailure = (check: (context: Context) => boolean, environment: Environment) => {
647
777
  try {
648
- return holds(expression, getContext(environment, undefined, undefined), description)
778
+ return check(getContext(environment, undefined, undefined))
649
779
  ? undefined
650
780
  : { message: undefined };
651
781
  } catch (error) {
@@ -659,25 +789,132 @@ export const findAssumptionViolation = (
659
789
  environment: Environment,
660
790
  ): Omit<Violation, "loopStart"> | undefined => {
661
791
  for (const assumption of assumptions.filter((candidate) => !candidate.isAxiom)) {
662
- const failure = getConstantFailure(assumption.expression, environment, "an assumption");
792
+ const failure = getConstantFailure(
793
+ (context) =>
794
+ expectBooleanBody(evaluate(assumption.expression, context), assumption.expression),
795
+ environment,
796
+ );
663
797
  if (failure) {
664
- return { name: describeRange(assumption.expression), trace: [], message: failure.message };
798
+ return { name: describeNode(assumption.expression), trace: [], message: failure.message };
665
799
  }
666
800
  }
667
801
  return undefined;
668
802
  };
669
803
 
804
+ export const prepareSearch = (options: CheckOptions) => {
805
+ const config =
806
+ typeof options.config === "string"
807
+ ? parseConfig(options.config, options.version)
808
+ : options.config;
809
+ const order = createTlcOrder(options.source, options.loadModule);
810
+ setStringOrder(order.getStringOrder(config));
811
+ setValueOptions(options);
812
+ setFingerprintPolynomial(options.fingerprintPolynomial ?? 0);
813
+ const specification = createEnvironment(config, {
814
+ source: options.source,
815
+ loadModule: options.loadModule,
816
+ order,
817
+ loadClass: options.loadClass,
818
+ print: options.onPrint ?? console.log,
819
+ files: {
820
+ readFile: options.readFile,
821
+ writeFile: options.writeFile,
822
+ makeDirectory: options.makeDirectory,
823
+ },
824
+ seed: options.seed,
825
+ isTool: options.isTool,
826
+ traceFile: options.traceSpec?.traceFile,
827
+ isSanyReported: options.isSanyReported,
828
+ isWarningEnabled: options.isWarningEnabled,
829
+ version: options.version,
830
+ moduleOperators: options.moduleOperators,
831
+ });
832
+ reportStartup(specification, config, options.onProgress);
833
+ const environment = specification.environment;
834
+ environment.runtime.getSpecification = () =>
835
+ getSpecificationValue(
836
+ config,
837
+ environment,
838
+ specification.variableLocations,
839
+ specification.instanceActions,
840
+ );
841
+ const search = createSearch(
842
+ config,
843
+ environment,
844
+ specification.variableLocations,
845
+ () => order.getDeclarationOrder("variable"),
846
+ options.onProgress,
847
+ specification.moduleOperators,
848
+ );
849
+ return { config, specification, environment, search };
850
+ };
851
+
852
+ export const reportAssumptionViolation = (
853
+ assumptions: Assumption[],
854
+ environment: Environment,
855
+ message: (code: number, text: string, toolText: string) => void,
856
+ ) => {
857
+ const assumption = findAssumptionViolation(assumptions, environment);
858
+ if (!assumption) return undefined;
859
+ if (assumption.message === undefined) {
860
+ const text = `Assumption ${assumption.name} is false.`;
861
+ message(MESSAGE_CODE.assumptionFalse, text, text);
862
+ return EXIT_STATUS.assumptionViolation;
863
+ }
864
+ const text = `Evaluating assumption ${assumption.name} failed.\n${assumption.message}`;
865
+ message(
866
+ MESSAGE_CODE.assumptionEvaluationError,
867
+ text,
868
+ formatInnerMessage(MESSAGE_CODE.assumptionEvaluationError, text, true),
869
+ );
870
+ return EXIT_STATUS.assumptionViolation;
871
+ };
872
+
873
+ export const createMissingOperatorError = (operator: ModuleOperator) =>
874
+ setExitCode(
875
+ new TlaEvaluationError(
876
+ `${UNEXPECTED_EXCEPTION}Could not find operator: ${operator.operator} in module: ${operator.module}`,
877
+ ),
878
+ EXIT_STATUS.error,
879
+ );
880
+
670
881
  export const createSearch = (
671
882
  config: ModelConfig,
672
883
  environment: Environment,
884
+ variableLocations: SourceLocation[],
673
885
  getVariableOrder: () => string[],
674
886
  onProgress?: CheckOptions["onProgress"],
887
+ moduleOperators: ResolvedModuleOperator[] = [],
675
888
  ): Search | undefined => {
889
+ const getModuleOperators = (kind: ResolvedModuleOperator["kind"]) =>
890
+ moduleOperators
891
+ .filter((operator) => operator.kind === kind)
892
+ .map((operator) => {
893
+ if (operator.key === undefined) throw createMissingOperatorError(operator);
894
+ return { name: operator.operator, key: operator.key };
895
+ });
676
896
  const configInvariants = getInvariants(config.invariants, environment);
677
- const spec = getSpecification(config, environment);
897
+ const spec = getSpecification(
898
+ config,
899
+ environment,
900
+ variableLocations,
901
+ getVariableOrder,
902
+ onProgress,
903
+ );
678
904
  const properties = getProperties(config, environment, onProgress);
905
+ const live = config.properties[0];
906
+ const liveRange = live && getDefinition(live, environment)?.location.range;
907
+ const specName = config.specification;
908
+ const specRange = specName && getDefinition(specName, environment)?.location.range;
909
+ if (spec.isPropertyFairness && liveRange && specRange) {
910
+ onProgress?.({
911
+ kind: "warning",
912
+ code: MESSAGE_CODE.fairnessTautology,
913
+ text: `Implied-temporal checking is a tautology.\nThe temporal formula ${live} at ${formatRange(liveRange)} equals\nthe fairness constraints of the behavior specification ${specName} at ${formatRange(specRange)}.\nTherefore, checking whether ${specName} => ${live} using TLC will never result in a violation of ${live}.`,
914
+ });
915
+ }
679
916
  const invariants = getStateChecks([...configInvariants, ...properties.invariants], environment);
680
- // The invariants TLC evaluates, each of which may have several conjuncts among the checks.
917
+ // Each may have several conjuncts among the checks.
681
918
  const invariantPredicates = [
682
919
  ...new Map(invariants.map((invariant) => [invariant.predicate, invariant])).values(),
683
920
  ];
@@ -700,15 +937,71 @@ export const createSearch = (
700
937
  if (spec.next === undefined && isCheckingBehaviors) {
701
938
  throw new TlaConfigError("The configuration file did not specify the next state predicate.");
702
939
  }
703
- const constraints = getStateChecks(
704
- getNamedExpressions("constraint", config.constraints, environment),
940
+ const namedConstraints = getNamedExpressions(
941
+ "constraint",
942
+ [...config.constraints, ...getModuleOperators("constraint").map((operator) => operator.name)],
705
943
  environment,
706
944
  );
945
+ const constraints = getStateChecks(namedConstraints, environment);
707
946
  const actionConstraints = getNamedExpressions(
708
947
  "action constraint",
709
948
  config.actionConstraints,
710
949
  environment,
711
950
  );
951
+ const coverage = environment.coverage;
952
+ // TLC counts an invariant or a constraint as a whole, and one a property implies as its formula.
953
+ const getCoveredChecks = (kind: CoverageKind, items: NamedExpression[], isDefined = true) =>
954
+ items.flatMap((item): CoveredCheck[] => {
955
+ if (!coverage) return [];
956
+ const expression = isDefined ? getPredicate(item.expression, environment) : item.expression;
957
+ const label = getCoverageLabel(isDefined ? item.name : undefined, expression, environment);
958
+ const node = addCoverageRelation(coverage, kind, label, expression, item.scope);
959
+ return [{ expression, scope: item.scope, node }];
960
+ });
961
+ const coveredInvariants = [
962
+ ...getCoveredChecks("invariant", configInvariants),
963
+ ...getCoveredChecks("invariant", properties.invariants, false),
964
+ ];
965
+ const coveredActionConstraints = getCoveredChecks("constraint", actionConstraints);
966
+ const coveredConstraints = getCoveredChecks("constraint", namedConstraints);
967
+ const coveredInitialPredicates = getCoveredChecks("implied", properties.initialPredicates, false);
968
+ const coveredActionProperties = getCoveredChecks(
969
+ "implied",
970
+ properties.actionProperties.map((property) => ({ ...property, expression: property.box })),
971
+ false,
972
+ );
973
+ // A check that fails or isn't a boolean is evaluated again outside coverage, which reports it.
974
+ const evaluateCovered = (
975
+ covered: Coverage,
976
+ check: CoveredCheck,
977
+ state: Value[],
978
+ next: Value[] | undefined,
979
+ ) => {
980
+ try {
981
+ return runAtCoverageNode(covered, check.node, () =>
982
+ evaluate(check.expression, getContext(environment, state, next, check.scope)),
983
+ );
984
+ } catch {
985
+ return undefined;
986
+ }
987
+ };
988
+ const isCoveredHeld = (checks: CoveredCheck[], state: Value[], next?: Value[]) =>
989
+ coverage !== undefined &&
990
+ checks.every((check) => evaluateCovered(coverage, check, state, next) === true);
991
+ // TLC counts a constraint's states as those it excludes and those it keeps.
992
+ const satisfiesCovered = (checks: CoveredCheck[], state: Value[], next?: Value[]) => {
993
+ if (!coverage) return undefined;
994
+ for (const check of checks) {
995
+ const value = evaluateCovered(coverage, check, state, next);
996
+ if (typeof value !== "boolean") return undefined;
997
+ if (!value) {
998
+ coverage.primary[check.node]++;
999
+ return false;
1000
+ }
1001
+ coverage.secondary[check.node]++;
1002
+ }
1003
+ return true;
1004
+ };
712
1005
  if (config.rlReward !== undefined) getConfigOperator("rlreward", config.rlReward, environment);
713
1006
  if (config.periodic !== undefined) getConfigOperator("periodic", config.periodic, environment);
714
1007
  const possible = getPossiblePredicates(config.possible, environment);
@@ -717,11 +1010,15 @@ export const createSearch = (
717
1010
  config.symmetry === undefined
718
1011
  ? undefined
719
1012
  : getSymmetryGroup(config.symmetry, environment, config.substitutions);
720
- if (config.view !== undefined) getConfigOperator("view function", config.view, environment);
721
- const view =
1013
+ const viewDefinition =
722
1014
  config.view === undefined
723
1015
  ? undefined
724
- : { name: config.view, expression: createIdentifier(config.view), scope: undefined };
1016
+ : getConfigDefinition("view function", config.view, environment);
1017
+ const viewName = config.view ?? getModuleOperators("view")[0]?.name;
1018
+ const view =
1019
+ viewName === undefined
1020
+ ? undefined
1021
+ : { name: viewName, expression: createIdentifier(viewName), scope: undefined };
725
1022
  const actionProperties = properties.actionProperties.map((property) => {
726
1023
  const unchanged: Expression = {
727
1024
  kind: "Unchanged",
@@ -760,6 +1057,32 @@ export const createSearch = (
760
1057
  : [getViewValue(view.expression, representative)],
761
1058
  );
762
1059
  };
1060
+ // With -continue, TLC goes on to the successors of a state that violates an invariant.
1061
+ const violatingStates = new WeakSet<Value[]>();
1062
+ const isViolated = (invariant: StateCheck, state: Value[], parent: Value[] | undefined) => {
1063
+ // A parent that satisfies every invariant leaves only what the step changed to fail.
1064
+ const checkedParent = parent && !violatingStates.has(parent) ? parent : undefined;
1065
+ if (isUnchangedFor(invariant, state, checkedParent)) return false;
1066
+ try {
1067
+ const context = getContext(environment, state, undefined, invariant.scope);
1068
+ const membership = invariant.membership;
1069
+ return checkedParent && membership
1070
+ ? !isUpdatedElementOf(
1071
+ state[membership.variable],
1072
+ checkedParent[membership.variable],
1073
+ evaluate(membership.set, context),
1074
+ )
1075
+ : !holdsAsConjunct(invariant, context);
1076
+ } catch (error) {
1077
+ // TLC reports a failure only on a state after the initial states as an invariant failure.
1078
+ if (!parent) throw error;
1079
+ throw withHeadline(
1080
+ setExitCode(error, EXIT_STATUS.safetyEvaluationFailure),
1081
+ MESSAGE_CODE.invariantEvaluationFailed,
1082
+ `Evaluating invariant ${invariant.name} failed.`,
1083
+ );
1084
+ }
1085
+ };
763
1086
  const isFingerprintedLikeTlc = hasWideString(config, environment);
764
1087
  runtime.getFingerprint = getTlcStateFingerprint;
765
1088
  const findUnwitnessedPossible = () => {
@@ -774,9 +1097,58 @@ export const createSearch = (
774
1097
  counts: prettyPrint(formatValue(getPossibleCounts(runtime), true)),
775
1098
  };
776
1099
  };
1100
+ // TLC prints a tuple VIEW as a state when it has as many elements as the VIEW names variables and
1101
+ // constants, labeling them in variable order, which mislabels <<y, x>> and <<x + 1>>. tla-ts
1102
+ // prints only a tuple of distinct variables as a state, each with its own value.
1103
+ const viewElements = viewDefinition?.body.kind === "Tuple" ? viewDefinition.body.elements : [];
1104
+ const viewNames = viewElements.flatMap((element) =>
1105
+ element.kind === "Identifier" && environment.variables.includes(element.name)
1106
+ ? [element.name]
1107
+ : [],
1108
+ );
1109
+ const isStateView =
1110
+ viewDefinition?.body.kind === "Tuple" &&
1111
+ viewNames.length === viewElements.length &&
1112
+ new Set(viewNames).size === viewNames.length;
1113
+ const getViewText = (expression: Expression, state: Value[]) =>
1114
+ isStateView
1115
+ ? getTlcOrder()
1116
+ .filter((index) => viewNames.includes(environment.variables[index]))
1117
+ .map(
1118
+ (index) =>
1119
+ `/\\ ${environment.variables[index]} = ${prettyPrint(formatValue(state[index]))}\n`,
1120
+ )
1121
+ .join("")
1122
+ : prettyPrint(formatValue(getViewValue(expression, state)));
1123
+ const holdsActionConstraint = (constraint: NamedExpression, state: Value[], next: Value[]) =>
1124
+ holdsLikeTlc(
1125
+ constraint.expression,
1126
+ getContext(environment, state, next),
1127
+ (expression) => `${UNEXPECTED_EXCEPTION}${getExpectedBoolean(expression, environment)}`,
1128
+ );
1129
+ const toRecord = (state: Value[]): Record<string, Value> => {
1130
+ const record = Object.fromEntries(
1131
+ getTlcOrder().map((index) => [environment.variables[index], state[index]]),
1132
+ );
1133
+ return view === undefined
1134
+ ? record
1135
+ : setViewText(record, () => getViewText(view.expression, state));
1136
+ };
777
1137
  return {
778
1138
  properties,
779
1139
  spec,
1140
+ toRecord,
1141
+ evaluateAlias: (alias, state, next, isTool) => {
1142
+ try {
1143
+ getConfigDefinition("alias", alias, environment);
1144
+ const value = evaluate(createIdentifier(alias), getContext(environment, state, next));
1145
+ const record = toAliasRecord(value);
1146
+ return record === undefined ? toRecord(state) : setAliasName(record, alias);
1147
+ } catch (error) {
1148
+ if (!(error instanceof TlaConfigError || error instanceof TlaEvaluationError)) throw error;
1149
+ return { ...toRecord(state), _ALIASEvalError: formatNestedMessage(error.message, isTool) };
1150
+ }
1151
+ },
780
1152
  isSymmetric: symmetryGroup !== undefined,
781
1153
  isConstrained: constraints.length > 0 || actionConstraints.length > 0,
782
1154
  getTlcOrder,
@@ -795,30 +1167,22 @@ export const createSearch = (
795
1167
  : getRepresentative(state, symmetryGroup, getTlcOrder());
796
1168
  return view === undefined ? representative : [getViewValue(view.expression, representative)];
797
1169
  },
798
- findViolatedInvariant: (state, parent) =>
799
- invariants.find((invariant) => {
800
- if (isUnchangedFor(invariant, state, parent)) return false;
801
- try {
802
- const context = getContext(environment, state, undefined, invariant.scope);
803
- const membership = invariant.membership;
804
- // The parent satisfies every invariant, so only the entries the step changed can fail.
805
- return parent && membership
806
- ? !isUpdatedElementOf(
807
- state[membership.variable],
808
- parent[membership.variable],
809
- evaluate(membership.set, context),
810
- )
811
- : !holdsAsConjunct(invariant, context);
812
- } catch (error) {
813
- // TLC reports a failure only on a state after the initial states as an invariant failure.
814
- if (!parent) throw error;
815
- throw withHeadline(
816
- setExitCode(error, EXIT_STATUS.safetyEvaluationFailure),
817
- MESSAGE_CODE.invariantEvaluationFailed,
818
- `Evaluating invariant ${invariant.name} failed.`,
819
- );
820
- }
821
- }),
1170
+ findViolatedInvariant: (state, parent) => {
1171
+ if (isCoveredHeld(coveredInvariants, state)) return undefined;
1172
+ const violated = invariants.find((invariant) => isViolated(invariant, state, parent));
1173
+ if (violated) violatingStates.add(state);
1174
+ return violated;
1175
+ },
1176
+ getViolatedInvariants: (state) => {
1177
+ const violated = invariantPredicates.filter((predicate) =>
1178
+ invariants.some(
1179
+ (invariant) =>
1180
+ invariant.predicate === predicate.predicate && isViolated(invariant, state, undefined),
1181
+ ),
1182
+ );
1183
+ if (violated.length > 0) violatingStates.add(state);
1184
+ return violated;
1185
+ },
822
1186
  checkReplayedInitialState: (state, tracing, addFingerprint) => {
823
1187
  const holdsIn = (expression: Expression, scope: Scope | undefined) =>
824
1188
  holdsLikeTlc(expression, getContext(tracing, state, undefined, scope));
@@ -844,8 +1208,7 @@ export const createSearch = (
844
1208
  actionConstraints.every((constraint) =>
845
1209
  holdsLikeTlc(constraint.expression, getContext(tracing, state, next, constraint.scope)),
846
1210
  );
847
- // ModelChecker.doNext checks the invariants of a successor it has not seen, which includes
848
- // one outside the model.
1211
+ // TLC checks the invariants of a successor it has not seen, even outside the model.
849
1212
  const isUnseen = isInModel ? addFingerprint() : true;
850
1213
  return (
851
1214
  (!isUnseen ||
@@ -861,51 +1224,63 @@ export const createSearch = (
861
1224
  );
862
1225
  },
863
1226
  satisfiesConstraints: (state, parent) =>
1227
+ satisfiesCovered(coveredConstraints, state) ??
864
1228
  constraints.every(
865
1229
  (constraint) =>
866
1230
  isUnchangedFor(constraint, state, parent) ||
867
1231
  holdsAsConjunct(constraint, getContext(environment, state, undefined)),
868
1232
  ),
869
1233
  findFailedInitialPredicate: (state) =>
870
- properties.initialPredicates.find(
871
- (predicate) =>
872
- !holdsLikeTlc(
873
- predicate.expression,
874
- getContext(environment, state, undefined, predicate.scope),
1234
+ isCoveredHeld(coveredInitialPredicates, state)
1235
+ ? undefined
1236
+ : properties.initialPredicates.find(
1237
+ (predicate) =>
1238
+ !holdsLikeTlc(
1239
+ predicate.expression,
1240
+ getContext(environment, state, undefined, predicate.scope),
1241
+ ),
875
1242
  ),
876
- ),
877
1243
  findViolatedActionProperty: (state, next) =>
878
- actionProperties.find((property) => {
879
- try {
880
- return (
881
- !holdsLikeTlc(
882
- property.action,
883
- getContext(environment, state, next, property.scope),
884
- () =>
885
- `Attempted to evaluate an expression of form [A]_e, but A was not a boolean.\n${describeRange(property.box)}`,
886
- ) &&
887
- !holds(
888
- property.unchanged,
889
- getContext(environment, state, next, property.scope),
890
- "a subscript",
891
- )
892
- );
893
- } catch (error) {
894
- throw withHeadline(
895
- withNextStateExitCode(error),
896
- MESSAGE_CODE.actionPropertyEvaluationFailed,
897
- `Evaluating action property ${property.name} failed.`,
898
- );
899
- }
900
- }),
1244
+ isCoveredHeld(coveredActionProperties, state, next)
1245
+ ? undefined
1246
+ : actionProperties.find((property) => {
1247
+ try {
1248
+ return (
1249
+ !holdsLikeTlc(
1250
+ property.action,
1251
+ getContext(environment, state, next, property.scope),
1252
+ () =>
1253
+ `Attempted to evaluate an expression of form [A]_e, but A was not a boolean.\n${describeRange(property.box)}`,
1254
+ ) &&
1255
+ !holds(
1256
+ property.unchanged,
1257
+ getContext(environment, state, next, property.scope),
1258
+ "a subscript",
1259
+ )
1260
+ );
1261
+ } catch (error) {
1262
+ throw withHeadline(
1263
+ withNextStateExitCode(error),
1264
+ MESSAGE_CODE.actionPropertyEvaluationFailed,
1265
+ `Evaluating action property ${property.name} failed.`,
1266
+ );
1267
+ }
1268
+ }),
901
1269
  satisfiesActionConstraints: (state, next) =>
902
- actionConstraints.every((constraint) =>
903
- holdsLikeTlc(
904
- constraint.expression,
905
- getContext(environment, state, next),
906
- (expression) => `${UNEXPECTED_EXCEPTION}${getExpectedBoolean(expression, environment)}`,
1270
+ satisfiesCovered(coveredActionConstraints, state, next) ??
1271
+ actionConstraints.every((constraint) => holdsActionConstraint(constraint, state, next)),
1272
+ getExcludingConstraints: (state, next) =>
1273
+ [
1274
+ ...constraints.filter(
1275
+ (constraint) => !holdsAsConjunct(constraint, getContext(environment, next, undefined)),
907
1276
  ),
908
- ),
1277
+ ...actionConstraints.filter(
1278
+ (constraint) => !holdsActionConstraint(constraint, state, next),
1279
+ ),
1280
+ ].map((constraint) => {
1281
+ const range = getBodyRange(constraint.name, environment);
1282
+ return range ? formatRange(range) : constraint.name;
1283
+ }),
909
1284
  trackStatePossible:
910
1285
  statePossible.length === 0
911
1286
  ? ignorePossible
@@ -917,29 +1292,48 @@ export const createSearch = (
917
1292
  : (state, next) =>
918
1293
  trackPossible(actionPossible, runtime, getContext(environment, state, next)),
919
1294
  findUnwitnessedPossible,
1295
+ getReward: (state, next, fallback) => {
1296
+ if (config.rlReward === undefined) return fallback;
1297
+ const expression = createIdentifier(config.rlReward);
1298
+ const value = evaluate(expression, getContext(environment, state, next));
1299
+ if (typeof value !== "number") {
1300
+ throw new TlaEvaluationError(getExpectedValue("integer", expression, environment));
1301
+ }
1302
+ return value;
1303
+ },
920
1304
  findPostconditionViolation: (isAfterViolation = false) => {
921
- // TLC replaces a definition it computes when it starts by its value, and then rejects it as
922
- // a postcondition before it checks any of them.
923
- const constant = config.postconditions.find((name) => {
924
- const definition = getDefinition(name, environment);
925
- return definition !== undefined && getStartupValue(definition, environment) !== undefined;
926
- });
927
- if (constant !== undefined) {
1305
+ const modulePostconditions = getModuleOperators("postcondition");
1306
+ // TLC replaces a startup definition by its value, and rejects it as a postcondition first.
1307
+ const rejection = config.postconditions
1308
+ .map((name) => {
1309
+ const definition = getDefinition(name, environment);
1310
+ if (!definition) {
1311
+ return `The post condition ${name} specified in the configuration file\nis not defined in the specification.`;
1312
+ }
1313
+ if (definition.kind === "Operator" && definition.params.length > 0) {
1314
+ return `TLC requires post condition not to take any argument, but one was given: ${name}`;
1315
+ }
1316
+ const isConstant =
1317
+ !isLiteralDefinition(definition) &&
1318
+ getStartupValue(definition, environment) !== undefined;
1319
+ return isConstant ? `The post condition ${name} cannot be a constant.` : undefined;
1320
+ })
1321
+ .find((message) => message !== undefined);
1322
+ if (rejection !== undefined) {
928
1323
  if (isAfterViolation) return undefined;
929
- throw setExitCode(
930
- new TlaEvaluationError(
931
- `${UNEXPECTED_EXCEPTION}The post condition ${constant} cannot be a constant.`,
932
- ),
933
- EXIT_STATUS.error,
934
- );
1324
+ throw setExitCode(new TlaEvaluationError(rejection), EXIT_STATUS.configParseError);
935
1325
  }
936
- const unwitnessed = findUnwitnessedPossible();
937
- if (unwitnessed) return unwitnessed;
938
- for (const name of config.postconditions) {
939
- const failure = getConstantFailure(createIdentifier(name), environment, "a postcondition");
940
- if (!failure) continue;
941
- const range = getBodyRange(name, environment);
942
- const location = range ? ` at ${formatRange(range)}` : "";
1326
+ const findViolation = (name: string, key: string) => {
1327
+ const failure = getConstantFailure(
1328
+ (context) => holdsLikeTlc(createIdentifier(key), context),
1329
+ environment,
1330
+ );
1331
+ if (!failure) return undefined;
1332
+ const body = getDefinition(key, environment)?.body;
1333
+ const range = getBodyRange(key, environment);
1334
+ const location = range
1335
+ ? ` at ${body?.kind === "Number" ? describeNode(body) : formatRange(range)}`
1336
+ : "";
943
1337
  return failure.message === undefined
944
1338
  ? {
945
1339
  name,
@@ -951,13 +1345,22 @@ export const createSearch = (
951
1345
  code: MESSAGE_CODE.postconditionFailed,
952
1346
  message: `Evaluating postcondition ${name}${location} failed.\n${failure.message}`,
953
1347
  };
1348
+ };
1349
+ for (const operator of modulePostconditions) {
1350
+ const violation = findViolation(operator.name, operator.key);
1351
+ if (violation) return violation;
1352
+ }
1353
+ const unwitnessed = findUnwitnessedPossible();
1354
+ if (unwitnessed) return unwitnessed;
1355
+ for (const name of config.postconditions) {
1356
+ const violation = findViolation(name, name);
1357
+ if (violation) return violation;
954
1358
  }
955
1359
  return undefined;
956
1360
  },
957
1361
  };
958
1362
  };
959
1363
 
960
- // TLC exits with the code of a standard module's failure only when the failure escapes the
961
- // computation of next states. In every other phase, the phase decides the code.
1364
+ // TLC exits with a standard module's code only when the failure escapes the next states.
962
1365
  export const withNextStateExitCode = (error: unknown) =>
963
1366
  error instanceof TlaModuleError ? setExitCode(error, error.exitCode) : error;