tla-ts 0.0.3-dev.31e0776 → 0.0.3-dev.3504663

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 (48) hide show
  1. package/dist/index.cjs +1 -1
  2. package/dist/index.d.cts +50 -22
  3. package/dist/index.d.ts +50 -22
  4. package/dist/index.js +1 -1
  5. package/dist/parallel-worker.cjs +1 -1
  6. package/dist/parallel-worker.js +2 -2
  7. package/dist/parallel.cjs +1 -1
  8. package/dist/parallel.js +2 -2
  9. package/dist/run-cli.cjs +14 -12
  10. package/dist/run-cli.js +22 -20
  11. package/dist/transfer.cjs +38 -21
  12. package/dist/transfer.js +38 -21
  13. package/package.json +1 -1
  14. package/src/ast.ts +11 -1
  15. package/src/builtins.ts +9 -3
  16. package/src/check.ts +357 -79
  17. package/src/codegen.ts +6 -3
  18. package/src/config.ts +224 -170
  19. package/src/environment.ts +90 -40
  20. package/src/errors.ts +89 -1
  21. package/src/evaluate.ts +182 -26
  22. package/src/exit-codes.ts +22 -3
  23. package/src/fingerprints.ts +2 -1
  24. package/src/instances.ts +1 -1
  25. package/src/levels.ts +173 -37
  26. package/src/live-check.ts +132 -70
  27. package/src/liveness.ts +117 -22
  28. package/src/parallel-worker.ts +2 -2
  29. package/src/parallel.ts +2 -2
  30. package/src/parser.ts +71 -19
  31. package/src/resolve.ts +429 -52
  32. package/src/run-cli.ts +59 -11
  33. package/src/sany-lexer.ts +615 -0
  34. package/src/sany-parse-error.ts +3143 -0
  35. package/src/spec-description.ts +1 -2
  36. package/src/standard-modules.ts +54 -45
  37. package/src/subexpressions.ts +25 -13
  38. package/src/substitution-levels.ts +38 -17
  39. package/src/successors.ts +121 -34
  40. package/src/symmetry.ts +16 -6
  41. package/src/tableau.ts +51 -24
  42. package/src/tlc-module.ts +6 -6
  43. package/src/tlc-modules.ts +4 -0
  44. package/src/tlc-order.ts +8 -4
  45. package/src/tlc-random.ts +9 -6
  46. package/src/tlc-summary.ts +20 -5
  47. package/src/value-sources.ts +29 -0
  48. package/src/values.ts +222 -57
package/src/resolve.ts CHANGED
@@ -6,16 +6,26 @@ import {
6
6
  type BoundPattern,
7
7
  type Definition,
8
8
  type Expression,
9
+ type Fact,
9
10
  type Instance,
11
+ type LabelExpression,
10
12
  type Module,
11
13
  type NewSymbol,
12
14
  type OperatorParam,
13
15
  type Proof,
14
16
  type ProofStep,
17
+ type Selector,
15
18
  type SourceLocation,
19
+ type SourceRange,
16
20
  type Theorem,
17
21
  } from "./ast";
18
- import { TlaSyntaxError } from "./errors";
22
+ import {
23
+ createSanyError,
24
+ createSemanticError,
25
+ formatRange,
26
+ TlaSyntaxError,
27
+ type SanyError,
28
+ } from "./errors";
19
29
 
