tla-ts 0.0.3-dev.33ae522 → 0.0.3-dev.3539317

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.
@@ -14,10 +14,13 @@ import type { ConfigValue, ModelConfig } from "./config";
14
14
  import type { FileSystem } from "./json";
15
15
  import {
16
16
  createSanyError,
17
+ formatRange,
18
+ formatSanyWarnings,
17
19
  TlaConfigError,
18
20
  TlaEvaluationError,
19
21
  TlaModuleError,
20
22
  TlaSyntaxError,
23
+ type SanyError,
21
24
  } from "./errors";
22
25
  import { EXIT_STATUS, setExitCode } from "./exit-codes";
23
26
  import {
@@ -38,21 +41,29 @@ import {
38
41
  import { overrideDefinitions } from "./java-overrides";
39
42
  import { extractModule, parseModule } from "./parser";
40
43
  import {
41
- checkRedefinitions,
42
44
  getArity,
45
+ getParamArities,
43
46
  isBefore,
47
+ isTheoremDefinition,
44
48
  KEY_SEPARATOR,
45
49
  LOCAL_RESOLUTION,
50
+ MODULE_START,
46
51
  resolveModule,
47
52
  resolveSubstitutions,
53
+ type ModuleReport,
48
54
  type ModuleSymbol,
55
+ type ModuleUnit,
56
+ type SymbolKind,
49
57
  type Symbols,
50
58
  } from "./resolve";
51
59
  import { createRuntime } from "./runtime";
60
+ import { parseModuleFile } from "./sany-parse-error";
52
61
  import { CORE_OPERATORS, getStandardModule, STANDARD_DEPENDENCIES } from "./standard-modules";
62
+ import { STANDARD_LEVELS } from "./standard-levels";
63
+ import { getStandardRange } from "./standard-ranges";
53
64
  import { resolveInstanceSubexpressions, resolveModuleSubexpressions } from "./subexpressions";
54
65
  import { checkModuleLevels, createLevelAnalyzer } from "./levels";
55
- import { checkInstances, type InstanceCheck } from "./substitution-levels";
66
+ import { createInstanceChecker, type InstanceCheck } from "./substitution-levels";
56
67
  import { getTlcDeclarationOrder } from "./tlc-order";
57
68
  import {
58
69
  checkInteger,
@@ -112,18 +123,28 @@ interface LinkedModule {
112
123
  exported: Symbols;
113
124
  modules: Map<string, LinkedModule>;
114
125
  extended: LinkedModule[];
126
+ facts: Set<string>;
115
127
  }
116
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.
117
131
  interface ModuleScope {
118
132
  id: string;
119
133
  symbols: Symbols;
120
134
  modules: Map<string, LinkedModule>;
121
135
  nested: Module[];
136
+ errors: SanyError[];
137
+ warnings: SanyError[];
138
+ levelChecks: (() => void)[];
122
139
  }
123
140
 
124
- const getDeclarations = (linked: LinkedModule) => [
141
+ const getDeclarations = (linked: LinkedModule): Declaration[] => [
125
142
  ...linked.constants,
126
- ...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
+ })),
127
148
  ];
128
149
 
129
150
  const createModuleRedefinedError = (module: Module) =>
@@ -131,6 +152,22 @@ const createModuleRedefinedError = (module: Module) =>
131
152
  `Multiply-defined module '${module.name}' at line ${module.location.line}, column ${module.location.column}`,
132
153
  );
