tla-ts 0.0.3-dev.037ac3b → 0.0.3-dev.0e500e5

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 (47) hide show
  1. package/dist/index.cjs +1 -1
  2. package/dist/index.d.cts +58 -22
  3. package/dist/index.d.ts +58 -22
  4. package/dist/index.js +1 -1
  5. package/dist/parallel-worker.cjs +1 -1
  6. package/dist/parallel-worker.js +2 -2
  7. package/dist/parallel.cjs +1 -1
  8. package/dist/parallel.js +2 -2
  9. package/dist/run-cli.cjs +14 -12
  10. package/dist/run-cli.js +22 -20
  11. package/dist/transfer.cjs +39 -21
  12. package/dist/transfer.js +39 -21
  13. package/package.json +1 -1
  14. package/src/ast.ts +26 -4
  15. package/src/builtins.ts +9 -3
  16. package/src/check.ts +309 -61
  17. package/src/codegen.ts +6 -3
  18. package/src/config.ts +224 -170
  19. package/src/environment.ts +223 -84
  20. package/src/errors.ts +100 -1
  21. package/src/evaluate.ts +172 -19
  22. package/src/exit-codes.ts +22 -3
  23. package/src/fingerprints.ts +2 -1
  24. package/src/instances.ts +1 -1
  25. package/src/levels.ts +176 -36
  26. package/src/live-check.ts +129 -49
  27. package/src/liveness.ts +68 -10
  28. package/src/parallel-worker.ts +2 -2
  29. package/src/parallel.ts +2 -2
  30. package/src/parser.ts +152 -48
  31. package/src/resolve.ts +878 -338
  32. package/src/run-cli.ts +61 -11
  33. package/src/sany-lexer.ts +615 -0
  34. package/src/sany-parse-error.ts +3143 -0
  35. package/src/spec-description.ts +1 -2
  36. package/src/standard-modules.ts +52 -38
  37. package/src/standard-ranges.ts +116 -0
  38. package/src/subexpressions.ts +25 -13
  39. package/src/substitution-levels.ts +38 -17
  40. package/src/successors.ts +111 -31
  41. package/src/symmetry.ts +16 -6
  42. package/src/tableau.ts +1 -1
  43. package/src/tlc-module.ts +6 -6
  44. package/src/tlc-modules.ts +4 -0
  45. package/src/tlc-order.ts +8 -4
  46. package/src/value-sources.ts +29 -0
  47. package/src/values.ts +184 -51
@@ -12,7 +12,16 @@ 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 {
16
+ createSanyError,
17
+ formatRange,
18
+ formatSanyWarnings,
19
+ TlaConfigError,
20
+ TlaEvaluationError,
21
+ TlaModuleError,
22
+ TlaSyntaxError,
23
+ type SanyError,
24
+ } from "./errors";
16
25
  import { EXIT_STATUS, setExitCode } from "./exit-codes";
