tla-ts 0.0.3-dev.b1578d0 → 0.0.3-dev.bcfa494

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.b1578d0",
3
+ "version": "0.0.3-dev.bcfa494",
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";
@@ -446,12 +447,12 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
446
447
  config.properties.forEach((name) => {
447
448
  const definition = getConfigPredicate("property", name, environment);
448
449
  if (!definition) return;
449
- expandTemporal(definition.body, undefined, environment, true).forEach((item) => {
450
+ expandTemporal(definition.body, undefined, environment, true, name).forEach((item) => {
450
451
  const conjunct = item.expression;
451
452
  if (isConstantTrue(item, environment, "property")) return;
452
453
  if (conjunct.kind === "Always" && conjunct.expression.kind === "BoxAction") {
453
454
  properties.actionProperties.push({
454
- name,
455
+ name: item.name,
455
456
  box: conjunct.expression,
456
457
  action: conjunct.expression.action,
457
458
  subscript: conjunct.expression.subscript,
@@ -463,12 +464,22 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
463
464
  conjunct.kind === "Always" &&
464
465
  getLevel(conjunct.expression, item.scope, environment) <= 1
465
466
  ) {
466
- properties.invariants.push({ name, expression: conjunct.expression, scope: item.scope });
467
+ // TLC names the invariant []P after P when P is an operator name.
468
+ const expression = conjunct.expression;
469
+ properties.invariants.push({
470
+ name: expression.kind === "Identifier" ? expression.name : item.name,
471
+ expression,
472
+ scope: item.scope,
473
+ });
467
474
  return;
468
475
  }
469
476
  const level = getLevel(conjunct, item.scope, environment);
470
477
  if (level < ACTION_LEVEL) {
471
- properties.initialPredicates.push({ name, expression: conjunct, scope: item.scope });
478
+ properties.initialPredicates.push({
479
+ name: item.name,
480
+ expression: conjunct,
481
+ scope: item.scope,
482
+ });
472
483
  return;
473
484
  }
474
485
  if (level === ACTION_LEVEL) {
@@ -528,7 +539,9 @@ const getMembership = (
528
539
  const getStateChecks = (named: NamedExpression[], environment: Environment): StateCheck[] =>
529
540
  named.flatMap((item) =>
530
541
  getConjuncts(item.expression, environment).map((expression) => {
531
- const variables = getReadVariables(expression, environment);
542
+ // A LET or an argument in the scope can read variables the expression doesn't name.
543
+ const variables =
544
+ item.scope === undefined ? getReadVariables(expression, environment) : undefined;
532
545
  return {
533
546
  name: item.name,
534
547
  expression,
@@ -775,11 +788,13 @@ export const createSearch = (
775
788
  if (view !== undefined || isFingerprintedLikeTlc) {
776
789
  return BigInt64Array.from(states, getTlcStateFingerprint);
777
790
  }
778
- const indices = getTlcOrder();
779
- const getFingerprint = createTlcFingerprinter();
780
- return BigInt64Array.from(fingerprintStates, (state) =>
781
- getFingerprint(indices.map((index) => state[index])),
791
+ const fingerprints = new BigInt64Array(fingerprintStates.length);
792
+ const fingerprint = createTlcFingerprinter(
793
+ getTlcOrder(),
794
+ new Int32Array(fingerprints.buffer),
782
795
  );
796
+ fingerprintStates.forEach(fingerprint);
797
+ return fingerprints;
783
798
  },
784
799
  getFingerprintState: (state) => {
785
800
  if (isFingerprintedLikeTlc) return [String(getTlcStateFingerprint(state))];
@@ -885,6 +900,18 @@ export const createSearch = (
885
900
  const withNextStateExitCode = (error: unknown) =>
886
901
  error instanceof TlaModuleError ? setExitCode(error, error.exitCode) : error;
887
902
 
903
+ // TLC reports a failure of the next-state relation as an unexpected exception, unless a standard
904
+ // module raised it as an EvalException.
905
+ const toNextStateError = (error: unknown) =>
906
+ error instanceof TlaEvaluationError &&
907
+ !(error instanceof TlaModuleError) &&
908
+ !(error instanceof TlaIncompleteStateError)
909
+ ? setExitCode(
910
+ new TlaEvaluationError(`${UNEXPECTED_EXCEPTION}${error.message}`, error),
911
+ getErrorExitCode(error),
912
+ )
913
+ : withNextStateExitCode(error);
914
+
888
915
  const withHeadline = (error: unknown, headline: string) =>
889
916
  error instanceof TlaEvaluationError
890
917
  ? setExitCode(
@@ -971,7 +998,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
971
998
  });
972
999
 
973
1000
  const search = createSearch(config, environment, () =>
974
- getTlcVariableOrder(options.source, options.loadModule),
1001
+ getTlcDeclarationOrder(options.source, options.loadModule, "variable"),
975
1002
  );
976
1003
  const assumptionViolation = findAssumptionViolation(specification.assumptions, environment);
977
1004
  if (assumptionViolation) return createResult("assumption-violation", assumptionViolation);
@@ -1035,7 +1062,9 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1035
1062
  const parents: number[] = [];
1036
1063
  const actions: (string | undefined)[] = [];
1037
1064
  const depths: number[] = [];
1038
- const buckets = new Map<number, number | number[]>();
1065
+ // A Map holds at most 2^24 entries, so an open-addressing table keeps each seen state's hash
1066
+ // and its index plus one side by side, probed by the hash.
1067
+ const seen = { slots: new Int32Array(1 << 17), size: 0, shift: 16 };
1039
1068
  const canonicalizeState = createCanonicalizer();
1040
1069
 
1041
1070
  const toRecord = (state: Value[]): Record<string, Value> =>
@@ -1195,19 +1224,35 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1195
1224
  }
1196
1225
  return true;
1197
1226
  };
1227
+ const getSlot = (hash: number) => (Math.imul(hash, 0x9e3779b1) >>> seen.shift) << 1;
1198
1228
  const findStateIndex = (hash: number, state: Value[]) => {
1199
- const bucket = buckets.get(hash);
1200
- if (bucket === undefined) return -1;
1201
- if (typeof bucket === "number") {
1202
- return isSameState(fingerprintStates[bucket], state) ? bucket : -1;
1229
+ const mask = seen.slots.length - 1;
1230
+ for (let slot = getSlot(hash); ; slot = (slot + 2) & mask) {
1231
+ const entry = seen.slots[slot + 1];
1232
+ if (entry === 0) return -1;
1233
+ if (seen.slots[slot] === hash && isSameState(fingerprintStates[entry - 1], state)) {
1234
+ return entry - 1;
1235
+ }
1203
1236
  }
1204
- return bucket.find((index) => isSameState(fingerprintStates[index], state)) ?? -1;
1237
+ };
1238
+ const insertSeen = (hash: number, entry: number) => {
1239
+ const mask = seen.slots.length - 1;
1240
+ let slot = getSlot(hash);
1241
+ while (seen.slots[slot + 1] !== 0) slot = (slot + 2) & mask;
1242
+ seen.slots[slot] = hash;
1243
+ seen.slots[slot + 1] = entry;
1205
1244
  };
1206
1245
  const markSeen = (hash: number, index: number) => {
1207
- const bucket = buckets.get(hash);
1208
- if (bucket === undefined) buckets.set(hash, index);
1209
- else if (typeof bucket === "number") buckets.set(hash, [bucket, index]);
1210
- else bucket.push(index);
1246
+ seen.size++;
1247
+ if (seen.size * 4 > seen.slots.length) {
1248
+ const slots = seen.slots;
1249
+ seen.slots = new Int32Array(slots.length * 2);
1250
+ seen.shift--;
1251
+ for (let slot = 0; slot < slots.length; slot += 2) {
1252
+ if (slots[slot + 1] !== 0) insertSeen(slots[slot], slots[slot + 1]);
1253
+ }
1254
+ }
1255
+ insertSeen(hash, index + 1);
1211
1256
  };
1212
1257
  const countDistinctState = (depth: number) => {
1213
1258
  runtime.distinctStates = states.length + 1;
@@ -1522,7 +1567,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1522
1567
  try {
1523
1568
  outcome.result = expandState(index);
1524
1569
  } catch (error) {
1525
- outcome.result = toFailure(withNextStateExitCode(error), getStateTrace(index));
1570
+ outcome.result = toFailure(toNextStateError(error), getStateTrace(index));
1526
1571
  }
1527
1572
  if (outcome.result) return outcome.result;
1528
1573
  outDegrees[getOutDegreeBucket()]++;
@@ -17,7 +17,8 @@ import { EXIT_STATUS, setExitCode } from "./exit-codes";
17
17
  import {
18
18
  createBigNumberError,
19
19
  createRealNumberError,
20
- isConstantLevel,
20
+ evaluate,
21
+ getDefinition,
21
22
  isTlcInteger,
22
23
  type Builtin,
23
24
  type Environment,
@@ -44,8 +45,9 @@ import {
44
45
  import { createRuntime } from "./runtime";
45
46
  import { CORE_OPERATORS, getStandardModule, STANDARD_DEPENDENCIES } from "./standard-modules";
46
47
  import { resolveInstanceSubexpressions, resolveModuleSubexpressions } from "./subexpressions";
47
- import { checkModuleLevels } from "./levels";
48
+ import { checkModuleLevels, createLevelAnalyzer } from "./levels";
48
49
  import { checkInstances, type InstanceCheck } from "./substitution-levels";
50
+ import { getTlcDeclarationOrder } from "./tlc-order";
49
51
  import {
50
52
  checkInteger,
51
53
  createModelValue,
@@ -212,6 +214,8 @@ export const createEnvironment = (
212
214
  const root = parseModule(options.source);
213
215
  const definitions = new Map<string, Definition>();
214
216
  const parameterized = new Map<string, boolean>();
217
+ // The definition each instance copy came from, and the instance parameters the copy adds.
218
+ const copySources = new Map<string, { source: string; prefix: number }>();
215
219
  const builtins = new Map<string, Builtin>(
216
220
  CORE_OPERATORS.map((operator) => [operator.name, operator]),
217
221
  );
@@ -379,10 +383,11 @@ export const createEnvironment = (
379
383
  variables: new Set(linked.variables),
380
384
  getDefinition: (key) => definitions.get(key),
381
385
  isParameterized: (key) => parameterized.get(key) === true,
382
- addDefinition: (name, create) => {
386
+ addDefinition: (source, name, create) => {
383
387
  const key = createName(`${name}@${module.name}`);
384
388
  definitions.set(key, create(key));
385
389
  parameterized.set(key, !isParameterFree);
390
+ copySources.set(key, { source, prefix: instance.params.length });
386
391
  return key;
387
392
  },
388
393
  createName,
@@ -544,7 +549,7 @@ export const createEnvironment = (
544
549
  variables: new Set(linked.variables),
545
550
  getDefinition: (key) => definitions.get(key),
546
551
  isParameterized: (key) => parameterized.get(key) === true,
547
- addDefinition: (name, create) => {
552
+ addDefinition: (_source, name, create) => {
548
553
  const key = `${name}${KEY_SEPARATOR}${instance.module}${suffix}.${copies.length}`;
549
554
  const definition = create(key);
550
555
  copies.push(
@@ -872,11 +877,51 @@ export const createEnvironment = (
872
877
  );
873
878
  }
874
879
  });
875
- declaredConstants.forEach((name) => {
876
- if (!constants.has(name) && !substitutions.has(name) && !operatorKeys.has(name)) {
877
- throw new TlaConfigError(`The constant ${name} is not assigned a value by the configuration`);
878
- }
880
+ // TLC sets a module-scoped entry on the body of the module's definition, which every instance of
881
+ // the module shares.
882
+ const scopedKeys = new Set(
883
+ [...config.constants, ...config.substitutions]
884
+ .filter((item) => item.module !== undefined)
885
+ .flatMap(getScopedKeys),
886
+ );
887
+ const getOverride = (
888
+ key: string,
889
+ prefix: number,
890
+ ): { key: string; prefix: number } | undefined => {
891
+ if (scopedKeys.has(key)) return { key, prefix };
892
+ const copy = copySources.get(key);
893
+ return copy && getOverride(copy.source, prefix + copy.prefix);
894
+ };
895
+ copySources.forEach((copy, key) => {
896
+ const override = getOverride(copy.source, copy.prefix);
897
+ const definition = definitions.get(key);
898
+ if (!override || !definition) return;
899
+ const params = definition.kind === "Operator" ? definition.params : [];
900
+ const alias = createLocalAlias(
901
+ key,
902
+ override.key,
903
+ params,
904
+ params.slice(override.prefix),
905
+ definition.location,
906
+ );
907
+ definitions.set(key, alias);
908
+ linkedRoot.visible.forEach((symbol, name) => {
909
+ if (symbol.key === key && name !== key) definitions.set(name, alias);
910
+ });
879
911
  });
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
+ }
880
925
 
881
926
  const environment: Environment = {
882
927
  runtime,
@@ -907,18 +952,41 @@ export const createEnvironment = (
907
952
  getDefinition: (symbol) => definitions.get(linked.visible.get(symbol)?.key ?? symbol),
908
953
  };
909
954
  });
955
+ // TLC evaluates a substitute at startup and rejects it only when that fails and the level bound it
956
+ // computes is above constant. The bound counts the operators that TLC's Java code overrides with
957
+ // a minimum level as state-level, so the analyzer takes them for variables.
958
+ const analyzer = createLevelAnalyzer({
959
+ constants: new Set(constants.keys()),
960
+ variables: new Set([
961
+ ...variables,
962
+ ...["TLCGet", "Trace", "CounterExample"].filter((name) => builtins.has(name)),
963
+ ]),
964
+ getDefinition: (name) => getDefinition(name, environment),
965
+ });
966
+ const isEvaluable = (body: Expression) => {
967
+ try {
968
+ evaluate(body, { environment, scope: undefined, state: undefined, next: undefined });
969
+ return true;
970
+ } catch (error) {
971
+ if (error instanceof TlaEvaluationError) return false;
972
+ throw error;
973
+ }
974
+ };
910
975
  substitutions.forEach((target, name) => {
911
976
  const definition = definitions.get(target);
912
977
  if (
913
978
  declaredConstants.includes(name) &&
914
- definition &&
915
- !isConstantLevel(definition, environment)
979
+ definition?.kind === "Operator" &&
980
+ definition.params.length === 0 &&
981
+ analyzer.analyzeDefinition(definition, new Map()).level > 0 &&
982
+ !isEvaluable(definition.body)
916
983
  ) {
917
984
  throw new TlaConfigError(
918
985
  `The configuration file substitutes constant ${name} with non-constant ${target}`,
919
986
  );
920
987
  }
921
988
  });
989
+ runtime.isStarted = true;
922
990
  return {
923
991
  environment,
924
992
  assumptions,
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
@@ -36,11 +36,11 @@ import {
36
36
  getIntervalElements,
37
37
  getSequenceElements,
38
38
  getValueHash,
39
- isEnumerable,
40
39
  isFunctionValue,
41
40
  isOverriddenSet,
42
41
  isSameValue,
43
42
  markLambdaFunction,
43
+ isReducible,
44
44
  isSetValue,
45
45
  MAXIMUM_INTEGER,
46
46
  MINIMUM_INTEGER,
@@ -1027,7 +1027,7 @@ export const getEvaluator = (expression: Expression, environment: Environment):
1027
1027
 
1028
1028
  const entryEvaluators = new WeakMap<Expression, Evaluator>();
1029
1029
 
1030
- const getEntryEvaluator = (expression: Expression, environment: Environment) => {
1030
+ export const getEntryEvaluator = (expression: Expression, environment: Environment) => {
1031
1031
  const cached = entryEvaluators.get(expression);
1032
1032
  if (cached) return cached;
1033
1033
  const evaluator =
@@ -1420,7 +1420,13 @@ const compileFunctionConstruction = (
1420
1420
  const set = getEvaluator(bound.set, environment);
1421
1421
  return (context) => {
1422
1422
  const domain = isSingleName ? set(context) : getBoundsDomain(bounds, context);
1423
- if (expression.isRecursive || isKeptLazy || !isEnumerable(domain)) {
1423
+ // TLC builds the function only when it reduces every domain, and evaluates the body lazily
1424
+ // otherwise.
1425
+ const domains =
1426
+ typeof domain === "object" && domain.kind === "ProductSet" && bounds.length > 1
1427
+ ? domain.factors
1428
+ : [domain];
1429
+ if (expression.isRecursive || isKeptLazy || !domains.every(isReducible)) {
1424
1430
  const functionValue = createLazyFunction(
1425
1431
  domain,
1426
1432
  (argument) => body(withScope(context, bindArgument(bounds, context.scope, argument))),
@@ -1514,10 +1520,7 @@ const compileSetComprehension = (
1514
1520
  predicate(withScope(context, bindPattern(context.scope, pattern, element))),
1515
1521
  "a set filter predicate",
1516
1522
  );
1517
- const isReducible =
1518
- typeof base === "object" &&
1519
- (base.kind === "Set" || base.kind === "MixedSet" || base.kind === "Interval");
1520
- if (!isReducible) {
1523
+ if (!isReducible(base)) {
1521
1524
  if (isSetValue(base)) return { kind: "FilteredSet", base, test };
1522
1525
  throw new TlaEvaluationError(
1523
1526
  `TLC encountered a non-enumerable quantifier bound ${formatValue(base)} at ${describeLocation(expression.bound.set)}`,
package/src/instances.ts CHANGED
@@ -219,7 +219,7 @@ interface Instantiation {
219
219
  variables: Set<string>;
220
220
  getDefinition: (key: string) => Definition | undefined;
221
221
  isParameterized: (key: string) => boolean;
222
- addDefinition: (name: string, create: (key: string) => Definition) => string;
222
+ addDefinition: (source: string, name: string, create: (key: string) => Definition) => string;
223
223
  createName: (name: string) => string;
224
224
  }
225
225
 
@@ -640,7 +640,7 @@ const copyDefinition = (rewrite: Rewrite, key: string): string => {
640
640
  const instantiation = rewrite.instantiation;
641
641
  const definition = instantiation.getDefinition(key);
642
642
  if (!definition) return key;
643
- return instantiation.addDefinition(definition.name, (copyKey) => {
643
+ return instantiation.addDefinition(key, definition.name, (copyKey) => {
644
644
  rewrite.copies.set(key, copyKey);
645
645
  const rename = createRenamer(rewrite);
646
646
  const mapped = renameParams(
@@ -679,7 +679,7 @@ export const createInstantiation = (instantiation: Instantiation) => {
679
679
  if (copy !== undefined) return copy;
680
680
  const definition = instantiation.getDefinition(key);
681
681
  if (!definition) return key;
682
- return instantiation.addDefinition(definition.name, () =>
682
+ return instantiation.addDefinition(key, definition.name, () =>
683
683
  withInstanceParams(definition, instantiation.params, definition.location),
684
684
  );
685
685
  },