133
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
+
134
171
  const createLocalFunction = (definition: Definition, key: string): Definition => ({
135
172
  kind: "Operator",
136
173
  name: key,
@@ -229,6 +266,8 @@ export const createEnvironment = (
229
266
  const runtime = createRuntime(config.checkDeadlock, options.seed);
230
267
  const linkedModules = new Map<string, LinkedModule>();
231
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>();
232
271
  const linkedList: LinkedModule[] = [];
233
272
  const dependencies = new Map<string, Set<string>>();
234
273
  const loading: Set<string>[] = [];
@@ -243,7 +282,25 @@ export const createEnvironment = (
243
282
  const copyCount = { value: 0 };
244
283
  const createName = (name: string) => `${name}#${copyCount.value++}`;
245
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
+ });
246
302
  const instanceActions = new Map<string, InstanceAction>();
303
+ const qualifiedNames = new Map<string, string>();
247
304
 
248
305
  const addStandardModule = (name: string): Symbols | undefined => {
249
306
  const cached = standardExports.get(name);
@@ -258,7 +315,13 @@ export const createEnvironment = (
258
315
  );
259
316
  standardModule.operators.forEach((operator) => {
260
317
  builtins.set(operator.name, operator);
261
- 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
+ });
262
325
  });
263
326
  standardExports.set(name, exported);
264
327
  return exported;
@@ -308,7 +371,7 @@ export const createEnvironment = (
308
371
  ],
309
372
  true,
310
373
  );
311
- const module = parseModule(source);
374
+ const module = parseModuleFile(source, name);
312
375
  if (module.name !== name) {
313
376
  throw createSanyError(
314
377
  [
@@ -333,6 +396,8 @@ export const createEnvironment = (
333
396
  }
334
397
  const closure = new Set<string>();
335
398
  const nested: Module[] = [];
399
+ const errors: SanyError[] = [];
400
+ const levelChecks: (() => void)[] = [];
336
401
  linking.push(parsed.name);
337
402
  loading.push(closure);
338
403
  const linked = linkModule(parsed, {
@@ -340,11 +405,19 @@ export const createEnvironment = (
340
405
  symbols: new Map(),
341
406
  modules: new Map(),
342
407
  nested,
408
+ errors,
409
+ warnings,
410
+ levelChecks,
343
411
  });
344
412
  loading.pop();
345
413
  linking.pop();
414
+ if (errors.length > 0) throw createSanyError(errors, false, undefined, warnings);
346
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);
347
419
  if (duplicate) throw createModuleRedefinedError(duplicate);
420
+ levelChecks.forEach((check) => check());
348
421
  return { linked, closure };
349
422
  };
350
423
 
@@ -364,23 +437,16 @@ export const createEnvironment = (
364
437
  const instantiate = (
365
438
  instance: Instance,
366
439
  module: Module,
367
- unit: {
368
- imported: Symbols;
369
- importedAt: Map<string, SourceLocation>;
370
- definitions: Map<string, Definition>;
371
- getKey: (definition: Definition) => string;
372
- },
440
+ unit: ModuleUnit,
373
441
  isParameterFree: boolean,
374
442
  nested: LinkedModule | undefined,
375
443
  ): Symbols => {
376
444
  const standardSymbols = nested ? undefined : getStandardSymbols(instance.module);
377
- if (standardSymbols) {
378
- if (instance.name === undefined) return standardSymbols;
379
- return new Map(
380
- [...standardSymbols].map(([name, symbol]) => [`${instance.name}!${name}`, symbol]),
381
- );
382
- }
445
+ if (standardSymbols) return getStandardInstanceSymbols(instance, standardSymbols);
383
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
+ );
384
450
  const declarations = getDeclarations(linked);
385
451
  const suffix = `#${copyCount.value++}`;
386
452
  const renamed = new Map(instance.params.map((param) => [param.name, `${param.name}${suffix}`]));
@@ -414,27 +480,69 @@ export const createEnvironment = (
414
480
  },
415
481
  createName,
416
482
  });
417
- const declared = new Set(declarations.map((declaration) => declaration.name));
418
- const symbols: Symbols = new Map();
419
- linked.exported.forEach((symbol, name) => {
420
- if (declared.has(name)) return;
421
- if (instance.name === undefined) {
422
- const key = instantiation.getKey(symbol.key);
423
- if (declarations.length > 0)
424
- instanceActions.set(key, { name, location: instance.location });
425
- symbols.set(name, { key, arity: symbol.arity });
426
- return;
427
- }
428
- const key = instantiation.getQualifiedKey(symbol.key);
429
- if (declarations.length > 0) {
430
- instanceActions.set(key, { name: `${instance.name}!${name}`, location: instance.location });
431
- }
432
- symbols.set(`${instance.name}!${name}`, {
433
- key,
434
- arity: symbol.arity + instance.params.length,
435
- });
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;
436
491
  });
437
- 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
+ );
438
546
  };
