tla-ts 0.0.3-dev.6a30eee → 0.0.3-dev.6d0aeb6

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 (54) hide show
  1. package/README.md +5 -1
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.cts +58 -22
  4. package/dist/index.d.ts +58 -22
  5. package/dist/index.js +1 -1
  6. package/dist/parallel-worker.cjs +1 -1
  7. package/dist/parallel-worker.js +2 -2
  8. package/dist/parallel.cjs +1 -1
  9. package/dist/parallel.js +2 -2
  10. package/dist/run-cli.cjs +20 -18
  11. package/dist/run-cli.js +22 -20
  12. package/dist/transfer.cjs +40 -15
  13. package/dist/transfer.js +40 -15
  14. package/package.json +1 -1
  15. package/src/ast.ts +101 -1
  16. package/src/builtins.ts +9 -3
  17. package/src/check.ts +473 -100
  18. package/src/cli-options.ts +11 -5
  19. package/src/codegen.ts +15 -22
  20. package/src/config.ts +224 -170
  21. package/src/dependencies.ts +2 -2
  22. package/src/environment.ts +158 -49
  23. package/src/errors.ts +93 -3
  24. package/src/evaluate.ts +214 -147
  25. package/src/exit-codes.ts +21 -14
  26. package/src/fingerprints.ts +2 -1
  27. package/src/instances.ts +16 -15
  28. package/src/levels.ts +181 -45
  29. package/src/live-check.ts +132 -70
  30. package/src/liveness.ts +118 -24
  31. package/src/parallel-worker.ts +2 -2
  32. package/src/parallel.ts +5 -2
  33. package/src/parser.ts +71 -19
  34. package/src/resolve.ts +490 -95
  35. package/src/run-cli.ts +104 -18
  36. package/src/runtime.ts +2 -0
  37. package/src/sany-lexer.ts +615 -0
  38. package/src/sany-parse-error.ts +3143 -0
  39. package/src/spec-description.ts +19 -8
  40. package/src/standard-modules.ts +54 -45
  41. package/src/state-graph.ts +157 -0
  42. package/src/subexpressions.ts +35 -23
  43. package/src/substitution-levels.ts +38 -17
  44. package/src/successors.ts +176 -36
  45. package/src/symmetry.ts +16 -6
  46. package/src/tableau.ts +51 -24
  47. package/src/tlc-ext.ts +29 -12
  48. package/src/tlc-module.ts +14 -33
  49. package/src/tlc-modules.ts +4 -0
  50. package/src/tlc-order.ts +8 -4
  51. package/src/tlc-random.ts +9 -6
  52. package/src/tlc-summary.ts +20 -5
  53. package/src/value-sources.ts +29 -0
  54. package/src/values.ts +242 -61
