tla-ts 0.0.3-dev.6a30eee → 0.0.3-dev.6d0aeb6

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