tla-ts 0.0.3-dev.3cf2ad0 → 0.0.3-dev.40085a4

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 (56) hide show
  1. package/README.md +16 -2
  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 +46 -16
  13. package/dist/transfer.js +46 -16
  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 +410 -130
  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 +17 -16
  28. package/src/levels.ts +185 -44
  29. package/src/lexer.ts +5 -1
  30. package/src/live-check.ts +772 -0
  31. package/src/liveness.ts +120 -543
  32. package/src/parallel-worker.ts +7 -3
  33. package/src/parallel.ts +20 -4
  34. package/src/parser.ts +184 -54
  35. package/src/resolve.ts +1378 -420
  36. package/src/run-cli.ts +115 -20
  37. package/src/runtime.ts +3 -1
  38. package/src/sany-lexer.ts +615 -0
  39. package/src/sany-parse-error.ts +3143 -0
  40. package/src/spec-description.ts +19 -8
  41. package/src/standard-modules.ts +54 -45
  42. package/src/standard-ranges.ts +116 -0
  43. package/src/state-graph.ts +157 -0
  44. package/src/subexpressions.ts +231 -171
  45. package/src/substitution-levels.ts +38 -17
  46. package/src/successors.ts +183 -39
  47. package/src/symmetry.ts +25 -7
  48. package/src/tableau.ts +51 -24
  49. package/src/tlc-ext.ts +29 -12
  50. package/src/tlc-module.ts +14 -33
  51. package/src/tlc-modules.ts +4 -0
  52. package/src/tlc-order.ts +25 -7
  53. package/src/tlc-random.ts +9 -6
  54. package/src/tlc-summary.ts +20 -5
  55. package/src/value-sources.ts +29 -0
  56. 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,23 +437,16 @@ 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 => {
350
444
  const standardSymbols = nested ? undefined : getStandardSymbols(instance.module);
351
- if (standardSymbols) {
352
- if (instance.name === undefined) return standardSymbols;
353
- return new Map(
354
- [...standardSymbols].map(([name, symbol]) => [`${instance.name}!${name}`, symbol]),
355
- );
356
- }
445
+ if (standardSymbols) return getStandardInstanceSymbols(instance, standardSymbols);
357
446
  const linked = nested ?? getLinkedModule(instance.module, module.name);
447
+ linked.facts.forEach((name) =>
448
+ unit.facts.add(instance.name === undefined ? name : `${instance.name}!${name}`),
449
+ );
358
450
  const declarations = getDeclarations(linked);
359
451
  const suffix = `#${copyCount.value++}`;
360
452
  const renamed = new Map(instance.params.map((param) => [param.name, `${param.name}${suffix}`]));
@@ -379,35 +471,78 @@ export const createEnvironment = (
379
471
  variables: new Set(linked.variables),
380
472
  getDefinition: (key) => definitions.get(key),
381
473
  isParameterized: (key) => parameterized.get(key) === true,
382
- addDefinition: (name, create) => {
474
+ addDefinition: (source, name, create) => {
383
475
  const key = createName(`${name}@${module.name}`);
384
476
  definitions.set(key, create(key));
385
477
  parameterized.set(key, !isParameterFree);
478
+ copySources.set(key, { source, prefix: instance.params.length });
386
479
  return key;
387
480
  },
388
481
  createName,
389
482
  });
390
- const declared = new Set(declarations.map((declaration) => declaration.name));
391
- const symbols: Symbols = new Map();
392
- linked.exported.forEach((symbol, name) => {
393
- if (declared.has(name)) return;
394
- if (instance.name === undefined) {
395
- const key = instantiation.getKey(symbol.key);
396
- if (declarations.length > 0)
397
- instanceActions.set(key, { name, location: instance.location });
398
- symbols.set(name, { key, arity: symbol.arity });
399
- return;
400
- }
401
- const key = instantiation.getQualifiedKey(symbol.key);
402
- if (declarations.length > 0) {
403
- instanceActions.set(key, { name: `${instance.name}!${name}`, location: instance.location });
404
- }
405
- symbols.set(`${instance.name}!${name}`, {
406
- key,
407
- arity: symbol.arity + instance.params.length,
408
- });
483
+ return getInstanceSymbols(instance, linked.exported, declarations, (key, name) => {
484
+ const copy =
485
+ instance.name === undefined
486
+ ? instantiation.getKey(key)
487
+ : instantiation.getQualifiedKey(key);
488
+ if (declarations.length > 0) instanceActions.set(copy, { name, location: instance.location });
489
+ if (instance.name !== undefined) qualifiedNames.set(copy, name);
490
+ return copy;
409
491
  });
410
- return symbols;
492
+ };
493
+
494
+ const getStandardInstanceSymbols = (instance: Instance, standardSymbols: Symbols): Symbols =>
495
+ instance.name === undefined
496
+ ? standardSymbols
497
+ : new Map(
498
+ [...standardSymbols].map(([name, symbol]) => [
499
+ `${instance.name}!${name}`,
500
+ { key: symbol.key, arity: symbol.arity, params: symbol.params, kind: symbol.kind },
501
+ ]),
502
+ );
503
+
504
+ // The names an INSTANCE adds for the definitions of the module it instantiates, each with the key
505
+ // that getKey gives it. SANY binds a copy of a definition that depends on the parameters at the
506
+ // INSTANCE.
507
+ const getInstanceSymbols = (
508
+ instance: Instance,
509
+ exported: Symbols,
510
+ declarations: Declaration[],
511
+ getKey: (key: string, name: string) => string,
512
+ ): Symbols => {
513
+ const declared = new Set(declarations.map((declaration) => declaration.name));
514
+ return new Map(
515
+ [...exported]
516
+ .filter(([name]) => !declared.has(name))
517
+ .map(([name, symbol]): [string, ModuleSymbol] => {
518
+ if (instance.name === undefined) {
519
+ return [
520
+ name,
521
+ {
522
+ key: getKey(symbol.key, name),
523
+ arity: symbol.arity,
524
+ params: symbol.params,
525
+ kind: symbol.kind,
526
+ range:
527
+ parameterized.get(symbol.key) === true ? instance.location.range : symbol.range,
528
+ },
529
+ ];
530
+ }
531
+ const qualified = `${instance.name}!${name}`;
532
+ return [
533
+ qualified,
534
+ {
535
+ key: getKey(symbol.key, qualified),
536
+ arity: symbol.arity + instance.params.length,
537
+ params: symbol.params && [
538
+ ...instance.params.map((param) => param.arity),
539
+ ...symbol.params,
540
+ ],
541
+ kind: symbol.kind,
542
+ },
543
+ ];
544
+ }),
545
+ );
411
546
  };
412
547
 
413
548
  const getLocalArguments = (params: OperatorParam[], location: SourceLocation) =>
@@ -544,7 +679,7 @@ export const createEnvironment = (
544
679
  variables: new Set(linked.variables),
545
680
  getDefinition: (key) => definitions.get(key),
546
681
  isParameterized: (key) => parameterized.get(key) === true,
547
- addDefinition: (name, create) => {
682
+ addDefinition: (_source, name, create) => {
548
683
  const key = `${name}${KEY_SEPARATOR}${instance.module}${suffix}.${copies.length}`;
549
684
  const definition = create(key);
550
685
  copies.push(
@@ -582,29 +717,59 @@ export const createEnvironment = (
582
717
 
583
718
  const linkModule = (unlinked: Module, scope: ModuleScope): LinkedModule => {
584
719
  const parsed = overrideDefinitions(unlinked, options.loadClass?.(unlinked.name));
720
+ const firstCheck = instanceChecks.length;
585
721
  const visible: Symbols = new Map([
586
722
  ...CORE_OPERATORS.map((operator): [string, ModuleSymbol] => [
587
723
  operator.name,
588
- { key: operator.name, arity: operator.arity },
724
+ { key: operator.name, arity: operator.arity, kind: "Builtin" },
589
725
  ]),
590
726
  ...scope.symbols,
591
727
  ]);
728
+ const extendsReport: ModuleReport = { location: MODULE_START, errors: [], warnings: [] };
729
+ const reports = [extendsReport];
730
+ // Context.mergeExtendContext keeps the first of the symbols the extended modules share by name,
731
+ // and warns of two definitions or two declarations but rejects a definition and a declaration.
732
+ const mergeExtended = (symbols: Symbols) =>
733
+ symbols.forEach((symbol, name) => {
734
+ const current = exported.get(name);
735
+ if (!current) {
736
+ visible.set(name, symbol);
737
+ exported.set(name, symbol);
738
+ return;
739
+ }
740
+ if (
741
+ !current.range ||
742
+ !symbol.range ||
743
+ formatRange(current.range) === formatRange(symbol.range)
744
+ ) {
745
+ return;
746
+ }
747
+ const location = formatRange(symbol.range);
748
+ const existing = formatRange(current.range);
749
+ if (getNodeClass(current.kind) === getNodeClass(symbol.kind)) {
750
+ extendsReport.warnings.push({
751
+ location,
752
+ message: `Warning: the ${getNodeWord(current.kind)} of '${name}' conflicts with \nits ${getNodeWord(current.kind)} at ${existing}.`,
753
+ });
754
+ return;
755
+ }
756
+ extendsReport.errors.push({
757
+ location,
758
+ message: `The ${getNodeWord(symbol.kind)} of '${name}' conflicts with \nits ${getNodeWord(current.kind)} at ${existing}.`,
759
+ });
760
+ });
592
761
  const exported: Symbols = new Map();
762
+ const facts = new Set<string>();
593
763
  const modules = new Map<string, LinkedModule>();
594
764
  const extended: LinkedModule[] = [];
595
765
  const constants = [...parsed.constants];
596
766
  const variables = parsed.variables.map((variable) => variable.name);
597
767
  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
768
  parsed.extends.forEach((name) => {
604
769
  const nested = scope.modules.get(name);
605
770
  const standardSymbols = nested ? undefined : getStandardSymbols(name);
606
771
  if (standardSymbols) {
607
- addSymbols(standardSymbols, true);
772
+ mergeExtended(standardSymbols);
608
773
  return;
609
774
  }
610
775
  const linked = nested ?? getLinkedModule(name, parsed.name);
@@ -618,61 +783,114 @@ export const createEnvironment = (
618
783
  variables.push(variable);
619
784
  variableLocations.push(linked.variableLocations[index]);
620
785
  });
621
- addSymbols(linked.exported, true);
786
+ mergeExtended(linked.exported);
787
+ linked.facts.forEach((name) => facts.add(name));
622
788
  linked.modules.forEach((module, moduleName) => modules.set(moduleName, module));
623
789
  extended.push(linked);
624
790
  });
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" }),
791
+ const bound = new Map(visible);
792
+ const declarations = [
793
+ ...parsed.constants.map((constant) => ({ ...constant, kind: "Constant" as const })),
794
+ ...parsed.variables.map((variable) => ({ ...variable, kind: "Variable" as const })),
795
+ ];
796
+ const getDeclarationSymbol = (declaration: (typeof declarations)[number]): ModuleSymbol => ({
797
+ key: declaration.name,
798
+ arity: declaration.arity,
799
+ kind: declaration.kind,
800
+ range: declaration.location.range,
801
+ });
802
+ declarations.forEach((declaration) =>
803
+ exported.set(declaration.name, getDeclarationSymbol(declaration)),
634
804
  );
805
+ const getDefinitionSymbol = (definition: Definition): ModuleSymbol => ({
806
+ key: getKey(definition),
807
+ arity: getArity(definition),
808
+ params: getParamArities(definition),
809
+ kind: isTheoremDefinition(parsed, definition) ? "Theorem" : "Definition",
810
+ range: definition.location.range,
811
+ });
635
812
  const isParameterFree = constants.length === 0 && variables.length === 0;
636
813
  const getKey = (definition: Definition) =>
637
814
  parsed === root ? definition.name : `${definition.name}${KEY_SEPARATOR}${scope.id}`;
638
- const importedAt = new Map<string, SourceLocation>();
639
- const getUnit = (module: Module) => ({
815
+ const instanced = new Map<Instance, Symbols>();
816
+ const getVisibleModules = () => new Map([...scope.modules, ...modules]);
817
+ const isInstancedAfterDefinition = (nested: Module) => {
818
+ const first = parsed.instances.find((instance) => instance.module === nested.name);
819
+ return first !== undefined && isBefore(nested.location, first.location);
820
+ };
821
+ const getLetModule = (instance: Instance) => {
822
+ const own = parsed.modules.find((nested) => nested.name === instance.module);
823
+ if (!own) return getVisibleModules().get(instance.module);
824
+ return isInstancedAfterDefinition(own) ? modules.get(own.name) : undefined;
825
+ };
826
+ const getUnit = (module: Module): ModuleUnit => ({
640
827
  imported: visible,
641
- importedAt,
642
- definitions: new Map(module.definitions.map((definition) => [definition.name, definition])),
828
+ getInstance: (instance) => {
829
+ const nested = getLetModule(instance);
830
+ const standardSymbols = nested ? undefined : getStandardSymbols(instance.module);
831
+ if (standardSymbols) {
832
+ return {
833
+ declarations: [],
834
+ symbols: getStandardInstanceSymbols(instance, standardSymbols),
835
+ instancer: parsed.name,
836
+ };
837
+ }
838
+ const linked = nested ?? getLinkedModule(instance.module, parsed.name);
839
+ const declarations = getDeclarations(linked);
840
+ return {
841
+ declarations,
842
+ symbols: getInstanceSymbols(instance, linked.exported, declarations, (key) => key),
843
+ instancer: parsed.name,
844
+ };
845
+ },
846
+ bound,
847
+ // SANY keeps the first of two definitions of a name.
848
+ definitions: new Map(
849
+ module.definitions.toReversed().map((definition) => [definition.name, definition]),
850
+ ),
643
851
  getKey,
852
+ instanced,
853
+ facts,
854
+ reports,
855
+ warnings: scope.warnings,
644
856
  });
645
- const getVisibleModules = () => new Map([...scope.modules, ...modules]);
646
857
  const getSymbolsBefore = (location: SourceLocation): Symbols =>
647
858
  new Map([
648
859
  ...visible,
649
- ...[
650
- ...parsed.constants.map((constant) => ({ ...constant, kind: "Constant" as const })),
651
- ...parsed.variables.map((variable) => ({ ...variable, kind: "Variable" as const })),
652
- ]
860
+ ...declarations
653
861
  .filter((declaration) => isBefore(declaration.location, location))
654
862
  .map((declaration): [string, ModuleSymbol] => [
655
863
  declaration.name,
656
- { key: declaration.name, arity: declaration.arity, declaration: declaration.kind },
864
+ getDeclarationSymbol(declaration),
657
865
  ]),
658
866
  ...parsed.definitions
659
867
  .filter((definition) => isBefore(definition.location, location))
660
868
  .map((definition): [string, ModuleSymbol] => [
661
869
  definition.name,
662
- { key: getKey(definition), arity: getArity(definition) },
870
+ getDefinitionSymbol(definition),
663
871
  ]),
664
872
  ]);
873
+ // Generator.generateModule reports the errors of a nested module and goes on, and then
874
+ // SymbolTable.addModule reports a module already defined.
665
875
  const linkNested = (nested: Module) => {
666
876
  const visibleModules = getVisibleModules();
667
- if (visibleModules.has(nested.name)) throw createModuleRedefinedError(nested);
877
+ const existing = visibleModules.get(nested.name);
878
+ const redefinition = existing && getModuleRedefinition(nested, existing.module);
879
+ if (existing && !redefinition) throw createModuleRedefinedError(nested);
668
880
  scope.nested.push(nested);
881
+ const report: ModuleReport = { location: nested.location, errors: [], warnings: [] };
882
+ reports.push(report);
669
883
  const linked = linkModule(nested, {
670
884
  id: `${scope.id}/${nested.name}`,
671
885
  symbols: getSymbolsBefore(nested.location),
672
886
  modules: visibleModules,
673
887
  nested: scope.nested,
888
+ errors: report.errors,
889
+ warnings: report.warnings,
890
+ levelChecks: scope.levelChecks,
674
891
  });
675
- modules.set(nested.name, linked);
892
+ if (redefinition) report.errors.push(redefinition);
893
+ if (!existing) modules.set(nested.name, linked);
676
894
  if (!nestedModules.has(nested.name)) nestedModules.set(nested.name, linked);
677
895
  };
678
896
  [
@@ -686,10 +904,12 @@ export const createEnvironment = (
686
904
  isParameterFree,
687
905
  getVisibleModules().get(instance.module),
688
906
  );
689
- symbols.forEach((_, name) => {
690
- if (!visible.has(name)) importedAt.set(name, instance.location);
907
+ instanced.set(instance, symbols);
908
+ symbols.forEach((symbol, name) => {
909
+ if (visible.has(name)) return;
910
+ visible.set(name, symbol);
911
+ if (!instance.isLocal) exported.set(name, symbol);
691
912
  });
692
- addSymbols(symbols, !instance.isLocal);
693
913
  },
694
914
  })),
695
915
  ...parsed.modules.map((nested) => ({
@@ -699,36 +919,21 @@ export const createEnvironment = (
699
919
  ]
700
920
  .sort((left, right) => (isBefore(left.location, right.location) ? -1 : 1))
701
921
  .forEach((unit) => unit.link());
702
- checkRedefinitions(parsed, getUnit(parsed));
703
- const isInstancedAfterDefinition = (nested: Module) => {
704
- const first = parsed.instances.find((instance) => instance.module === nested.name);
705
- return first !== undefined && isBefore(nested.location, first.location);
706
- };
707
- const getLetModule = (instance: Instance) => {
708
- const own = parsed.modules.find((nested) => nested.name === instance.module);
709
- if (!own) return getVisibleModules().get(instance.module);
710
- return isInstancedAfterDefinition(own) ? modules.get(own.name) : undefined;
711
- };
712
922
  const module = resolveModuleSubexpressions(
713
923
  withLetInstances(parsed, (instance, lets) =>
714
924
  instantiateLocally(instance, lets, parsed.name, getLetModule(instance)),
715
925
  ),
716
926
  getAvailableDefinitions(visible),
717
927
  );
718
- resolveModule(module, getUnit(module));
928
+ scope.errors.push(...resolveModule(module, getUnit(module)));
719
929
  module.definitions.forEach((definition) => {
720
930
  const key = getKey(definition);
721
931
  definitions.set(key, definition);
722
932
  parameterized.set(key, !isParameterFree);
723
- const symbol = { key, arity: getArity(definition) };
933
+ const symbol = getDefinitionSymbol(definition);
724
934
  visible.set(definition.name, symbol);
725
935
  if (!definition.isLocal) exported.set(definition.name, symbol);
726
936
  });
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
937
  const linked = {
733
938
  module,
734
939
  constants,
@@ -738,12 +943,36 @@ export const createEnvironment = (
738
943
  exported,
739
944
  modules,
740
945
  extended,
946
+ facts: new Set([
947
+ ...facts,
948
+ ...[...module.theorems, ...module.assumptions].flatMap((fact) => fact.name ?? []),
949
+ ]),
741
950
  };
951
+ if (!checkedModules.has(parsed.name)) checkedModules.set(parsed.name, linked);
952
+ // SANY checks the instances of a module with its definitions and theorems, so it reports their
953
+ // errors together.
954
+ const checks = instanceChecks
955
+ .splice(firstCheck)
956
+ .map((check) => ({ location: check.location, check: () => checkInstance(check) }));
957
+ scope.levelChecks.push(() =>
958
+ checkModuleLevels(
959
+ module,
960
+ {
961
+ constants: new Set(constants.map((constant) => constant.name)),
962
+ variables: new Set(variables),
963
+ getDefinition: (symbol) => definitions.get(visible.get(symbol)?.key ?? symbol),
964
+ getQualifiedName: (symbol) => qualifiedNames.get(visible.get(symbol)?.key ?? symbol),
965
+ },
966
+ checks,
967
+ warnings,
968
+ ),
969
+ );
742
970
  linkedList.push(linked);
743
971
  return linked;
744
972
  };
745
973
 
746
974
  const linkedRoot = linkTopLevel(root).linked;
975
+ if (warnings.length > 0) options.print(formatSanyWarnings(warnings));
747
976
  const getRootKey = (name: string) => linkedRoot.visible.get(name)?.key ?? name;
748
977
  linkedRoot.visible.forEach((symbol, name) => {
749
978
  const definition = definitions.get(symbol.key);
@@ -872,11 +1101,51 @@ export const createEnvironment = (
872
1101
  );
873
1102
  }
874
1103
  });
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
- }
1104
+ // TLC sets a module-scoped entry on the body of the module's definition, which every instance of
1105
+ // the module shares.
1106
+ const scopedKeys = new Set(
1107
+ [...config.constants, ...config.substitutions]
1108
+ .filter((item) => item.module !== undefined)
1109
+ .flatMap(getScopedKeys),
1110
+ );
1111
+ const getOverride = (
1112
+ key: string,
1113
+ prefix: number,
1114
+ ): { key: string; prefix: number } | undefined => {
1115
+ if (scopedKeys.has(key)) return { key, prefix };
1116
+ const copy = copySources.get(key);
1117
+ return copy && getOverride(copy.source, prefix + copy.prefix);
1118
+ };
1119
+ copySources.forEach((copy, key) => {
1120
+ const override = getOverride(copy.source, copy.prefix);
1121
+ const definition = definitions.get(key);
1122
+ if (!override || !definition) return;
1123
+ const params = definition.kind === "Operator" ? definition.params : [];
1124
+ const alias = createLocalAlias(
1125
+ key,
1126
+ override.key,
1127
+ params,
1128
+ params.slice(override.prefix),
1129
+ definition.location,
1130
+ );
1131
+ definitions.set(key, alias);
1132
+ linkedRoot.visible.forEach((symbol, name) => {
1133
+ if (symbol.key === key && name !== key) definitions.set(name, alias);
1134
+ });
879
1135
  });
1136
+ const unassigned = declaredConstants.filter(
1137
+ (name) => !constants.has(name) && !substitutions.has(name) && !operatorKeys.has(name),
1138
+ );
1139
+ if (unassigned.length > 0) {
1140
+ // TLC reports the first constant it finds unassigned in SANY's order of declarations.
1141
+ const name =
1142
+ getTlcDeclarationOrder(options.source, options.loadModule, "constant").find((constant) =>
1143
+ unassigned.includes(constant),
1144
+ ) ?? unassigned[0];
1145
+ throw new TlaConfigError(
1146
+ `The constant parameter ${name} is not assigned a value by the configuration file.`,
1147
+ );
1148
+ }
880
1149
 
881
1150
  const environment: Environment = {
882
1151
  runtime,
@@ -893,32 +1162,43 @@ export const createEnvironment = (
893
1162
  constantLevels: new Map(),
894
1163
  evaluators: new WeakMap(),
895
1164
  };
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
- };
1165
+ // TLC evaluates a substitute at startup and rejects it only when that fails and the level bound it
1166
+ // computes is above constant. The bound counts the operators that TLC's Java code overrides with
1167
+ // a minimum level as state-level, so the analyzer takes them for variables.
1168
+ const analyzer = createLevelAnalyzer({
1169
+ constants: new Set(constants.keys()),
1170
+ variables: new Set([
1171
+ ...variables,
1172
+ ...["TLCGet", "Trace", "CounterExample"].filter((name) => builtins.has(name)),
1173
+ ]),
1174
+ getDefinition: (name) => getDefinition(name, environment),
909
1175
  });
1176
+ const getEvaluationError = (body: Expression) => {
1177
+ try {
1178
+ evaluate(body, { environment, scope: undefined, state: undefined, next: undefined });
1179
+ return undefined;
1180
+ } catch (error) {
1181
+ if (error instanceof TlaEvaluationError) return error;
1182
+ throw error;
1183
+ }
1184
+ };
910
1185
  substitutions.forEach((target, name) => {
911
1186
  const definition = definitions.get(target);
912
- if (
1187
+ const error =
913
1188
  declaredConstants.includes(name) &&
914
- definition &&
915
- !isConstantLevel(definition, environment)
916
- ) {
1189
+ definition?.kind === "Operator" &&
1190
+ definition.params.length === 0 &&
1191
+ analyzer.analyzeDefinition(definition, new Map()).level > 0
1192
+ ? getEvaluationError(definition.body)
1193
+ : undefined;
1194
+ // TLC adds the reason unless a standard module's Java code failed.
1195
+ if (error) {
917
1196
  throw new TlaConfigError(
918
- `The configuration file substitutes constant ${name} with non-constant ${target}`,
1197
+ `The configuration file substitutes constant ${name} with non-constant ${target}${error instanceof TlaModuleError ? "" : ` - specifically: ${error.message}`}`,
919
1198
  );
920
1199
  }
921
1200
  });
1201
+ runtime.isStarted = true;
922
1202
  return {
923
1203
  environment,
924
1204
  assumptions,