17
26
  import {
18
27
  createBigNumberError,
@@ -32,21 +41,28 @@ import {
32
41
  import { overrideDefinitions } from "./java-overrides";
33
42
  import { extractModule, parseModule } from "./parser";
34
43
  import {
35
- checkRedefinitions,
36
44
  getArity,
37
45
  isBefore,
46
+ isTheoremDefinition,
38
47
  KEY_SEPARATOR,
39
48
  LOCAL_RESOLUTION,
49
+ MODULE_START,
40
50
  resolveModule,
41
51
  resolveSubstitutions,
52
+ type ModuleReport,
42
53
  type ModuleSymbol,
54
+ type ModuleUnit,
55
+ type SymbolKind,
43
56
  type Symbols,
44
57
  } from "./resolve";
45
58
  import { createRuntime } from "./runtime";
59
+ import { parseModuleFile } from "./sany-parse-error";
46
60
  import { CORE_OPERATORS, getStandardModule, STANDARD_DEPENDENCIES } from "./standard-modules";
61
+ import { getStandardRange } from "./standard-ranges";
47
62
  import { resolveInstanceSubexpressions, resolveModuleSubexpressions } from "./subexpressions";
48
63
  import { checkModuleLevels, createLevelAnalyzer } from "./levels";
49
- import { checkInstances, type InstanceCheck } from "./substitution-levels";
64
+ import { createInstanceChecker, type InstanceCheck } from "./substitution-levels";
65
+ import { getTlcDeclarationOrder } from "./tlc-order";
50
66
  import {
51
67
  checkInteger,
52
68
  createModelValue,
@@ -124,6 +140,22 @@ const createModuleRedefinedError = (module: Module) =>
124
140
  `Multiply-defined module '${module.name}' at line ${module.location.line}, column ${module.location.column}`,
125
141
  );
126
142
 
143
+ const getModuleRedefinition = (module: Module, existing: Module): SanyError | undefined =>
144
+ module.location.range &&
145
+ existing.location.range && {
146
+ location: formatRange(module.location.range),
147
+ message: `Multiply-defined module '${module.name}': this definition or declaration conflicts \nwith the one at ${formatRange(existing.location.range)}.`,
148
+ };
149
+
150
+ // Context.kindOfNode names a definition or a parameter a definition, and any other symbol a
151
+ // declaration.
152
+ const getNodeWord = (kind: SymbolKind) =>
153
+ ["Builtin", "Definition", "Instance", "Parameter"].includes(kind) ? "definition" : "declaration";
154
+
155
+ // The Java class of the node SANY binds a symbol to.
156
+ const getNodeClass = (kind: SymbolKind) =>
157
+ kind === "Theorem" ? "ThmOrAssumpDefNode" : getNodeWord(kind);
158
+
127
159
  const createLocalFunction = (definition: Definition, key: string): Definition => ({
128
160
  kind: "Operator",
129
161
  name: key,
@@ -222,6 +254,8 @@ export const createEnvironment = (
222
254
  const runtime = createRuntime(config.checkDeadlock, options.seed);
223
255
  const linkedModules = new Map<string, LinkedModule>();
224
256
  const nestedModules = new Map<string, LinkedModule>();
257
+ // Each module by name, from the time its level checks run.
258
+ const checkedModules = new Map<string, LinkedModule>();
225
259
  const linkedList: LinkedModule[] = [];
226
260
  const dependencies = new Map<string, Set<string>>();
227
261
  const loading: Set<string>[] = [];
@@ -236,7 +270,25 @@ export const createEnvironment = (
236
270
  const copyCount = { value: 0 };
237
271
  const createName = (name: string) => `${name}#${copyCount.value++}`;
238
272
  const instanceChecks: InstanceCheck[] = [];
273
+ // The warnings SANY reports for the spec.
274
+ const warnings: SanyError[] = [];
275
+ const checkInstance = createInstanceChecker((name) => {
276
+ const linked = checkedModules.get(name) ?? getLinkedModule(name, name);
277
+ return {
278
+ constants: linked.constants,
279
+ variables: linked.variables,
280
+ definitions: [
281
+ ...new Set(
282
+ [...linked.visible.values()].flatMap((symbol) => definitions.get(symbol.key) ?? []),
283
+ ),
284
+ ],
285
+ assumptions: linked.module.assumptions.map((assumption) => assumption.expression),
286
+ theorems: linked.module.theorems,
287
+ getDefinition: (symbol) => definitions.get(linked.visible.get(symbol)?.key ?? symbol),
288
+ };
289
+ });
239
290
  const instanceActions = new Map<string, InstanceAction>();
291
+ const qualifiedNames = new Map<string, string>();
240
292
 
241
293
  const addStandardModule = (name: string): Symbols | undefined => {
242
294
  const cached = standardExports.get(name);
@@ -251,7 +303,12 @@ export const createEnvironment = (
251
303
  );
252
304
  standardModule.operators.forEach((operator) => {
253
305
  builtins.set(operator.name, operator);
254
- exported.set(operator.name, { key: operator.name, arity: operator.arity });
306
+ exported.set(operator.name, {
307
+ key: operator.name,
308
+ arity: operator.arity,
309
+ kind: "Definition",
310
+ range: getStandardRange(name, operator.name) ?? exported.get(operator.name)?.range,
311
+ });
255
312
  });
256
313
  standardExports.set(name, exported);
257
314
  return exported;
@@ -259,7 +316,11 @@ export const createEnvironment = (
259
316
 
260
317
  const getStandardSymbols = (name: string) => {
261
318
  const symbols = addStandardModule(name);
262
- if (symbols) useModule(name, STANDARD_DEPENDENCIES.get(name) ?? []);
319
+ const dependencies = STANDARD_DEPENDENCIES.get(name) ?? [];
320
+ if (symbols) useModule(name, dependencies);
321
+ // TLC loads the Java class of each module a standard module uses, so one that uses Integers
322
+ // overrides the arithmetic of Naturals.
323
+ if (symbols && dependencies.includes("Integers")) addStandardModule("Integers");
263
324
  return symbols;
264
325
  };
265
326
 
@@ -288,13 +349,25 @@ export const createEnvironment = (
288
349
  BUNDLED_MODULES.get(name) ??
289
350
  extractModule(options.source, name);
290
351
  if (source === undefined)
291
- throw new TlaSyntaxError(
292
- `Cannot find source file for module ${name} imported in module ${importer}.`,
352
+ throw createSanyError(
353
+ [
354
+ {
355
+ location: `In module ${importer}`,
356
+ message: `Cannot find source file for module ${name} imported in module ${importer}.`,
357
+ },
358
+ ],
359
+ true,
293
360
  );
294
- const module = parseModule(source);
361
+ const module = parseModuleFile(source, name);
295
362
  if (module.name !== name) {
296
- throw new TlaSyntaxError(
297
- `File name '${name}' does not match the name '${module.name}' of the top level module it contains.`,
363
+ throw createSanyError(
364
+ [
365
+ {
366
+ location: "Unknown location",
367
+ message: `File name '${name}' does not match the name '${module.name}' of the top level module it contains.`,
368
+ },
369
+ ],
370
+ true,
298
371
  );
299
372
  }
300
373
  return rejectModuleLiterals(module);
@@ -321,6 +394,9 @@ export const createEnvironment = (
321
394
  loading.pop();
322
395
  linking.pop();
323
396
  const duplicate = nested.find((module) => closure.has(module.name));
397
+ const loaded = duplicate && linkedModules.get(duplicate.name);
398
+ const redefinition = loaded && getModuleRedefinition(duplicate, loaded.module);
399
+ if (redefinition) throw createSanyError([redefinition], false, undefined, warnings);
324
400
  if (duplicate) throw createModuleRedefinedError(duplicate);
325
401
  return { linked, closure };
326
402
  };
@@ -341,12 +417,7 @@ export const createEnvironment = (
341
417
  const instantiate = (
342
418
  instance: Instance,
343
419
  module: Module,
344
- unit: {
345
- imported: Symbols;
346
- importedAt: Map<string, SourceLocation>;
347
- definitions: Map<string, Definition>;
348
- getKey: (definition: Definition) => string;
349
- },
420
+ unit: ModuleUnit,
350
421
  isParameterFree: boolean,
351
422
  nested: LinkedModule | undefined,
352
423
  ): Symbols => {
@@ -354,7 +425,10 @@ export const createEnvironment = (
354
425
  if (standardSymbols) {
355
426
  if (instance.name === undefined) return standardSymbols;
356
427
  return new Map(
357
- [...standardSymbols].map(([name, symbol]) => [`${instance.name}!${name}`, symbol]),
428
+ [...standardSymbols].map(([name, symbol]) => [
429
+ `${instance.name}!${name}`,
430
+ { key: symbol.key, arity: symbol.arity, kind: symbol.kind },
431
+ ]),
358
432
  );
359
433
  }
360
434
  const linked = nested ?? getLinkedModule(instance.module, module.name);
@@ -399,16 +473,24 @@ export const createEnvironment = (
399
473
  const key = instantiation.getKey(symbol.key);
400
474
  if (declarations.length > 0)
401
475
  instanceActions.set(key, { name, location: instance.location });
402
- symbols.set(name, { key, arity: symbol.arity });
476
+ // SANY binds a copy of a definition that depends on the parameters at the INSTANCE.
477
+ symbols.set(name, {
478
+ key,
479
+ arity: symbol.arity,
480
+ kind: symbol.kind,
481
+ range: parameterized.get(symbol.key) === true ? instance.location.range : symbol.range,
482
+ });
403
483
  return;
404
484
  }
405
485
  const key = instantiation.getQualifiedKey(symbol.key);
406
486
  if (declarations.length > 0) {
407
487
  instanceActions.set(key, { name: `${instance.name}!${name}`, location: instance.location });
408
488
  }
489
+ qualifiedNames.set(key, `${instance.name}!${name}`);
409
490
  symbols.set(`${instance.name}!${name}`, {
410
491
  key,
411
492
  arity: symbol.arity + instance.params.length,
493
+ kind: symbol.kind,
412
494
  });
413
495
  });
414
496
  return symbols;
@@ -586,29 +668,58 @@ export const createEnvironment = (
586
668
 
587
669
  const linkModule = (unlinked: Module, scope: ModuleScope): LinkedModule => {
588
670
  const parsed = overrideDefinitions(unlinked, options.loadClass?.(unlinked.name));
671
+ const firstCheck = instanceChecks.length;
589
672
  const visible: Symbols = new Map([
590
673
  ...CORE_OPERATORS.map((operator): [string, ModuleSymbol] => [
591
674
  operator.name,
592
- { key: operator.name, arity: operator.arity },
675
+ { key: operator.name, arity: operator.arity, kind: "Builtin" },
593
676
  ]),
594
677
  ...scope.symbols,
595
678
  ]);
679
+ const extendsReport: ModuleReport = { location: MODULE_START, errors: [], warnings: [] };
680
+ const reports = [extendsReport];
681
+ // Context.mergeExtendContext keeps the first of the symbols the extended modules share by name,
682
+ // and warns of two definitions or two declarations but rejects a definition and a declaration.
683
+ const mergeExtended = (symbols: Symbols) =>
684
+ symbols.forEach((symbol, name) => {
685
+ const current = exported.get(name);
686
+ if (!current) {
687
+ visible.set(name, symbol);
688
+ exported.set(name, symbol);
689
+ return;
690
+ }
691
+ if (
692
+ !current.range ||
693
+ !symbol.range ||
694
+ formatRange(current.range) === formatRange(symbol.range)
695
+ ) {
696
+ return;
697
+ }
698
+ const location = formatRange(symbol.range);
699
+ const existing = formatRange(current.range);
700
+ if (getNodeClass(current.kind) === getNodeClass(symbol.kind)) {
701
+ extendsReport.warnings.push({
702
+ location,
703
+ message: `Warning: the ${getNodeWord(current.kind)} of '${name}' conflicts with \nits ${getNodeWord(current.kind)} at ${existing}.`,
704
+ });
705
+ return;
706
+ }
707
+ extendsReport.errors.push({
708
+ location,
709
+ message: `The ${getNodeWord(symbol.kind)} of '${name}' conflicts with \nits ${getNodeWord(current.kind)} at ${existing}.`,
710
+ });
711
+ });
596
712
  const exported: Symbols = new Map();
597
713
  const modules = new Map<string, LinkedModule>();
598
714
  const extended: LinkedModule[] = [];
599
715
  const constants = [...parsed.constants];
600
716
  const variables = parsed.variables.map((variable) => variable.name);
601
717
  const variableLocations = parsed.variables.map((variable) => variable.location);
602
- const addSymbols = (symbols: Symbols, isExported: boolean) =>
603
- symbols.forEach((symbol, name) => {
604
- visible.set(name, symbol);
605
- if (isExported) exported.set(name, symbol);
606
- });
607
718
  parsed.extends.forEach((name) => {
608
719
  const nested = scope.modules.get(name);
609
720
  const standardSymbols = nested ? undefined : getStandardSymbols(name);
610
721
  if (standardSymbols) {
611
- addSymbols(standardSymbols, true);
722
+ mergeExtended(standardSymbols);
612
723
  return;
613
724
  }
614
725
  const linked = nested ?? getLinkedModule(name, parsed.name);
@@ -622,53 +733,72 @@ export const createEnvironment = (
622
733
  variables.push(variable);
623
734
  variableLocations.push(linked.variableLocations[index]);
624
735
  });
625
- addSymbols(linked.exported, true);
736
+ mergeExtended(linked.exported);
626
737
  linked.modules.forEach((module, moduleName) => modules.set(moduleName, module));
627
738
  extended.push(linked);
628
739
  });
629
- parsed.constants.forEach((constant) =>
630
- exported.set(constant.name, {
631
- key: constant.name,
632
- arity: constant.arity,
633
- declaration: "Constant",
634
- }),
635
- );
636
- parsed.variables.forEach((variable) =>
637
- exported.set(variable.name, { key: variable.name, arity: 0, declaration: "Variable" }),
740
+ const bound = new Map(visible);
741
+ const declarations = [
742
+ ...parsed.constants.map((constant) => ({ ...constant, kind: "Constant" as const })),
743
+ ...parsed.variables.map((variable) => ({ ...variable, kind: "Variable" as const })),
744
+ ];
745
+ const getDeclarationSymbol = (declaration: (typeof declarations)[number]): ModuleSymbol => ({
746
+ key: declaration.name,
747
+ arity: declaration.arity,
748
+ kind: declaration.kind,
749
+ range: declaration.location.range,
750
+ });
751
+ declarations.forEach((declaration) =>
752
+ exported.set(declaration.name, getDeclarationSymbol(declaration)),
638
753
  );
754
+ const getDefinitionSymbol = (definition: Definition): ModuleSymbol => ({
755
+ key: getKey(definition),
756
+ arity: getArity(definition),
757
+ kind: isTheoremDefinition(parsed, definition) ? "Theorem" : "Definition",
758
+ range: definition.location.range,
759
+ });
639
760
  const isParameterFree = constants.length === 0 && variables.length === 0;
640
761
  const getKey = (definition: Definition) =>
641
762
  parsed === root ? definition.name : `${definition.name}${KEY_SEPARATOR}${scope.id}`;
642
- const importedAt = new Map<string, SourceLocation>();
643
- const getUnit = (module: Module) => ({
763
+ const instanced = new Map<Instance, Symbols>();
764
+ const getUnit = (module: Module): ModuleUnit => ({
644
765
  imported: visible,
645
- importedAt,
646
- definitions: new Map(module.definitions.map((definition) => [definition.name, definition])),
766
+ bound,
767
+ // SANY keeps the first of two definitions of a name.
768
+ definitions: new Map(
769
+ module.definitions.toReversed().map((definition) => [definition.name, definition]),
770
+ ),
647
771
  getKey,
772
+ instanced,
773
+ reports,
774
+ warnings,
648
775
  });
649
776
  const getVisibleModules = () => new Map([...scope.modules, ...modules]);
650
777
  const getSymbolsBefore = (location: SourceLocation): Symbols =>
651
778
  new Map([
652
779
  ...visible,
653
- ...[
654
- ...parsed.constants.map((constant) => ({ ...constant, kind: "Constant" as const })),
655
- ...parsed.variables.map((variable) => ({ ...variable, kind: "Variable" as const })),
656
- ]
780
+ ...declarations
657
781
  .filter((declaration) => isBefore(declaration.location, location))
658
782
  .map((declaration): [string, ModuleSymbol] => [
659
783
  declaration.name,
660
- { key: declaration.name, arity: declaration.arity, declaration: declaration.kind },
784
+ getDeclarationSymbol(declaration),
661
785
  ]),
662
786
  ...parsed.definitions
663
787
  .filter((definition) => isBefore(definition.location, location))
664
788
  .map((definition): [string, ModuleSymbol] => [
665
789
  definition.name,
666
- { key: getKey(definition), arity: getArity(definition) },
790
+ getDefinitionSymbol(definition),
667
791
  ]),
668
792
  ]);
669
793
  const linkNested = (nested: Module) => {
670
794
  const visibleModules = getVisibleModules();
671
- if (visibleModules.has(nested.name)) throw createModuleRedefinedError(nested);
795
+ const existing = visibleModules.get(nested.name);
796
+ const redefinition = existing && getModuleRedefinition(nested, existing.module);
797
+ if (redefinition) {
798
+ reports.push({ location: nested.location, errors: [redefinition], warnings: [] });
799
+ } else if (existing) {
800
+ throw createModuleRedefinedError(nested);
801
+ }
672
802
  scope.nested.push(nested);
673
803
  const linked = linkModule(nested, {
674
804
  id: `${scope.id}/${nested.name}`,
@@ -676,7 +806,7 @@ export const createEnvironment = (
676
806
  modules: visibleModules,
677
807
  nested: scope.nested,
678
808
  });
679
- modules.set(nested.name, linked);
809
+ if (!existing) modules.set(nested.name, linked);
680
810
  if (!nestedModules.has(nested.name)) nestedModules.set(nested.name, linked);
681
811
  };
682
812
  [
@@ -690,10 +820,12 @@ export const createEnvironment = (
690
820
  isParameterFree,
691
821
  getVisibleModules().get(instance.module),
692
822
  );
693
- symbols.forEach((_, name) => {
694
- if (!visible.has(name)) importedAt.set(name, instance.location);
823
+ instanced.set(instance, symbols);
824
+ symbols.forEach((symbol, name) => {
825
+ if (visible.has(name)) return;
826
+ visible.set(name, symbol);
827
+ if (!instance.isLocal) exported.set(name, symbol);
695
828
  });
696
- addSymbols(symbols, !instance.isLocal);
697
829
  },
698
830
  })),
699
831
  ...parsed.modules.map((nested) => ({
@@ -703,7 +835,6 @@ export const createEnvironment = (
703
835
  ]
704
836
  .sort((left, right) => (isBefore(left.location, right.location) ? -1 : 1))
705
837
  .forEach((unit) => unit.link());
706
- checkRedefinitions(parsed, getUnit(parsed));
707
838
  const isInstancedAfterDefinition = (nested: Module) => {
708
839
  const first = parsed.instances.find((instance) => instance.module === nested.name);
709
840
  return first !== undefined && isBefore(nested.location, first.location);
@@ -724,15 +855,10 @@ export const createEnvironment = (
724
855
  const key = getKey(definition);
725
856
  definitions.set(key, definition);
726
857
  parameterized.set(key, !isParameterFree);
727
- const symbol = { key, arity: getArity(definition) };
858
+ const symbol = getDefinitionSymbol(definition);
728
859
  visible.set(definition.name, symbol);
729
860
  if (!definition.isLocal) exported.set(definition.name, symbol);
730
861
  });
731
- checkModuleLevels(module, {
732
- constants: new Set(constants.map((constant) => constant.name)),
733
- variables: new Set(variables),
734
- getDefinition: (symbol) => definitions.get(visible.get(symbol)?.key ?? symbol),
735
- });
736
862
  const linked = {
737
863
  module,
738
864
  constants,
@@ -743,11 +869,28 @@ export const createEnvironment = (
743
869
  modules,
744
870
  extended,
745
871
  };
872
+ if (!checkedModules.has(parsed.name)) checkedModules.set(parsed.name, linked);
873
+ // SANY checks the instances of a module with its definitions and theorems, so it reports their
874
+ // errors together.
875
+ checkModuleLevels(
876
+ module,
877
+ {
878
+ constants: new Set(constants.map((constant) => constant.name)),
879
+ variables: new Set(variables),
880
+ getDefinition: (symbol) => definitions.get(visible.get(symbol)?.key ?? symbol),
881
+ getQualifiedName: (symbol) => qualifiedNames.get(visible.get(symbol)?.key ?? symbol),
882
+ },
883
+ instanceChecks
884
+ .splice(firstCheck)
885
+ .map((check) => ({ location: check.location, check: () => checkInstance(check) })),
886
+ warnings,
887
+ );
746
888
  linkedList.push(linked);
747
889
  return linked;
748
890
  };
749
891
 
750
892
  const linkedRoot = linkTopLevel(root).linked;
893
+ if (warnings.length > 0) options.print(formatSanyWarnings(warnings));
751
894
  const getRootKey = (name: string) => linkedRoot.visible.get(name)?.key ?? name;
752
895
  linkedRoot.visible.forEach((symbol, name) => {
753
896
  const definition = definitions.get(symbol.key);
@@ -908,11 +1051,19 @@ export const createEnvironment = (
908
1051
  if (symbol.key === key && name !== key) definitions.set(name, alias);
909
1052
  });
910
1053
  });
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
- });
1054
+ const unassigned = declaredConstants.filter(
1055
+ (name) => !constants.has(name) && !substitutions.has(name) && !operatorKeys.has(name),
1056
+ );
1057
+ if (unassigned.length > 0) {
1058
+ // TLC reports the first constant it finds unassigned in SANY's order of declarations.
1059
+ const name =
1060
+ getTlcDeclarationOrder(options.source, options.loadModule, "constant").find((constant) =>
1061
+ unassigned.includes(constant),
1062
+ ) ?? unassigned[0];
1063
+ throw new TlaConfigError(
1064
+ `The constant parameter ${name} is not assigned a value by the configuration file.`,
1065
+ );
1066
+ }
916
1067
 
917
1068
  const environment: Environment = {
918
1069
  runtime,
@@ -929,20 +1080,6 @@ export const createEnvironment = (
929
1080
  constantLevels: new Map(),
930
1081
  evaluators: new WeakMap(),
931
1082
  };
932
- checkInstances(instanceChecks, (name) => {
933
- const linked = linkedModules.get(name) ?? nestedModules.get(name) ?? linkedRoot;
934
- return {
935
- constants: linked.constants,
936
- variables: linked.variables,
937
- definitions: [
938
- ...new Set(
939
- [...linked.visible.values()].flatMap((symbol) => definitions.get(symbol.key) ?? []),
940
- ),
941
- ],
942
- assumptions: linked.module.assumptions.map((assumption) => assumption.expression),
943
- getDefinition: (symbol) => definitions.get(linked.visible.get(symbol)?.key ?? symbol),
944
- };
945
- });
946
1083
  // TLC evaluates a substitute at startup and rejects it only when that fails and the level bound it
947
1084
  // computes is above constant. The bound counts the operators that TLC's Java code overrides with
948
1085
  // a minimum level as state-level, so the analyzer takes them for variables.
@@ -954,26 +1091,28 @@ export const createEnvironment = (
954
1091
  ]),
955
1092
  getDefinition: (name) => getDefinition(name, environment),
956
1093
  });
957
- const isEvaluable = (body: Expression) => {
1094
+ const getEvaluationError = (body: Expression) => {
958
1095
  try {
959
1096
  evaluate(body, { environment, scope: undefined, state: undefined, next: undefined });
960
- return true;
1097
+ return undefined;
961
1098
  } catch (error) {
962
- if (error instanceof TlaEvaluationError) return false;
1099
+ if (error instanceof TlaEvaluationError) return error;
963
1100
  throw error;
964
1101
  }
965
1102
  };
966
1103
  substitutions.forEach((target, name) => {
967
1104
  const definition = definitions.get(target);
968
- if (
1105
+ const error =
969
1106
  declaredConstants.includes(name) &&
970
1107
  definition?.kind === "Operator" &&
971
1108
  definition.params.length === 0 &&
972
- analyzer.analyzeDefinition(definition, new Map()).level > 0 &&
973
- !isEvaluable(definition.body)
974
- ) {
1109
+ analyzer.analyzeDefinition(definition, new Map()).level > 0
1110
+ ? getEvaluationError(definition.body)
1111
+ : undefined;
1112
+ // TLC adds the reason unless a standard module's Java code failed.
1113
+ if (error) {
975
1114
  throw new TlaConfigError(
976
- `The configuration file substitutes constant ${name} with non-constant ${target}`,
1115
+ `The configuration file substitutes constant ${name} with non-constant ${target}${error instanceof TlaModuleError ? "" : ` - specifically: ${error.message}`}`,
977
1116
  );
978
1117
  }
979
1118
  });
package/src/errors.ts CHANGED
@@ -1,10 +1,19 @@
1
+ import type { SourceRange } from "./ast";
1
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,66 @@ 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, and the warnings it prints before them. A fatal error stops it
38
+ // before semantic analysis. SANY's parser prints its message for a module it rejects before the
39
+ // report.
40
+ export interface SanyReport {
41
+ errors: SanyError[];
42
+ warnings: SanyError[];
43
+ isFatal: boolean;
44
+ parseError?: string;
45
+ }
46
+
22
47
  export class TlaSyntaxError extends TlaError {
23
48
  failure: SyntaxFailure | undefined;
49
+ sany: SanyReport | undefined;
24
50
 
25
- constructor(message: string, cause?: unknown, failure?: SyntaxFailure) {
51
+ constructor(message: string, cause?: unknown, failure?: SyntaxFailure, sany?: SanyReport) {
26
52
  super(message, cause);
27
53
  this.name = "TlaSyntaxError";
28
54
  this.failure = failure;
55
+ this.sany = sany;
29
56
  }
30
57
  }
31
58
 
59
+ export const createSanyError = (
60
+ errors: SanyError[],
61
+ isFatal = false,
62
+ parseError?: string,
63
+ warnings: SanyError[] = [],
64
+ ) =>
65
+ new TlaSyntaxError(
66
+ errors.map((error) => `${error.location}\n\n${error.message}`).join("\n\n"),
67
+ undefined,
68
+ undefined,
69
+ { errors, warnings, isFatal, parseError },
70
+ );
71
+
72
+ // How SANY prints the warnings it reports, which do not stop TLC.
73
+ export const formatSanyWarnings = (warnings: SanyError[]) =>
74
+ `*** Warnings: ${warnings.length}\n\n${warnings.map((warning) => `${warning.location}\n\n${warning.message}\n\n\n`).join("\n")}`;
75
+
76
+ // SANY's message for a module its parser rejects, such as a "***Parse Error***" with the
77
+ // productions it was in.
78
+ export class TlaParseError extends TlaError {
79
+ constructor(message: string) {
80
+ super(message);
81
+ this.name = "TlaParseError";
82
+ }
83
+ }
84
+
85
+ export const formatRange = (range: SourceRange) =>
86
+ `line ${range.start.line}, col ${range.start.column} to line ${range.end.line}, col ${range.end.column} of module ${range.module}`;
87
+
88
+ export const createSemanticError = (message: string, range: SourceRange) =>
89
+ createSanyError([{ location: formatRange(range), message }]);
90
+
32
91
  export class TlaConfigError extends TlaError {
33
92
  constructor(message: string, cause?: unknown) {
34
93
  super(message, cause);
@@ -55,6 +114,46 @@ export class TlaModuleError extends TlaEvaluationError {
55
114
  }
56
115
  }
57
116
 
117
+ // A variable that a partial state leaves without a value.
118
+ export class TlaUnassignedError extends TlaEvaluationError {
119
+ variable: string;
120
+
121
+ constructor(message: string, variable: string) {
122
+ super(message);
123
+ this.name = "TlaEvaluationError";
124
+ this.variable = variable;
125
+ }
126
+ }
127
+
128
+ // TLC reports a successor state that the next-state relation leaves incomplete as an error of its
129
+ // own, not as an exception. It keeps the name TlaEvaluationError, and index.ts doesn't export it.
130
+ export class TlaIncompleteStateError extends TlaEvaluationError {
131
+ state: (Value | undefined)[];
132
+ action: string | undefined;
133
+ missing: string[];
134
+
135
+ constructor(state: (Value | undefined)[], action: string | undefined, missing: string[]) {
136
+ super(
137
+ `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`,
138
+ );
139
+ this.name = "TlaEvaluationError";
140
+ this.state = state;
141
+ this.action = action;
142
+ this.missing = missing;
143
+ }
144
+ }
145
+
146
+ // TLC reports an initial state that the initial predicate leaves incomplete as an illegal state.
147
+ export class TlaIllegalStateError extends TlaEvaluationError {
148
+ state: (Value | undefined)[];
149
+
150
+ constructor(state: (Value | undefined)[]) {
151
+ super("current state is not a legal state");
152
+ this.name = "TlaEvaluationError";
153
+ this.state = state;
154
+ }
155
+ }
156
+
58
157
  export interface TlapmReport {
59
158
  failure?: string;
60
159
  exception?: string;