20
30
  export interface ModuleSymbol {
21
31
  key: string;
@@ -25,12 +35,24 @@ export interface ModuleSymbol {
25
35
 
26
36
  export type Symbols = Map<string, ModuleSymbol>;
27
37
 
38
+ // A named theorem or proof step whose parts a name such as foo!lab or <1>2!1 selects. isInProof
39
+ // holds while SANY analyzes the proof of the theorem or step.
40
+ interface Goal {
41
+ statement: Expression | AssumeProve;
42
+ isSuffices: boolean;
43
+ isInProof: boolean;
44
+ }
45
+
28
46
  interface LocalName {
29
47
  name: string;
30
48
  arity: number;
31
49
  parent: LocalName | undefined;
50
+ goal?: Goal;
32
51
  }
33
52
 
53
+ // errors collects the errors SANY reports while it goes on analyzing the unit. A label may appear
54
+ // where hasLabelScope holds, in a definition, a named theorem, or a numbered step,
55
+ // except where isLabelForbidden holds, in the scope of a NEW in a nested ASSUME.
34
56
  interface Unit {
35
57
  imported: Symbols;
36
58
  definitions: Map<string, Definition>;
@@ -38,8 +60,20 @@ interface Unit {
38
60
  location: SourceLocation;
39
61
  self: Definition | undefined;
40
62
  facts: Set<string>;
63
+ goals: Map<string, Goal>;
64
+ errors: SanyError[];
65
+ hasLabelScope: boolean;
66
+ isLabelForbidden: boolean;
41
67
  }
42
68
 
69
+ interface SelectionState {
70
+ node: Expression | NewSymbol | AssumeProve;
71
+ isGoal: boolean;
72
+ isSufficesOpen: boolean;
73
+ }
74
+
75
+ type Reference = Expression & { kind: "Identifier" | "Apply" | "Subexpression" };
76
+
43
77
  export const LOCAL_RESOLUTION = { kind: "Local" } as const;
44
78
 
45
79
  const renamedArities = new WeakMap<Expression, number>();
@@ -103,6 +137,21 @@ const findSymbol = (name: string, unit: Unit): ModuleSymbol | undefined => {
103
137
  : unit.imported.get(name);
104
138
  };
105
139
 
140
+ // SANY reports a name at the range of its text.
141
+ const getNameRange = (location: SourceLocation, name: string): SourceRange => ({
142
+ module: location.range?.module ?? "",
143
+ start: location,
144
+ end: { line: location.line, column: location.column + name.length - 1 },
145
+ });
146
+
147
+ // SANY reports an operator symbol applied to operands as one it cannot resolve.
148
+ const getFixity = (expression: Expression) => {
149
+ if (expression.kind !== "Apply") return undefined;
150
+ if (expression.args.length === 2) return "infix";
151
+ if (expression.args.length !== 1) return undefined;
152
+ return isBefore(expression.location, expression.args[0].location) ? "prefix" : "postfix";
153
+ };
154
+
106
155
  // SANY names an undefined operator symbol such as + differently from an undefined identifier.
107
156
  const isOperatorSymbol = (name: string) =>
108
157
  name[0].toLowerCase() === name[0].toUpperCase() &&
@@ -112,6 +161,185 @@ const isOperatorSymbol = (name: string) =>
112
161
  const isStepName = (name: string) =>
113
162
  name.startsWith("<") && ((name[1] >= "0" && name[1] <= "9") || name[1] === "*");
114
163
 
164
+ export const getOperandIndex = (operand: number | "<<" | ">>", count: number) => {
165
+ if (typeof operand === "number") return operand >= 1 && operand <= count ? operand - 1 : -1;
166
+ if (operand === "<<") return count > 0 ? 0 : -1;
167
+ return count === 2 ? 1 : -1;
168
+ };
169
+
170
+ const getSelectors = (reference: Reference): Selector[] =>
171
+ reference.kind === "Subexpression"
172
+ ? reference.selectors
173
+ : (reference.kind === "Identifier" ? reference.name : reference.operator)
174
+ .split("!")
175
+ .map((name) => ({ kind: "Name", name, args: [] }));
176
+
177
+ const isReference = (expression: Expression): expression is Reference =>
178
+ expression.kind === "Identifier" ||
179
+ expression.kind === "Apply" ||
180
+ expression.kind === "Subexpression";
181
+
182
+ const isInScopeOfDeclaration = (assumeProve: AssumeProve, clause: number) =>
183
+ assumeProve.assumptions.slice(0, clause).some((assumption) => assumption.kind === "NewSymbol");
184
+
185
+ const findLabel = (expression: Expression, name: string): LabelExpression | undefined => {
186
+ if (expression.kind === "Label") return expression.name === name ? expression : undefined;
187
+ if (expression.kind === "Lambda") return undefined;
188
+ if (expression.kind === "Let") return findLabel(expression.body, name);
189
+ return getChildren(expression).reduce<LabelExpression | undefined>(
190
+ (found, child) => found ?? findLabel(child, name),
191
+ undefined,
192
+ );
193
+ };
194
+
195
+ // SANY drops a label in the scope of a NEW in a nested ASSUME, after it reports the label.
196
+ const findClauseLabel = (
197
+ clause: Expression | NewSymbol | AssumeProve,
198
+ name: string,
199
+ isForbidden: boolean,
200
+ ): LabelExpression | undefined => {
201
+ if (clause.kind === "AssumeProve") {
202
+ return [...clause.assumptions, clause.conclusion].reduce<LabelExpression | undefined>(
203
+ (found, inner, index) =>
204
+ found ?? findClauseLabel(inner, name, isForbidden || isInScopeOfDeclaration(clause, index)),
205
+ undefined,
206
+ );
207
+ }
208
+ if (isForbidden) return undefined;
209
+ if (clause.kind === "NewSymbol") return clause.set && findLabel(clause.set, name);
210
+ return findLabel(clause, name);
211
+ };
212
+
213
+ const getOperandName = (operand: number | "<<" | ">>") =>
214
+ typeof operand === "number" ? `argument selector ${operand}` : operand;
215
+
216
+ const SCOPE_MESSAGE = "within the scope of a declaration\n from outside that declaration's scope.";
217
+
218
+ // Generator.selectorToNode for a name that selects part of a theorem or step. A part in the scope of
219
+ // a NEW in its ASSUME may be selected only within the proof of the theorem, or only after the proof
220
+ // of a SUFFICES step. A fact may select an ASSUME/PROVE or a NEW clause.
221
+ const checkSelection = (
222
+ reference: Reference,
223
+ selectors: Selector[],
224
+ goal: Goal,
225
+ unit: Unit,
226
+ isFact: boolean,
227
+ ) => {
228
+ const report = (index: number | undefined, message: string) => {
229
+ const range =
230
+ (index === undefined ? undefined : reference.selectorRanges?.[index]) ??
231
+ reference.location.range;
232
+ if (range) unit.errors.push({ location: formatRange(range), message });
233
+ };
234
+ const isOutOfScope = goal.isSuffices === goal.isInProof;
235
+ const statement = goal.statement;
236
+ const second = selectors[1];
237
+ if (second.kind === "Name") {
238
+ const clauses =
239
+ statement.kind === "AssumeProve"
240
+ ? [...statement.assumptions, statement.conclusion]
241
+ : [statement];
242
+ const found = clauses
243
+ .map((clause, index) => ({ index, label: findClauseLabel(clause, second.name, false) }))
244
+ .find((item) => item.label !== undefined);
245
+ if (!found) return report(1, `Cannot find label \`${second.name}'.`);
246
+ if (
247
+ statement.kind === "AssumeProve" &&
248
+ isInScopeOfDeclaration(statement, found.index) &&
249
+ isOutOfScope
250
+ ) {
251
+ return report(
252
+ 1,
253
+ `Accessing subexpression labeled \`${second.name}' of ASSUME/PROVE clause ${SCOPE_MESSAGE}`,
254
+ );
255
+ }
256
+ selectors.slice(2).reduce((label, selector, offset) => {
257
+ if (!label || selector.kind !== "Name") return undefined;
258
+ const inner = findLabel(label.body, selector.name);
259
+ if (!inner) report(offset + 2, `Cannot find label \`${selector.name}'.`);
260
+ return inner;
261
+ }, found.label);
262
+ return;
263
+ }
264
+ const state: SelectionState = {
265
+ node: statement,
266
+ isGoal: true,
267
+ isSufficesOpen: goal.isSuffices,
268
+ };
269
+ for (const [offset, selector] of selectors.slice(1).entries()) {
270
+ const index = offset + 1;
271
+ const node = state.node;
272
+ if (selector.kind !== "Operand") return;
273
+ if (state.isSufficesOpen) {
274
+ if (getOperandIndex(selector.operand, 1) !== 0) {
275
+ return report(
276
+ index,
277
+ node.kind === "AssumeProve"
278
+ ? "Accessing non-existent subexpression of a SUFFICES"
279
+ : `Nonexistent operand specified by \`${getOperandName(selector.operand)}'.`,
280
+ );
281
+ }
282
+ state.isSufficesOpen = false;
283
+ continue;
284
+ }
285
+ if (node.kind !== "AssumeProve") return;
286
+ const clauses = [...node.assumptions, node.conclusion];
287
+ const position = getOperandIndex(selector.operand, clauses.length);
288
+ if (position === -1) {
289
+ return report(
290
+ index,
291
+ `Nonexistent operand specified by \`${getOperandName(selector.operand)}'.`,
292
+ );
293
+ }
294
+ if (isInScopeOfDeclaration(node, position) && (!state.isGoal || isOutOfScope)) {
295
+ return report(index, `Accessing ASSUME/PROVE clause ${SCOPE_MESSAGE}`);
296
+ }
297
+ const clause = clauses[position];
298
+ if (clause.kind === "NewSymbol" && index !== selectors.length - 1) {
299
+ return report(index, "Selected a subexpression of a NEW clause of an ASSUME.");
300
+ }
301
+ state.node = clause;
302
+ state.isGoal = false;
303
+ }
304
+ if (isFact) return;
305
+ if (state.node.kind === "AssumeProve") {
306
+ report(undefined, "Selected ASSUME/PROVE instead of expression.");
307
+ }
308
+ if (state.node.kind === "NewSymbol") {
309
+ report(undefined, "Selected a NEW declaration as an expression or operator.");
310
+ }
311
+ };
312
+
313
+ // Generator.generateLabel reports a label where it may not appear, and skips the label's body.
314
+ const isLabelReported = (label: LabelExpression, unit: Unit) => {
315
+ const message = !unit.hasLabelScope
316
+ ? "Label not in definition or proof step."
317
+ : unit.isLabelForbidden
318
+ ? "Label not allowed within scope of declaration in nested ASSUME/PROVE."
319
+ : undefined;
320
+ if (message === undefined || !label.location.range) return false;
321
+ unit.errors.push({ location: formatRange(label.location.range), message });
322
+ return true;
323
+ };
324
+
325
+ // Checks a name that selects part of a theorem or step, and tells whether it is one.
326
+ const checkReference = (
327
+ expression: Expression,
328
+ scope: LocalName | undefined,
329
+ unit: Unit,
330
+ isFact: boolean,
331
+ ) => {
332
+ if (!isReference(expression)) return false;
333
+ const selectors = getSelectors(expression);
334
+ const first = selectors[0];
335
+ const goal =
336
+ selectors.length > 1 && first.kind === "Name"
337
+ ? (lookupLocal(scope, first.name)?.goal ?? unit.goals.get(first.name))
338
+ : undefined;
339
+ if (goal) checkSelection(expression, selectors, goal, unit, isFact);
340
+ return goal !== undefined;
341
+ };
342
+
115
343
  const getSymbolArity = (
116
344
  expression: Expression & { kind: "Identifier" | "Apply" | "OperatorReference" },
117
345
  name: string,
@@ -122,7 +350,9 @@ const getSymbolArity = (
122
350
  const renamed = renamedArities.get(expression);
123
351
  if (renamed !== undefined) return renamed;
124
352
  if (isKey(name)) return expression.kind === "Apply" ? expression.args.length : 0;
125
- if (isStepName(name)) return 0;
353
+ if (checkReference(expression, scope, unit, false) || isStepName(name)) {
354
+ return expression.kind === "Apply" ? expression.args.length : 0;
355
+ }
126
356
  const local = lookupLocal(scope, name);
127
357
  if (local && expression.kind !== "OperatorReference") expression.resolution = LOCAL_RESOLUTION;
128
358
  if (local) return local.arity;
@@ -135,7 +365,7 @@ const getSymbolArity = (
135
365
  }
136
366
  // A name such as Inv!P1 selects the label P1 of a definition or theorem, which takes its own
137
367
  // arguments.
138
- const prefix = name.slice(0, name.indexOf("!"));
368
+ const prefix = name.includes("!") ? name.slice(0, name.indexOf("!")) : "";
139
369
  const isSelected =
140
370
  prefix !== "" &&
141
371
  (lookupLocal(scope, prefix) !== undefined ||
@@ -144,11 +374,23 @@ const getSymbolArity = (
144
374
  if (isSelected) {
145
375
  return expression.kind === "Apply" ? expression.args.length : 0;
146
376
  }
147
- const position = `at line ${location.line}, column ${location.column}`;
148
- throw new TlaSyntaxError(
149
- isOperatorSymbol(name)
150
- ? `Could not find declaration or definition of symbol '${name}' ${position}`
151
- : `Unknown operator: \`${name}' ${position}`,
377
+ const range = getNameRange(location, name === "-." ? "-" : name);
378
+ if (!isOperatorSymbol(name)) throw createSemanticError(`Unknown operator: \`${name}'.`, range);
379
+ const missing = {
380
+ location: formatRange(range),
381
+ message: `Could not find declaration or definition of symbol '${name}'.`,
382
+ };
383
+ const fixity = getFixity(expression);
384
+ throw createSanyError(
385
+ fixity && location.range
386
+ ? [
387
+ missing,
388
+ {
389
+ location: formatRange(location.range),
390
+ message: `Couldn't resolve ${fixity} operator symbol \`${name}'.`,
391
+ },
392
+ ]
393
+ : [missing],
152
394
  );
153
395
  };
154
396
 
@@ -171,7 +413,8 @@ const markRecursiveConstructions = (expression: Expression, name: string): void
171
413
  getChildren(expression).forEach((child) => markRecursiveConstructions(child, name));
172
414
  };
173
415
 
174
- const resolveDefinition = (definition: Definition, scope: LocalName | undefined, unit: Unit) => {
416
+ const resolveDefinition = (definition: Definition, scope: LocalName | undefined, outer: Unit) => {
417
+ const unit = outer.hasLabelScope ? outer : { ...outer, hasLabelScope: true };
175
418
  const self = bindNames(scope, definition.kind === "Function" ? [definition.name] : []);
176
419
  if (definition.kind === "Function") {
177
420
  resolveExpression(definition.body, resolveBounds(definition.bounds, self, unit), unit);
@@ -235,13 +478,13 @@ const resolveApply = (
235
478
  scope: LocalName | undefined,
236
479
  unit: Unit,
237
480
  ) => {
238
- const callee = lookupLocal(scope, expression.operator)
239
- ? undefined
240
- : getVisibleDefinition(expression.operator, unit);
241
- const arity = getSymbolArity(expression, expression.operator, scope, unit);
481
+ const operator = expression.operator;
482
+ const callee = lookupLocal(scope, operator) ? undefined : getVisibleDefinition(operator, unit);
483
+ const arity = getSymbolArity(expression, operator, scope, unit);
242
484
  if (arity !== expression.args.length) {
243
- throw new TlaSyntaxError(
244
- `The operator ${expression.operator} requires ${arity} arguments at line ${expression.location.line}, column ${expression.location.column}`,
485
+ throw createSemanticError(
486
+ `The operator ${operator} requires ${arity} arguments.`,
487
+ expression.argumentsRange ?? getNameRange(expression.location, operator),
245
488
  );
246
489
  }
247
490
  expression.args.forEach((arg, index) => {
@@ -275,10 +518,12 @@ const resolveExpression = (
275
518
  case "ExceptAt":
276
519
  return;
277
520
  case "Identifier": {
278
- const arity = getSymbolArity(expression, expression.name, scope, unit);
521
+ const name = expression.name;
522
+ const arity = getSymbolArity(expression, name, scope, unit);
279
523
  if (arity > 0) {
280
- throw new TlaSyntaxError(
281
- `The operator ${expression.name} requires ${arity} arguments at line ${expression.location.line}, column ${expression.location.column}`,
524
+ throw createSemanticError(
525
+ `The operator ${name} requires ${arity} arguments.`,
526
+ getNameRange(expression.location, name),
282
527
  );
283
528
  }
284
529
  return;
@@ -347,14 +592,21 @@ const resolveExpression = (
347
592
  resolveAll([expression.domain, expression.range]);
348
593
  return;
349
594
  case "Record":
350
- case "RecordSet":
351
- if (new Set(expression.fields.map((field) => field.name)).size < expression.fields.length) {
352
- throw new TlaSyntaxError(
353
- `Non-unique fields in constructor at line ${expression.location.line}, column ${expression.location.column}`,
595
+ case "RecordSet": {
596
+ const repeated = expression.fields.filter((field, index) =>
597
+ expression.fields.slice(0, index).some((earlier) => earlier.name === field.name),
598
+ );
599
+ if (repeated.length > 0) {
600
+ throw createSanyError(
601
+ repeated.map((field) => ({
602
+ location: formatRange(field.location.range ?? getNameRange(field.location, field.name)),
603
+ message: "Non-unique fields in constructor.",
604
+ })),
354
605
  );
355
606
  }
356
607
  resolveAll(expression.fields.map((field) => field.value));
357
608
  return;
609
+ }
358
610
  case "Except":
359
611
  resolveAll([
360
612
  expression.function,
@@ -382,34 +634,67 @@ const resolveExpression = (
382
634
  resolveAll([expression.subscript, expression.action]);
383
635
  return;
384
636
  case "Label":
385
- resolveExpression(expression.body, scope, unit);
637
+ if (!isLabelReported(expression, unit)) resolveExpression(expression.body, scope, unit);
386
638
  return;
387
- case "Subexpression":
639
+ case "Subexpression": {
388
640
  expression.selectors
389
641
  .flatMap((selector) => ("args" in selector ? selector.args : []))
390
642
  .forEach((arg) => resolveArgument(arg, scope, unit));
643
+ checkReference(expression, scope, unit, false);
644
+ }
391
645
  }
392
646
  };
393
647
 
648
+ // SANY analyzes the facts of a proof apart from their names, which may name theorems and modules.
649
+ const checkFacts = (facts: Fact[], scope: LocalName | undefined, unit: Unit) => {
650
+ const check = (expression: Expression, isFact: boolean, inner: Unit): void => {
651
+ if (expression.kind === "Label" && isLabelReported(expression, inner)) return;
652
+ checkReference(expression, scope, inner, isFact);
653
+ getChildren(expression).forEach((child) =>
654
+ check(
655
+ child,
656
+ false,
657
+ expression.kind === "Let" && child !== expression.body
658
+ ? { ...inner, hasLabelScope: true }
659
+ : inner,
660
+ ),
661
+ );
662
+ };
663
+ facts.forEach((fact) => {
664
+ if (fact.kind !== "ModuleFact") check(fact, true, { ...unit, hasLabelScope: false });
665
+ });
666
+ };
667
+
394
668
  const resolveNewSymbol = (symbol: NewSymbol, scope: LocalName | undefined, unit: Unit) => {
395
669
  if (symbol.set) resolveExpression(symbol.set, scope, unit);
396
670
  return { name: symbol.name, arity: symbol.arity, parent: scope };
397
671
  };
398
672
 
399
- // The NEW symbols of an ASSUME stay in scope for its conclusion and the proof that follows.
673
+ // The NEW symbols of an ASSUME stay in scope for its conclusion and the proof that follows. SANY
674
+ // forbids a label in the scope of a NEW in a nested ASSUME.
400
675
  const resolveAssumeProve = (
401
676
  assumeProve: AssumeProve,
402
677
  scope: LocalName | undefined,
403
678
  unit: Unit,
679
+ isNested = false,
404
680
  ): LocalName | undefined => {
405
- const assumed = assumeProve.assumptions.reduce((current, assumption) => {
406
- if (assumption.kind === "NewSymbol") return resolveNewSymbol(assumption, current, unit);
407
- if (assumption.kind === "AssumeProve") resolveAssumeProve(assumption, current, unit);
408
- else resolveExpression(assumption, current, unit);
409
- return current;
410
- }, scope);
411
- resolveExpression(assumeProve.conclusion, assumed, unit);
412
- return assumed;
681
+ const assumed = assumeProve.assumptions.reduce(
682
+ (current, assumption) => {
683
+ if (assumption.kind === "NewSymbol") {
684
+ return {
685
+ scope: resolveNewSymbol(assumption, current.scope, current.unit),
686
+ unit: isNested ? { ...current.unit, isLabelForbidden: true } : current.unit,
687
+ };
688
+ }
689
+ if (assumption.kind === "AssumeProve") {
690
+ resolveAssumeProve(assumption, current.scope, current.unit, true);
691
+ } else resolveExpression(assumption, current.scope, current.unit);
692
+ return current;
693
+ },
694
+ { scope, unit },
695
+ );
696
+ resolveExpression(assumeProve.conclusion, assumed.scope, assumed.unit);
697
+ return assumed.scope;
413
698
  };
414
699
 
415
700
  const resolveStatement = (
@@ -424,7 +709,9 @@ const resolveStatement = (
424
709
 
425
710
  // SANY resolves the expressions of a proof, while its facts and DEF clauses may also name
426
711
  // theorems, assumptions, and modules.
427
- const resolveProof = (proof: Proof | undefined, scope: LocalName | undefined, unit: Unit) => {
712
+ const resolveProof = (proof: Proof | undefined, scope: LocalName | undefined, outer: Unit) => {
713
+ const unit = outer.hasLabelScope ? { ...outer, hasLabelScope: false } : outer;
714
+ if (proof?.kind === "By") checkFacts(proof.facts, scope, unit);
428
715
  if (proof?.kind !== "Steps") return;
429
716
  proof.steps.reduce((current, step) => resolveStep(step, current, unit), scope);
430
717
  };
@@ -435,12 +722,24 @@ const resolveStep = (
435
722
  unit: Unit,
436
723
  ): LocalName | undefined => {
437
724
  const body = step.body;
725
+ const stepUnit = step.name === undefined ? unit : { ...unit, hasLabelScope: true };
438
726
  switch (body.kind) {
439
727
  case "Assert": {
440
- const assumed = resolveStatement(body.statement, scope, unit);
441
- resolveProof(step.proof, assumed, unit);
442
- return body.isSuffices ? assumed : scope;
728
+ const assumed = resolveStatement(body.statement, scope, stepUnit);
729
+ const name = step.name;
730
+ if (name === undefined) {
731
+ resolveProof(step.proof, assumed, unit);
732
+ return body.isSuffices ? assumed : scope;
733
+ }
734
+ const goal = { statement: body.statement, isSuffices: body.isSuffices, isInProof: true };
735
+ resolveProof(step.proof, { name, arity: 0, parent: assumed, goal }, unit);
736
+ goal.isInProof = false;
737
+ return { name, arity: 0, parent: body.isSuffices ? assumed : scope, goal };
443
738
  }
739
+ case "Use":
740
+ case "Hide":
741
+ checkFacts(body.facts, scope, unit);
742
+ return scope;
444
743
  case "Define":
445
744
  return resolveDefinitions(
446
745
  body.definitions.flatMap((definition) =>
@@ -451,17 +750,17 @@ const resolveStep = (
451
750
  );
452
751
  case "Have":
453
752
  case "Case":
454
- resolveExpression(body.expression, scope, unit);
753
+ resolveExpression(body.expression, scope, stepUnit);
455
754
  resolveProof(step.proof, scope, unit);
456
755
  return scope;
457
756
  case "Witness":
458
- body.expressions.forEach((expression) => resolveExpression(expression, scope, unit));
757
+ body.expressions.forEach((expression) => resolveExpression(expression, scope, stepUnit));
459
758
  return scope;
460
759
  case "Take":
461
- return bindNames(resolveBounds(body.bounds, scope, unit), body.names);
760
+ return bindNames(resolveBounds(body.bounds, scope, stepUnit), body.names);
462
761
  case "Pick": {
463
- const picked = bindNames(resolveBounds(body.bounds, scope, unit), body.names);
464
- resolveExpression(body.body, picked, unit);
762
+ const picked = bindNames(resolveBounds(body.bounds, scope, stepUnit), body.names);
763
+ resolveExpression(body.body, picked, stepUnit);
465
764
  resolveProof(step.proof, scope, unit);
466
765
  return picked;
467
766
  }
@@ -474,7 +773,10 @@ const resolveStep = (
474
773
  const resolveTheorem = (theorem: Theorem, unit: Unit) => {
475
774
  const isDefinition = theorem.name !== undefined && theorem.statement.kind !== "AssumeProve";
476
775
  const scope = isDefinition ? undefined : resolveStatement(theorem.statement, undefined, unit);
776
+ const goal = unit.goals.get(theorem.name ?? "");
777
+ if (goal) goal.isInProof = true;
477
778
  resolveProof(theorem.proof, scope, unit);
779
+ if (goal) goal.isInProof = false;
478
780
  };
479
781
 
480
782
  interface ModuleUnit {
@@ -734,6 +1036,10 @@ export const resolveSubstitutions = (
734
1036
  location: instance.location,
735
1037
  self: undefined,
736
1038
  facts: new Set(),
1039
+ goals: new Map(),
1040
+ errors: [],
1041
+ hasLabelScope: true,
1042
+ isLabelForbidden: false,
737
1043
  };
738
1044
  const explicit = new Map(instance.substitutions.map((item) => [item.name, item.expression]));
739
1045
  const position = `in the instance of ${instance.module} at line ${instance.location.line}, column ${instance.location.column}`;
@@ -769,26 +1075,97 @@ export const resolveSubstitutions = (
769
1075
  );
770
1076
  };
771
1077
 
1078
+ // SANY reports the errors of every unit it checks, in the order of the units in the module. A unit
1079
+ // reports to its list the errors after which SANY goes on, and throws the one that stops it.
1080
+ export const collectSemanticErrors = (
1081
+ units: { location: SourceLocation; check: (reported: SanyError[]) => void }[],
1082
+ ) => {
1083
+ const errors: SanyError[] = [];
1084
+ units
1085
+ .toSorted((left, right) => (isBefore(left.location, right.location) ? -1 : 1))
1086
+ .forEach((unit) => {
1087
+ const reported: SanyError[] = [];
1088
+ try {
1089
+ unit.check(reported);
1090
+ } catch (error) {
1091
+ if (!(error instanceof TlaSyntaxError) || !error.sany) throw error;
1092
+ reported.push(...error.sany.errors);
1093
+ }
1094
+ reported.forEach((item) => {
1095
+ if (
1096
+ errors.every(
1097
+ (existing) => existing.location !== item.location || existing.message !== item.message,
1098
+ )
1099
+ ) {
1100
+ errors.push(item);
1101
+ }
1102
+ });
1103
+ });
1104
+ if (errors.length > 0) throw createSanyError(errors);
1105
+ };
1106
+
772
1107
  export const resolveModule = (module: Module, unit: ModuleUnit) => {
773
1108
  const symbols = createSymbols(module, unit.imported);
774
1109
  const facts = new Set(
775
1110
  [...module.theorems, ...module.assumptions].flatMap((fact) => fact.name ?? []),
776
1111
  );
777
- const createUnit = (location: SourceLocation, self: Definition | undefined) => ({
1112
+ const goals = new Map(
1113
+ module.theorems.flatMap((theorem): [string, Goal][] =>
1114
+ theorem.name !== undefined && theorem.statement.kind === "AssumeProve"
1115
+ ? [[theorem.name, { statement: theorem.statement, isSuffices: false, isInProof: false }]]
1116
+ : [],
1117
+ ),
1118
+ );
1119
+ const createUnit = (
1120
+ location: SourceLocation,
1121
+ self: Definition | undefined,
1122
+ errors: SanyError[],
1123
+ hasLabelScope: boolean,
1124
+ ): Unit => ({
778
1125
  imported: symbols,
779
1126
  definitions: unit.definitions,
780
1127
  getKey: unit.getKey,
781
1128
  location,
782
1129
  self,
783
1130
  facts,
1131
+ goals,
1132
+ errors,
1133
+ hasLabelScope,
1134
+ isLabelForbidden: false,
784
1135
  });
785
- module.definitions.forEach((definition) =>
786
- resolveDefinition(definition, undefined, createUnit(definition.location, definition)),
787
- );
788
- module.assumptions.forEach((assumption) =>
789
- resolveExpression(assumption.expression, undefined, createUnit(assumption.location, undefined)),
790
- );
791
- module.theorems.forEach((theorem) =>
792
- resolveTheorem(theorem, createUnit(theorem.location, undefined)),
793
- );
1136
+ collectSemanticErrors([
1137
+ ...module.definitions.map((definition) => ({
1138
+ location: definition.location,
1139
+ check: (errors: SanyError[]) =>
1140
+ resolveDefinition(
1141
+ definition,
1142
+ undefined,
1143
+ createUnit(definition.location, definition, errors, true),
1144
+ ),
1145
+ })),
1146
+ // An assumption holds the subexpressions its references select, labels and all, so its own
1147
+ // labels go unchecked.
1148
+ ...module.assumptions.map((assumption) => ({
1149
+ location: assumption.location,
1150
+ check: (errors: SanyError[]) =>
1151
+ resolveExpression(
1152
+ assumption.expression,
1153
+ undefined,
1154
+ createUnit(assumption.location, undefined, errors, true),
1155
+ ),
1156
+ })),
1157
+ ...module.theorems.map((theorem) => ({
1158
+ location: theorem.location,
1159
+ check: (errors: SanyError[]) =>
1160
+ resolveTheorem(
1161
+ theorem,
1162
+ createUnit(theorem.location, undefined, errors, theorem.name !== undefined),
1163
+ ),
1164
+ })),
1165
+ ...module.uses.map((use) => ({
1166
+ location: use.location,
1167
+ check: (errors: SanyError[]) =>
1168
+ checkFacts(use.facts, undefined, createUnit(use.location, undefined, errors, false)),
1169
+ })),
1170
+ ]);
794
1171
  };