tla-ts 0.0.3-dev.d34b19a → 0.0.3-dev.e5b05b9

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 (55) hide show
  1. package/README.md +5 -1
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.cts +71 -22
  4. package/dist/index.d.ts +71 -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 -17
  11. package/dist/run-cli.js +22 -19
  12. package/dist/transfer.cjs +45 -15
  13. package/dist/transfer.js +45 -15
  14. package/package.json +1 -1
  15. package/src/ast.ts +121 -4
  16. package/src/builtins.ts +9 -3
  17. package/src/check.ts +514 -99
  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 +334 -96
  23. package/src/errors.ts +109 -3
  24. package/src/evaluate.ts +255 -159
  25. package/src/exit-codes.ts +39 -42
  26. package/src/fingerprints.ts +2 -1
  27. package/src/instances.ts +16 -15
  28. package/src/levels.ts +185 -44
  29. package/src/live-check.ts +772 -0
  30. package/src/liveness.ts +120 -543
  31. package/src/parallel-worker.ts +2 -2
  32. package/src/parallel.ts +20 -4
  33. package/src/parser.ts +182 -53
  34. package/src/resolve.ts +1302 -412
  35. package/src/run-cli.ts +115 -20
  36. package/src/runtime.ts +3 -1
  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/standard-ranges.ts +116 -0
  42. package/src/state-graph.ts +157 -0
  43. package/src/subexpressions.ts +124 -159
  44. package/src/substitution-levels.ts +38 -17
  45. package/src/successors.ts +183 -39
  46. package/src/symmetry.ts +16 -6
  47. package/src/tableau.ts +51 -24
  48. package/src/tlc-ext.ts +29 -12
  49. package/src/tlc-module.ts +14 -33
  50. package/src/tlc-modules.ts +4 -0
  51. package/src/tlc-order.ts +25 -7
  52. package/src/tlc-random.ts +9 -6
  53. package/src/tlc-summary.ts +20 -5
  54. package/src/value-sources.ts +29 -0
  55. package/src/values.ts +242 -61
@@ -1,23 +1,33 @@
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
+ formatRange,
18
+ formatSanyWarnings,
19
+ TlaConfigError,
20
+ TlaEvaluationError,
21
+ TlaModuleError,
22
+ TlaSyntaxError,
23
+ type SanyError,
24
+ } from "./errors";
15
25
  import { EXIT_STATUS, setExitCode } from "./exit-codes";