439
547
 
440
548
  const getLocalArguments = (params: OperatorParam[], location: SourceLocation) =>
@@ -609,29 +717,59 @@ export const createEnvironment = (
609
717
 
610
718
  const linkModule = (unlinked: Module, scope: ModuleScope): LinkedModule => {
611
719
  const parsed = overrideDefinitions(unlinked, options.loadClass?.(unlinked.name));
720
+ const firstCheck = instanceChecks.length;
612
721
  const visible: Symbols = new Map([
613
722
  ...CORE_OPERATORS.map((operator): [string, ModuleSymbol] => [
614
723
  operator.name,
615
- { key: operator.name, arity: operator.arity },
724
+ { key: operator.name, arity: operator.arity, kind: "Builtin" },
616
725
  ]),
617
726
  ...scope.symbols,
618
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
+ });
619
761
  const exported: Symbols = new Map();
762
+ const facts = new Set<string>();
620
763
  const modules = new Map<string, LinkedModule>();
621
764
  const extended: LinkedModule[] = [];
622
765
  const constants = [...parsed.constants];
623
766
  const variables = parsed.variables.map((variable) => variable.name);
624
767
  const variableLocations = parsed.variables.map((variable) => variable.location);
625
- const addSymbols = (symbols: Symbols, isExported: boolean) =>
626
- symbols.forEach((symbol, name) => {
627
- visible.set(name, symbol);
628
- if (isExported) exported.set(name, symbol);
629
- });
630
768
  parsed.extends.forEach((name) => {
631
769
  const nested = scope.modules.get(name);
632
770
  const standardSymbols = nested ? undefined : getStandardSymbols(name);
633
771
  if (standardSymbols) {
634
- addSymbols(standardSymbols, true);
772
+ mergeExtended(standardSymbols);
635
773
  return;
636
774
  }
637
775
  const linked = nested ?? getLinkedModule(name, parsed.name);
@@ -645,61 +783,114 @@ export const createEnvironment = (
645
783
  variables.push(variable);
646
784
  variableLocations.push(linked.variableLocations[index]);
647
785
  });
648
- addSymbols(linked.exported, true);
786
+ mergeExtended(linked.exported);
787
+ linked.facts.forEach((name) => facts.add(name));
649
788
  linked.modules.forEach((module, moduleName) => modules.set(moduleName, module));
650
789
  extended.push(linked);
651
790
  });
652
- parsed.constants.forEach((constant) =>
653
- exported.set(constant.name, {
654
- key: constant.name,
655
- arity: constant.arity,
656
- declaration: "Constant",
657
- }),
658
- );
659
- parsed.variables.forEach((variable) =>
660
- 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)),
661
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
+ });
662
812
  const isParameterFree = constants.length === 0 && variables.length === 0;
663
813
  const getKey = (definition: Definition) =>
664
814
  parsed === root ? definition.name : `${definition.name}${KEY_SEPARATOR}${scope.id}`;
665
- const importedAt = new Map<string, SourceLocation>();
666
- 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 => ({
667
827
  imported: visible,
668
- importedAt,
669
- 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
+ ),
670
851
  getKey,
852
+ instanced,
853
+ facts,
854
+ reports,
855
+ warnings: scope.warnings,
671
856
  });
672
- const getVisibleModules = () => new Map([...scope.modules, ...modules]);
673
857
  const getSymbolsBefore = (location: SourceLocation): Symbols =>
