tla-ts 0.0.3-dev.5e999f2 → 0.0.3-dev.5fd6731

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.
@@ -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, TlaModuleError, 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,27 @@ 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";
50
65
  import { getTlcDeclarationOrder } from "./tlc-order";
51
66
  import {
52
67
  checkInteger,
@@ -108,16 +123,25 @@ interface LinkedModule {
108
123
  extended: LinkedModule[];
109
124
  }
110
125
 
126
+ // errors and warnings collect what SANY reports for the module, and levelChecks the level checks of
127
+ // the modules in its file, which SANY runs only when it reports no error.
111
128
  interface ModuleScope {
112
129
  id: string;
113
130
  symbols: Symbols;
114
131
  modules: Map<string, LinkedModule>;
115
132
  nested: Module[];
133
+ errors: SanyError[];
134
+ warnings: SanyError[];
135
+ levelChecks: (() => void)[];
116
136
  }
117
137
 
118
- const getDeclarations = (linked: LinkedModule) => [
138
+ const getDeclarations = (linked: LinkedModule): Declaration[] => [
119
139
  ...linked.constants,
120
- ...linked.variables.map((variable) => ({ name: variable, arity: 0 })),
140
+ ...linked.variables.map((variable, index) => ({
141
+ name: variable,
142
+ arity: 0,
143
+ location: linked.variableLocations[index],
144
+ })),
121
145
  ];
122
146
 
123
147
  const createModuleRedefinedError = (module: Module) =>
@@ -125,6 +149,22 @@ const createModuleRedefinedError = (module: Module) =>
125
149
  `Multiply-defined module '${module.name}' at line ${module.location.line}, column ${module.location.column}`,
126
150
  );
127
151
 
152
+ const getModuleRedefinition = (module: Module, existing: Module): SanyError | undefined =>
153
+ module.location.range &&
154
+ existing.location.range && {
155
+ location: formatRange(module.location.range),
156
+ message: `Multiply-defined module '${module.name}': this definition or declaration conflicts \nwith the one at ${formatRange(existing.location.range)}.`,
157
+ };
158
+
159
+ // Context.kindOfNode names a definition or a parameter a definition, and any other symbol a
160
+ // declaration.
161
+ const getNodeWord = (kind: SymbolKind) =>
162
+ ["Builtin", "Definition", "Instance", "Parameter"].includes(kind) ? "definition" : "declaration";
163
+
164
+ // The Java class of the node SANY binds a symbol to.
165
+ const getNodeClass = (kind: SymbolKind) =>
166
+ kind === "Theorem" ? "ThmOrAssumpDefNode" : getNodeWord(kind);
167
+
128
168
  const createLocalFunction = (definition: Definition, key: string): Definition => ({
129
169
  kind: "Operator",
130
170
  name: key,
@@ -223,6 +263,8 @@ export const createEnvironment = (
223
263
  const runtime = createRuntime(config.checkDeadlock, options.seed);
224
264
  const linkedModules = new Map<string, LinkedModule>();
225
265
  const nestedModules = new Map<string, LinkedModule>();
266
+ // Each module by name, from the time its level checks run.
267
+ const checkedModules = new Map<string, LinkedModule>();
226
268
  const linkedList: LinkedModule[] = [];
227
269
  const dependencies = new Map<string, Set<string>>();
228
270
  const loading: Set<string>[] = [];
@@ -237,7 +279,25 @@ export const createEnvironment = (
237
279
  const copyCount = { value: 0 };
238
280
  const createName = (name: string) => `${name}#${copyCount.value++}`;
239
281
  const instanceChecks: InstanceCheck[] = [];
282
+ // The warnings SANY reports for the spec.
283
+ const warnings: SanyError[] = [];
284
+ const checkInstance = createInstanceChecker((name) => {
285
+ const linked = checkedModules.get(name) ?? getLinkedModule(name, name);
286
+ return {
287
+ constants: linked.constants,
288
+ variables: linked.variables,
289
+ definitions: [
290
+ ...new Set(
291
+ [...linked.visible.values()].flatMap((symbol) => definitions.get(symbol.key) ?? []),
292
+ ),
293
+ ],
294
+ assumptions: linked.module.assumptions.map((assumption) => assumption.expression),
295
+ theorems: linked.module.theorems,
296
+ getDefinition: (symbol) => definitions.get(linked.visible.get(symbol)?.key ?? symbol),
297
+ };
298
+ });
240
299
  const instanceActions = new Map<string, InstanceAction>();
300
+ const qualifiedNames = new Map<string, string>();
241
301
 
242
302
  const addStandardModule = (name: string): Symbols | undefined => {
243
303
  const cached = standardExports.get(name);
@@ -252,7 +312,12 @@ export const createEnvironment = (
252
312
  );
253
313
  standardModule.operators.forEach((operator) => {
254
314
  builtins.set(operator.name, operator);
255
- exported.set(operator.name, { key: operator.name, arity: operator.arity });
315
+ exported.set(operator.name, {
316
+ key: operator.name,
317
+ arity: operator.arity,
318
+ kind: "Definition",
319
+ range: getStandardRange(name, operator.name) ?? exported.get(operator.name)?.range,
320
+ });
256
321
  });
257
322
  standardExports.set(name, exported);
258
323
  return exported;
@@ -260,7 +325,11 @@ export const createEnvironment = (
260
325
 
261
326
  const getStandardSymbols = (name: string) => {
262
327
  const symbols = addStandardModule(name);
263
- if (symbols) useModule(name, STANDARD_DEPENDENCIES.get(name) ?? []);
328
+ const dependencies = STANDARD_DEPENDENCIES.get(name) ?? [];
329
+ if (symbols) useModule(name, dependencies);
330
+ // TLC loads the Java class of each module a standard module uses, so one that uses Integers
331
+ // overrides the arithmetic of Naturals.
332
+ if (symbols && dependencies.includes("Integers")) addStandardModule("Integers");
264
333
  return symbols;
265
334
  };
266
335
 
@@ -289,13 +358,25 @@ export const createEnvironment = (
289
358
  BUNDLED_MODULES.get(name) ??
290
359
  extractModule(options.source, name);
291
360
  if (source === undefined)
292
- throw new TlaSyntaxError(
293
- `Cannot find source file for module ${name} imported in module ${importer}.`,
361
+ throw createSanyError(
362
+ [
363
+ {
364
+ location: `In module ${importer}`,
365
+ message: `Cannot find source file for module ${name} imported in module ${importer}.`,
366
+ },
367
+ ],
368
+ true,
294
369
  );
295
- const module = parseModule(source);
370
+ const module = parseModuleFile(source, name);
296
371
  if (module.name !== name) {
297
- throw new TlaSyntaxError(
298
- `File name '${name}' does not match the name '${module.name}' of the top level module it contains.`,
372
+ throw createSanyError(
373
+ [
374
+ {
375
+ location: "Unknown location",
376
+ message: `File name '${name}' does not match the name '${module.name}' of the top level module it contains.`,
377
+ },
378
+ ],
379
+ true,
299
380
  );
300
381
  }
301
382
  return rejectModuleLiterals(module);
@@ -311,6 +392,8 @@ export const createEnvironment = (
311
392
  }
312
393
  const closure = new Set<string>();
313
394
  const nested: Module[] = [];
395
+ const errors: SanyError[] = [];
396
+ const levelChecks: (() => void)[] = [];
314
397
  linking.push(parsed.name);
315
398
  loading.push(closure);
316
399
  const linked = linkModule(parsed, {
@@ -318,11 +401,19 @@ export const createEnvironment = (
318
401
  symbols: new Map(),
319
402
  modules: new Map(),
320
403
  nested,
404
+ errors,
405
+ warnings,
406
+ levelChecks,
321
407
  });
322
408
  loading.pop();
323
409
  linking.pop();
410
+ if (errors.length > 0) throw createSanyError(errors, false, undefined, warnings);
324
411
  const duplicate = nested.find((module) => closure.has(module.name));
412
+ const loaded = duplicate && linkedModules.get(duplicate.name);
413
+ const redefinition = loaded && getModuleRedefinition(duplicate, loaded.module);
414
+ if (redefinition) throw createSanyError([redefinition], false, undefined, warnings);
325
415
  if (duplicate) throw createModuleRedefinedError(duplicate);
416
+ levelChecks.forEach((check) => check());
326
417
  return { linked, closure };
327
418
  };
328
419
 
@@ -342,12 +433,7 @@ export const createEnvironment = (
342
433
  const instantiate = (
343
434
  instance: Instance,
344
435
  module: Module,
345
- unit: {
346
- imported: Symbols;
347
- importedAt: Map<string, SourceLocation>;
348
- definitions: Map<string, Definition>;
349
- getKey: (definition: Definition) => string;
350
- },
436
+ unit: ModuleUnit,
351
437
  isParameterFree: boolean,
352
438
  nested: LinkedModule | undefined,
353
439
  ): Symbols => {
@@ -355,7 +441,10 @@ export const createEnvironment = (
355
441
  if (standardSymbols) {
356
442
  if (instance.name === undefined) return standardSymbols;
357
443
  return new Map(
358
- [...standardSymbols].map(([name, symbol]) => [`${instance.name}!${name}`, symbol]),
444
+ [...standardSymbols].map(([name, symbol]) => [
445
+ `${instance.name}!${name}`,
446
+ { key: symbol.key, arity: symbol.arity, kind: symbol.kind },
447
+ ]),
359
448
  );
360
449
  }
361
450
  const linked = nested ?? getLinkedModule(instance.module, module.name);
@@ -400,16 +489,24 @@ export const createEnvironment = (
400
489
  const key = instantiation.getKey(symbol.key);
401
490
  if (declarations.length > 0)
402
491
  instanceActions.set(key, { name, location: instance.location });
403
- symbols.set(name, { key, arity: symbol.arity });
492
+ // SANY binds a copy of a definition that depends on the parameters at the INSTANCE.
493
+ symbols.set(name, {
494
+ key,
495
+ arity: symbol.arity,
496
+ kind: symbol.kind,
497
+ range: parameterized.get(symbol.key) === true ? instance.location.range : symbol.range,
498
+ });
404
499
  return;
405
500
  }
406
501
  const key = instantiation.getQualifiedKey(symbol.key);
407
502
  if (declarations.length > 0) {
408
503
  instanceActions.set(key, { name: `${instance.name}!${name}`, location: instance.location });
409
504
  }
505
+ qualifiedNames.set(key, `${instance.name}!${name}`);
410
506
  symbols.set(`${instance.name}!${name}`, {
411
507
  key,
412
508
  arity: symbol.arity + instance.params.length,
509
+ kind: symbol.kind,
413
510
  });
414
511
  });
415
512
  return symbols;
@@ -587,29 +684,58 @@ export const createEnvironment = (
587
684
 
588
685
  const linkModule = (unlinked: Module, scope: ModuleScope): LinkedModule => {
589
686
  const parsed = overrideDefinitions(unlinked, options.loadClass?.(unlinked.name));
687
+ const firstCheck = instanceChecks.length;
590
688
  const visible: Symbols = new Map([
591
689
  ...CORE_OPERATORS.map((operator): [string, ModuleSymbol] => [
592
690
  operator.name,
593
- { key: operator.name, arity: operator.arity },
691
+ { key: operator.name, arity: operator.arity, kind: "Builtin" },
594
692
  ]),
595
693
  ...scope.symbols,
596
694
  ]);
695
+ const extendsReport: ModuleReport = { location: MODULE_START, errors: [], warnings: [] };
696
+ const reports = [extendsReport];
697
+ // Context.mergeExtendContext keeps the first of the symbols the extended modules share by name,
698
+ // and warns of two definitions or two declarations but rejects a definition and a declaration.
699
+ const mergeExtended = (symbols: Symbols) =>
700
+ symbols.forEach((symbol, name) => {
701
+ const current = exported.get(name);
702
+ if (!current) {
703
+ visible.set(name, symbol);
704
+ exported.set(name, symbol);
705
+ return;
706
+ }
707
+ if (
708
+ !current.range ||
709
+ !symbol.range ||
710
+ formatRange(current.range) === formatRange(symbol.range)
711
+ ) {
712
+ return;
713
+ }
714
+ const location = formatRange(symbol.range);
715
+ const existing = formatRange(current.range);
716
+ if (getNodeClass(current.kind) === getNodeClass(symbol.kind)) {
717
+ extendsReport.warnings.push({
718
+ location,
719
+ message: `Warning: the ${getNodeWord(current.kind)} of '${name}' conflicts with \nits ${getNodeWord(current.kind)} at ${existing}.`,
720
+ });
721
+ return;
722
+ }
723
+ extendsReport.errors.push({
724
+ location,
725
+ message: `The ${getNodeWord(symbol.kind)} of '${name}' conflicts with \nits ${getNodeWord(current.kind)} at ${existing}.`,
726
+ });
727
+ });
597
728
  const exported: Symbols = new Map();
598
729
  const modules = new Map<string, LinkedModule>();
599
730
  const extended: LinkedModule[] = [];
600
731
  const constants = [...parsed.constants];
601
732
  const variables = parsed.variables.map((variable) => variable.name);
602
733
  const variableLocations = parsed.variables.map((variable) => variable.location);
603
- const addSymbols = (symbols: Symbols, isExported: boolean) =>
604
- symbols.forEach((symbol, name) => {
605
- visible.set(name, symbol);
606
- if (isExported) exported.set(name, symbol);
607
- });
608
734
  parsed.extends.forEach((name) => {
609
735
  const nested = scope.modules.get(name);
610
736
  const standardSymbols = nested ? undefined : getStandardSymbols(name);
611
737
  if (standardSymbols) {
612
- addSymbols(standardSymbols, true);
738
+ mergeExtended(standardSymbols);
613
739
  return;
614
740
  }
615
741
  const linked = nested ?? getLinkedModule(name, parsed.name);
@@ -623,61 +749,84 @@ export const createEnvironment = (
623
749
  variables.push(variable);
624
750
  variableLocations.push(linked.variableLocations[index]);
625
751
  });
626
- addSymbols(linked.exported, true);
752
+ mergeExtended(linked.exported);
627
753
  linked.modules.forEach((module, moduleName) => modules.set(moduleName, module));
628
754
  extended.push(linked);
629
755
  });
630
- parsed.constants.forEach((constant) =>
631
- exported.set(constant.name, {
632
- key: constant.name,
633
- arity: constant.arity,
634
- declaration: "Constant",
635
- }),
636
- );
637
- parsed.variables.forEach((variable) =>
638
- exported.set(variable.name, { key: variable.name, arity: 0, declaration: "Variable" }),
756
+ const bound = new Map(visible);
757
+ const declarations = [
758
+ ...parsed.constants.map((constant) => ({ ...constant, kind: "Constant" as const })),
759
+ ...parsed.variables.map((variable) => ({ ...variable, kind: "Variable" as const })),
760
+ ];
761
+ const getDeclarationSymbol = (declaration: (typeof declarations)[number]): ModuleSymbol => ({
762
+ key: declaration.name,
763
+ arity: declaration.arity,
764
+ kind: declaration.kind,
765
+ range: declaration.location.range,
766
+ });
767
+ declarations.forEach((declaration) =>
768
+ exported.set(declaration.name, getDeclarationSymbol(declaration)),
639
769
  );
770
+ const getDefinitionSymbol = (definition: Definition): ModuleSymbol => ({
771
+ key: getKey(definition),
772
+ arity: getArity(definition),
773
+ kind: isTheoremDefinition(parsed, definition) ? "Theorem" : "Definition",
774
+ range: definition.location.range,
775
+ });
640
776
  const isParameterFree = constants.length === 0 && variables.length === 0;
641
777
  const getKey = (definition: Definition) =>
642
778
  parsed === root ? definition.name : `${definition.name}${KEY_SEPARATOR}${scope.id}`;
643
- const importedAt = new Map<string, SourceLocation>();
644
- const getUnit = (module: Module) => ({
779
+ const instanced = new Map<Instance, Symbols>();
780
+ const getUnit = (module: Module): ModuleUnit => ({
645
781
  imported: visible,
646
- importedAt,
647
- definitions: new Map(module.definitions.map((definition) => [definition.name, definition])),
782
+ bound,
783
+ // SANY keeps the first of two definitions of a name.
784
+ definitions: new Map(
785
+ module.definitions.toReversed().map((definition) => [definition.name, definition]),
786
+ ),
648
787
  getKey,
788
+ instanced,
789
+ reports,
790
+ warnings: scope.warnings,
649
791
  });
650
792
  const getVisibleModules = () => new Map([...scope.modules, ...modules]);
651
793
  const getSymbolsBefore = (location: SourceLocation): Symbols =>
652
794
  new Map([
653
795
  ...visible,
654
- ...[
655
- ...parsed.constants.map((constant) => ({ ...constant, kind: "Constant" as const })),
656
- ...parsed.variables.map((variable) => ({ ...variable, kind: "Variable" as const })),
657
- ]
796
+ ...declarations
658
797
  .filter((declaration) => isBefore(declaration.location, location))
659
798
  .map((declaration): [string, ModuleSymbol] => [
660
799
  declaration.name,
661
- { key: declaration.name, arity: declaration.arity, declaration: declaration.kind },
800
+ getDeclarationSymbol(declaration),
662
801
  ]),
663
802
  ...parsed.definitions
664
803
  .filter((definition) => isBefore(definition.location, location))
665
804
  .map((definition): [string, ModuleSymbol] => [
666
805
  definition.name,
667
- { key: getKey(definition), arity: getArity(definition) },
806
+ getDefinitionSymbol(definition),
668
807
  ]),
669
808
  ]);
809
+ // Generator.generateModule reports the errors of a nested module and goes on, and then
810
+ // SymbolTable.addModule reports a module already defined.
670
811
  const linkNested = (nested: Module) => {
671
812
  const visibleModules = getVisibleModules();
672
- if (visibleModules.has(nested.name)) throw createModuleRedefinedError(nested);
813
+ const existing = visibleModules.get(nested.name);
814
+ const redefinition = existing && getModuleRedefinition(nested, existing.module);
815
+ if (existing && !redefinition) throw createModuleRedefinedError(nested);
673
816
  scope.nested.push(nested);
817
+ const report: ModuleReport = { location: nested.location, errors: [], warnings: [] };
818
+ reports.push(report);
674
819
  const linked = linkModule(nested, {
675
820
  id: `${scope.id}/${nested.name}`,
676
821
  symbols: getSymbolsBefore(nested.location),
677
822
  modules: visibleModules,
678
823
  nested: scope.nested,
824
+ errors: report.errors,
825
+ warnings: report.warnings,
826
+ levelChecks: scope.levelChecks,
679
827
  });
680
- modules.set(nested.name, linked);
828
+ if (redefinition) report.errors.push(redefinition);
829
+ if (!existing) modules.set(nested.name, linked);
681
830
  if (!nestedModules.has(nested.name)) nestedModules.set(nested.name, linked);
682
831
  };
683
832
  [
@@ -691,10 +840,12 @@ export const createEnvironment = (
691
840
  isParameterFree,
692
841
  getVisibleModules().get(instance.module),
693
842
  );
694
- symbols.forEach((_, name) => {
695
- if (!visible.has(name)) importedAt.set(name, instance.location);
843
+ instanced.set(instance, symbols);
844
+ symbols.forEach((symbol, name) => {
845
+ if (visible.has(name)) return;
846
+ visible.set(name, symbol);
847
+ if (!instance.isLocal) exported.set(name, symbol);
696
848
  });
697
- addSymbols(symbols, !instance.isLocal);
698
849
  },
699
850
  })),
700
851
  ...parsed.modules.map((nested) => ({
@@ -704,7 +855,6 @@ export const createEnvironment = (
704
855
  ]
705
856
  .sort((left, right) => (isBefore(left.location, right.location) ? -1 : 1))
706
857
  .forEach((unit) => unit.link());
707
- checkRedefinitions(parsed, getUnit(parsed));
708
858
  const isInstancedAfterDefinition = (nested: Module) => {
709
859
  const first = parsed.instances.find((instance) => instance.module === nested.name);
710
860
  return first !== undefined && isBefore(nested.location, first.location);
@@ -720,20 +870,15 @@ export const createEnvironment = (
720
870
  ),
721
871
  getAvailableDefinitions(visible),
722
872
  );
723
- resolveModule(module, getUnit(module));
873
+ scope.errors.push(...resolveModule(module, getUnit(module)));
724
874
  module.definitions.forEach((definition) => {
725
875
  const key = getKey(definition);
726
876
  definitions.set(key, definition);
727
877
  parameterized.set(key, !isParameterFree);
728
- const symbol = { key, arity: getArity(definition) };
878
+ const symbol = getDefinitionSymbol(definition);
729
879
  visible.set(definition.name, symbol);
730
880
  if (!definition.isLocal) exported.set(definition.name, symbol);
731
881
  });
732
- checkModuleLevels(module, {
733
- constants: new Set(constants.map((constant) => constant.name)),
734
- variables: new Set(variables),
735
- getDefinition: (symbol) => definitions.get(visible.get(symbol)?.key ?? symbol),
736
- });
737
882
  const linked = {
738
883
  module,
739
884
  constants,
@@ -744,11 +889,31 @@ export const createEnvironment = (
744
889
  modules,
745
890
  extended,
746
891
  };
892
+ if (!checkedModules.has(parsed.name)) checkedModules.set(parsed.name, linked);
893
+ // SANY checks the instances of a module with its definitions and theorems, so it reports their
894
+ // errors together.
895
+ const checks = instanceChecks
896
+ .splice(firstCheck)
897
+ .map((check) => ({ location: check.location, check: () => checkInstance(check) }));
898
+ scope.levelChecks.push(() =>
899
+ checkModuleLevels(
900
+ module,
901
+ {
902
+ constants: new Set(constants.map((constant) => constant.name)),
903
+ variables: new Set(variables),
904
+ getDefinition: (symbol) => definitions.get(visible.get(symbol)?.key ?? symbol),
905
+ getQualifiedName: (symbol) => qualifiedNames.get(visible.get(symbol)?.key ?? symbol),
906
+ },
907
+ checks,
908
+ warnings,
909
+ ),
910
+ );
747
911
  linkedList.push(linked);
748
912
  return linked;
749
913
  };
750
914
 
751
915
  const linkedRoot = linkTopLevel(root).linked;
916
+ if (warnings.length > 0) options.print(formatSanyWarnings(warnings));
752
917
  const getRootKey = (name: string) => linkedRoot.visible.get(name)?.key ?? name;
753
918
  linkedRoot.visible.forEach((symbol, name) => {
754
919
  const definition = definitions.get(symbol.key);
@@ -938,20 +1103,6 @@ export const createEnvironment = (
938
1103
  constantLevels: new Map(),
939
1104
  evaluators: new WeakMap(),
940
1105
  };
941
- checkInstances(instanceChecks, (name) => {
942
- const linked = linkedModules.get(name) ?? nestedModules.get(name) ?? linkedRoot;
943
- return {
944
- constants: linked.constants,
945
- variables: linked.variables,
946
- definitions: [
947
- ...new Set(
948
- [...linked.visible.values()].flatMap((symbol) => definitions.get(symbol.key) ?? []),
949
- ),
950
- ],
951
- assumptions: linked.module.assumptions.map((assumption) => assumption.expression),
952
- getDefinition: (symbol) => definitions.get(linked.visible.get(symbol)?.key ?? symbol),
953
- };
954
- });
955
1106
  // TLC evaluates a substitute at startup and rejects it only when that fails and the level bound it
956
1107
  // computes is above constant. The bound counts the operators that TLC's Java code overrides with
957
1108
  // a minimum level as state-level, so the analyzer takes them for variables.
package/src/errors.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { SourceRange } from "./ast";
1
2
  import { EXIT_STATUS, getExitCode } from "./exit-codes";
2
3
  import type { Value } from "./values";
3
4
 
@@ -27,16 +28,66 @@ export interface SyntaxFailure {
27
28
  isEnd: boolean;
28
29
  }
29
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
+
30
47
  export class TlaSyntaxError extends TlaError {
31
48
  failure: SyntaxFailure | undefined;
49
+ sany: SanyReport | undefined;
32
50
 
33
- constructor(message: string, cause?: unknown, failure?: SyntaxFailure) {
51
+ constructor(message: string, cause?: unknown, failure?: SyntaxFailure, sany?: SanyReport) {
34
52
  super(message, cause);
35
53
  this.name = "TlaSyntaxError";
36
54
  this.failure = failure;
55
+ this.sany = sany;
56
+ }
57
+ }
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";
37
82
  }
38
83
  }
39
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
+
40
91
  export class TlaConfigError extends TlaError {
41
92
  constructor(message: string, cause?: unknown) {
42
93
  super(message, cause);
@@ -63,6 +114,17 @@ export class TlaModuleError extends TlaEvaluationError {
63
114
  }
64
115
  }
65
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
+
66
128
  // TLC reports a successor state that the next-state relation leaves incomplete as an error of its
67
129
  // own, not as an exception. It keeps the name TlaEvaluationError, and index.ts doesn't export it.
68
130
  export class TlaIncompleteStateError extends TlaEvaluationError {
@@ -81,6 +143,17 @@ export class TlaIncompleteStateError extends TlaEvaluationError {
81
143
  }
82
144
  }
83
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
+
84
157
  export interface TlapmReport {
85
158
  failure?: string;
86
159
  exception?: string;