tla-ts 0.0.3-dev.eba78ea → 0.0.3-dev.f362080

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tla-ts",
3
- "version": "0.0.3-dev.eba78ea",
3
+ "version": "0.0.3-dev.f362080",
4
4
  "description": "A TLA+ interpreter and model checker in TypeScript, 2× faster than TLC",
5
5
  "keywords": [
6
6
  "formal verification",
package/src/check.ts CHANGED
@@ -13,6 +13,7 @@ import {
13
13
  getErrorExitCode,
14
14
  TlaConfigError,
15
15
  TlaEvaluationError,
16
+ TlaIncompleteStateError,
16
17
  TlaModuleError,
17
18
  UNEXPECTED_EXCEPTION,
18
19
  } from "./errors";
@@ -59,7 +60,7 @@ import {
59
60
  type StateWriter,
60
61
  } from "./state-graph";
61
62
  import { getRepresentative, getSymmetryGroup } from "./symmetry";
62
- import { getTlcStringOrder, getTlcVariableOrder } from "./tlc-order";
63
+ import { getTlcStringOrder, getTlcDeclarationOrder } from "./tlc-order";
63
64
  import { createTlcFingerprinter, getTlcFingerprint } from "./tlc-random";
64
65
  import { createCanonicalizer } from "./canonical";
65
66
  import { getPossibleCounts, type CheckerRuntime } from "./runtime";
@@ -276,8 +277,11 @@ const getInvariants = (names: string[], environment: Environment) => {
276
277
  levels.params.size === 0
277
278
  ? ""
278
279
  : "\nNote that a bug can cause TLC to incorrectly report this error.\nIf you believe your TLA+ or PlusCal specification to be correct,\nplease check if this bug described in LevelNode.java starting at line 590ff affects you.";
279
- throw new TlaConfigError(
280
- `The invariant ${name} is not a state predicate (one with no primes or temporal operators).${note}`,
280
+ throw setExitCode(
281
+ new TlaConfigError(
282
+ `The invariant ${name} is not a state predicate (one with no primes or temporal operators).${note}`,
283
+ ),
284
+ EXIT_STATUS.safetyEvaluationFailure,
281
285
  );
282
286
  }
283
287
  return [{ name, expression: createIdentifier(name), scope: undefined }];
@@ -446,12 +450,12 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
446
450
  config.properties.forEach((name) => {
447
451
  const definition = getConfigPredicate("property", name, environment);
448
452
  if (!definition) return;
449
- expandTemporal(definition.body, undefined, environment, true).forEach((item) => {
453
+ expandTemporal(definition.body, undefined, environment, true, name).forEach((item) => {
450
454
  const conjunct = item.expression;
451
455
  if (isConstantTrue(item, environment, "property")) return;
452
456
  if (conjunct.kind === "Always" && conjunct.expression.kind === "BoxAction") {
453
457
  properties.actionProperties.push({
454
- name,
458
+ name: item.name,
455
459
  box: conjunct.expression,
456
460
  action: conjunct.expression.action,
457
461
  subscript: conjunct.expression.subscript,
@@ -463,12 +467,22 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
463
467
  conjunct.kind === "Always" &&
464
468
  getLevel(conjunct.expression, item.scope, environment) <= 1
465
469
  ) {
466
- properties.invariants.push({ name, expression: conjunct.expression, scope: item.scope });
470
+ // TLC names the invariant []P after P when P is an operator name.
471
+ const expression = conjunct.expression;
472
+ properties.invariants.push({
473
+ name: expression.kind === "Identifier" ? expression.name : item.name,
474
+ expression,
475
+ scope: item.scope,
476
+ });
467
477
  return;
468
478
  }
469
479
  const level = getLevel(conjunct, item.scope, environment);
470
480
  if (level < ACTION_LEVEL) {
471
- properties.initialPredicates.push({ name, expression: conjunct, scope: item.scope });
481
+ properties.initialPredicates.push({
482
+ name: item.name,
483
+ expression: conjunct,
484
+ scope: item.scope,
485
+ });
472
486
  return;
473
487
  }
474
488
  if (level === ACTION_LEVEL) {
@@ -777,11 +791,13 @@ export const createSearch = (
777
791
  if (view !== undefined || isFingerprintedLikeTlc) {
778
792
  return BigInt64Array.from(states, getTlcStateFingerprint);
779
793
  }
780
- const indices = getTlcOrder();
781
- const getFingerprint = createTlcFingerprinter();
782
- return BigInt64Array.from(fingerprintStates, (state) =>
783
- getFingerprint(indices.map((index) => state[index])),
794
+ const fingerprints = new BigInt64Array(fingerprintStates.length);
795
+ const fingerprint = createTlcFingerprinter(
796
+ getTlcOrder(),
797
+ new Int32Array(fingerprints.buffer),
784
798
  );
799
+ fingerprintStates.forEach(fingerprint);
800
+ return fingerprints;
785
801
  },
786
802
  getFingerprintState: (state) => {
787
803
  if (isFingerprintedLikeTlc) return [String(getTlcStateFingerprint(state))];
@@ -887,6 +903,18 @@ export const createSearch = (
887
903
  const withNextStateExitCode = (error: unknown) =>
888
904
  error instanceof TlaModuleError ? setExitCode(error, error.exitCode) : error;
889
905
 
906
+ // TLC reports a failure of the next-state relation as an unexpected exception, unless a standard
907
+ // module raised it as an EvalException.
908
+ const toNextStateError = (error: unknown) =>
909
+ error instanceof TlaEvaluationError &&
910
+ !(error instanceof TlaModuleError) &&
911
+ !(error instanceof TlaIncompleteStateError)
912
+ ? setExitCode(
913
+ new TlaEvaluationError(`${UNEXPECTED_EXCEPTION}${error.message}`, error),
914
+ getErrorExitCode(error),
915
+ )
916
+ : withNextStateExitCode(error);
917
+
890
918
  const withHeadline = (error: unknown, headline: string) =>
891
919
  error instanceof TlaEvaluationError
892
920
  ? setExitCode(
@@ -973,7 +1001,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
973
1001
  });
974
1002
 
975
1003
  const search = createSearch(config, environment, () =>
976
- getTlcVariableOrder(options.source, options.loadModule),
1004
+ getTlcDeclarationOrder(options.source, options.loadModule, "variable"),
977
1005
  );
978
1006
  const assumptionViolation = findAssumptionViolation(specification.assumptions, environment);
979
1007
  if (assumptionViolation) return createResult("assumption-violation", assumptionViolation);
@@ -1542,7 +1570,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1542
1570
  try {
1543
1571
  outcome.result = expandState(index);
1544
1572
  } catch (error) {
1545
- outcome.result = toFailure(withNextStateExitCode(error), getStateTrace(index));
1573
+ outcome.result = toFailure(toNextStateError(error), getStateTrace(index));
1546
1574
  }
1547
1575
  if (outcome.result) return outcome.result;
1548
1576
  outDegrees[getOutDegreeBucket()]++;
package/src/codegen.ts CHANGED
@@ -10,6 +10,8 @@ import {
10
10
  getSubsetOperator,
11
11
  getEvaluator,
12
12
  getFieldError,
13
+ getNonFunctionError,
14
+ getNonRecordError,
13
15
  isClosedConstant,
14
16
  isTlcInteger,
15
17
  isValueArgument,
@@ -250,12 +252,13 @@ const generateExpression = (generator: Generator, expression: Expression, frame:
250
252
  case "FunctionApplication": {
251
253
  keepLazy(expression.function);
252
254
  const functionCode = generate(expression.function);
255
+ const describeNonFunction = addReference(generator, getNonFunctionError(expression));
253
256
  if (expression.args.length === 1)
254
- return `apply(${functionCode}, ${generate(expression.args[0])})`;
255
- return `apply(${functionCode}, tuple([${expression.args.map((arg) => generate(arg)).join(", ")}]))`;
257
+ return `apply(${functionCode}, ${generate(expression.args[0])}, undefined, ${describeNonFunction})`;
258
+ return `apply(${functionCode}, tuple([${expression.args.map((arg) => generate(arg)).join(", ")}]), undefined, ${describeNonFunction})`;
256
259
  }
257
260
  case "FieldAccess":
258
- return `apply(${generate(expression.record)}, ${JSON.stringify(expression.field)}, ${addReference(generator, getFieldError(expression))})`;
261
+ return `apply(${generate(expression.record)}, ${JSON.stringify(expression.field)}, ${addReference(generator, getFieldError(expression))}, ${addReference(generator, getNonRecordError(expression))})`;
259
262
  case "Record": {
260
263
  const fields = getSortedFields(expression.fields);
261
264
  if (hasDuplicateFields(fields)) return generateDelegate(generator, expression, frame);
@@ -12,7 +12,7 @@ import {
12
12
  import { BUNDLED_MODULES } from "./bundled-modules";
13
13
  import type { ConfigValue, ModelConfig } from "./config";
14
14
  import type { FileSystem } from "./json";
15
- import { TlaConfigError, TlaEvaluationError, TlaSyntaxError } from "./errors";
15
+ import { TlaConfigError, TlaEvaluationError, TlaModuleError, TlaSyntaxError } from "./errors";
16
16
  import { EXIT_STATUS, setExitCode } from "./exit-codes";
17
17
  import {
18
18
  createBigNumberError,
@@ -47,6 +47,7 @@ import { CORE_OPERATORS, getStandardModule, STANDARD_DEPENDENCIES } from "./stan
47
47
  import { resolveInstanceSubexpressions, resolveModuleSubexpressions } from "./subexpressions";
48
48
  import { checkModuleLevels, createLevelAnalyzer } from "./levels";
49
49
  import { checkInstances, type InstanceCheck } from "./substitution-levels";
50
+ import { getTlcDeclarationOrder } from "./tlc-order";
50
51
  import {
51
52
  checkInteger,
52
53
  createModelValue,
@@ -908,11 +909,19 @@ export const createEnvironment = (
908
909
  if (symbol.key === key && name !== key) definitions.set(name, alias);
909
910
  });
910
911
  });
911
- declaredConstants.forEach((name) => {
912
- if (!constants.has(name) && !substitutions.has(name) && !operatorKeys.has(name)) {
913
- throw new TlaConfigError(`The constant ${name} is not assigned a value by the configuration`);
914
- }
915
- });
912
+ const unassigned = declaredConstants.filter(
913
+ (name) => !constants.has(name) && !substitutions.has(name) && !operatorKeys.has(name),
914
+ );
915
+ if (unassigned.length > 0) {
916
+ // TLC reports the first constant it finds unassigned in SANY's order of declarations.
917
+ const name =
918
+ getTlcDeclarationOrder(options.source, options.loadModule, "constant").find((constant) =>
919
+ unassigned.includes(constant),
920
+ ) ?? unassigned[0];
921
+ throw new TlaConfigError(
922
+ `The constant parameter ${name} is not assigned a value by the configuration file.`,
923
+ );
924
+ }
916
925
 
917
926
  const environment: Environment = {
918
927
  runtime,
@@ -954,26 +963,28 @@ export const createEnvironment = (
954
963
  ]),
955
964
  getDefinition: (name) => getDefinition(name, environment),
956
965
  });
957
- const isEvaluable = (body: Expression) => {
966
+ const getEvaluationError = (body: Expression) => {
958
967
  try {
959
968
  evaluate(body, { environment, scope: undefined, state: undefined, next: undefined });
960
- return true;
969
+ return undefined;
961
970
  } catch (error) {
962
- if (error instanceof TlaEvaluationError) return false;
971
+ if (error instanceof TlaEvaluationError) return error;
963
972
  throw error;
964
973
  }
965
974
  };
966
975
  substitutions.forEach((target, name) => {
967
976
  const definition = definitions.get(target);
968
- if (
977
+ const error =
969
978
  declaredConstants.includes(name) &&
970
979
  definition?.kind === "Operator" &&
971
980
  definition.params.length === 0 &&
972
- analyzer.analyzeDefinition(definition, new Map()).level > 0 &&
973
- !isEvaluable(definition.body)
974
- ) {
981
+ analyzer.analyzeDefinition(definition, new Map()).level > 0
982
+ ? getEvaluationError(definition.body)
983
+ : undefined;
984
+ // TLC adds the reason unless a standard module's Java code failed.
985
+ if (error) {
975
986
  throw new TlaConfigError(
976
- `The configuration file substitutes constant ${name} with non-constant ${target}`,
987
+ `The configuration file substitutes constant ${name} with non-constant ${target}${error instanceof TlaModuleError ? "" : ` - specifically: ${error.message}`}`,
977
988
  );
978
989
  }
979
990
  });
package/src/errors.ts CHANGED
@@ -55,6 +55,15 @@ export class TlaModuleError extends TlaEvaluationError {
55
55
  }
56
56
  }
57
57
 
58
+ // TLC reports a successor state that the next-state relation leaves incomplete as an error of its
59
+ // own, not as an exception. It keeps the name TlaEvaluationError, and index.ts doesn't export it.
60
+ export class TlaIncompleteStateError extends TlaEvaluationError {
61
+ constructor(message: string) {
62
+ super(message);
63
+ this.name = "TlaEvaluationError";
64
+ }
65
+ }
66
+
58
67
  export interface TlapmReport {
59
68
  failure?: string;
60
69
  exception?: string;
package/src/evaluate.ts CHANGED
@@ -30,6 +30,7 @@ import {
30
30
  createSortedSet,
31
31
  createWrittenRecord,
32
32
  createTuple,
33
+ describeMissingField,
33
34
  formatValue,
34
35
  getDomain,
35
36
  getFunctionDomain,
@@ -38,6 +39,7 @@ import {
38
39
  getValueHash,
39
40
  isFunctionValue,
40
41
  isOverriddenSet,
42
+ isRecordValue,
41
43
  isSameValue,
42
44
  markLambdaFunction,
43
45
  isReducible,
@@ -47,6 +49,7 @@ import {
47
49
  toFiniteSet,
48
50
  updateFunction,
49
51
  valuesEqual,
52
+ type FunctionValue,
50
53
  type LazyFunctionSource,
51
54
  type LazyFunctionValue,
52
55
  type Value,
@@ -182,8 +185,17 @@ export const getConjunctError = (
182
185
  };
183
186
 
184
187
  export const getFieldError =
185
- (expression: Expression & { kind: "FieldAccess" }) => (record: Value) =>
186
- `Attempted to select nonexistent field "${expression.field}" from the record\n${formatValue(record)}\n${describeRange(expression)}`;
188
+ (expression: Expression & { kind: "FieldAccess" }) => (record: FunctionValue) =>
189
+ isRecordValue(record)
190
+ ? `Attempted to select nonexistent field "${expression.field}" from the record\n${formatValue(record)}\n${describeRange(expression)}`
191
+ : describeMissingField(record, expression.field);
192
+
193
+ export const getNonFunctionError = (expression: Expression) => (value: Value) =>
194
+ `A non-function (${getKindString(value)}) was applied as a function.\n${describeRange(expression)}`;
195
+
196
+ export const getNonRecordError =
197
+ (expression: Expression & { kind: "FieldAccess" }) => (value: Value) =>
198
+ `Attempted to select field "${expression.field}" from a non-record value ${formatValue(value)}\n${describeRange(expression)}`;
187
199
 
188
200
  export const getDomainOperator = (expression: Expression) => (value: Value) => {
189
201
  if (!isFunctionValue(value)) {
@@ -1027,7 +1039,7 @@ export const getEvaluator = (expression: Expression, environment: Environment):
1027
1039
 
1028
1040
  const entryEvaluators = new WeakMap<Expression, Evaluator>();
1029
1041
 
1030
- const getEntryEvaluator = (expression: Expression, environment: Environment) => {
1042
+ export const getEntryEvaluator = (expression: Expression, environment: Environment) => {
1031
1043
  const cached = entryEvaluators.get(expression);
1032
1044
  if (cached) return cached;
1033
1045
  const evaluator =
@@ -1574,7 +1586,9 @@ export const hasDuplicateFields = (sortedFields: RecordField[]) =>
1574
1586
  sortedFields.some((field, index) => index > 0 && sortedFields[index - 1].name === field.name);
1575
1587
 
1576
1588
  export const createUnassignedError = (name: string, expression: Expression) =>
1577
- new TlaEvaluationError(`The variable ${name} is not assigned at ${describeLocation(expression)}`);
1589
+ new TlaEvaluationError(
1590
+ `In evaluation, the identifier ${name} is either undefined or not an operator.\n${describeRange(expression)}`,
1591
+ );
1578
1592
 
1579
1593
  export const createPrimeOutsideActionError = (expression: Expression) =>
1580
1594
  new TlaEvaluationError(
@@ -1762,18 +1776,31 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1762
1776
  keepLazy(expression.function);
1763
1777
  const evaluateFunction = child(expression.function);
1764
1778
  const args = expression.args.map(child);
1779
+ const describeNonFunction = getNonFunctionError(expression);
1765
1780
  if (args.length === 1) {
1766
1781
  const argument = args[0];
1767
- return (context) => applyFunction(evaluateFunction(context), argument(context));
1782
+ return (context) =>
1783
+ applyFunction(
1784
+ evaluateFunction(context),
1785
+ argument(context),
1786
+ undefined,
1787
+ describeNonFunction,
1788
+ );
1768
1789
  }
1769
1790
  return (context) =>
1770
- applyFunction(evaluateFunction(context), createTuple(args.map((arg) => arg(context))));
1791
+ applyFunction(
1792
+ evaluateFunction(context),
1793
+ createTuple(args.map((arg) => arg(context))),
1794
+ undefined,
1795
+ describeNonFunction,
1796
+ );
1771
1797
  }
1772
1798
  case "FieldAccess": {
1773
1799
  const record = child(expression.record);
1774
1800
  const field = expression.field;
1775
1801
  const describeMissing = getFieldError(expression);
1776
- return (context) => applyFunction(record(context), field, describeMissing);
1802
+ const describeNonRecord = getNonRecordError(expression);
1803
+ return (context) => applyFunction(record(context), field, describeMissing, describeNonRecord);
1777
1804
  }
1778
1805
  case "Product": {
1779
1806
  const factors = expression.factors.map(child);