tla-ts 0.0.3-dev.51ddd47 → 0.0.3-dev.598a74f

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.51ddd47",
3
+ "version": "0.0.3-dev.598a74f",
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);
@@ -1037,7 +1065,9 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1037
1065
  const parents: number[] = [];
1038
1066
  const actions: (string | undefined)[] = [];
1039
1067
  const depths: number[] = [];
1040
- const buckets = new Map<number, number | number[]>();
1068
+ // A Map holds at most 2^24 entries, so an open-addressing table keeps each seen state's hash
1069
+ // and its index plus one side by side, probed by the hash.
1070
+ const seen = { slots: new Int32Array(1 << 17), size: 0, shift: 16 };
1041
1071
  const canonicalizeState = createCanonicalizer();
1042
1072
 
1043
1073
  const toRecord = (state: Value[]): Record<string, Value> =>
@@ -1197,19 +1227,35 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1197
1227
  }
1198
1228
  return true;
1199
1229
  };
1230
+ const getSlot = (hash: number) => (Math.imul(hash, 0x9e3779b1) >>> seen.shift) << 1;
1200
1231
  const findStateIndex = (hash: number, state: Value[]) => {
1201
- const bucket = buckets.get(hash);
1202
- if (bucket === undefined) return -1;
1203
- if (typeof bucket === "number") {
1204
- return isSameState(fingerprintStates[bucket], state) ? bucket : -1;
1232
+ const mask = seen.slots.length - 1;
1233
+ for (let slot = getSlot(hash); ; slot = (slot + 2) & mask) {
1234
+ const entry = seen.slots[slot + 1];
1235
+ if (entry === 0) return -1;
1236
+ if (seen.slots[slot] === hash && isSameState(fingerprintStates[entry - 1], state)) {
1237
+ return entry - 1;
1238
+ }
1205
1239
  }
1206
- return bucket.find((index) => isSameState(fingerprintStates[index], state)) ?? -1;
1240
+ };
1241
+ const insertSeen = (hash: number, entry: number) => {
1242
+ const mask = seen.slots.length - 1;
1243
+ let slot = getSlot(hash);
1244
+ while (seen.slots[slot + 1] !== 0) slot = (slot + 2) & mask;
1245
+ seen.slots[slot] = hash;
1246
+ seen.slots[slot + 1] = entry;
1207
1247
  };
1208
1248
  const markSeen = (hash: number, index: number) => {
1209
- const bucket = buckets.get(hash);
1210
- if (bucket === undefined) buckets.set(hash, index);
1211
- else if (typeof bucket === "number") buckets.set(hash, [bucket, index]);
1212
- else bucket.push(index);
1249
+ seen.size++;
1250
+ if (seen.size * 4 > seen.slots.length) {
1251
+ const slots = seen.slots;
1252
+ seen.slots = new Int32Array(slots.length * 2);
1253
+ seen.shift--;
1254
+ for (let slot = 0; slot < slots.length; slot += 2) {
1255
+ if (slots[slot + 1] !== 0) insertSeen(slots[slot], slots[slot + 1]);
1256
+ }
1257
+ }
1258
+ insertSeen(hash, index + 1);
1213
1259
  };
1214
1260
  const countDistinctState = (depth: number) => {
1215
1261
  runtime.distinctStates = states.length + 1;
@@ -1524,7 +1570,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1524
1570
  try {
1525
1571
  outcome.result = expandState(index);
1526
1572
  } catch (error) {
1527
- outcome.result = toFailure(withNextStateExitCode(error), getStateTrace(index));
1573
+ outcome.result = toFailure(toNextStateError(error), getStateTrace(index));
1528
1574
  }
1529
1575
  if (outcome.result) return outcome.result;
1530
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);
@@ -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,
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,23 +30,26 @@ import {
30
30
  createSortedSet,
31
31
  createWrittenRecord,
32
32
  createTuple,
33
+ describeMissingField,
33
34
  formatValue,
34
35
  getDomain,
35
36
  getFunctionDomain,
36
37
  getIntervalElements,
37
38
  getSequenceElements,
38
39
  getValueHash,
39
- isEnumerable,
40
40
  isFunctionValue,
41
41
  isOverriddenSet,
42
+ isRecordValue,
42
43
  isSameValue,
43
44
  markLambdaFunction,
45
+ isReducible,
44
46
  isSetValue,
45
47
  MAXIMUM_INTEGER,
46
48
  MINIMUM_INTEGER,
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 =
@@ -1420,7 +1432,13 @@ const compileFunctionConstruction = (
1420
1432
  const set = getEvaluator(bound.set, environment);
1421
1433
  return (context) => {
1422
1434
  const domain = isSingleName ? set(context) : getBoundsDomain(bounds, context);
1423
- if (expression.isRecursive || isKeptLazy || !isEnumerable(domain)) {
1435
+ // TLC builds the function only when it reduces every domain, and evaluates the body lazily
1436
+ // otherwise.
1437
+ const domains =
1438
+ typeof domain === "object" && domain.kind === "ProductSet" && bounds.length > 1
1439
+ ? domain.factors
1440
+ : [domain];
1441
+ if (expression.isRecursive || isKeptLazy || !domains.every(isReducible)) {
1424
1442
  const functionValue = createLazyFunction(
1425
1443
  domain,
1426
1444
  (argument) => body(withScope(context, bindArgument(bounds, context.scope, argument))),
@@ -1514,10 +1532,7 @@ const compileSetComprehension = (
1514
1532
  predicate(withScope(context, bindPattern(context.scope, pattern, element))),
1515
1533
  "a set filter predicate",
1516
1534
  );
1517
- const isReducible =
1518
- typeof base === "object" &&
1519
- (base.kind === "Set" || base.kind === "MixedSet" || base.kind === "Interval");
1520
- if (!isReducible) {
1535
+ if (!isReducible(base)) {
1521
1536
  if (isSetValue(base)) return { kind: "FilteredSet", base, test };
1522
1537
  throw new TlaEvaluationError(
1523
1538
  `TLC encountered a non-enumerable quantifier bound ${formatValue(base)} at ${describeLocation(expression.bound.set)}`,
@@ -1571,7 +1586,9 @@ export const hasDuplicateFields = (sortedFields: RecordField[]) =>
1571
1586
  sortedFields.some((field, index) => index > 0 && sortedFields[index - 1].name === field.name);
1572
1587
 
1573
1588
  export const createUnassignedError = (name: string, expression: Expression) =>
1574
- 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
+ );
1575
1592
 
1576
1593
  export const createPrimeOutsideActionError = (expression: Expression) =>
1577
1594
  new TlaEvaluationError(
@@ -1759,18 +1776,31 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1759
1776
  keepLazy(expression.function);
1760
1777
  const evaluateFunction = child(expression.function);
1761
1778
  const args = expression.args.map(child);
1779
+ const describeNonFunction = getNonFunctionError(expression);
1762
1780
  if (args.length === 1) {
1763
1781
  const argument = args[0];
1764
- return (context) => applyFunction(evaluateFunction(context), argument(context));
1782
+ return (context) =>
1783
+ applyFunction(
1784
+ evaluateFunction(context),
1785
+ argument(context),
1786
+ undefined,
1787
+ describeNonFunction,
1788
+ );
1765
1789
  }
1766
1790
  return (context) =>
1767
- 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
+ );
1768
1797
  }
1769
1798
  case "FieldAccess": {
1770
1799
  const record = child(expression.record);
1771
1800
  const field = expression.field;
1772
1801
  const describeMissing = getFieldError(expression);
1773
- return (context) => applyFunction(record(context), field, describeMissing);
1802
+ const describeNonRecord = getNonRecordError(expression);
1803
+ return (context) => applyFunction(record(context), field, describeMissing, describeNonRecord);
1774
1804
  }
1775
1805
  case "Product": {
1776
1806
  const factors = expression.factors.map(child);