674
858
  new Map([
675
859
  ...visible,
676
- ...[
677
- ...parsed.constants.map((constant) => ({ ...constant, kind: "Constant" as const })),
678
- ...parsed.variables.map((variable) => ({ ...variable, kind: "Variable" as const })),
679
- ]
860
+ ...declarations
680
861
  .filter((declaration) => isBefore(declaration.location, location))
681
862
  .map((declaration): [string, ModuleSymbol] => [
682
863
  declaration.name,
683
- { key: declaration.name, arity: declaration.arity, declaration: declaration.kind },
864
+ getDeclarationSymbol(declaration),
684
865
  ]),
685
866
  ...parsed.definitions
686
867
  .filter((definition) => isBefore(definition.location, location))
687
868
  .map((definition): [string, ModuleSymbol] => [
688
869
  definition.name,
689
- { key: getKey(definition), arity: getArity(definition) },
870
+ getDefinitionSymbol(definition),
690
871
  ]),
691
872
  ]);
873
+ // Generator.generateModule reports the errors of a nested module and goes on, and then
874
+ // SymbolTable.addModule reports a module already defined.
692
875
  const linkNested = (nested: Module) => {
693
876
  const visibleModules = getVisibleModules();
694
- 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);
695
880
  scope.nested.push(nested);
881
+ const report: ModuleReport = { location: nested.location, errors: [], warnings: [] };
882
+ reports.push(report);
696
883
  const linked = linkModule(nested, {
697
884
  id: `${scope.id}/${nested.name}`,
698
885
  symbols: getSymbolsBefore(nested.location),
699
886
  modules: visibleModules,
700
887
  nested: scope.nested,
888
+ errors: report.errors,
889
+ warnings: report.warnings,
890
+ levelChecks: scope.levelChecks,
701
891
  });
702
- modules.set(nested.name, linked);
892
+ if (redefinition) report.errors.push(redefinition);
893
+ if (!existing) modules.set(nested.name, linked);
703
894
  if (!nestedModules.has(nested.name)) nestedModules.set(nested.name, linked);
704
895
  };
705
896
  [
@@ -713,10 +904,12 @@ export const createEnvironment = (
713
904
  isParameterFree,
714
905
  getVisibleModules().get(instance.module),
715
906
  );
716
- symbols.forEach((_, name) => {
717
- 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);
718
912
  });
719
- addSymbols(symbols, !instance.isLocal);
720
913
  },
721
914
  })),
