tla-ts 0.0.3-dev.cf3b82c → 0.0.3-dev.cfd469d

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