@@ -1,23 +1,30 @@
1
- import type {
2
- Assumption,
3
- Declaration,
4
- Definition,
5
- Expression,
6
- Instance,
7
- Module,
8
- OperatorParam,
9
- SourceLocation,
1
+ import {
2
+ getChildren,
3
+ type Assumption,
4
+ type Declaration,
5
+ type Definition,
6
+ type Expression,
7
+ type Instance,
8
+ type Module,
9
+ type OperatorParam,
10
+ type SourceLocation,
10
11
  } from "./ast";
11
12
  import { BUNDLED_MODULES } from "./bundled-modules";
12
13
  import type { ConfigValue, ModelConfig } from "./config";
13
14
  import type { FileSystem } from "./json";
14
- import { TlaConfigError, TlaEvaluationError, TlaSyntaxError } from "./errors";
15
+ import {
16
+ createSanyError,
17
+ TlaConfigError,
18
+ TlaEvaluationError,
19
+ TlaModuleError,
20
+ TlaSyntaxError,
21
+ } from "./errors";
15
22
  import { EXIT_STATUS, setExitCode } from "./exit-codes";
16
23
  import {
17
24
  createBigNumberError,
18
25
  createRealNumberError,
19
- getChildren,
20
- isConstantLevel,
26
+ evaluate,
27
+ getDefinition,
21
28
  isTlcInteger,
22
29
  type Builtin,
23
30
  type Environment,
@@ -42,10 +49,12 @@ import {
42
49
  type Symbols,
43
50
  } from "./resolve";
44
51
  import { createRuntime } from "./runtime";
52
+ import { parseModuleFile } from "./sany-parse-error";
45
53
  import { CORE_OPERATORS, getStandardModule, STANDARD_DEPENDENCIES } from "./standard-modules";
46
54
  import { resolveInstanceSubexpressions, resolveModuleSubexpressions } from "./subexpressions";
47
- import { checkModuleLevels } from "./levels";
48
- import { checkInstances, type InstanceCheck } from "./substitution-levels";
55
+ import { checkModuleLevels, createLevelAnalyzer } from "./levels";
56
+ import { createInstanceChecker, type InstanceCheck } from "./substitution-levels";
57
+ import { getTlcDeclarationOrder } from "./tlc-order";
49
58
  import {
50
59
  checkInteger,
51
60
  createModelValue,
@@ -212,6 +221,8 @@ export const createEnvironment = (
212
221
  const root = parseModule(options.source);
213
222
  const definitions = new Map<string, Definition>();
214
223
  const parameterized = new Map<string, boolean>();
224
+ // The definition each instance copy came from, and the instance parameters the copy adds.
225
+ const copySources = new Map<string, { source: string; prefix: number }>();
215
226
  const builtins = new Map<string, Builtin>(
216
227
  CORE_OPERATORS.map((operator) => [operator.name, operator]),
217
228
  );
@@ -219,6 +230,8 @@ export const createEnvironment = (
219
230
  const runtime = createRuntime(config.checkDeadlock, options.seed);
220
231
  const linkedModules = new Map<string, LinkedModule>();
221
232
  const nestedModules = new Map<string, LinkedModule>();
233
+ // Each module by name, from the time its level checks run.
234
+ const checkedModules = new Map<string, LinkedModule>();
222
235
  const linkedList: LinkedModule[] = [];
223
236
  const dependencies = new Map<string, Set<string>>();
224
237
  const loading: Set<string>[] = [];
@@ -233,7 +246,23 @@ export const createEnvironment = (
233
246
  const copyCount = { value: 0 };
234
247
  const createName = (name: string) => `${name}#${copyCount.value++}`;
235
248
  const instanceChecks: InstanceCheck[] = [];
249
+ const checkInstance = createInstanceChecker((name) => {
250
+ const linked = checkedModules.get(name) ?? getLinkedModule(name, name);
251
+ return {
252
+ constants: linked.constants,
253
+ variables: linked.variables,
254
+ definitions: [
255
+ ...new Set(
256
+ [...linked.visible.values()].flatMap((symbol) => definitions.get(symbol.key) ?? []),
257
+ ),
258
+ ],
259
+ assumptions: linked.module.assumptions.map((assumption) => assumption.expression),
260
+ theorems: linked.module.theorems,
261
+ getDefinition: (symbol) => definitions.get(linked.visible.get(symbol)?.key ?? symbol),
262
+ };
263
+ });
236
264
  const instanceActions = new Map<string, InstanceAction>();
265
+ const qualifiedNames = new Map<string, string>();
237
266
 
238
267
  const addStandardModule = (name: string): Symbols | undefined => {
239
268
  const cached = standardExports.get(name);
@@ -256,7 +285,11 @@ export const createEnvironment = (
256
285
 
257
286
  const getStandardSymbols = (name: string) => {
258
287
  const symbols = addStandardModule(name);
259
- if (symbols) useModule(name, STANDARD_DEPENDENCIES.get(name) ?? []);
288
+ const dependencies = STANDARD_DEPENDENCIES.get(name) ?? [];
289
+ if (symbols) useModule(name, dependencies);
290
+ // TLC loads the Java class of each module a standard module uses, so one that uses Integers
291
+ // overrides the arithmetic of Naturals.
292
+ if (symbols && dependencies.includes("Integers")) addStandardModule("Integers");
260
293
  return symbols;
261
294
  };
262
295
 
@@ -285,13 +318,25 @@ export const createEnvironment = (
285
318
  BUNDLED_MODULES.get(name) ??
286
319
  extractModule(options.source, name);
287
320
  if (source === undefined)
288
- throw new TlaSyntaxError(
289
- `Cannot find source file for module ${name} imported in module ${importer}.`,
321
+ throw createSanyError(
322
+ [
323
+ {
324
+ location: `In module ${importer}`,
325
+ message: `Cannot find source file for module ${name} imported in module ${importer}.`,
326
+ },
327
+ ],
328
+ true,
290
329
  );
291
- const module = parseModule(source);
330
+ const module = parseModuleFile(source, name);
292
331
  if (module.name !== name) {
293
- throw new TlaSyntaxError(
294
- `File name '${name}' does not match the name '${module.name}' of the top level module it contains.`,
332
+ throw createSanyError(
333
+ [
334
+ {
335
+ location: "Unknown location",
336
+ message: `File name '${name}' does not match the name '${module.name}' of the top level module it contains.`,
337
+ },
338
+ ],
339
+ true,
295
340
  );
296
341
  }
297
342
  return rejectModuleLiterals(module);
@@ -379,10 +424,11 @@ export const createEnvironment = (
379
424
  variables: new Set(linked.variables),
380
425
  getDefinition: (key) => definitions.get(key),
381
426
  isParameterized: (key) => parameterized.get(key) === true,
382
- addDefinition: (name, create) => {
427
+ addDefinition: (source, name, create) => {
383
428
  const key = createName(`${name}@${module.name}`);
384
429
  definitions.set(key, create(key));
385
430
  parameterized.set(key, !isParameterFree);
431
+ copySources.set(key, { source, prefix: instance.params.length });
386
432
  return key;
387
433
  },
388
434
  createName,
@@ -402,6 +448,7 @@ export const createEnvironment = (
402
448
  if (declarations.length > 0) {
403
449
  instanceActions.set(key, { name: `${instance.name}!${name}`, location: instance.location });
404
450
  }
451
+ qualifiedNames.set(key, `${instance.name}!${name}`);
405
452
  symbols.set(`${instance.name}!${name}`, {
406
453
  key,
407
454
  arity: symbol.arity + instance.params.length,
@@ -544,7 +591,7 @@ export const createEnvironment = (
544
591
  variables: new Set(linked.variables),
545
592
  getDefinition: (key) => definitions.get(key),
546
593
  isParameterized: (key) => parameterized.get(key) === true,
547
- addDefinition: (name, create) => {
594
+ addDefinition: (_source, name, create) => {
548
595
  const key = `${name}${KEY_SEPARATOR}${instance.module}${suffix}.${copies.length}`;
549
596
  const definition = create(key);
550
597
  copies.push(
@@ -582,6 +629,7 @@ export const createEnvironment = (
582
629
 
583
630
  const linkModule = (unlinked: Module, scope: ModuleScope): LinkedModule => {
584
631
  const parsed = overrideDefinitions(unlinked, options.loadClass?.(unlinked.name));
632
+ const firstCheck = instanceChecks.length;
585
633
  const visible: Symbols = new Map([
586
634
  ...CORE_OPERATORS.map((operator): [string, ModuleSymbol] => [
587
635
  operator.name,
@@ -724,11 +772,6 @@ export const createEnvironment = (
724
772
  visible.set(definition.name, symbol);
725
773
  if (!definition.isLocal) exported.set(definition.name, symbol);
726
774
  });
727
- checkModuleLevels(module, {
728
- constants: new Set(constants.map((constant) => constant.name)),
729
- variables: new Set(variables),
730
- getDefinition: (symbol) => definitions.get(visible.get(symbol)?.key ?? symbol),
731
- });
732
775
  const linked = {
733
776
  module,
734
777
  constants,
@@ -739,6 +782,21 @@ export const createEnvironment = (
739
782
  modules,
740
783
  extended,
741
784
  };
785
+ if (!checkedModules.has(parsed.name)) checkedModules.set(parsed.name, linked);
786
+ // SANY checks the instances of a module with its definitions and theorems, so it reports their
787
+ // errors together.
788
+ checkModuleLevels(
789
+ module,
790
+ {
791
+ constants: new Set(constants.map((constant) => constant.name)),
792
+ variables: new Set(variables),
793
+ getDefinition: (symbol) => definitions.get(visible.get(symbol)?.key ?? symbol),
794
+ getQualifiedName: (symbol) => qualifiedNames.get(visible.get(symbol)?.key ?? symbol),
795
+ },
796
+ instanceChecks
797
+ .splice(firstCheck)
798
+ .map((check) => ({ location: check.location, check: () => checkInstance(check) })),
799
+ );
742
800
  linkedList.push(linked);
743
801
  return linked;
744
802
  };
@@ -872,11 +930,51 @@ export const createEnvironment = (
872
930
  );
873
931
  }
874
932
  });
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
- }
933
+ // TLC sets a module-scoped entry on the body of the module's definition, which every instance of
934
+ // the module shares.
935
+ const scopedKeys = new Set(
936
+ [...config.constants, ...config.substitutions]
937
+ .filter((item) => item.module !== undefined)
938
+ .flatMap(getScopedKeys),
939
+ );
940
+ const getOverride = (
941
+ key: string,
942
+ prefix: number,
943
+ ): { key: string; prefix: number } | undefined => {
944
+ if (scopedKeys.has(key)) return { key, prefix };
945
+ const copy = copySources.get(key);
946
+ return copy && getOverride(copy.source, prefix + copy.prefix);
947
+ };
948
+ copySources.forEach((copy, key) => {
949
+ const override = getOverride(copy.source, copy.prefix);
950
+ const definition = definitions.get(key);
951
+ if (!override || !definition) return;
952
+ const params = definition.kind === "Operator" ? definition.params : [];
953
+ const alias = createLocalAlias(
954
+ key,
955
+ override.key,
956
+ params,
957
+ params.slice(override.prefix),
958
+ definition.location,
959
+ );
960
+ definitions.set(key, alias);
961
+ linkedRoot.visible.forEach((symbol, name) => {
962
+ if (symbol.key === key && name !== key) definitions.set(name, alias);
963
+ });
879
964
  });
965
+ const unassigned = declaredConstants.filter(
966
+ (name) => !constants.has(name) && !substitutions.has(name) && !operatorKeys.has(name),
967
+ );
968
+ if (unassigned.length > 0) {
969
+ // TLC reports the first constant it finds unassigned in SANY's order of declarations.
970
+ const name =
971
+ getTlcDeclarationOrder(options.source, options.loadModule, "constant").find((constant) =>
972
+ unassigned.includes(constant),
973
+ ) ?? unassigned[0];
974
+ throw new TlaConfigError(
975
+ `The constant parameter ${name} is not assigned a value by the configuration file.`,
976
+ );
977
+ }
880
978
 
881
979
  const environment: Environment = {
882
980
  runtime,
@@ -893,32 +991,43 @@ export const createEnvironment = (
893
991
  constantLevels: new Map(),
894
992
  evaluators: new WeakMap(),
895
993
  };
896
- checkInstances(instanceChecks, (name) => {
897
- const linked = linkedModules.get(name) ?? nestedModules.get(name) ?? linkedRoot;
898
- return {
899
- constants: linked.constants,
900
- variables: linked.variables,
901
- definitions: [
902
- ...new Set(
903
- [...linked.visible.values()].flatMap((symbol) => definitions.get(symbol.key) ?? []),
904
- ),
905
- ],
906
- assumptions: linked.module.assumptions.map((assumption) => assumption.expression),
907
- getDefinition: (symbol) => definitions.get(linked.visible.get(symbol)?.key ?? symbol),
908
- };
994
+ // TLC evaluates a substitute at startup and rejects it only when that fails and the level bound it
995
+ // computes is above constant. The bound counts the operators that TLC's Java code overrides with
996
+ // a minimum level as state-level, so the analyzer takes them for variables.
997
+ const analyzer = createLevelAnalyzer({
998
+ constants: new Set(constants.keys()),
999
+ variables: new Set([
1000
+ ...variables,
1001
+ ...["TLCGet", "Trace", "CounterExample"].filter((name) => builtins.has(name)),
1002
+ ]),
1003
+ getDefinition: (name) => getDefinition(name, environment),
909
1004
  });
1005
+ const getEvaluationError = (body: Expression) => {
1006
+ try {
1007
+ evaluate(body, { environment, scope: undefined, state: undefined, next: undefined });
1008
+ return undefined;
1009
+ } catch (error) {
1010
+ if (error instanceof TlaEvaluationError) return error;
1011
+ throw error;
1012
+ }
1013
+ };
910
1014
  substitutions.forEach((target, name) => {
911
1015
  const definition = definitions.get(target);
912
- if (
1016
+ const error =
913
1017
  declaredConstants.includes(name) &&
914
- definition &&
915
- !isConstantLevel(definition, environment)
916
- ) {
1018
+ definition?.kind === "Operator" &&
1019
+ definition.params.length === 0 &&
1020
+ analyzer.analyzeDefinition(definition, new Map()).level > 0
1021
+ ? getEvaluationError(definition.body)
1022
+ : undefined;
1023
+ // TLC adds the reason unless a standard module's Java code failed.
1024
+ if (error) {
917
1025
  throw new TlaConfigError(
918
- `The configuration file substitutes constant ${name} with non-constant ${target}`,
1026
+ `The configuration file substitutes constant ${name} with non-constant ${target}${error instanceof TlaModuleError ? "" : ` - specifically: ${error.message}`}`,
919
1027
  );
920
1028
  }
921
1029
  });
1030
+ runtime.isStarted = true;
922
1031
  return {
923
1032
  environment,
924
1033
  assumptions,
package/src/errors.ts CHANGED
@@ -1,10 +1,19 @@
1
- import { EXIT_STATUS, getExitCode, setModuleExitCode } from "./exit-codes";
1
+ import type { SourceRange } from "./ast";
2
+ import { EXIT_STATUS, getExitCode } from "./exit-codes";
3
+ import type { Value } from "./values";
2
4
 
3
5
  // How TLC reports a RuntimeException it did not expect, such as one raised while computing next
4
6
  // states.
5
7
  export const UNEXPECTED_EXCEPTION =
6
8
  "TLC threw an unexpected exception.\nThis was probably caused by an error in the spec or model.\nSee the User Output or TLC Console for clues to what happened.\nThe exception was a java.lang.RuntimeException\n: ";
7
9
 
10
+ // How TLC reports a Java StackOverflowError, which V8 raises as this RangeError.
11
+ export const STACK_OVERFLOW =
12
+ "This was a Java StackOverflowError. It was probably the result\nof an incorrect recursive function definition that caused TLC to enter\nan infinite loop when trying to compute the function or its application\nto an element in its putative domain.";
13
+
14
+ export const isStackOverflow = (error: unknown) =>
15
+ error instanceof RangeError && error.message === "Maximum call stack size exceeded";
16
+
8
17
  export class TlaError extends Error {
9
18
  constructor(message: string, cause?: unknown) {
10
19
  super(message, { cause });
@@ -19,16 +28,55 @@ export interface SyntaxFailure {
19
28
  isEnd: boolean;
20
29
  }
21
30
 
31
+ // An error SANY reports at a location, such as "In module M" or a range in a module.
32
+ export interface SanyError {
33
+ location: string;
34
+ message: string;
35
+ }
36
+
37
+ // The errors SANY reports for a spec. A fatal error stops it before semantic analysis. SANY's
38
+ // parser prints its message for a module it rejects before the report.
39
+ export interface SanyReport {
40
+ errors: SanyError[];
41
+ isFatal: boolean;
42
+ parseError?: string;
43
+ }
44
+
22
45
  export class TlaSyntaxError extends TlaError {
23
46
  failure: SyntaxFailure | undefined;
47
+ sany: SanyReport | undefined;
24
48
 
25
- constructor(message: string, cause?: unknown, failure?: SyntaxFailure) {
49
+ constructor(message: string, cause?: unknown, failure?: SyntaxFailure, sany?: SanyReport) {
26
50
  super(message, cause);
27
51
  this.name = "TlaSyntaxError";
28
52
  this.failure = failure;
53
+ this.sany = sany;
29
54
  }
30
55
  }
31
56
 
57
+ export const createSanyError = (errors: SanyError[], isFatal = false, parseError?: string) =>
58
+ new TlaSyntaxError(
59
+ errors.map((error) => `${error.location}\n\n${error.message}`).join("\n\n"),
60
+ undefined,
61
+ undefined,
62
+ { errors, isFatal, parseError },
63
+ );
64
+
65
+ // SANY's message for a module its parser rejects, such as a "***Parse Error***" with the
66
+ // productions it was in.
67
+ export class TlaParseError extends TlaError {
68
+ constructor(message: string) {
69
+ super(message);
70
+ this.name = "TlaParseError";
71
+ }
72
+ }
73
+
74
+ export const formatRange = (range: SourceRange) =>
75
+ `line ${range.start.line}, col ${range.start.column} to line ${range.end.line}, col ${range.end.column} of module ${range.module}`;
76
+
77
+ export const createSemanticError = (message: string, range: SourceRange) =>
78
+ createSanyError([{ location: formatRange(range), message }]);
79
+
32
80
  export class TlaConfigError extends TlaError {
33
81
  constructor(message: string, cause?: unknown) {
34
82
  super(message, cause);
@@ -46,10 +94,52 @@ export class TlaEvaluationError extends TlaError {
46
94
  // An evaluation error that TLC raises as an EvalException from a standard module's Java code. It
47
95
  // keeps the name TlaEvaluationError, and index.ts doesn't export it.
48
96
  export class TlaModuleError extends TlaEvaluationError {
97
+ exitCode: number;
98
+
49
99
  constructor(message: string, exitCode: number = EXIT_STATUS.error) {
50
100
  super(message);
51
101
  this.name = "TlaEvaluationError";
52
- setModuleExitCode(this, exitCode);
102
+ this.exitCode = exitCode;
103
+ }
104
+ }
105
+
106
+ // A variable that a partial state leaves without a value.
107
+ export class TlaUnassignedError extends TlaEvaluationError {
108
+ variable: string;
109
+
110
+ constructor(message: string, variable: string) {
111
+ super(message);
112
+ this.name = "TlaEvaluationError";
113
+ this.variable = variable;
114
+ }
115
+ }
116
+
117
+ // TLC reports a successor state that the next-state relation leaves incomplete as an error of its
118
+ // own, not as an exception. It keeps the name TlaEvaluationError, and index.ts doesn't export it.
119
+ export class TlaIncompleteStateError extends TlaEvaluationError {
120
+ state: (Value | undefined)[];
121
+ action: string | undefined;
122
+ missing: string[];
123
+
124
+ constructor(state: (Value | undefined)[], action: string | undefined, missing: string[]) {
125
+ super(
126
+ `Successor state is not completely specified by the next-state action. The following variable${missing.length > 1 ? "s are" : " is"} not defined: ${missing.join(", ")}.\n`,
127
+ );
128
+ this.name = "TlaEvaluationError";
129
+ this.state = state;
130
+ this.action = action;
131
+ this.missing = missing;
132
+ }
133
+ }
134
+
135
+ // TLC reports an initial state that the initial predicate leaves incomplete as an illegal state.
136
+ export class TlaIllegalStateError extends TlaEvaluationError {
137
+ state: (Value | undefined)[];
138
+
139
+ constructor(state: (Value | undefined)[]) {
140
+ super("current state is not a legal state");
141
+ this.name = "TlaEvaluationError";
142
+ this.state = state;
53
143
  }
54
144
  }
55
145