16
26
  import {
17
27
  createBigNumberError,
18
28
  createRealNumberError,
19
- getChildren,
20
- isConstantLevel,
29
+ evaluate,
30
+ getDefinition,
21
31
  isTlcInteger,
22
32
  type Builtin,
23
33
  type Environment,
@@ -31,21 +41,30 @@ import {
31
41
  import { overrideDefinitions } from "./java-overrides";
32
42
  import { extractModule, parseModule } from "./parser";
33
43
  import {
34
- checkRedefinitions,
35
44
  getArity,
45
+ getParamArities,
36
46
  isBefore,
47
+ isTheoremDefinition,
37
48
  KEY_SEPARATOR,
38
49
  LOCAL_RESOLUTION,
50
+ MODULE_START,
39
51
  resolveModule,
40
52
  resolveSubstitutions,
53
+ type ModuleReport,
41
54
  type ModuleSymbol,
55
+ type ModuleUnit,
56
+ type SymbolKind,
42
57
  type Symbols,
43
58
  } from "./resolve";
44
59
  import { createRuntime } from "./runtime";
60
+ import { parseModuleFile } from "./sany-parse-error";
45
61
  import { CORE_OPERATORS, getStandardModule, STANDARD_DEPENDENCIES } from "./standard-modules";
62
+ import { STANDARD_LEVELS } from "./standard-levels";
63
+ import { getStandardRange } from "./standard-ranges";
46
64
  import { resolveInstanceSubexpressions, resolveModuleSubexpressions } from "./subexpressions";
47
- import { checkModuleLevels } from "./levels";
48
- import { checkInstances, type InstanceCheck } from "./substitution-levels";
65
+ import { checkModuleLevels, createLevelAnalyzer } from "./levels";
66
+ import { createInstanceChecker, type InstanceCheck } from "./substitution-levels";
67
+ import { getTlcDeclarationOrder } from "./tlc-order";
49
68
  import {
50
69
  checkInteger,
51
70
  createModelValue,
@@ -104,18 +123,28 @@ interface LinkedModule {
104
123
  exported: Symbols;
105
124
  modules: Map<string, LinkedModule>;
106
125
  extended: LinkedModule[];
126
+ facts: Set<string>;
107
127
  }
108
128
 
129
+ // errors and warnings collect what SANY reports for the module, and levelChecks the level checks of
130
+ // the modules in its file, which SANY runs only when it reports no error.
109
131
  interface ModuleScope {
110
132
  id: string;
111
133
  symbols: Symbols;
112
134
  modules: Map<string, LinkedModule>;
113
135
  nested: Module[];
136
+ errors: SanyError[];
137
+ warnings: SanyError[];
138
+ levelChecks: (() => void)[];
114
139
  }
115
140
 
116
- const getDeclarations = (linked: LinkedModule) => [
141
+ const getDeclarations = (linked: LinkedModule): Declaration[] => [
117
142
  ...linked.constants,
118
- ...linked.variables.map((variable) => ({ name: variable, arity: 0 })),
143
+ ...linked.variables.map((variable, index) => ({
144
+ name: variable,
145
+ arity: 0,
146
+ location: linked.variableLocations[index],
147
+ })),
119
148
  ];
120
149
 
121
150
  const createModuleRedefinedError = (module: Module) =>
@@ -123,6 +152,22 @@ const createModuleRedefinedError = (module: Module) =>
123
152
  `Multiply-defined module '${module.name}' at line ${module.location.line}, column ${module.location.column}`,
124
153
  );
125
154
 
155
+ const getModuleRedefinition = (module: Module, existing: Module): SanyError | undefined =>
156
+ module.location.range &&
157
+ existing.location.range && {
158
+ location: formatRange(module.location.range),
159
+ message: `Multiply-defined module '${module.name}': this definition or declaration conflicts \nwith the one at ${formatRange(existing.location.range)}.`,
160
+ };
161
+
162
+ // Context.kindOfNode names a definition or a parameter a definition, and any other symbol a
163
+ // declaration.
164
+ const getNodeWord = (kind: SymbolKind) =>
165
+ ["Builtin", "Definition", "Instance", "Parameter"].includes(kind) ? "definition" : "declaration";
166
+
167
+ // The Java class of the node SANY binds a symbol to.
168
+ const getNodeClass = (kind: SymbolKind) =>
169
+ kind === "Theorem" ? "ThmOrAssumpDefNode" : getNodeWord(kind);
170
+
126
171
  const createLocalFunction = (definition: Definition, key: string): Definition => ({
127
172
  kind: "Operator",
128
173
  name: key,
@@ -212,6 +257,8 @@ export const createEnvironment = (
212
257
  const root = parseModule(options.source);
213
258
  const definitions = new Map<string, Definition>();
214
259
  const parameterized = new Map<string, boolean>();
260
+ // The definition each instance copy came from, and the instance parameters the copy adds.
261
+ const copySources = new Map<string, { source: string; prefix: number }>();
215
262
  const builtins = new Map<string, Builtin>(
216
263
  CORE_OPERATORS.map((operator) => [operator.name, operator]),
217
264
  );
@@ -219,6 +266,8 @@ export const createEnvironment = (
219
266
  const runtime = createRuntime(config.checkDeadlock, options.seed);
220
267
  const linkedModules = new Map<string, LinkedModule>();
221
268
  const nestedModules = new Map<string, LinkedModule>();
269
+ // Each module by name, from the time its level checks run.
270
+ const checkedModules = new Map<string, LinkedModule>();
222
271
  const linkedList: LinkedModule[] = [];
223
272
  const dependencies = new Map<string, Set<string>>();
224
273
  const loading: Set<string>[] = [];
@@ -233,7 +282,25 @@ export const createEnvironment = (
233
282
  const copyCount = { value: 0 };
234
283
  const createName = (name: string) => `${name}#${copyCount.value++}`;
235
284
  const instanceChecks: InstanceCheck[] = [];
285
+ // The warnings SANY reports for the spec.
286
+ const warnings: SanyError[] = [];
287
+ const checkInstance = createInstanceChecker((name) => {
288
+ const linked = checkedModules.get(name) ?? getLinkedModule(name, name);
289
+ return {
290
+ constants: linked.constants,
291
+ variables: linked.variables,
292
+ definitions: [
293
+ ...new Set(
294
+ [...linked.visible.values()].flatMap((symbol) => definitions.get(symbol.key) ?? []),
295
+ ),
296
+ ],
297
+ assumptions: linked.module.assumptions.map((assumption) => assumption.expression),
298
+ theorems: linked.module.theorems,
299
+ getDefinition: (symbol) => definitions.get(linked.visible.get(symbol)?.key ?? symbol),
300
+ };
301
+ });
236
302
  const instanceActions = new Map<string, InstanceAction>();
303
+ const qualifiedNames = new Map<string, string>();
237
304
 
238
305
  const addStandardModule = (name: string): Symbols | undefined => {
239
306
  const cached = standardExports.get(name);
@@ -248,7 +315,13 @@ export const createEnvironment = (
248
315
  );
249
316
  standardModule.operators.forEach((operator) => {
250
317
  builtins.set(operator.name, operator);
251
- exported.set(operator.name, { key: operator.name, arity: operator.arity });
318
+ exported.set(operator.name, {
319
+ key: operator.name,
320
+ arity: operator.arity,
321
+ params: STANDARD_LEVELS.get(operator.name)?.formals.map((formal) => formal.arity),
322
+ kind: "Definition",
323
+ range: getStandardRange(name, operator.name) ?? exported.get(operator.name)?.range,
324
+ });
252
325
  });
253
326
  standardExports.set(name, exported);
254
327
  return exported;
@@ -256,7 +329,11 @@ export const createEnvironment = (
256
329
 
257
330
  const getStandardSymbols = (name: string) => {
258
331
  const symbols = addStandardModule(name);
259
- if (symbols) useModule(name, STANDARD_DEPENDENCIES.get(name) ?? []);
332
+ const dependencies = STANDARD_DEPENDENCIES.get(name) ?? [];
333
+ if (symbols) useModule(name, dependencies);
334
+ // TLC loads the Java class of each module a standard module uses, so one that uses Integers
335
+ // overrides the arithmetic of Naturals.
336
+ if (symbols && dependencies.includes("Integers")) addStandardModule("Integers");
260
337
  return symbols;
261
338
  };
262
339
 
@@ -285,13 +362,25 @@ export const createEnvironment = (
285
362
  BUNDLED_MODULES.get(name) ??
286
363
  extractModule(options.source, name);
287
364
  if (source === undefined)
288
- throw new TlaSyntaxError(
289
- `Cannot find source file for module ${name} imported in module ${importer}.`,
365
+ throw createSanyError(
366
+ [
367
+ {
368
+ location: `In module ${importer}`,
369
+ message: `Cannot find source file for module ${name} imported in module ${importer}.`,
370
+ },
371
+ ],
372
+ true,
290
373
  );
291
- const module = parseModule(source);
374
+ const module = parseModuleFile(source, name);
292
375
  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.`,
376
+ throw createSanyError(
377
+ [
378
+ {
379
+ location: "Unknown location",
380
+ message: `File name '${name}' does not match the name '${module.name}' of the top level module it contains.`,
381
+ },
382
+ ],
383
+ true,
295
384
  );
296
385
  }
297
386
  return rejectModuleLiterals(module);
@@ -307,6 +396,8 @@ export const createEnvironment = (
307
396
  }
308
397
  const closure = new Set<string>();
309
398
  const nested: Module[] = [];
399
+ const errors: SanyError[] = [];
400
+ const levelChecks: (() => void)[] = [];
310
401
  linking.push(parsed.name);
311
402
  loading.push(closure);
312
403
  const linked = linkModule(parsed, {
@@ -314,11 +405,19 @@ export const createEnvironment = (
314
405
  symbols: new Map(),
315
406
  modules: new Map(),
316
407
  nested,
408
+ errors,
409
+ warnings,
410
+ levelChecks,
317
411
  });
318
412
  loading.pop();
319
413
  linking.pop();
414
+ if (errors.length > 0) throw createSanyError(errors, false, undefined, warnings);
320
415
  const duplicate = nested.find((module) => closure.has(module.name));
416
+ const loaded = duplicate && linkedModules.get(duplicate.name);
417
+ const redefinition = loaded && getModuleRedefinition(duplicate, loaded.module);
418
+ if (redefinition) throw createSanyError([redefinition], false, undefined, warnings);
321
419
  if (duplicate) throw createModuleRedefinedError(duplicate);
420
+ levelChecks.forEach((check) => check());
322
421
  return { linked, closure };
323
422
  };
324
423
 
@@ -338,12 +437,7 @@ export const createEnvironment = (
338
437
  const instantiate = (
339
438
  instance: Instance,
340
439
  module: Module,
341
- unit: {
342
- imported: Symbols;
343
- importedAt: Map<string, SourceLocation>;
344
- definitions: Map<string, Definition>;
345
- getKey: (definition: Definition) => string;
346
- },
440
+ unit: ModuleUnit,
347
441
  isParameterFree: boolean,
348
442
  nested: LinkedModule | undefined,
349
443
  ): Symbols => {
@@ -351,10 +445,16 @@ export const createEnvironment = (
351
445
  if (standardSymbols) {
352
446
  if (instance.name === undefined) return standardSymbols;
353
447
  return new Map(
354
- [...standardSymbols].map(([name, symbol]) => [`${instance.name}!${name}`, symbol]),
448
+ [...standardSymbols].map(([name, symbol]) => [
449
+ `${instance.name}!${name}`,
450
+ { key: symbol.key, arity: symbol.arity, params: symbol.params, kind: symbol.kind },
451
+ ]),
355
452
  );
356
453
  }
357
454
  const linked = nested ?? getLinkedModule(instance.module, module.name);
455
+ linked.facts.forEach((name) =>
456
+ unit.facts.add(instance.name === undefined ? name : `${instance.name}!${name}`),
457
+ );
358
458
  const declarations = getDeclarations(linked);
359
459
  const suffix = `#${copyCount.value++}`;
360
460
  const renamed = new Map(instance.params.map((param) => [param.name, `${param.name}${suffix}`]));
@@ -379,10 +479,11 @@ export const createEnvironment = (
379
479
  variables: new Set(linked.variables),
380
480
  getDefinition: (key) => definitions.get(key),
381
481
  isParameterized: (key) => parameterized.get(key) === true,
382
- addDefinition: (name, create) => {
482
+ addDefinition: (source, name, create) => {
383
483
  const key = createName(`${name}@${module.name}`);
384
484
  definitions.set(key, create(key));
385
485
  parameterized.set(key, !isParameterFree);
486
+ copySources.set(key, { source, prefix: instance.params.length });
386
487
  return key;
387
488
  },
388
489
  createName,
@@ -395,16 +496,26 @@ export const createEnvironment = (
395
496
  const key = instantiation.getKey(symbol.key);
396
497
  if (declarations.length > 0)
397
498
  instanceActions.set(key, { name, location: instance.location });
398
- symbols.set(name, { key, arity: symbol.arity });
499
+ // SANY binds a copy of a definition that depends on the parameters at the INSTANCE.
500
+ symbols.set(name, {
501
+ key,
502
+ arity: symbol.arity,
503
+ params: symbol.params,
504
+ kind: symbol.kind,
505
+ range: parameterized.get(symbol.key) === true ? instance.location.range : symbol.range,
506
+ });
399
507
  return;
400
508
  }
401
509
  const key = instantiation.getQualifiedKey(symbol.key);
402
510
  if (declarations.length > 0) {
403
511
  instanceActions.set(key, { name: `${instance.name}!${name}`, location: instance.location });
404
512
  }
513
+ qualifiedNames.set(key, `${instance.name}!${name}`);
405
514
  symbols.set(`${instance.name}!${name}`, {
406
515
  key,
407
516
  arity: symbol.arity + instance.params.length,
517
+ params: symbol.params && [...instance.params.map((param) => param.arity), ...symbol.params],
518
+ kind: symbol.kind,
408
519
  });
409
520
  });
410
521
  return symbols;
@@ -544,7 +655,7 @@ export const createEnvironment = (
544
655
  variables: new Set(linked.variables),
545
656
  getDefinition: (key) => definitions.get(key),
546
657
  isParameterized: (key) => parameterized.get(key) === true,
547
- addDefinition: (name, create) => {
658
+ addDefinition: (_source, name, create) => {
548
659
  const key = `${name}${KEY_SEPARATOR}${instance.module}${suffix}.${copies.length}`;
549
660
  const definition = create(key);
550
661
  copies.push(
@@ -582,29 +693,59 @@ export const createEnvironment = (
582
693
 
583
694
  const linkModule = (unlinked: Module, scope: ModuleScope): LinkedModule => {
584
695
  const parsed = overrideDefinitions(unlinked, options.loadClass?.(unlinked.name));
696
+ const firstCheck = instanceChecks.length;
585
697
  const visible: Symbols = new Map([
586
698
  ...CORE_OPERATORS.map((operator): [string, ModuleSymbol] => [
587
699
  operator.name,
588
- { key: operator.name, arity: operator.arity },
700
+ { key: operator.name, arity: operator.arity, kind: "Builtin" },
589
701
  ]),
590
702
  ...scope.symbols,
591
703
  ]);
704
+ const extendsReport: ModuleReport = { location: MODULE_START, errors: [], warnings: [] };
705
+ const reports = [extendsReport];
706
+ // Context.mergeExtendContext keeps the first of the symbols the extended modules share by name,
707
+ // and warns of two definitions or two declarations but rejects a definition and a declaration.
708
+ const mergeExtended = (symbols: Symbols) =>
709
+ symbols.forEach((symbol, name) => {
710
+ const current = exported.get(name);
711
+ if (!current) {
712
+ visible.set(name, symbol);
713
+ exported.set(name, symbol);
714
+ return;
715
+ }
716
+ if (
717
+ !current.range ||
718
+ !symbol.range ||
719
+ formatRange(current.range) === formatRange(symbol.range)
720
+ ) {
721
+ return;
722
+ }
723
+ const location = formatRange(symbol.range);
724
+ const existing = formatRange(current.range);
725
+ if (getNodeClass(current.kind) === getNodeClass(symbol.kind)) {
726
+ extendsReport.warnings.push({
727
+ location,
728
+ message: `Warning: the ${getNodeWord(current.kind)} of '${name}' conflicts with \nits ${getNodeWord(current.kind)} at ${existing}.`,
729
+ });
730
+ return;
731
+ }
732
+ extendsReport.errors.push({
733
+ location,
734
+ message: `The ${getNodeWord(symbol.kind)} of '${name}' conflicts with \nits ${getNodeWord(current.kind)} at ${existing}.`,
735
+ });
736
+ });
592
737
  const exported: Symbols = new Map();
738
+ const facts = new Set<string>();
593
739
  const modules = new Map<string, LinkedModule>();
594
740
  const extended: LinkedModule[] = [];
595
741
  const constants = [...parsed.constants];
596
742
  const variables = parsed.variables.map((variable) => variable.name);
597
743
  const variableLocations = parsed.variables.map((variable) => variable.location);
598
- const addSymbols = (symbols: Symbols, isExported: boolean) =>
599
- symbols.forEach((symbol, name) => {
600
- visible.set(name, symbol);
601
- if (isExported) exported.set(name, symbol);
602
- });
603
744
  parsed.extends.forEach((name) => {
604
745
  const nested = scope.modules.get(name);
605
746
  const standardSymbols = nested ? undefined : getStandardSymbols(name);
606
747
  if (standardSymbols) {
607
- addSymbols(standardSymbols, true);
748
+ mergeExtended(standardSymbols);
608
749
  return;
609
750
  }
610
751
  const linked = nested ?? getLinkedModule(name, parsed.name);
@@ -618,61 +759,87 @@ export const createEnvironment = (
618
759
  variables.push(variable);
619
760
  variableLocations.push(linked.variableLocations[index]);
620
761
  });
621
- addSymbols(linked.exported, true);
762
+ mergeExtended(linked.exported);
763
+ linked.facts.forEach((name) => facts.add(name));
622
764
  linked.modules.forEach((module, moduleName) => modules.set(moduleName, module));
623
765
  extended.push(linked);
624
766
  });
625
- parsed.constants.forEach((constant) =>
626
- exported.set(constant.name, {
627
- key: constant.name,
628
- arity: constant.arity,
629
- declaration: "Constant",
630
- }),
631
- );
632
- parsed.variables.forEach((variable) =>
633
- exported.set(variable.name, { key: variable.name, arity: 0, declaration: "Variable" }),
767
+ const bound = new Map(visible);
768
+ const declarations = [
769
+ ...parsed.constants.map((constant) => ({ ...constant, kind: "Constant" as const })),
770
+ ...parsed.variables.map((variable) => ({ ...variable, kind: "Variable" as const })),
771
+ ];
772
+ const getDeclarationSymbol = (declaration: (typeof declarations)[number]): ModuleSymbol => ({
773
+ key: declaration.name,
774
+ arity: declaration.arity,
775
+ kind: declaration.kind,
776
+ range: declaration.location.range,
777
+ });
778
+ declarations.forEach((declaration) =>
779
+ exported.set(declaration.name, getDeclarationSymbol(declaration)),
634
780
  );
781
+ const getDefinitionSymbol = (definition: Definition): ModuleSymbol => ({
782
+ key: getKey(definition),
783
+ arity: getArity(definition),
784
+ params: getParamArities(definition),
785
+ kind: isTheoremDefinition(parsed, definition) ? "Theorem" : "Definition",
786
+ range: definition.location.range,
787
+ });
635
788
  const isParameterFree = constants.length === 0 && variables.length === 0;
636
789
  const getKey = (definition: Definition) =>
637
790
  parsed === root ? definition.name : `${definition.name}${KEY_SEPARATOR}${scope.id}`;
638
- const importedAt = new Map<string, SourceLocation>();
639
- const getUnit = (module: Module) => ({
791
+ const instanced = new Map<Instance, Symbols>();
792
+ const getUnit = (module: Module): ModuleUnit => ({
640
793
  imported: visible,
641
- importedAt,
642
- definitions: new Map(module.definitions.map((definition) => [definition.name, definition])),
794
+ bound,
795
+ // SANY keeps the first of two definitions of a name.
796
+ definitions: new Map(
797
+ module.definitions.toReversed().map((definition) => [definition.name, definition]),
798
+ ),
643
799
  getKey,
800
+ instanced,
801
+ facts,
802
+ reports,
803
+ warnings: scope.warnings,
644
804
  });
645
805
  const getVisibleModules = () => new Map([...scope.modules, ...modules]);
646
806
  const getSymbolsBefore = (location: SourceLocation): Symbols =>
647
807
  new Map([
648
808
  ...visible,
649
- ...[
650
- ...parsed.constants.map((constant) => ({ ...constant, kind: "Constant" as const })),
651
- ...parsed.variables.map((variable) => ({ ...variable, kind: "Variable" as const })),
652
- ]
809
+ ...declarations
653
810
  .filter((declaration) => isBefore(declaration.location, location))
654
811
  .map((declaration): [string, ModuleSymbol] => [
655
812
  declaration.name,
656
- { key: declaration.name, arity: declaration.arity, declaration: declaration.kind },
813
+ getDeclarationSymbol(declaration),
657
814
  ]),
658
815
  ...parsed.definitions
659
816
  .filter((definition) => isBefore(definition.location, location))
660
817
  .map((definition): [string, ModuleSymbol] => [
661
818
  definition.name,
662
- { key: getKey(definition), arity: getArity(definition) },
819
+ getDefinitionSymbol(definition),
663
820
  ]),
664
821
  ]);
822
+ // Generator.generateModule reports the errors of a nested module and goes on, and then
823
+ // SymbolTable.addModule reports a module already defined.
665
824
  const linkNested = (nested: Module) => {
666
825
  const visibleModules = getVisibleModules();
667
- if (visibleModules.has(nested.name)) throw createModuleRedefinedError(nested);
826
+ const existing = visibleModules.get(nested.name);
827
+ const redefinition = existing && getModuleRedefinition(nested, existing.module);
828
+ if (existing && !redefinition) throw createModuleRedefinedError(nested);
668
829
  scope.nested.push(nested);
830
+ const report: ModuleReport = { location: nested.location, errors: [], warnings: [] };
831
+ reports.push(report);
669
832
  const linked = linkModule(nested, {
670
833
  id: `${scope.id}/${nested.name}`,
671
834
  symbols: getSymbolsBefore(nested.location),
672
835
  modules: visibleModules,
673
836
  nested: scope.nested,
837
+ errors: report.errors,
838
+ warnings: report.warnings,
839
+ levelChecks: scope.levelChecks,
674
840
  });
675
- modules.set(nested.name, linked);
841
+ if (redefinition) report.errors.push(redefinition);
842
+ if (!existing) modules.set(nested.name, linked);
676
843
  if (!nestedModules.has(nested.name)) nestedModules.set(nested.name, linked);
677
844
  };
678
845
  [
@@ -686,10 +853,12 @@ export const createEnvironment = (
686
853
  isParameterFree,
687
854
  getVisibleModules().get(instance.module),
688
855
  );
689
- symbols.forEach((_, name) => {
690
- if (!visible.has(name)) importedAt.set(name, instance.location);
856
+ instanced.set(instance, symbols);
857
+ symbols.forEach((symbol, name) => {
858
+ if (visible.has(name)) return;
859
+ visible.set(name, symbol);
860
+ if (!instance.isLocal) exported.set(name, symbol);
691
861
  });
692
- addSymbols(symbols, !instance.isLocal);
693
862
  },
694
863
  })),
695
864
  ...parsed.modules.map((nested) => ({
@@ -699,7 +868,6 @@ export const createEnvironment = (
699
868
  ]
700
869
  .sort((left, right) => (isBefore(left.location, right.location) ? -1 : 1))
701
870
  .forEach((unit) => unit.link());
702
- checkRedefinitions(parsed, getUnit(parsed));
703
871
  const isInstancedAfterDefinition = (nested: Module) => {
704
872
  const first = parsed.instances.find((instance) => instance.module === nested.name);
705
873
  return first !== undefined && isBefore(nested.location, first.location);
@@ -715,20 +883,15 @@ export const createEnvironment = (
715
883
  ),
716
884
  getAvailableDefinitions(visible),
717
885
  );
718
- resolveModule(module, getUnit(module));
886
+ scope.errors.push(...resolveModule(module, getUnit(module)));
719
887
  module.definitions.forEach((definition) => {
720
888
  const key = getKey(definition);
721
889
  definitions.set(key, definition);
722
890
  parameterized.set(key, !isParameterFree);
723
- const symbol = { key, arity: getArity(definition) };
891
+ const symbol = getDefinitionSymbol(definition);
724
892
  visible.set(definition.name, symbol);
725
893
  if (!definition.isLocal) exported.set(definition.name, symbol);
726
894
  });
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
895
  const linked = {
733
896
  module,
734
897
  constants,
@@ -738,12 +901,36 @@ export const createEnvironment = (
738
901
  exported,
739
902
  modules,
740
903
  extended,
904
+ facts: new Set([
905
+ ...facts,
906
+ ...[...module.theorems, ...module.assumptions].flatMap((fact) => fact.name ?? []),
907
+ ]),
741
908
  };
909
+ if (!checkedModules.has(parsed.name)) checkedModules.set(parsed.name, linked);
910
+ // SANY checks the instances of a module with its definitions and theorems, so it reports their
911
+ // errors together.
912
+ const checks = instanceChecks
913
+ .splice(firstCheck)
914
+ .map((check) => ({ location: check.location, check: () => checkInstance(check) }));
915
+ scope.levelChecks.push(() =>
916
+ checkModuleLevels(
917
+ module,
918
+ {
919
+ constants: new Set(constants.map((constant) => constant.name)),
920
+ variables: new Set(variables),
921
+ getDefinition: (symbol) => definitions.get(visible.get(symbol)?.key ?? symbol),
922
+ getQualifiedName: (symbol) => qualifiedNames.get(visible.get(symbol)?.key ?? symbol),
923
+ },
924
+ checks,
925
+ warnings,
926
+ ),
927
+ );
742
928
  linkedList.push(linked);
743
929
  return linked;
744
930
  };
745
931
 
746
932
  const linkedRoot = linkTopLevel(root).linked;
933
+ if (warnings.length > 0) options.print(formatSanyWarnings(warnings));
747
934
  const getRootKey = (name: string) => linkedRoot.visible.get(name)?.key ?? name;
748
935
  linkedRoot.visible.forEach((symbol, name) => {
749
936
  const definition = definitions.get(symbol.key);
@@ -872,11 +1059,51 @@ export const createEnvironment = (
872
1059
  );
873
1060
  }
874
1061
  });
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
- }
1062
+ // TLC sets a module-scoped entry on the body of the module's definition, which every instance of
1063
+ // the module shares.
1064
+ const scopedKeys = new Set(
1065
+ [...config.constants, ...config.substitutions]
1066
+ .filter((item) => item.module !== undefined)
1067
+ .flatMap(getScopedKeys),
1068
+ );
1069
+ const getOverride = (
1070
+ key: string,
1071
+ prefix: number,
1072
+ ): { key: string; prefix: number } | undefined => {
1073
+ if (scopedKeys.has(key)) return { key, prefix };
1074
+ const copy = copySources.get(key);
1075
+ return copy && getOverride(copy.source, prefix + copy.prefix);
1076
+ };
1077
+ copySources.forEach((copy, key) => {
1078
+ const override = getOverride(copy.source, copy.prefix);
1079
+ const definition = definitions.get(key);
1080
+ if (!override || !definition) return;
1081
+ const params = definition.kind === "Operator" ? definition.params : [];
1082
+ const alias = createLocalAlias(
1083
+ key,
1084
+ override.key,
1085
+ params,
1086
+ params.slice(override.prefix),
1087
+ definition.location,
1088
+ );
1089
+ definitions.set(key, alias);
1090
+ linkedRoot.visible.forEach((symbol, name) => {
1091
+ if (symbol.key === key && name !== key) definitions.set(name, alias);
1092
+ });
879
1093
  });
1094
+ const unassigned = declaredConstants.filter(
1095
+ (name) => !constants.has(name) && !substitutions.has(name) && !operatorKeys.has(name),
1096
+ );
1097
+ if (unassigned.length > 0) {
1098
+ // TLC reports the first constant it finds unassigned in SANY's order of declarations.
1099
+ const name =
1100
+ getTlcDeclarationOrder(options.source, options.loadModule, "constant").find((constant) =>
1101
+ unassigned.includes(constant),
1102
+ ) ?? unassigned[0];
1103
+ throw new TlaConfigError(
1104
+ `The constant parameter ${name} is not assigned a value by the configuration file.`,
1105
+ );
1106
+ }
880
1107
 
881
1108
  const environment: Environment = {
882
1109
  runtime,
@@ -893,32 +1120,43 @@ export const createEnvironment = (
893
1120
  constantLevels: new Map(),
894
1121
  evaluators: new WeakMap(),
895
1122
  };
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
- };
1123
+ // TLC evaluates a substitute at startup and rejects it only when that fails and the level bound it
1124
+ // computes is above constant. The bound counts the operators that TLC's Java code overrides with
1125
+ // a minimum level as state-level, so the analyzer takes them for variables.
1126
+ const analyzer = createLevelAnalyzer({
1127
+ constants: new Set(constants.keys()),
1128
+ variables: new Set([
1129
+ ...variables,
1130
+ ...["TLCGet", "Trace", "CounterExample"].filter((name) => builtins.has(name)),
1131
+ ]),
1132
+ getDefinition: (name) => getDefinition(name, environment),
909
1133
  });
1134
+ const getEvaluationError = (body: Expression) => {
1135
+ try {
1136
+ evaluate(body, { environment, scope: undefined, state: undefined, next: undefined });
1137
+ return undefined;
1138
+ } catch (error) {
1139
+ if (error instanceof TlaEvaluationError) return error;
1140
+ throw error;
1141
+ }
1142
+ };
910
1143
  substitutions.forEach((target, name) => {
911
1144
  const definition = definitions.get(target);
912
- if (
1145
+ const error =
913
1146
  declaredConstants.includes(name) &&
914
- definition &&
915
- !isConstantLevel(definition, environment)
916
- ) {
1147
+ definition?.kind === "Operator" &&
1148
+ definition.params.length === 0 &&
1149
+ analyzer.analyzeDefinition(definition, new Map()).level > 0
1150
+ ? getEvaluationError(definition.body)
1151
+ : undefined;
1152
+ // TLC adds the reason unless a standard module's Java code failed.
1153
+ if (error) {
917
1154
  throw new TlaConfigError(
918
- `The configuration file substitutes constant ${name} with non-constant ${target}`,
1155
+ `The configuration file substitutes constant ${name} with non-constant ${target}${error instanceof TlaModuleError ? "" : ` - specifically: ${error.message}`}`,
919
1156
  );
920
1157
  }
921
1158
  });
1159
+ runtime.isStarted = true;
922
1160
  return {
923
1161
  environment,
924
1162
  assumptions,