722
915
  ...parsed.modules.map((nested) => ({
@@ -726,36 +919,21 @@ export const createEnvironment = (
726
919
  ]
727
920
  .sort((left, right) => (isBefore(left.location, right.location) ? -1 : 1))
728
921
  .forEach((unit) => unit.link());
729
- checkRedefinitions(parsed, getUnit(parsed));
730
- const isInstancedAfterDefinition = (nested: Module) => {
731
- const first = parsed.instances.find((instance) => instance.module === nested.name);
732
- return first !== undefined && isBefore(nested.location, first.location);
733
- };
734
- const getLetModule = (instance: Instance) => {
735
- const own = parsed.modules.find((nested) => nested.name === instance.module);
736
- if (!own) return getVisibleModules().get(instance.module);
737
- return isInstancedAfterDefinition(own) ? modules.get(own.name) : undefined;
738
- };
739
922
  const module = resolveModuleSubexpressions(
740
923
  withLetInstances(parsed, (instance, lets) =>
741
924
  instantiateLocally(instance, lets, parsed.name, getLetModule(instance)),
742
925
  ),
743
926
  getAvailableDefinitions(visible),
744
927
  );
745
- resolveModule(module, getUnit(module));
928
+ scope.errors.push(...resolveModule(module, getUnit(module)));
746
929
  module.definitions.forEach((definition) => {
747
930
  const key = getKey(definition);
748
931
  definitions.set(key, definition);
749
932
  parameterized.set(key, !isParameterFree);
750
- const symbol = { key, arity: getArity(definition) };
933
+ const symbol = getDefinitionSymbol(definition);
751
934
  visible.set(definition.name, symbol);
752
935
  if (!definition.isLocal) exported.set(definition.name, symbol);
753
936
  });
754
- checkModuleLevels(module, {
755
- constants: new Set(constants.map((constant) => constant.name)),
756
- variables: new Set(variables),
757
- getDefinition: (symbol) => definitions.get(visible.get(symbol)?.key ?? symbol),
758
- });
759
937
  const linked = {
760
938
  module,
761
939
  constants,
@@ -765,12 +943,36 @@ export const createEnvironment = (
765
943
  exported,
766
944
  modules,
767
945
  extended,
946
+ facts: new Set([
947
+ ...facts,
948
+ ...[...module.theorems, ...module.assumptions].flatMap((fact) => fact.name ?? []),
949
+ ]),
768
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
+ );
769
970
  linkedList.push(linked);
770
971
  return linked;
771
972
  };
772
973
 
773
974
  const linkedRoot = linkTopLevel(root).linked;
975
+ if (warnings.length > 0) options.print(formatSanyWarnings(warnings));
774
976
  const getRootKey = (name: string) => linkedRoot.visible.get(name)?.key ?? name;
775
977
  linkedRoot.visible.forEach((symbol, name) => {
776
978
  const definition = definitions.get(symbol.key);
@@ -960,20 +1162,6 @@ export const createEnvironment = (
960
1162
  constantLevels: new Map(),
961
1163
  evaluators: new WeakMap(),
962
1164
  };
963
- checkInstances(instanceChecks, (name) => {
964
- const linked = linkedModules.get(name) ?? nestedModules.get(name) ?? linkedRoot;
965
- return {
966
- constants: linked.constants,
967
- variables: linked.variables,
968
- definitions: [
969
- ...new Set(
970
- [...linked.visible.values()].flatMap((symbol) => definitions.get(symbol.key) ?? []),
971
- ),
972
- ],
973
- assumptions: linked.module.assumptions.map((assumption) => assumption.expression),
974
- getDefinition: (symbol) => definitions.get(linked.visible.get(symbol)?.key ?? symbol),
975
- };
976
- });
977
1165
  // TLC evaluates a substitute at startup and rejects it only when that fails and the level bound it
978
1166
  // computes is above constant. The bound counts the operators that TLC's Java code overrides with
979
1167
  // a minimum level as state-level, so the analyzer takes them for variables.
package/src/errors.ts CHANGED
@@ -34,10 +34,14 @@ export interface SanyError {
34
34
  message: string;
35
35
  }
36
36
 
37
- // The errors SANY reports for a spec. A fatal error stops it before semantic analysis.
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.
38
40
  export interface SanyReport {
39
41
  errors: SanyError[];
42
+ warnings: SanyError[];
40
43
  isFatal: boolean;
44
+ parseError?: string;
41
45
  }
42
46
 
43
47
  export class TlaSyntaxError extends TlaError {
@@ -52,14 +56,32 @@ export class TlaSyntaxError extends TlaError {
52
56
  }
53
57
  }
54
58
 
55
- export const createSanyError = (errors: SanyError[], isFatal = false) =>
59
+ export const createSanyError = (
60
+ errors: SanyError[],
61
+ isFatal = false,
62
+ parseError?: string,
63
+ warnings: SanyError[] = [],
64
+ ) =>
56
65
  new TlaSyntaxError(
57
66
  errors.map((error) => `${error.location}\n\n${error.message}`).join("\n\n"),
58
67
  undefined,
59
68
  undefined,
60
- { errors, isFatal },
69
+ { errors, warnings, isFatal, parseError },
61
70
  );
62
71
 
72
+ // How SANY prints the warnings it reports, which do not stop TLC.
73
+ export const formatSanyWarnings = (warnings: SanyError[]) =>
74
+ `*** Warnings: ${warnings.length}\n\n${warnings.map((warning) => `${warning.location}\n\n${warning.message}\n\n\n`).join("\n")}`;
75
+
76
+ // SANY's message for a module its parser rejects, such as a "***Parse Error***" with the
77
+ // productions it was in.
78
+ export class TlaParseError extends TlaError {
79
+ constructor(message: string) {
80
+ super(message);
81
+ this.name = "TlaParseError";
82
+ }
83
+ }
84
+
63
85
  export const formatRange = (range: SourceRange) =>
64
86
  `line ${range.start.line}, col ${range.start.column} to line ${range.end.line}, col ${range.end.column} of module ${range.module}`;
65
87