tla-ts 0.0.3-dev.bffbba3 → 0.0.3-dev.c2b256f

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 (81) hide show
  1. package/dist/cli.cjs +1 -1
  2. package/dist/cli.js +1 -1
  3. package/dist/index.cjs +1 -1
  4. package/dist/index.d.cts +150 -8
  5. package/dist/index.d.ts +150 -8
  6. package/dist/index.js +1 -1
  7. package/dist/parallel-worker.cjs +1 -1
  8. package/dist/parallel-worker.js +2 -2
  9. package/dist/parallel.cjs +1 -1
  10. package/dist/parallel.js +2 -2
  11. package/dist/run-cli.cjs +1351 -20
  12. package/dist/run-cli.js +1351 -20
  13. package/dist/transfer.cjs +86 -28
  14. package/dist/transfer.js +86 -28
  15. package/package.json +5 -1
  16. package/src/ast.ts +57 -6
  17. package/src/bags.ts +4 -7
  18. package/src/builtins.ts +29 -11
  19. package/src/bundled-modules.ts +3 -3
  20. package/src/canonical.ts +4 -3
  21. package/src/check.ts +1358 -219
  22. package/src/cli.ts +8 -1
  23. package/src/codegen.ts +68 -18
  24. package/src/config.ts +252 -179
  25. package/src/environment.ts +457 -132
  26. package/src/errors.ts +217 -3
  27. package/src/evaluate.ts +724 -117
  28. package/src/exit-codes.ts +5 -4
  29. package/src/index.ts +1 -0
  30. package/src/instances.ts +4 -2
  31. package/src/java-overrides.ts +104 -25
  32. package/src/levels.ts +183 -37
  33. package/src/lexer.ts +112 -29
  34. package/src/live-check.ts +220 -84
  35. package/src/liveness.ts +192 -65
  36. package/src/obligation-expression.ts +2 -2
  37. package/src/obligation-source.ts +2 -0
  38. package/src/parallel-worker.ts +8 -3
  39. package/src/parallel.ts +56 -5
  40. package/src/parser.ts +445 -147
  41. package/src/pcal-ast.ts +770 -0
  42. package/src/pcal-parse.ts +1523 -0
  43. package/src/pcal-tokenize.ts +516 -0
  44. package/src/pcal-translate.ts +1230 -0
  45. package/src/pcal-validate.ts +454 -0
  46. package/src/randomization.ts +24 -7
  47. package/src/resolve.ts +1439 -411
  48. package/src/run-cli.ts +1167 -155
  49. package/src/runtime.ts +16 -0
  50. package/src/sany-builtins.ts +147 -0
  51. package/src/sany-generator.ts +3112 -0
  52. package/src/sany-levels.ts +1208 -0
  53. package/src/sany-lexer.ts +545 -0
  54. package/src/sany-linter.ts +122 -0
  55. package/src/sany-modules.ts +1398 -0
  56. package/src/sany-nodes.ts +463 -0
  57. package/src/sany-parse-error.ts +2161 -0
  58. package/src/sany-report.ts +354 -0
  59. package/src/sany-selectors.ts +738 -0
  60. package/src/sany-source.ts +248 -0
  61. package/src/sany-xml.ts +1017 -0
  62. package/src/spec-description.ts +26 -7
  63. package/src/standard-modules.ts +203 -146
  64. package/src/standard-ranges.ts +116 -0
  65. package/src/state-graph.ts +29 -6
  66. package/src/subexpressions.ts +221 -161
  67. package/src/substitution-levels.ts +38 -17
  68. package/src/successors.ts +162 -114
  69. package/src/symmetry.ts +180 -52
  70. package/src/tableau.ts +4 -2
  71. package/src/tlc-ext.ts +13 -17
  72. package/src/tlc-messages.ts +329 -0
  73. package/src/tlc-module.ts +46 -18
  74. package/src/tlc-order.ts +56 -6
  75. package/src/tlc-random.ts +37 -9
  76. package/src/tlc-replay.ts +655 -0
  77. package/src/tlc-summary.ts +20 -5
  78. package/src/tlc-version.ts +18 -0
  79. package/src/transfer.ts +15 -3
  80. package/src/value-sources.ts +29 -0
  81. package/src/values.ts +684 -204
package/src/resolve.ts CHANGED
@@ -4,44 +4,121 @@ import {
4
4
  type AssumeProve,
5
5
  type Bound,
6
6
  type BoundPattern,
7
+ type Declaration,
7
8
  type Definition,
8
9
  type Expression,
10
+ type Fact,
9
11
  type Instance,
12
+ type LabelExpression,
10
13
  type Module,
11
14
  type NewSymbol,
12
15
  type OperatorParam,
13
16
  type Proof,
14
17
  type ProofStep,
18
+ type Selector,
15
19
  type SourceLocation,
20
+ type SourceRange,
16
21
  type Theorem,
17
22
  } from "./ast";
18
- import { TlaSyntaxError } from "./errors";
23
+ import { formatRange, TlaSyntaxError, type SanyError } from "./errors";
19
24
 
20
- export interface ModuleSymbol {
21
- key: string;
25
+ // The kinds of symbol SANY tells apart when it binds a name twice. A parameter is also a bound name,
26
+ // and a NEW symbol has a kind for each level.
27
+ export type SymbolKind =
28
+ | "Builtin"
29
+ | "Constant"
30
+ | "Variable"
31
+ | "Definition"
32
+ | "Instance"
33
+ | "Theorem"
34
+ | "Parameter"
35
+ | `New${NewSymbol["level"]}`;
36
+
37
+ // range is where SANY reports the symbol, and two symbols at one range are one node to SANY. params
38
+ // holds the arity of each parameter of a defined operator.
39
+ export interface Binding {
40
+ kind: SymbolKind;
22
41
  arity: number;
23
- declaration?: "Constant" | "Variable";
42
+ params?: number[];
43
+ range?: SourceRange;
44
+ }
45
+
46
+ export interface ModuleSymbol extends Binding {
47
+ key: string;
24
48
  }
25
49
 
26
50
  export type Symbols = Map<string, ModuleSymbol>;
27
51
 
28
- interface LocalName {
52
+ // A named theorem or proof step whose parts a name such as foo!lab or <1>2!1 selects. isInProof
53
+ // holds while SANY analyzes the proof of the theorem or step.
54
+ interface Goal {
55
+ statement: Expression | AssumeProve;
56
+ isSuffices: boolean;
57
+ isInProof: boolean;
58
+ }
59
+
60
+ // isPending holds for an operator a RECURSIVE declaration names until its definition.
61
+ interface LocalName extends Binding {
29
62
  name: string;
30
- arity: number;
31
63
  parent: LocalName | undefined;
64
+ goal?: Goal;
65
+ isPending?: boolean;
66
+ }
67
+
68
+ // A name the module binds, from position on.
69
+ interface ModuleBinding extends Binding {
70
+ position: SourceLocation;
71
+ isPending?: boolean;
32
72
  }
33
73
 
74
+ // errors and warnings collect what SANY reports while it goes on analyzing the unit, and bindings
75
+ // holds the names the module binds. A label may appear where hasLabelScope holds, in a definition, a
76
+ // named theorem, or a numbered step, except where isLabelForbidden holds, in the scope of a NEW in a
77
+ // nested ASSUME, or where isInExcept holds, in the new value of an EXCEPT. labelParams holds the
78
+ // names bound since the innermost definition, label, or step, which a label must take as parameters,
79
+ // and labels the labels there. isGenerated holds in a definition tla-ts generates for a LET INSTANCE,
80
+ // and in a subexpression that a name selects, which SANY analyzes where it is defined.
81
+ // getInstance gives what an INSTANCE in a LET or a proof instantiates.
34
82
  interface Unit {
35
83
  imported: Symbols;
84
+ getInstance: (instance: Instance) => InstancedModule;
36
85
  definitions: Map<string, Definition>;
37
86
  getKey: (definition: Definition) => string;
38
87
  location: SourceLocation;
39
88
  self: Definition | undefined;
40
89
  facts: Set<string>;
90
+ goals: Map<string, Goal>;
91
+ bindings: Map<string, ModuleBinding>;
92
+ errors: SanyError[];
93
+ warnings: SanyError[];
94
+ hasLabelScope: boolean;
95
+ isLabelForbidden: boolean;
96
+ isInExcept: boolean;
97
+ labelParams: string[];
98
+ labels: Set<string>;
99
+ isGenerated: boolean;
100
+ }
101
+
102
+ interface SelectionError {
103
+ args: Expression[];
104
+ error: SanyError;
41
105
  }
42
106
 
107
+ interface SelectionState {
108
+ node: Expression | NewSymbol | AssumeProve;
109
+ isGoal: boolean;
110
+ isSufficesOpen: boolean;
111
+ }
112
+
113
+ type Reference = Expression & { kind: "Identifier" | "Apply" | "Subexpression" };
114
+
43
115
  export const LOCAL_RESOLUTION = { kind: "Local" } as const;
44
116
 
117
+ // The subexpressions that names select, and for a name that selects none, the error SANY reports and
118
+ // the arguments it analyzes before it.
119
+ export const selections = new WeakSet<Expression>();
120
+ export const selectionErrors = new WeakMap<Expression, SelectionError>();
121
+
45
122
  const renamedArities = new WeakMap<Expression, number>();
46
123
 
47
124
  export const KEY_SEPARATOR = "@";
@@ -53,7 +130,7 @@ const isKey = (name: string) => {
53
130
  };
54
131
 
55
132
  const CORE_SYMBOLS: Symbols = new Map(
56
- ["~>", "-+->", "\\cdot"].map((name) => [name, { key: name, arity: 2 }]),
133
+ ["~>", "-+->", "\\cdot"].map((name) => [name, { key: name, arity: 2, kind: "Builtin" }]),
57
134
  );
58
135
 
59
136
  export const isBefore = (left: SourceLocation, right: SourceLocation) =>
@@ -62,6 +139,9 @@ export const isBefore = (left: SourceLocation, right: SourceLocation) =>
62
139
  export const getArity = (definition: Definition) =>
63
140
  definition.kind === "Operator" ? definition.params.length : 0;
64
141
 
142
+ export const getParamArities = (definition: Definition) =>
143
+ definition.kind === "Operator" ? definition.params.map((param) => param.arity) : [];
144
+
65
145
  const isInstantiated = (definition: Definition) => definition.name.includes("!");
66
146
 
67
147
  const lookupLocal = (scope: LocalName | undefined, name: string) => {
@@ -71,12 +151,99 @@ const lookupLocal = (scope: LocalName | undefined, name: string) => {
71
151
  return undefined;
72
152
  };
73
153
 
74
- const bindNames = (scope: LocalName | undefined, names: string[], arity = 0) =>
75
- names.reduce<LocalName | undefined>((parent, name) => ({ name, arity, parent }), scope);
154
+ // A name the module binds before the unit and before the range, which a copy of a subexpression
155
+ // that a reference selects keeps from its definition.
156
+ const getModuleBinding = (name: string, unit: Unit, range: SourceRange | undefined) => {
157
+ const binding = unit.bindings.get(name);
158
+ return binding &&
159
+ isBefore(binding.position, unit.location) &&
160
+ (!range || isBefore(binding.position, range.start))
161
+ ? binding
162
+ : undefined;
163
+ };
164
+
165
+ const isSameRange = (left: SourceRange | undefined, right: SourceRange | undefined) =>
166
+ left !== undefined && right !== undefined && formatRange(left) === formatRange(right);
167
+
168
+ // SymbolTable.addSymbol binds a name nothing binds yet. It rejects a built-in operator, a parameter
169
+ // or bound name already in use, and a symbol of another kind or arity than the one bound, and warns
170
+ // of any other duplicate. tla-ts binds a symbol SANY never sees, such as one it generates. Tells
171
+ // whether to bind the added symbol.
172
+ const isBindable = (name: string, current: Binding | undefined, added: Binding, unit: Unit) => {
173
+ if (current === undefined) return true;
174
+ if (isSameRange(current.range, added.range)) return false;
175
+ const range = added.range;
176
+ if (range === undefined || unit.isGenerated || (current.kind !== "Builtin" && !current.range)) {
177
+ return true;
178
+ }
179
+ const location = formatRange(range);
180
+ const existing = current.range && formatRange(current.range);
181
+ if (current.kind === "Builtin") {
182
+ unit.errors.push({
183
+ location,
184
+ message: `Symbol ${name} is a built-in operator, and cannot be redefined.`,
185
+ });
186
+ } else if (
187
+ added.kind === "Parameter" ||
188
+ current.kind !== added.kind ||
189
+ current.arity !== added.arity
190
+ ) {
191
+ unit.errors.push({
192
+ location,
193
+ message: `Multiply-defined symbol '${name}': this definition or declaration conflicts \nwith the one at ${existing}.`,
194
+ });
195
+ } else {
196
+ unit.warnings.push({
197
+ location,
198
+ message: `Multiple declarations or definitions for symbol ${name}. \nThis duplicates the one at ${existing}.`,
199
+ });
200
+ }
201
+ return false;
202
+ };
203
+
204
+ const bindName = (
205
+ scope: LocalName | undefined,
206
+ name: string,
207
+ added: Binding,
208
+ unit: Unit,
209
+ ): LocalName | undefined =>
210
+ isBindable(
211
+ name,
212
+ lookupLocal(scope, name) ?? getModuleBinding(name, unit, added.range),
213
+ added,
214
+ unit,
215
+ )
216
+ ? { ...added, name, parent: scope }
217
+ : scope;
218
+
219
+ // Binds the names of a module from the unit on.
220
+ const bindModuleName = (name: string, added: Binding, unit: Unit) => {
221
+ if (isBindable(name, unit.bindings.get(name), added, unit)) {
222
+ unit.bindings.set(name, { ...added, position: unit.location });
223
+ }
224
+ };
225
+
226
+ const bindNames = (
227
+ scope: LocalName | undefined,
228
+ names: string[],
229
+ ranges: SourceRange[] | undefined,
230
+ unit: Unit,
231
+ ) =>
232
+ names.reduce(
233
+ (parent, name, index) =>
234
+ bindName(parent, name, { kind: "Parameter", arity: 0, range: ranges?.[index] }, unit),
235
+ scope,
236
+ );
76
237
 
77
- const bindParams = (scope: LocalName | undefined, params: OperatorParam[]) =>
78
- params.reduce<LocalName | undefined>(
79
- (parent, param) => ({ name: param.name, arity: param.arity, parent }),
238
+ const bindParams = (scope: LocalName | undefined, params: OperatorParam[], unit: Unit) =>
239
+ params.reduce(
240
+ (parent, param) =>
241
+ bindName(
242
+ parent,
243
+ param.name,
244
+ { kind: "Parameter", arity: param.arity, range: param.location?.range },
245
+ unit,
246
+ ),
80
247
  scope,
81
248
  );
82
249
 
@@ -99,19 +266,452 @@ const getVisibleDefinition = (name: string, unit: Unit) => {
99
266
  const findSymbol = (name: string, unit: Unit): ModuleSymbol | undefined => {
100
267
  const definition = getVisibleDefinition(name, unit);
101
268
  return definition
102
- ? { key: unit.getKey(definition), arity: getArity(definition) }
269
+ ? {
270
+ key: unit.getKey(definition),
271
+ arity: getArity(definition),
272
+ params: getParamArities(definition),
273
+ kind: "Definition",
274
+ }
103
275
  : unit.imported.get(name);
104
276
  };
105
277
 
278
+ const findBinding = (name: string, scope: LocalName | undefined, unit: Unit): Binding | undefined =>
279
+ lookupLocal(scope, name) ?? findSymbol(name, unit);
280
+
281
+ // SANY reports a name at the range of its text.
282
+ const getNameRange = (location: SourceLocation, name: string): SourceRange => ({
283
+ module: location.range?.module ?? "",
284
+ start: location,
285
+ end: { line: location.line, column: location.column + name.length - 1 },
286
+ });
287
+
288
+ // SANY reports a name at its tokens, such as M ! ⊕ for M!\oplus.
289
+ const getSpelledNameRange = (
290
+ expression: Expression & { kind: "Identifier" | "Apply" | "OperatorReference" },
291
+ name: string,
292
+ ): SourceRange => {
293
+ const selectorRange =
294
+ expression.kind === "OperatorReference" ? undefined : expression.selectorRanges?.at(-1);
295
+ return selectorRange
296
+ ? { module: selectorRange.module, start: expression.location, end: selectorRange.end }
297
+ : getNameRange(expression.location, expression.spelling ?? name);
298
+ };
299
+
300
+ // SANY reports an operator symbol applied to operands as one it cannot resolve.
301
+ const getFixity = (expression: Expression) => {
302
+ if (expression.kind !== "Apply") return undefined;
303
+ if (expression.args.length === 2) return "infix";
304
+ if (expression.args.length !== 1) return undefined;
305
+ return isBefore(expression.location, expression.args[0].location) ? "prefix" : "postfix";
306
+ };
307
+
106
308
  // SANY names an undefined operator symbol such as + differently from an undefined identifier.
107
- const isOperatorSymbol = (name: string) =>
108
- name[0].toLowerCase() === name[0].toUpperCase() &&
109
- name[0] !== "_" &&
110
- (name[0] < "0" || name[0] > "9");
309
+ const isOperatorSymbol = (name: string) => !/^[\p{L}\d_]/u.test(name);
111
310
 
112
311
  const isStepName = (name: string) =>
113
312
  name.startsWith("<") && ((name[1] >= "0" && name[1] <= "9") || name[1] === "*");
114
313
 
314
+ export const getOperandIndex = (operand: number | "<<" | ">>", count: number) => {
315
+ if (typeof operand === "number") return operand >= 1 && operand <= count ? operand - 1 : -1;
316
+ if (operand === "<<") return count > 0 ? 0 : -1;
317
+ return count === 2 ? 1 : -1;
318
+ };
319
+
320
+ // The parts of a name such as F(x)!l(y), each with its own arguments. counts holds the number each
321
+ // part takes, when a part before the last takes some.
322
+ export const getNameSelectors = (
323
+ name: string,
324
+ args: Expression[],
325
+ counts: number[] | undefined,
326
+ ): Selector[] => {
327
+ const parts = name.split("!");
328
+ const partCounts =
329
+ counts ?? parts.map((_, index) => (index === parts.length - 1 ? args.length : 0));
330
+ return parts.map((part, index) => {
331
+ const start = partCounts.slice(0, index).reduce((sum, count) => sum + count, 0);
332
+ return { kind: "Name", name: part, args: args.slice(start, start + partCounts[index]) };
333
+ });
334
+ };
335
+
336
+ const getSelectors = (reference: Reference): Selector[] =>
337
+ reference.kind === "Subexpression"
338
+ ? reference.selectors
339
+ : reference.kind === "Identifier"
340
+ ? getNameSelectors(reference.name, [], undefined)
341
+ : getNameSelectors(reference.operator, reference.args, reference.argumentCounts);
342
+
343
+ const getBoundSets = (bounds: Bound[]) =>
344
+ bounds
345
+ .filter((bound, index) => index === 0 || bounds[index - 1].set !== bound.set)
346
+ .map((bound) => bound.set);
347
+
348
+ // The names a binder binds, its body, and the sets it binds them to, which a selector such as !1
349
+ // chooses from.
350
+ export const getBinder = (
351
+ expression: Expression,
352
+ ): { names: string[]; body: Expression; sets: Expression[] } | undefined => {
353
+ switch (expression.kind) {
354
+ case "Forall":
355
+ case "Exists":
356
+ case "FunctionConstruction":
357
+ return {
358
+ names: getBoundNames(expression.bounds),
359
+ body: expression.body,
360
+ sets: getBoundSets(expression.bounds),
361
+ };
362
+ case "SetMap":
363
+ return {
364
+ names: getBoundNames(expression.bounds),
365
+ body: expression.expression,
366
+ sets: getBoundSets(expression.bounds),
367
+ };
368
+ case "SetFilter":
369
+ return {
370
+ names: getPatternNames(expression.bound.pattern),
371
+ body: expression.predicate,
372
+ sets: [expression.bound.set],
373
+ };
374
+ case "Choose":
375
+ return {
376
+ names: getPatternNames(expression.pattern),
377
+ body: expression.body,
378
+ sets: expression.set ? [expression.set] : [],
379
+ };
380
+ case "UnboundedQuantifier":
381
+ case "Lambda":
382
+ return {
383
+ names: expression.kind === "Lambda" ? expression.params : expression.names,
384
+ body: expression.body,
385
+ sets: [],
386
+ };
387
+ default:
388
+ return undefined;
389
+ }
390
+ };
391
+
392
+ // The operands that a selector such as !1 chooses from, where they do not depend on bound names.
393
+ export const getOperands = (expression: Expression): Expression[] | undefined => {
394
+ switch (expression.kind) {
395
+ case "Apply":
396
+ return expression.args;
397
+ case "And":
398
+ case "Or":
399
+ return expression.operands;
400
+ case "If":
401
+ return [expression.condition, expression.consequent, expression.alternative];
402
+ case "Tuple":
403
+ case "SetEnumeration":
404
+ return expression.elements;
405
+ case "Record":
406
+ case "RecordSet":
407
+ return expression.fields.map((field) => field.value);
408
+ case "FunctionApplication":
409
+ return [
410
+ expression.function,
411
+ expression.args.length === 1
412
+ ? expression.args[0]
413
+ : { kind: "Tuple", elements: expression.args, location: expression.location },
414
+ ];
415
+ case "FieldAccess":
416
+ return [
417
+ expression.record,
418
+ { kind: "String", value: expression.field, location: expression.location },
419
+ ];
420
+ case "Prime":
421
+ case "Unchanged":
422
+ case "Enabled":
423
+ case "Always":
424
+ case "Eventually":
425
+ return [expression.expression];
426
+ case "BoxAction":
427
+ case "AngleAction":
428
+ return [expression.action, expression.subscript];
429
+ case "WeakFairness":
430
+ case "StrongFairness":
431
+ return [expression.subscript, expression.action];
432
+ case "FunctionSet":
433
+ return [expression.domain, expression.range];
434
+ case "Product":
435
+ return expression.factors;
436
+ case "Except":
437
+ return [expression.function];
438
+ default:
439
+ return undefined;
440
+ }
441
+ };
442
+
443
+ const isReference = (expression: Expression): expression is Reference =>
444
+ expression.kind === "Identifier" ||
445
+ expression.kind === "Apply" ||
446
+ expression.kind === "Subexpression";
447
+
448
+ const isInScopeOfDeclaration = (assumeProve: AssumeProve, clause: number) =>
449
+ assumeProve.assumptions.slice(0, clause).some((assumption) => assumption.kind === "NewSymbol");
450
+
451
+ const findLabel = (expression: Expression, name: string): LabelExpression | undefined => {
452
+ if (expression.kind === "Label") return expression.name === name ? expression : undefined;
453
+ if (expression.kind === "Lambda") return undefined;
454
+ if (expression.kind === "Let") return findLabel(expression.body, name);
455
+ return getChildren(expression).reduce<LabelExpression | undefined>(
456
+ (found, child) => found ?? findLabel(child, name),
457
+ undefined,
458
+ );
459
+ };
460
+
461
+ // SANY drops a label in the scope of a NEW in a nested ASSUME, after it reports the label.
462
+ const findClauseLabel = (
463
+ clause: Expression | NewSymbol | AssumeProve,
464
+ name: string,
465
+ isForbidden: boolean,
466
+ ): LabelExpression | undefined => {
467
+ if (clause.kind === "AssumeProve") {
468
+ return [...clause.assumptions, clause.conclusion].reduce<LabelExpression | undefined>(
469
+ (found, inner, index) =>
470
+ found ?? findClauseLabel(inner, name, isForbidden || isInScopeOfDeclaration(clause, index)),
471
+ undefined,
472
+ );
473
+ }
474
+ if (isForbidden) return undefined;
475
+ if (clause.kind === "NewSymbol") return clause.set && findLabel(clause.set, name);
476
+ return findLabel(clause, name);
477
+ };
478
+
479
+ const getLabelBody = (expression: Expression): Expression =>
480
+ expression.kind === "Label" ? getLabelBody(expression.body) : expression;
481
+
482
+ const getOperandName = (operand: number | "<<" | ">>") =>
483
+ typeof operand === "number" ? `argument selector ${operand}` : operand;
484
+
485
+ const SCOPE_MESSAGE = "within the scope of a declaration\n from outside that declaration's scope.";
486
+
487
+ // Generator.selectorToNode for a name that selects part of a theorem or step. A part in the scope of
488
+ // a NEW in its ASSUME may be selected only within the proof of the theorem, or only after the proof
489
+ // of a SUFFICES step. A label takes its own arguments, and an operand must exist, unless the part
490
+ // selected depends on bound names. A fact may select an ASSUME/PROVE or a NEW clause.
491
+ const checkSelection = (
492
+ reference: Reference,
493
+ selectors: Selector[],
494
+ goal: Goal,
495
+ scope: LocalName | undefined,
496
+ unit: Unit,
497
+ isFact: boolean,
498
+ ) => {
499
+ const report = (index: number | undefined, message: string) => {
500
+ const range =
501
+ (index === undefined ? undefined : reference.selectorRanges?.[index]) ??
502
+ reference.location.range;
503
+ if (range) unit.errors.push({ location: formatRange(range), message });
504
+ };
505
+ const isOutOfScope = goal.isSuffices === goal.isInProof;
506
+ const statement = goal.statement;
507
+ const state: SelectionState = {
508
+ node: statement,
509
+ isGoal: true,
510
+ isSufficesOpen: goal.isSuffices,
511
+ };
512
+ for (const [offset, selector] of selectors.slice(1).entries()) {
513
+ const index = offset + 1;
514
+ const node = state.node;
515
+ if (selector.kind === "Name") {
516
+ if (selectors[index - 1].kind !== "Name") {
517
+ const isLet =
518
+ node.kind !== "NewSymbol" &&
519
+ node.kind !== "AssumeProve" &&
520
+ getLabelBody(node).kind === "Let";
521
+ return isLet
522
+ ? undefined
523
+ : report(index - 1, "A name selector here must be from a LET clause.");
524
+ }
525
+ const clauses =
526
+ statement.kind === "AssumeProve"
527
+ ? [...statement.assumptions, statement.conclusion]
528
+ : [statement];
529
+ const found =
530
+ index === 1
531
+ ? clauses
532
+ .map((clause, position) => ({
533
+ position,
534
+ label: findClauseLabel(clause, selector.name, false),
535
+ }))
536
+ .find((item) => item.label !== undefined)
537
+ : {
538
+ position: 0,
539
+ label: node.kind === "Label" ? findLabel(node.body, selector.name) : undefined,
540
+ };
541
+ if (!found?.label) return report(index, `Cannot find label \`${selector.name}'.`);
542
+ if (
543
+ index === 1 &&
544
+ statement.kind === "AssumeProve" &&
545
+ isInScopeOfDeclaration(statement, found.position) &&
546
+ isOutOfScope
547
+ ) {
548
+ return report(
549
+ 1,
550
+ `Accessing subexpression labeled \`${selector.name}' of ASSUME/PROVE clause ${SCOPE_MESSAGE}`,
551
+ );
552
+ }
553
+ if (selector.args.length !== found.label.params.length) {
554
+ return report(index, `Label \`${selector.name}' used with wrong number of arguments.`);
555
+ }
556
+ state.node = found.label;
557
+ state.isGoal = false;
558
+ state.isSufficesOpen = false;
559
+ continue;
560
+ }
561
+ if (selector.kind !== "Operand") return;
562
+ const operand = getOperandName(selector.operand);
563
+ if (state.isSufficesOpen) {
564
+ if (getOperandIndex(selector.operand, 1) !== 0) {
565
+ return report(
566
+ index,
567
+ node.kind === "AssumeProve"
568
+ ? "Accessing non-existent subexpression of a SUFFICES"
569
+ : `Nonexistent operand specified by \`${operand}'.`,
570
+ );
571
+ }
572
+ state.isSufficesOpen = false;
573
+ continue;
574
+ }
575
+ if (node.kind === "NewSymbol") return;
576
+ if (node.kind !== "AssumeProve") {
577
+ const expression = getLabelBody(node);
578
+ if (["Number", "Decimal", "String"].includes(expression.kind)) {
579
+ return report(index, "Selecting subexpression of expression that has none.");
580
+ }
581
+ const kind =
582
+ expression.kind === "Identifier"
583
+ ? findBinding(expression.name, scope, unit)?.kind
584
+ : undefined;
585
+ if (kind === "Variable" || kind?.startsWith("New")) {
586
+ return report(index, `Choosing operand \`${operand}' of subexpression with no operands.`);
587
+ }
588
+ const sets = getBinder(expression)?.sets;
589
+ const operands =
590
+ expression.kind === "Identifier"
591
+ ? []
592
+ : sets
593
+ ? sets.length > 0
594
+ ? sets
595
+ : undefined
596
+ : expression.kind === "Except"
597
+ ? undefined
598
+ : getOperands(expression);
599
+ if (!operands) return;
600
+ const position = getOperandIndex(selector.operand, operands.length);
601
+ if (position === -1) return report(index, `Nonexistent operand specified by \`${operand}'.`);
602
+ state.node = operands[position];
603
+ state.isGoal = false;
604
+ continue;
605
+ }
606
+ const clauses = [...node.assumptions, node.conclusion];
607
+ const position = getOperandIndex(selector.operand, clauses.length);
608
+ if (position === -1) return report(index, `Nonexistent operand specified by \`${operand}'.`);
609
+ if (isInScopeOfDeclaration(node, position) && (!state.isGoal || isOutOfScope)) {
610
+ return report(index, `Accessing ASSUME/PROVE clause ${SCOPE_MESSAGE}`);
611
+ }
612
+ const clause = clauses[position];
613
+ if (clause.kind === "NewSymbol" && index !== selectors.length - 1) {
614
+ return report(index, "Selected a subexpression of a NEW clause of an ASSUME.");
615
+ }
616
+ state.node = clause;
617
+ state.isGoal = false;
618
+ }
619
+ if (isFact) return;
620
+ if (state.node.kind === "AssumeProve") {
621
+ report(undefined, "Selected ASSUME/PROVE instead of expression.");
622
+ }
623
+ if (state.node.kind === "NewSymbol") {
624
+ report(undefined, "Selected a NEW declaration as an expression or operator.");
625
+ }
626
+ };
627
+
628
+ // Generator.generateLabel reports a label where it may not appear, and skips the label's body.
629
+ const isLabelReported = (label: LabelExpression, unit: Unit) => {
630
+ const message = unit.isGenerated
631
+ ? undefined
632
+ : !unit.hasLabelScope
633
+ ? "Label not in definition or proof step."
634
+ : unit.isLabelForbidden
635
+ ? "Label not allowed within scope of declaration in nested ASSUME/PROVE."
636
+ : unit.isInExcept
637
+ ? "Labels inside EXCEPT clauses are not yet implemented."
638
+ : undefined;
639
+ if (message === undefined || !label.location.range) return false;
640
+ unit.errors.push({ location: formatRange(label.location.range), message });
641
+ return true;
642
+ };
643
+
644
+ // Generator.generateLabel reports, after the label's body, each parameter that names no bound name,
645
+ // then formalParamsEqual each parameter given twice, each name bound since the label scope began
646
+ // that the label leaves out, and the parameters it adds, and then a label of a name already used.
647
+ const checkLabel = (label: LabelExpression, scope: LocalName | undefined, unit: Unit) => {
648
+ const range = label.location.range;
649
+ if (!range || unit.isGenerated) return;
650
+ const location = formatRange(range);
651
+ const legal = label.params.filter((param, index) => {
652
+ const isLegal = lookupLocal(scope, param)?.kind === "Parameter";
653
+ const paramRange = label.paramRanges?.[index];
654
+ if (!isLegal && paramRange) {
655
+ unit.errors.push({
656
+ location: formatRange(paramRange),
657
+ message: `Illegal parameter ${param} of label \`${label.name}'.`,
658
+ });
659
+ }
660
+ return isLegal;
661
+ });
662
+ legal
663
+ .filter((param, index) => legal.indexOf(param) !== index)
664
+ .forEach((param) =>
665
+ unit.errors.push({
666
+ location,
667
+ message: `Repeated formal parameter ${param} \nin label \`${label.name}'.`,
668
+ }),
669
+ );
670
+ unit.labelParams
671
+ .filter((param) => !legal.includes(param))
672
+ .forEach((param) =>
673
+ unit.errors.push({
674
+ location,
675
+ message: `Label ${label.name} must contain formal parameter \`${param}'.`,
676
+ }),
677
+ );
678
+ const extra = [
679
+ ...new Set(legal.filter((param) => !unit.labelParams.includes(param))),
680
+ ...label.params.filter((param) => !legal.includes(param)),
681
+ ];
682
+ if (extra.length > 0) {
683
+ unit.errors.push({
684
+ location,
685
+ message: `Label ${label.name} declares extra parameter(s) ${extra.map((param) => `${param} `).join("")}`,
686
+ });
687
+ }
688
+ if (unit.labels.has(label.name)) {
689
+ unit.errors.push({ location, message: `Duplicate label \`${label.name}'.` });
690
+ }
691
+ unit.labels.add(label.name);
692
+ };
693
+
694
+ // Checks a name that selects part of a theorem or step, and tells whether it is one.
695
+ const checkReference = (
696
+ expression: Expression,
697
+ scope: LocalName | undefined,
698
+ unit: Unit,
699
+ isFact: boolean,
700
+ ) => {
701
+ if (!isReference(expression)) return false;
702
+ const selectors = getSelectors(expression);
703
+ const first = selectors[0];
704
+ const goal =
705
+ selectors.length > 1 && first.kind === "Name"
706
+ ? (lookupLocal(scope, first.name)?.goal ?? unit.goals.get(first.name))
707
+ : undefined;
708
+ if (goal) checkSelection(expression, selectors, goal, scope, unit, isFact);
709
+ return goal !== undefined;
710
+ };
711
+
712
+ // Generator.selectorToNode reports an unknown operator and goes on without analyzing its arguments,
713
+ // so its arity is undefined. It does the same for an operator given the wrong number of arguments,
714
+ // and for a name that selects nothing, after the arguments of the parts before.
115
715
  const getSymbolArity = (
116
716
  expression: Expression & { kind: "Identifier" | "Apply" | "OperatorReference" },
117
717
  name: string,
@@ -119,10 +719,16 @@ const getSymbolArity = (
119
719
  unit: Unit,
120
720
  ) => {
121
721
  const location = expression.location;
722
+ if (isSelectionReported(expression, scope, unit)) return undefined;
122
723
  const renamed = renamedArities.get(expression);
123
724
  if (renamed !== undefined) return renamed;
124
725
  if (isKey(name)) return expression.kind === "Apply" ? expression.args.length : 0;
125
- if (isStepName(name)) return 0;
726
+ if (
727
+ checkReference(expression, scope, unit, false) ||
728
+ (isStepName(name) && lookupLocal(scope, name))
729
+ ) {
730
+ return expression.kind === "Apply" ? expression.args.length : 0;
731
+ }
126
732
  const local = lookupLocal(scope, name);
127
733
  if (local && expression.kind !== "OperatorReference") expression.resolution = LOCAL_RESOLUTION;
128
734
  if (local) return local.arity;
@@ -135,7 +741,7 @@ const getSymbolArity = (
135
741
  }
136
742
  // A name such as Inv!P1 selects the label P1 of a definition or theorem, which takes its own
137
743
  // arguments.
138
- const prefix = name.slice(0, name.indexOf("!"));
744
+ const prefix = name.includes("!") ? name.slice(0, name.indexOf("!")) : "";
139
745
  const isSelected =
140
746
  prefix !== "" &&
141
747
  (lookupLocal(scope, prefix) !== undefined ||
@@ -144,18 +750,35 @@ const getSymbolArity = (
144
750
  if (isSelected) {
145
751
  return expression.kind === "Apply" ? expression.args.length : 0;
146
752
  }
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}`,
753
+ const spelling = (expression.kind === "Identifier" ? undefined : expression.spelling) ?? name;
754
+ const range = formatRange(
755
+ expression.kind === "Apply" && spelling === "-."
756
+ ? getNameRange(location, "-")
757
+ : getSpelledNameRange(expression, name),
152
758
  );
759
+ if (!isOperatorSymbol(name) || isStepName(name)) {
760
+ unit.errors.push({ location: range, message: `Unknown operator: \`${name}'.` });
761
+ return undefined;
762
+ }
763
+ unit.errors.push({
764
+ location: range,
765
+ message: `Could not find declaration or definition of symbol '${spelling}'.`,
766
+ });
767
+ const fixity = getFixity(expression);
768
+ if (fixity && location.range) {
769
+ unit.errors.push({
770
+ location: formatRange(location.range),
771
+ message: `Couldn't resolve ${fixity} operator symbol \`${spelling}'.`,
772
+ });
773
+ }
774
+ return undefined;
153
775
  };
154
776
 
155
777
  const resolveBounds = (bounds: Bound[], scope: LocalName | undefined, unit: Unit) => {
156
778
  bounds.forEach((bound) => resolveExpression(bound.set, scope, unit));
157
779
  return bounds.reduce(
158
- (current, bound) => bindNames(current, getPatternNames(bound.pattern)),
780
+ (current, bound) =>
781
+ bindNames(current, getPatternNames(bound.pattern), bound.pattern.ranges, unit),
159
782
  scope,
160
783
  );
161
784
  };
@@ -171,94 +794,276 @@ const markRecursiveConstructions = (expression: Expression, name: string): void
171
794
  getChildren(expression).forEach((child) => markRecursiveConstructions(child, name));
172
795
  };
173
796
 
174
- const resolveDefinition = (definition: Definition, scope: LocalName | undefined, unit: Unit) => {
175
- const self = bindNames(scope, definition.kind === "Function" ? [definition.name] : []);
797
+ // Generator.processOperator binds the parameters, reports a name already bound unless a RECURSIVE
798
+ // declaration of this level awaits the definition, analyzes the body, and then binds the name.
799
+ // processFunction binds the bound names before it looks up the name, and binds the name only where
800
+ // nothing else does. recursive holds the declarations of this level. Tells whether to bind the name.
801
+ const resolveDefinition = (
802
+ definition: Definition,
803
+ scope: LocalName | undefined,
804
+ outer: Unit,
805
+ recursive: Set<Binding>,
806
+ ) => {
807
+ const unit = {
808
+ ...outer,
809
+ hasLabelScope: true,
810
+ labelParams: definition.kind === "Function" ? getBoundNames(definition.bounds) : [],
811
+ labels: new Set<string>(),
812
+ };
813
+ const name = definition.name;
814
+ const range = definition.location.range;
815
+ const report = (message: string) => {
816
+ if (range && !unit.isGenerated) unit.errors.push({ location: formatRange(range), message });
817
+ };
818
+ const inner =
819
+ definition.kind === "Function"
820
+ ? resolveBounds(definition.bounds, scope, unit)
821
+ : bindParams(scope, definition.params, unit);
822
+ const current = lookupLocal(inner, name) ?? getModuleBinding(name, unit, range);
823
+ const isDeclared = current?.isPending === true && recursive.has(current);
824
+ if (current?.isPending && !isDeclared) {
825
+ report(
826
+ `Recursive ${definition.kind === "Function" ? "function" : "operator"} ${name} defined at wrong LET/IN level.`,
827
+ );
828
+ } else if (current && !isDeclared) {
829
+ report(
830
+ definition.kind === "Function"
831
+ ? `Function name \`${name}' already defined or declared.`
832
+ : `Operator ${name} already defined or declared.`,
833
+ );
834
+ }
176
835
  if (definition.kind === "Function") {
177
- resolveExpression(definition.body, resolveBounds(definition.bounds, self, unit), unit);
178
- markRecursiveConstructions(definition.body, definition.name);
179
- return;
836
+ resolveExpression(
837
+ definition.body,
838
+ { name, kind: "Parameter", arity: 0, range, parent: inner },
839
+ unit,
840
+ );
841
+ markRecursiveConstructions(definition.body, name);
842
+ definition.isSelfReferential = isReferenced(definition.body, name);
843
+ } else resolveExpression(definition.body, inner, unit);
844
+ if (current && isDeclared) {
845
+ current.isPending = false;
846
+ current.range = range;
847
+ return false;
180
848
  }
181
- resolveExpression(definition.body, bindParams(self, definition.params), unit);
849
+ return definition.kind === "Function"
850
+ ? current === undefined
851
+ : isBindable(
852
+ name,
853
+ lookupLocal(scope, name) ?? getModuleBinding(name, unit, range),
854
+ { kind: "Definition", arity: getArity(definition), range },
855
+ unit,
856
+ );
182
857
  };
183
858
 
859
+ // SANY analyzes an INSTANCE in a LET where it appears, before the definitions that follow it, which
860
+ // tla-ts generates at its location and analyzes without reporting.
184
861
  const resolveDefinitions = (
185
862
  definitions: Definition[],
186
863
  scope: LocalName | undefined,
187
864
  unit: Unit,
865
+ instances: Instance[] = [],
188
866
  ) => {
189
- const recursiveScope = definitions
867
+ const recursive = new Set<Binding>();
868
+ const declared = definitions
190
869
  .filter((definition) => definition.isRecursive)
191
- .reduce<LocalName | undefined>(
192
- (parent, definition) => ({ name: definition.name, arity: getArity(definition), parent }),
193
- scope,
194
- );
195
- return definitions.reduce((current, definition) => {
196
- if (!isInstantiated(definition)) resolveDefinition(definition, current, unit);
197
- return { name: definition.name, arity: getArity(definition), parent: current };
198
- }, recursiveScope);
870
+ .reduce<LocalName | undefined>((parent, definition) => {
871
+ if (lookupLocal(parent, definition.name)?.isPending) return parent;
872
+ const local: LocalName = {
873
+ name: definition.name,
874
+ arity: getArity(definition),
875
+ params: getParamArities(definition),
876
+ kind: "Definition",
877
+ parent,
878
+ isPending: true,
879
+ };
880
+ recursive.add(local);
881
+ return local;
882
+ }, scope);
883
+ const pending = unit.isGenerated ? [] : [...instances];
884
+ const resolveInstances = (
885
+ current: LocalName | undefined,
886
+ isDue: (instance: Instance) => boolean,
887
+ ) => {
888
+ const count = pending.findIndex((instance) => !isDue(instance));
889
+ return pending
890
+ .splice(0, count === -1 ? pending.length : count)
891
+ .reduce((parent, instance) => resolveLocalInstance(instance, parent, unit), current);
892
+ };
893
+ const resolved = definitions.reduce<LocalName | undefined>((previous, definition) => {
894
+ const current = isKey(definition.name)
895
+ ? previous
896
+ : resolveInstances(previous, (instance) => !isBefore(definition.location, instance.location));
897
+ const local: LocalName = {
898
+ name: definition.name,
899
+ arity: getArity(definition),
900
+ kind: "Definition",
901
+ range: definition.location.range,
902
+ parent: current,
903
+ };
904
+ if (isInstantiated(definition)) return local;
905
+ const isInstanced = instances.some((instance) => instance.location === definition.location);
906
+ const isGenerated = unit.isGenerated || definition.isLocal || isKey(definition.name);
907
+ const inner = isInstanced
908
+ ? { ...unit, isGenerated: true, errors: [], warnings: [] }
909
+ : isGenerated
910
+ ? { ...unit, isGenerated }
911
+ : unit;
912
+ return resolveDefinition(definition, current, inner, recursive)
913
+ ? { ...local, params: getParamArities(definition) }
914
+ : current;
915
+ }, declared);
916
+ return resolveInstances(resolved, () => true);
199
917
  };
200
918
 
201
- // OpDefNode#match: a parameter of arity 0 takes an expression, and a parameter of arity n takes an
202
- // operator of arity n whose own parameters take expressions.
203
- const checkArgument = (
204
- definition: Definition,
205
- index: number,
206
- arg: Expression,
207
- argArity: number,
208
- argDefinition: Definition | undefined,
919
+ // The INSTANCE that a name such as K!C starts with, whose arguments SANY requires at its name.
920
+ const findInstance = (name: string, scope: LocalName | undefined, unit: Unit) => {
921
+ const prefix = name.split("!")[0];
922
+ const binding =
923
+ prefix === name
924
+ ? undefined
925
+ : (lookupLocal(scope, prefix) ?? getModuleBinding(prefix, unit, undefined));
926
+ return binding?.kind === "Instance" ? { name: prefix, arity: binding.arity } : undefined;
927
+ };
928
+
929
+ // Generator.selectorToNode reports an INSTANCE given the wrong number of arguments at its name,
930
+ // as in K!C or K(1, 2)!C, and goes on without analyzing them. Tells whether it reports one.
931
+ const isInstanceArityReported = (
932
+ expression: Expression,
933
+ scope: LocalName | undefined,
934
+ unit: Unit,
209
935
  ) => {
210
- const param = definition.kind === "Operator" ? definition.params[index] : undefined;
211
- const location = arg.location;
212
- if (param?.arity === 0 && argArity > 0) {
213
- throw new TlaSyntaxError(
214
- `Operator used in argument number ${index + 1} has incorrect number of arguments at line ${location.line}, column ${location.column}`,
215
- );
216
- }
217
- const isHigherOrder =
218
- argDefinition?.kind === "Operator" && argDefinition.params.some((inner) => inner.arity > 0);
219
- if (param !== undefined && param.arity > 0 && (argArity !== param.arity || isHigherOrder)) {
220
- throw new TlaSyntaxError(
221
- `Argument number ${index + 1} to operator '${definition.name}' should be a ${param.arity}-parameter operator at line ${location.line}, column ${location.column}`,
222
- );
936
+ if (expression.kind !== "Identifier" && expression.kind !== "Apply") return false;
937
+ const instance = findInstance(
938
+ expression.kind === "Identifier" ? expression.name : expression.operator,
939
+ scope,
940
+ unit,
941
+ );
942
+ const count = expression.kind === "Apply" ? (expression.argumentCounts?.[0] ?? 0) : 0;
943
+ if (!instance || count === instance.arity) return false;
944
+ const range =
945
+ (expression.kind === "Apply" ? expression.argumentRanges?.[0] : undefined) ??
946
+ expression.location.range;
947
+ if (range) {
948
+ unit.errors.push({
949
+ location: formatRange(range),
950
+ message: `The operator ${instance.name} requires ${instance.arity} arguments.`,
951
+ });
223
952
  }
953
+ return true;
224
954
  };
225
955
 
226
- const getArgumentName = (arg: Expression) =>
227
- arg.kind === "Identifier"
228
- ? arg.name
229
- : arg.kind === "OperatorReference"
230
- ? arg.operator
231
- : undefined;
232
-
956
+ // Generator.generateExprOrOpArg analyzes an argument as an expression, unless a defined operator
957
+ // takes an operator in its place, which a name, a built-in operator, or a LAMBDA of the parameter's
958
+ // arity must give. OpDefNode#match then reports each argument that gives no such operator, or one
959
+ // whose own parameters take operators. tla-ts lets an operator whose parameters it does not know
960
+ // take any argument.
233
961
  const resolveApply = (
234
962
  expression: Expression & { kind: "Apply" },
235
963
  scope: LocalName | undefined,
236
964
  unit: Unit,
237
965
  ) => {
238
- const callee = lookupLocal(scope, expression.operator)
239
- ? undefined
240
- : getVisibleDefinition(expression.operator, unit);
241
- const arity = getSymbolArity(expression, expression.operator, scope, unit);
966
+ if (isInstanceArityReported(expression, scope, unit)) return;
967
+ const operator = expression.operator;
968
+ const callee = findBinding(operator, scope, unit);
969
+ const arity = getSymbolArity(expression, operator, scope, unit);
970
+ if (arity === undefined) return;
242
971
  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}`,
245
- );
972
+ unit.errors.push({
973
+ location: formatRange(expression.argumentsRange ?? getSpelledNameRange(expression, operator)),
974
+ message: `The operator ${operator} requires ${arity - (findInstance(operator, scope, unit)?.arity ?? 0)} arguments.`,
975
+ });
976
+ return;
246
977
  }
247
- expression.args.forEach((arg, index) => {
248
- const name = getArgumentName(arg);
249
- const argDefinition =
250
- name === undefined || lookupLocal(scope, name) ? undefined : getVisibleDefinition(name, unit);
251
- const argArity = resolveArgument(arg, scope, unit);
252
- if (callee) checkArgument(callee, index, arg, argArity, argDefinition);
253
- });
978
+ const params = callee && (callee.kind === "Definition" ? callee.params : []);
979
+ if (params === undefined) {
980
+ expression.args.forEach((arg) => resolveArgument(arg, scope, unit));
981
+ return;
982
+ }
983
+ const report = (range: SourceRange | undefined, message: string) => {
984
+ if (range) unit.errors.push({ location: formatRange(range), message });
985
+ };
986
+ expression.args
987
+ .map((arg, index) => {
988
+ const expected = params[index] ?? 0;
989
+ const range = arg.location.range;
990
+ if (expected === 0) {
991
+ // SANY fails on an operator here with an internal error, so tla-ts words it as it does for
992
+ // a name.
993
+ if (arg.kind === "Lambda" && arg.operator !== undefined) {
994
+ report(range, `The operator ${arg.operator} requires 1 arguments.`);
995
+ } else if (arg.kind === "Lambda" && range) {
996
+ report(range, "LAMBDA expression used where an expression is required.");
997
+ } else if (arg.kind === "OperatorReference") {
998
+ const argArity = getSymbolArity(arg, arg.operator, scope, unit);
999
+ if (argArity !== undefined) {
1000
+ report(range, `The operator ${arg.operator} requires ${argArity} arguments.`);
1001
+ }
1002
+ } else resolveExpression(arg, scope, unit);
1003
+ return true;
1004
+ }
1005
+ // A name that selects a subexpression gives an operator of the names it leaves unbound.
1006
+ if (arg.kind === "Lambda") {
1007
+ resolveExpression(arg, scope, unit);
1008
+ const isMatched = arg.params.length === expected;
1009
+ if (!isMatched && selections.has(arg)) {
1010
+ report(
1011
+ range,
1012
+ `Expected arity ${expected} but found operator of arity ${arg.params.length}.`,
1013
+ );
1014
+ } else if (!isMatched && range && arg.operator === undefined) {
1015
+ report(
1016
+ expression.selectorRanges?.at(-1) ?? getSpelledNameRange(expression, operator),
1017
+ `Lambda expression with arity ${arg.params.length} used as argument ${index + 1} of operator \`${operator}', \nbut an operator of arity ${expected} is required.`,
1018
+ );
1019
+ }
1020
+ return isMatched;
1021
+ }
1022
+ if (arg.kind === "Subexpression") {
1023
+ resolveExpression(arg, scope, unit);
1024
+ return true;
1025
+ }
1026
+ if (arg.kind !== "Identifier" && arg.kind !== "OperatorReference") {
1027
+ report(
1028
+ range,
1029
+ `An expression appears as argument number ${index + 1} (counting from 1) to operator '${operator}', in a position an operator is required.`,
1030
+ );
1031
+ return false;
1032
+ }
1033
+ const name = arg.kind === "Identifier" ? arg.name : arg.operator;
1034
+ const argParams = findBinding(name, scope, unit)?.params ?? [];
1035
+ const argArity = getSymbolArity(arg, name, scope, unit);
1036
+ if (arg.kind === "Identifier" && argArity !== undefined && argArity !== expected) {
1037
+ report(
1038
+ getSpelledNameRange(arg, name),
1039
+ `Expected arity ${expected} but found operator of arity ${argArity}.`,
1040
+ );
1041
+ }
1042
+ return argArity === expected && argParams.every((param) => param === 0);
1043
+ })
1044
+ .forEach((isMatched, index) => {
1045
+ if (!isMatched) {
1046
+ report(
1047
+ expression.location.range,
1048
+ `Argument number ${index + 1} to operator '${operator}' \nshould be a ${params[index]}-parameter operator.`,
1049
+ );
1050
+ }
1051
+ });
254
1052
  };
255
1053
 
256
1054
  // An argument may name an operator that takes arguments of its own.
257
1055
  const resolveArgument = (arg: Expression, scope: LocalName | undefined, unit: Unit) => {
258
- if (arg.kind === "Identifier") return getSymbolArity(arg, arg.name, scope, unit);
259
- if (arg.kind === "OperatorReference") return getSymbolArity(arg, arg.operator, scope, unit);
260
- resolveExpression(arg, scope, unit);
261
- return arg.kind === "Lambda" ? arg.params.length : 0;
1056
+ if (arg.kind === "Identifier") getSymbolArity(arg, arg.name, scope, unit);
1057
+ else resolveExpression(arg, scope, unit);
1058
+ };
1059
+
1060
+ // Reports the error of a name that selects nothing, after the arguments SANY analyzes before it.
1061
+ const isSelectionReported = (expression: Expression, scope: LocalName | undefined, unit: Unit) => {
1062
+ const failed = selectionErrors.get(expression);
1063
+ if (!failed) return false;
1064
+ failed.args.forEach((arg) => resolveArgument(arg, scope, unit));
1065
+ unit.errors.push(failed.error);
1066
+ return true;
262
1067
  };
263
1068
 
264
1069
  const resolveExpression = (
@@ -266,8 +1071,16 @@ const resolveExpression = (
266
1071
  scope: LocalName | undefined,
267
1072
  unit: Unit,
268
1073
  ): void => {
1074
+ if (selections.has(expression) && !unit.isGenerated) {
1075
+ resolveExpression(expression, scope, { ...unit, isGenerated: true });
1076
+ return;
1077
+ }
269
1078
  const resolveAll = (expressions: Expression[]) =>
270
1079
  expressions.forEach((child) => resolveExpression(child, scope, unit));
1080
+ const bindLabelParams = (names: string[]) => ({
1081
+ ...unit,
1082
+ labelParams: [...unit.labelParams, ...names],
1083
+ });
271
1084
  switch (expression.kind) {
272
1085
  case "Number":
273
1086
  case "Decimal":
@@ -275,11 +1088,14 @@ const resolveExpression = (
275
1088
  case "ExceptAt":
276
1089
  return;
277
1090
  case "Identifier": {
278
- const arity = getSymbolArity(expression, expression.name, scope, unit);
279
- if (arity > 0) {
280
- throw new TlaSyntaxError(
281
- `The operator ${expression.name} requires ${arity} arguments at line ${expression.location.line}, column ${expression.location.column}`,
282
- );
1091
+ if (isInstanceArityReported(expression, scope, unit)) return;
1092
+ const name = expression.name;
1093
+ const arity = getSymbolArity(expression, name, scope, unit);
1094
+ if (arity !== undefined && arity > 0) {
1095
+ unit.errors.push({
1096
+ location: formatRange(getSpelledNameRange(expression, name)),
1097
+ message: `The operator ${name} requires ${arity} arguments.`,
1098
+ });
283
1099
  }
284
1100
  return;
285
1101
  }
@@ -290,7 +1106,11 @@ const resolveExpression = (
290
1106
  resolveApply(expression, scope, unit);
291
1107
  return;
292
1108
  case "Lambda":
293
- resolveExpression(expression.body, bindNames(scope, expression.params), unit);
1109
+ resolveExpression(
1110
+ expression.body,
1111
+ bindNames(scope, expression.params, expression.paramRanges, unit),
1112
+ bindLabelParams(expression.params),
1113
+ );
294
1114
  return;
295
1115
  case "And":
296
1116
  case "Or":
@@ -313,24 +1133,32 @@ const resolveExpression = (
313
1133
  case "Let":
314
1134
  resolveExpression(
315
1135
  expression.body,
316
- resolveDefinitions(expression.definitions, scope, unit),
1136
+ resolveDefinitions(expression.definitions, scope, unit, expression.instances),
317
1137
  unit,
318
1138
  );
319
1139
  return;
320
1140
  case "Forall":
321
1141
  case "Exists":
322
1142
  case "FunctionConstruction":
323
- resolveExpression(expression.body, resolveBounds(expression.bounds, scope, unit), unit);
1143
+ resolveExpression(
1144
+ expression.body,
1145
+ resolveBounds(expression.bounds, scope, unit),
1146
+ bindLabelParams(getBoundNames(expression.bounds)),
1147
+ );
324
1148
  return;
325
1149
  case "UnboundedQuantifier":
326
- resolveExpression(expression.body, bindNames(scope, expression.names), unit);
1150
+ resolveExpression(
1151
+ expression.body,
1152
+ bindNames(scope, expression.names, expression.nameRanges, unit),
1153
+ bindLabelParams(expression.names),
1154
+ );
327
1155
  return;
328
1156
  case "Choose":
329
1157
  if (expression.set) resolveExpression(expression.set, scope, unit);
330
1158
  resolveExpression(
331
1159
  expression.body,
332
- bindNames(scope, getPatternNames(expression.pattern)),
333
- unit,
1160
+ bindNames(scope, getPatternNames(expression.pattern), expression.pattern.ranges, unit),
1161
+ bindLabelParams(getPatternNames(expression.pattern)),
334
1162
  );
335
1163
  return;
336
1164
  case "SetEnumeration":
@@ -338,31 +1166,40 @@ const resolveExpression = (
338
1166
  resolveAll(expression.elements);
339
1167
  return;
340
1168
  case "SetFilter":
341
- resolveExpression(expression.predicate, resolveBounds([expression.bound], scope, unit), unit);
1169
+ resolveExpression(
1170
+ expression.predicate,
1171
+ resolveBounds([expression.bound], scope, unit),
1172
+ bindLabelParams(getPatternNames(expression.bound.pattern)),
1173
+ );
342
1174
  return;
343
1175
  case "SetMap":
344
- resolveExpression(expression.expression, resolveBounds(expression.bounds, scope, unit), unit);
1176
+ resolveExpression(
1177
+ expression.expression,
1178
+ resolveBounds(expression.bounds, scope, unit),
1179
+ bindLabelParams(getBoundNames(expression.bounds)),
1180
+ );
345
1181
  return;
346
1182
  case "FunctionSet":
347
1183
  resolveAll([expression.domain, expression.range]);
348
1184
  return;
349
1185
  case "Record":
350
1186
  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}`,
354
- );
355
- }
356
- resolveAll(expression.fields.map((field) => field.value));
1187
+ expression.fields.forEach((field, index) => {
1188
+ if (expression.fields.slice(0, index).some((earlier) => earlier.name === field.name)) {
1189
+ unit.errors.push({
1190
+ location: formatRange(field.location.range ?? getNameRange(field.location, field.name)),
1191
+ message: "Non-unique fields in constructor.",
1192
+ });
1193
+ }
1194
+ resolveExpression(field.value, scope, unit);
1195
+ });
357
1196
  return;
358
1197
  case "Except":
359
- resolveAll([
360
- expression.function,
361
- ...expression.updates.flatMap((update) => [
362
- ...update.path.flatMap((step) => (step.kind === "Index" ? step.args : [])),
363
- update.value,
364
- ]),
365
- ]);
1198
+ resolveExpression(expression.function, scope, unit);
1199
+ expression.updates.forEach((update) => {
1200
+ resolveAll(update.path.flatMap((step) => (step.kind === "Index" ? step.args : [])));
1201
+ resolveExpression(update.value, scope, { ...unit, isInExcept: true });
1202
+ });
366
1203
  return;
367
1204
  case "FunctionApplication":
368
1205
  resolveAll([expression.function, ...expression.args]);
@@ -382,34 +1219,72 @@ const resolveExpression = (
382
1219
  resolveAll([expression.subscript, expression.action]);
383
1220
  return;
384
1221
  case "Label":
385
- resolveExpression(expression.body, scope, unit);
1222
+ if (isLabelReported(expression, unit)) return;
1223
+ resolveExpression(expression.body, scope, { ...unit, labelParams: [], labels: new Set() });
1224
+ checkLabel(expression, scope, unit);
386
1225
  return;
387
- case "Subexpression":
1226
+ case "Subexpression": {
1227
+ if (isSelectionReported(expression, scope, unit)) return;
388
1228
  expression.selectors
389
1229
  .flatMap((selector) => ("args" in selector ? selector.args : []))
390
1230
  .forEach((arg) => resolveArgument(arg, scope, unit));
1231
+ checkReference(expression, scope, unit, false);
1232
+ }
391
1233
  }
392
1234
  };
393
1235
 
1236
+ // Generator.generateUseOrHide looks up a fact that is a name as it looks up a name in an expression,
1237
+ // except that the name may select an ASSUME/PROVE or a NEW clause or name a theorem or assumption,
1238
+ // and analyzes any other fact as an expression.
1239
+ const checkFacts = (facts: Fact[], scope: LocalName | undefined, unit: Unit) =>
1240
+ facts.forEach((fact) => {
1241
+ if (
1242
+ fact.kind === "ModuleFact" ||
1243
+ isInstanceArityReported(fact, scope, unit) ||
1244
+ checkReference(fact, scope, unit, true)
1245
+ ) {
1246
+ return;
1247
+ }
1248
+ const name =
1249
+ fact.kind === "Identifier" ? fact.name : fact.kind === "Apply" ? fact.operator : "";
1250
+ if (!unit.facts.has(name)) resolveExpression(fact, scope, unit);
1251
+ });
1252
+
394
1253
  const resolveNewSymbol = (symbol: NewSymbol, scope: LocalName | undefined, unit: Unit) => {
395
1254
  if (symbol.set) resolveExpression(symbol.set, scope, unit);
396
- return { name: symbol.name, arity: symbol.arity, parent: scope };
1255
+ return bindName(
1256
+ scope,
1257
+ symbol.name,
1258
+ { kind: `New${symbol.level}`, arity: symbol.arity, range: symbol.nameRange },
1259
+ unit,
1260
+ );
397
1261
  };
398
1262
 
399
- // The NEW symbols of an ASSUME stay in scope for its conclusion and the proof that follows.
1263
+ // The NEW symbols of an ASSUME stay in scope for its conclusion and the proof that follows. SANY
1264
+ // forbids a label in the scope of a NEW in a nested ASSUME.
400
1265
  const resolveAssumeProve = (
401
1266
  assumeProve: AssumeProve,
402
1267
  scope: LocalName | undefined,
403
1268
  unit: Unit,
1269
+ isNested = false,
404
1270
  ): 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;
1271
+ const assumed = assumeProve.assumptions.reduce(
1272
+ (current, assumption) => {
1273
+ if (assumption.kind === "NewSymbol") {
1274
+ return {
1275
+ scope: resolveNewSymbol(assumption, current.scope, current.unit),
1276
+ unit: isNested ? { ...current.unit, isLabelForbidden: true } : current.unit,
1277
+ };
1278
+ }
1279
+ if (assumption.kind === "AssumeProve") {
1280
+ resolveAssumeProve(assumption, current.scope, current.unit, true);
1281
+ } else resolveExpression(assumption, current.scope, current.unit);
1282
+ return current;
1283
+ },
1284
+ { scope, unit },
1285
+ );
1286
+ resolveExpression(assumeProve.conclusion, assumed.scope, assumed.unit);
1287
+ return assumed.scope;
413
1288
  };
414
1289
 
415
1290
  const resolveStatement = (
@@ -424,371 +1299,524 @@ const resolveStatement = (
424
1299
 
425
1300
  // SANY resolves the expressions of a proof, while its facts and DEF clauses may also name
426
1301
  // theorems, assumptions, and modules.
427
- const resolveProof = (proof: Proof | undefined, scope: LocalName | undefined, unit: Unit) => {
1302
+ const resolveProof = (proof: Proof | undefined, scope: LocalName | undefined, outer: Unit) => {
1303
+ const unit = outer.hasLabelScope ? { ...outer, hasLabelScope: false } : outer;
1304
+ if (proof?.kind === "By") checkFacts(proof.facts, scope, unit);
428
1305
  if (proof?.kind !== "Steps") return;
429
1306
  proof.steps.reduce((current, step) => resolveStep(step, current, unit), scope);
430
1307
  };
431
1308
 
1309
+ // A LET or a step binds the name of the INSTANCE after the names it adds.
1310
+ const resolveLocalInstance = (instance: Instance, scope: LocalName | undefined, unit: Unit) => {
1311
+ const instanced = resolveInstance(instance, scope, unit);
1312
+ return instance.name === undefined
1313
+ ? instanced
1314
+ : bindName(
1315
+ instanced,
1316
+ instance.name,
1317
+ { kind: "Instance", arity: instance.params.length, range: instance.location.range },
1318
+ unit,
1319
+ );
1320
+ };
1321
+
1322
+ // Generator.generateProof binds the name of a step after its statement and before its proof, or
1323
+ // after the step where it takes no proof.
432
1324
  const resolveStep = (
433
1325
  step: ProofStep,
434
1326
  scope: LocalName | undefined,
435
1327
  unit: Unit,
436
1328
  ): LocalName | undefined => {
437
1329
  const body = step.body;
1330
+ const stepUnit =
1331
+ step.name === undefined
1332
+ ? unit
1333
+ : { ...unit, hasLabelScope: true, labelParams: [], labels: new Set<string>() };
1334
+ const bindStep = (parent: LocalName | undefined): LocalName | undefined =>
1335
+ step.name === undefined ? parent : { name: step.name, arity: 0, kind: "Theorem", parent };
438
1336
  switch (body.kind) {
1337
+ // The NEW symbols of a SUFFICES ASSUME are in scope after its proof, and those of any other
1338
+ // ASSUME in its proof.
439
1339
  case "Assert": {
440
- const assumed = resolveStatement(body.statement, scope, unit);
441
- resolveProof(step.proof, assumed, unit);
442
- return body.isSuffices ? assumed : scope;
1340
+ const assumed = resolveStatement(body.statement, scope, stepUnit);
1341
+ const proofScope = body.isSuffices ? scope : assumed;
1342
+ const name = step.name;
1343
+ if (name === undefined) {
1344
+ resolveProof(step.proof, proofScope, unit);
1345
+ return body.isSuffices ? assumed : scope;
1346
+ }
1347
+ const goal = { statement: body.statement, isSuffices: body.isSuffices, isInProof: true };
1348
+ resolveProof(step.proof, { name, arity: 0, kind: "Theorem", parent: proofScope, goal }, unit);
1349
+ goal.isInProof = false;
1350
+ return { name, arity: 0, kind: "Theorem", parent: body.isSuffices ? assumed : scope, goal };
443
1351
  }
1352
+ case "Use":
1353
+ case "Hide":
1354
+ checkFacts(body.facts, scope, unit);
1355
+ return bindStep(scope);
1356
+ case "Instance":
1357
+ return bindStep(resolveLocalInstance(body, scope, stepUnit));
444
1358
  case "Define":
445
- return resolveDefinitions(
446
- body.definitions.flatMap((definition) =>
447
- definition.kind === "Instance" ? [] : [definition],
1359
+ return bindStep(
1360
+ body.definitions.reduce(
1361
+ (current, definition) =>
1362
+ definition.kind === "Instance"
1363
+ ? resolveLocalInstance(definition, current, stepUnit)
1364
+ : resolveDefinitions([definition], current, unit),
1365
+ scope,
448
1366
  ),
449
- scope,
450
- unit,
451
1367
  );
452
1368
  case "Have":
453
1369
  case "Case":
454
- resolveExpression(body.expression, scope, unit);
455
- resolveProof(step.proof, scope, unit);
456
- return scope;
1370
+ resolveExpression(body.expression, scope, stepUnit);
1371
+ resolveProof(step.proof, bindStep(scope), unit);
1372
+ return bindStep(scope);
457
1373
  case "Witness":
458
- body.expressions.forEach((expression) => resolveExpression(expression, scope, unit));
459
- return scope;
1374
+ body.expressions.forEach((expression) => resolveExpression(expression, scope, stepUnit));
1375
+ return bindStep(scope);
460
1376
  case "Take":
461
- return bindNames(resolveBounds(body.bounds, scope, unit), body.names);
1377
+ return bindStep(
1378
+ bindNames(
1379
+ resolveBounds(body.bounds, scope, stepUnit),
1380
+ body.names,
1381
+ body.nameRanges,
1382
+ stepUnit,
1383
+ ),
1384
+ );
462
1385
  case "Pick": {
463
- const picked = bindNames(resolveBounds(body.bounds, scope, unit), body.names);
464
- resolveExpression(body.body, picked, unit);
465
- resolveProof(step.proof, scope, unit);
466
- return picked;
1386
+ const picked = bindNames(
1387
+ resolveBounds(body.bounds, scope, stepUnit),
1388
+ body.names,
1389
+ body.nameRanges,
1390
+ stepUnit,
1391
+ );
1392
+ resolveExpression(body.body, picked, {
1393
+ ...stepUnit,
1394
+ labelParams: [...stepUnit.labelParams, ...getBoundNames(body.bounds), ...body.names],
1395
+ });
1396
+ resolveProof(step.proof, bindStep(scope), unit);
1397
+ return bindStep(picked);
467
1398
  }
468
1399
  default:
469
- resolveProof(step.proof, scope, unit);
470
- return scope;
1400
+ resolveProof(step.proof, bindStep(scope), unit);
1401
+ return bindStep(scope);
471
1402
  }
472
1403
  };
473
1404
 
1405
+ // SANY binds the name of a theorem after its statement and before its proof.
474
1406
  const resolveTheorem = (theorem: Theorem, unit: Unit) => {
475
1407
  const isDefinition = theorem.name !== undefined && theorem.statement.kind !== "AssumeProve";
476
1408
  const scope = isDefinition ? undefined : resolveStatement(theorem.statement, undefined, unit);
1409
+ if (theorem.name !== undefined) {
1410
+ bindModuleName(
1411
+ theorem.name,
1412
+ { kind: "Theorem", arity: 0, range: theorem.location.range },
1413
+ unit,
1414
+ );
1415
+ }
1416
+ const goal = unit.goals.get(theorem.name ?? "");
1417
+ if (goal) goal.isInProof = true;
477
1418
  resolveProof(theorem.proof, scope, unit);
1419
+ if (goal) goal.isInProof = false;
478
1420
  };
479
1421
 
480
- interface ModuleUnit {
481
- imported: Symbols;
482
- importedAt: Map<string, SourceLocation>;
483
- definitions: Map<string, Definition>;
484
- getKey: (definition: Definition) => string;
1422
+ // The declarations of the module an INSTANCE instantiates, the names the INSTANCE adds, and the
1423
+ // module that instantiates it.
1424
+ export interface InstancedModule {
1425
+ declarations: Declaration[];
1426
+ symbols: Symbols;
1427
+ instancer: string;
485
1428
  }
486
1429
 
487
- interface ModuleName {
488
- name: string;
489
- kind: "Definition" | "Constant" | "Variable";
1430
+ // What SANY reports at a location as it links a module, such as a conflict between the modules it
1431
+ // extends.
1432
+ export interface ModuleReport {
490
1433
  location: SourceLocation;
491
- isRecursive: boolean;
1434
+ errors: SanyError[];
1435
+ warnings: SanyError[];
492
1436
  }
493
1437
 
494
- type IsDefined = (name: string) => boolean;
1438
+ // bound holds the names in scope where the module starts: the built-in operators, the names of the
1439
+ // module that encloses it, and those of the modules it extends. instanced holds the names each
1440
+ // INSTANCE adds, getInstance what an INSTANCE in a LET or a proof instantiates, facts the theorems
1441
+ // and assumptions the modules it extends or instantiates export, and warnings the warnings SANY
1442
+ // reports for the spec.
1443
+ export interface ModuleUnit {
1444
+ imported: Symbols;
1445
+ getInstance: (instance: Instance) => InstancedModule;
1446
+ bound: Symbols;
1447
+ definitions: Map<string, Definition>;
1448
+ getKey: (definition: Definition) => string;
1449
+ instanced: Map<Instance, Symbols>;
1450
+ facts: Set<string>;
1451
+ reports: ModuleReport[];
1452
+ warnings: SanyError[];
1453
+ }
495
1454
 
496
- const createRedefinitionError = (name: string, location: SourceLocation) =>
497
- new TlaSyntaxError(
498
- `Multiply-defined symbol '${name}' at line ${location.line}, column ${location.column}`,
499
- );
1455
+ export const MODULE_START: SourceLocation = { line: 0, column: 0 };
500
1456
 
501
- const bindUnique = (
502
- scope: LocalName | undefined,
503
- names: string[],
504
- isDefined: IsDefined,
505
- location: SourceLocation,
506
- ) =>
507
- names.reduce<LocalName | undefined>((parent, name) => {
508
- if (lookupLocal(parent, name) || isDefined(name)) throw createRedefinitionError(name, location);
509
- return { name, arity: 0, parent };
510
- }, scope);
1457
+ // A named theorem or assumption is linked as a definition too.
1458
+ export const isTheoremDefinition = (module: Module, definition: Definition) =>
1459
+ [...module.theorems, ...module.assumptions].some(
1460
+ (item) =>
1461
+ item.name === definition.name &&
1462
+ item.location.line === definition.location.line &&
1463
+ item.location.column === definition.location.column,
1464
+ );
511
1465
 
512
- const checkBoundNames = (
513
- bounds: Bound[],
514
- scope: LocalName | undefined,
515
- isDefined: IsDefined,
516
- location: SourceLocation,
517
- ) => {
518
- bounds.forEach((bound) => checkNames(bound.set, scope, isDefined));
519
- return bounds.reduce(
520
- (current, bound) => bindUnique(current, getPatternNames(bound.pattern), isDefined, location),
521
- scope,
1466
+ const createSymbols = (module: Module, imported: Symbols) => {
1467
+ const symbols = new Map([...CORE_SYMBOLS, ...imported]);
1468
+ module.constants.forEach((constant) =>
1469
+ symbols.set(constant.name, { key: constant.name, arity: constant.arity, kind: "Constant" }),
1470
+ );
1471
+ module.variables.forEach((variable) =>
1472
+ symbols.set(variable.name, { key: variable.name, arity: 0, kind: "Variable" }),
522
1473
  );
1474
+ return symbols;
523
1475
  };
524
1476
 
525
- const checkDefinitionNames = (
526
- definition: Definition,
527
- scope: LocalName | undefined,
528
- isDefined: IsDefined,
1477
+ // Generator.processSubst analyzes the explicit substitutions in the order they appear, then the
1478
+ // implicit ones, and then reports each declaration left without one. The parameters of the INSTANCE
1479
+ // are in scope.
1480
+ const checkSubstitutions = (
1481
+ instance: Instance,
1482
+ declarations: Declaration[],
1483
+ instancer: string,
1484
+ outer: LocalName | undefined,
1485
+ unit: Unit,
529
1486
  ) => {
530
- if (definition.kind === "Function") {
531
- const self = bindNames(scope, [definition.name]);
532
- const bound = checkBoundNames(definition.bounds, self, isDefined, definition.location);
533
- checkNames(definition.body, bound, isDefined);
534
- return;
535
- }
536
- const params = bindUnique(
537
- scope,
538
- definition.params.map((param) => param.name),
539
- isDefined,
540
- definition.location,
1487
+ const scope = instance.params.reduce<LocalName | undefined>(
1488
+ (parent, param) => ({ name: param.name, arity: param.arity, kind: "Parameter", parent }),
1489
+ outer,
541
1490
  );
542
- checkNames(definition.body, params, isDefined);
543
- };
544
-
545
- const checkNames = (
546
- expression: Expression,
547
- scope: LocalName | undefined,
548
- isDefined: IsDefined,
549
- ): void => {
550
- const location = expression.location;
551
- switch (expression.kind) {
552
- case "Lambda":
553
- checkNames(
554
- expression.body,
555
- bindUnique(scope, expression.params, isDefined, location),
556
- isDefined,
557
- );
558
- return;
559
- case "Let": {
560
- const recursive = expression.definitions
561
- .filter((definition) => definition.isRecursive)
562
- .map((definition) => definition.name);
563
- const inner = expression.definitions.reduce((current, definition) => {
564
- if (lookupLocal(current, definition.name) || isDefined(definition.name)) {
565
- throw createRedefinitionError(definition.name, definition.location);
566
- }
567
- checkDefinitionNames(definition, bindNames(current, recursive), isDefined);
568
- return bindNames(current, [definition.name]);
569
- }, scope);
570
- checkNames(
571
- expression.body,
572
- bindUnique(
573
- inner,
574
- (expression.instances ?? []).flatMap((instance) =>
575
- instance.name === undefined ? [] : [instance.name],
576
- ),
577
- isDefined,
578
- location,
579
- ),
580
- isDefined,
581
- );
1491
+ const resolveSubstitute = (declaration: Declaration, expression: Expression) => {
1492
+ if (declaration.arity === 0 || expression.kind !== "Identifier") {
1493
+ resolveExpression(expression, scope, unit);
582
1494
  return;
583
1495
  }
584
- case "Forall":
585
- case "Exists":
586
- case "FunctionConstruction":
587
- checkNames(
588
- expression.body,
589
- checkBoundNames(expression.bounds, scope, isDefined, location),
590
- isDefined,
591
- );
592
- return;
593
- case "SetFilter":
594
- checkNames(
595
- expression.predicate,
596
- checkBoundNames([expression.bound], scope, isDefined, location),
597
- isDefined,
598
- );
599
- return;
600
- case "SetMap":
601
- checkNames(
602
- expression.expression,
603
- checkBoundNames(expression.bounds, scope, isDefined, location),
604
- isDefined,
605
- );
606
- return;
607
- case "UnboundedQuantifier":
608
- checkNames(
609
- expression.body,
610
- bindUnique(scope, expression.names, isDefined, location),
611
- isDefined,
612
- );
613
- return;
614
- case "Choose":
615
- if (expression.set) checkNames(expression.set, scope, isDefined);
616
- checkNames(
617
- expression.body,
618
- bindUnique(scope, getPatternNames(expression.pattern), isDefined, location),
619
- isDefined,
1496
+ const arity = getSymbolArity(expression, expression.name, scope, unit);
1497
+ if (arity !== undefined && arity !== declaration.arity) {
1498
+ throw new TlaSyntaxError(
1499
+ `An operator must be substituted for symbol '${declaration.name}', and it must have arity ${declaration.arity} in the instance of ${instance.module} at line ${instance.location.line}, column ${instance.location.column}`,
620
1500
  );
621
- return;
622
- default:
623
- getChildren(expression).forEach((child) => checkNames(child, scope, isDefined));
624
- }
625
- };
626
-
627
- const getModuleNames = (module: Module) => [
628
- ...module.definitions.map((definition): ModuleName => ({
629
- name: definition.name,
630
- kind: "Definition",
631
- location: definition.location,
632
- isRecursive: definition.isRecursive,
633
- })),
634
- ...module.instances.flatMap((instance): ModuleName[] =>
635
- instance.name === undefined
636
- ? []
637
- : [
638
- {
639
- name: instance.name,
640
- kind: "Definition",
641
- location: instance.location,
642
- isRecursive: false,
643
- },
644
- ],
645
- ),
646
- ...module.constants.map((constant): ModuleName => ({
647
- name: constant.name,
648
- kind: "Constant",
649
- location: constant.location,
650
- isRecursive: false,
651
- })),
652
- ...module.variables.map((variable): ModuleName => ({
653
- name: variable.name,
654
- kind: "Variable",
655
- location: variable.location,
656
- isRecursive: false,
657
- })),
658
- ];
659
-
660
- export const checkRedefinitions = (module: Module, unit: ModuleUnit) => {
661
- const byName = new Map<string, ModuleName[]>();
662
- getModuleNames(module)
663
- .sort((left, right) => (isBefore(left.location, right.location) ? -1 : 1))
664
- .forEach((entry) => byName.set(entry.name, [...(byName.get(entry.name) ?? []), entry]));
665
- const isImportedBefore = (name: string, location: SourceLocation) => {
666
- if (!unit.imported.has(name) && !CORE_SYMBOLS.has(name)) return false;
667
- const importedAt = unit.importedAt.get(name);
668
- return importedAt === undefined || isBefore(importedAt, location);
1501
+ }
669
1502
  };
670
- byName.forEach((entries) =>
671
- entries.forEach((entry, index) => {
672
- const isDuplicate = entries
673
- .slice(0, index)
674
- .some(
675
- (earlier) =>
676
- earlier.kind === "Definition" ||
677
- entry.kind === "Definition" ||
678
- earlier.kind !== entry.kind,
679
- );
680
- // A module may declare again a constant or variable that it extends or that encloses it.
681
- const isRedeclared = unit.imported.get(entry.name)?.declaration === entry.kind;
682
- if (isDuplicate || (!isRedeclared && isImportedBefore(entry.name, entry.location)))
683
- throw createRedefinitionError(entry.name, entry.location);
684
- }),
685
- );
686
- const getIsDefined =
687
- (location: SourceLocation): IsDefined =>
688
- (name) =>
689
- (byName.get(name) ?? []).some(
690
- (entry) => entry.isRecursive || isBefore(entry.location, location),
691
- ) || isImportedBefore(name, location);
692
- module.definitions.forEach((definition) =>
693
- checkDefinitionNames(definition, undefined, getIsDefined(definition.location)),
694
- );
695
- module.assumptions.forEach((assumption) =>
696
- checkNames(assumption.expression, undefined, getIsDefined(assumption.location)),
697
- );
698
- module.instances.forEach((instance) => {
699
- const isDefined = getIsDefined(instance.location);
700
- const params = bindUnique(
701
- undefined,
702
- instance.params.map((param) => param.name),
703
- isDefined,
704
- instance.location,
705
- );
706
- instance.substitutions.forEach((substitution) =>
707
- checkNames(substitution.expression, params, isDefined),
708
- );
1503
+ const substitutions = new Map<string, Expression>();
1504
+ instance.substitutions.forEach((substitution) => {
1505
+ const name = substitution.name;
1506
+ const declaration = declarations.find((item) => item.name === name);
1507
+ if (!declaration) {
1508
+ unit.errors.push({
1509
+ location: formatRange(substitution.nameRange),
1510
+ message: `Identifier '${name}' is not a legal target of a substitution. \nA legal target must be a declared CONSTANT or VARIABLE in the module being instantiated. \n(Also, check for warnings about multiple declarations of this same identifier.)`,
1511
+ });
1512
+ return;
1513
+ }
1514
+ const expression = substitution.expression;
1515
+ resolveSubstitute(declaration, expression);
1516
+ const range = expression.location.range;
1517
+ if (!substitutions.has(name)) substitutions.set(name, expression);
1518
+ else if (range) {
1519
+ unit.errors.push({
1520
+ location: formatRange(range),
1521
+ message: `Multiple substitutions for symbol '${name}' in substitution.`,
1522
+ });
1523
+ }
1524
+ });
1525
+ const implicit = declarations.filter((declaration) => !substitutions.has(declaration.name));
1526
+ const isMissing = (declaration: Declaration) =>
1527
+ !lookupLocal(scope, declaration.name) && !findSymbol(declaration.name, unit);
1528
+ implicit
1529
+ .filter((declaration) => !isMissing(declaration))
1530
+ .forEach((declaration) => {
1531
+ const expression: Expression = {
1532
+ kind: "Identifier",
1533
+ name: declaration.name,
1534
+ location: instance.location,
1535
+ };
1536
+ resolveSubstitute(declaration, expression);
1537
+ substitutions.set(declaration.name, expression);
1538
+ });
1539
+ implicit.filter(isMissing).forEach((declaration) => {
1540
+ const range = instance.location.range;
1541
+ const declared = declaration.location.range;
1542
+ if (range && declared) {
1543
+ unit.errors.push({
1544
+ location: formatRange(range),
1545
+ message: `Substitution missing for symbol ${declaration.name} declared at ${formatRange(declared)} \nand instantiated in module ${instancer}.`,
1546
+ });
1547
+ }
709
1548
  });
1549
+ return substitutions;
710
1550
  };
711
1551
 
712
- const createSymbols = (module: Module, imported: Symbols) => {
713
- const symbols = new Map([...CORE_SYMBOLS, ...imported]);
714
- module.constants.forEach((constant) =>
715
- symbols.set(constant.name, { key: constant.name, arity: constant.arity }),
716
- );
717
- module.variables.forEach((variable) =>
718
- symbols.set(variable.name, { key: variable.name, arity: 0 }),
1552
+ // Generator.processSubst analyzes an INSTANCE in a LET or a proof, which then binds the names the
1553
+ // INSTANCE adds.
1554
+ const resolveInstance = (instance: Instance, scope: LocalName | undefined, unit: Unit) => {
1555
+ const instanced = unit.getInstance(instance);
1556
+ checkSubstitutions(instance, instanced.declarations, instanced.instancer, scope, unit);
1557
+ return [...instanced.symbols].reduce(
1558
+ (parent, [name, symbol]) => bindName(parent, name, symbol, unit),
1559
+ scope,
719
1560
  );
720
- return symbols;
721
1561
  };
722
1562
 
1563
+ // tla-ts reports what SANY goes on after with an INSTANCE of the module.
723
1564
  export const resolveSubstitutions = (
724
1565
  instance: Instance,
725
- declarations: OperatorParam[],
1566
+ declarations: Declaration[],
726
1567
  module: Module,
727
1568
  unit: ModuleUnit,
728
1569
  ) => {
729
- const scope = bindParams(undefined, instance.params);
730
- const context: Unit = {
731
- imported: createSymbols(module, unit.imported),
1570
+ const imported = createSymbols(module, unit.imported);
1571
+ const report: ModuleReport = { location: instance.location, errors: [], warnings: [] };
1572
+ unit.reports.push(report);
1573
+ return checkSubstitutions(instance, declarations, module.name, undefined, {
1574
+ imported,
1575
+ getInstance: unit.getInstance,
732
1576
  definitions: unit.definitions,
733
1577
  getKey: unit.getKey,
734
1578
  location: instance.location,
735
1579
  self: undefined,
736
1580
  facts: new Set(),
737
- };
738
- const explicit = new Map(instance.substitutions.map((item) => [item.name, item.expression]));
739
- const position = `in the instance of ${instance.module} at line ${instance.location.line}, column ${instance.location.column}`;
740
- explicit.forEach((_, name) => {
741
- if (declarations.every((declaration) => declaration.name !== name)) {
742
- throw new TlaSyntaxError(
743
- `Identifier '${name}' is not a legal target of a substitution ${position}`,
744
- );
745
- }
1581
+ goals: new Map(),
1582
+ bindings: new Map(
1583
+ [...imported].map(([name, symbol]) => [name, { ...symbol, position: MODULE_START }]),
1584
+ ),
1585
+ errors: report.errors,
1586
+ warnings: report.warnings,
1587
+ hasLabelScope: false,
1588
+ isLabelForbidden: false,
1589
+ isInExcept: false,
1590
+ labelParams: [],
1591
+ labels: new Set(),
1592
+ isGenerated: false,
746
1593
  });
747
- return new Map(
748
- declarations.map((declaration): [string, Expression] => {
749
- const name = declaration.name;
750
- if (!explicit.has(name) && !lookupLocal(scope, name) && !findSymbol(name, context)) {
751
- throw new TlaSyntaxError(`Substitution missing for symbol ${name} ${position}`);
752
- }
753
- const expression: Expression = explicit.get(name) ?? {
754
- kind: "Identifier",
755
- name,
756
- location: instance.location,
757
- };
758
- if (declaration.arity === 0 || expression.kind !== "Identifier") {
759
- resolveExpression(expression, scope, context);
760
- return [name, expression];
761
- }
762
- if (getSymbolArity(expression, expression.name, scope, context) !== declaration.arity) {
763
- throw new TlaSyntaxError(
764
- `An operator must be substituted for symbol '${name}', and it must have arity ${declaration.arity} ${position}`,
765
- );
1594
+ };
1595
+
1596
+ // SANY reports the errors of every unit it checks, in the order of the units in the module, after
1597
+ // the warnings it reports for the spec. A unit reports to its lists what SANY goes on after, and
1598
+ // throws the error that stops it. An error tla-ts cannot word as SANY does yields to the errors the
1599
+ // unit reported before it. Returns the errors.
1600
+ export const collectSemanticErrors = (
1601
+ units: {
1602
+ location: SourceLocation;
1603
+ check: (reported: SanyError[], warned: SanyError[]) => void;
1604
+ }[],
1605
+ warnings: SanyError[],
1606
+ ) => {
1607
+ const errors: SanyError[] = [];
1608
+ const add = (list: SanyError[], item: SanyError) => {
1609
+ if (
1610
+ list.every(
1611
+ (existing) => existing.location !== item.location || existing.message !== item.message,
1612
+ )
1613
+ ) {
1614
+ list.push(item);
1615
+ }
1616
+ };
1617
+ units
1618
+ .toSorted((left, right) =>
1619
+ isBefore(left.location, right.location)
1620
+ ? -1
1621
+ : isBefore(right.location, left.location)
1622
+ ? 1
1623
+ : 0,
1624
+ )
1625
+ .forEach((unit) => {
1626
+ const reported: SanyError[] = [];
1627
+ const warned: SanyError[] = [];
1628
+ try {
1629
+ unit.check(reported, warned);
1630
+ } catch (error) {
1631
+ if (!(error instanceof TlaSyntaxError) || (!error.sany && reported.length === 0)) {
1632
+ throw error;
1633
+ }
1634
+ reported.push(...(error.sany?.errors ?? []));
766
1635
  }
767
- return [name, expression];
768
- }),
769
- );
1636
+ reported.forEach((item) => add(errors, item));
1637
+ warned.forEach((item) => add(warnings, item));
1638
+ });
1639
+ return errors;
770
1640
  };
771
1641
 
1642
+ // SANY binds the names of a module in the order of its units, and reports a RECURSIVE declaration
1643
+ // that no definition follows at the end. Returns the errors.
772
1644
  export const resolveModule = (module: Module, unit: ModuleUnit) => {
773
1645
  const symbols = createSymbols(module, unit.imported);
774
- const facts = new Set(
775
- [...module.theorems, ...module.assumptions].flatMap((fact) => fact.name ?? []),
1646
+ const facts = new Set([
1647
+ ...unit.facts,
1648
+ ...[...module.theorems, ...module.assumptions].flatMap((fact) => fact.name ?? []),
1649
+ ]);
1650
+ const goals = new Map(
1651
+ module.theorems.flatMap((theorem): [string, Goal][] =>
1652
+ theorem.name !== undefined && theorem.statement.kind === "AssumeProve"
1653
+ ? [[theorem.name, { statement: theorem.statement, isSuffices: false, isInProof: false }]]
1654
+ : [],
1655
+ ),
776
1656
  );
777
- const createUnit = (location: SourceLocation, self: Definition | undefined) => ({
1657
+ const bindings = new Map<string, ModuleBinding>(
1658
+ [...CORE_SYMBOLS, ...unit.bound].map(([name, symbol]) => [
1659
+ name,
1660
+ { ...symbol, position: MODULE_START },
1661
+ ]),
1662
+ );
1663
+ const recursive = new Set<Binding>();
1664
+ const declarations: { declaration: Declaration; binding: ModuleBinding | undefined }[] = [];
1665
+ const createUnit = (
1666
+ location: SourceLocation,
1667
+ self: Definition | undefined,
1668
+ errors: SanyError[],
1669
+ warnings: SanyError[],
1670
+ hasLabelScope: boolean,
1671
+ ): Unit => ({
778
1672
  imported: symbols,
1673
+ getInstance: unit.getInstance,
779
1674
  definitions: unit.definitions,
780
1675
  getKey: unit.getKey,
781
1676
  location,
782
1677
  self,
783
1678
  facts,
1679
+ goals,
1680
+ bindings,
1681
+ errors,
1682
+ warnings,
1683
+ hasLabelScope,
1684
+ isLabelForbidden: false,
1685
+ isInExcept: false,
1686
+ labelParams: [],
1687
+ labels: new Set(),
1688
+ isGenerated: false,
784
1689
  });
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)),
1690
+ const bindDeclarations = (declarations: Declaration[], kind: "Constant" | "Variable") =>
1691
+ declarations.map((declaration) => ({
1692
+ location: declaration.location,
1693
+ check: (errors: SanyError[], warnings: SanyError[]) =>
1694
+ bindModuleName(
1695
+ declaration.name,
1696
+ { kind, arity: declaration.arity, range: declaration.location.range },
1697
+ createUnit(declaration.location, undefined, errors, warnings, false),
1698
+ ),
1699
+ }));
1700
+ return collectSemanticErrors(
1701
+ [
1702
+ ...unit.reports.map((report) => ({
1703
+ location: report.location,
1704
+ check: (errors: SanyError[], warnings: SanyError[]) => {
1705
+ errors.push(...report.errors);
1706
+ warnings.push(...report.warnings);
1707
+ },
1708
+ })),
1709
+ ...bindDeclarations(module.constants, "Constant"),
1710
+ ...bindDeclarations(module.variables, "Variable"),
1711
+ ...module.units
1712
+ .flatMap((item) => (item.kind === "Recursive" ? item.declarations : []))
1713
+ .map((declaration) => ({
1714
+ location: declaration.location,
1715
+ check: (errors: SanyError[], warnings: SanyError[]) => {
1716
+ const binding: ModuleBinding = {
1717
+ kind: "Definition",
1718
+ arity: declaration.arity,
1719
+ range: declaration.location.range,
1720
+ position: declaration.location,
1721
+ isPending: true,
1722
+ };
1723
+ const isBound = isBindable(
1724
+ declaration.name,
1725
+ bindings.get(declaration.name),
1726
+ binding,
1727
+ createUnit(declaration.location, undefined, errors, warnings, false),
1728
+ );
1729
+ if (isBound) {
1730
+ bindings.set(declaration.name, binding);
1731
+ recursive.add(binding);
1732
+ }
1733
+ declarations.push({ declaration, binding: isBound ? binding : undefined });
1734
+ },
1735
+ })),
1736
+ ...module.definitions.map((definition) => ({
1737
+ location: definition.location,
1738
+ check: (errors: SanyError[], warnings: SanyError[]) => {
1739
+ const inner = createUnit(definition.location, definition, errors, warnings, true);
1740
+ if (isTheoremDefinition(module, definition)) {
1741
+ resolveExpression(definition.body, undefined, inner);
1742
+ } else if (resolveDefinition(definition, undefined, inner, recursive)) {
1743
+ bindings.set(definition.name, {
1744
+ kind: "Definition",
1745
+ arity: getArity(definition),
1746
+ range: definition.location.range,
1747
+ position: definition.location,
1748
+ });
1749
+ }
1750
+ },
1751
+ })),
1752
+ ...module.instances.map((instance) => ({
1753
+ location: instance.location,
1754
+ check: (errors: SanyError[], warnings: SanyError[]) => {
1755
+ const inner = createUnit(instance.location, undefined, errors, warnings, false);
1756
+ bindParams(undefined, instance.params, inner);
1757
+ unit.instanced
1758
+ .get(instance)
1759
+ ?.forEach((symbol, name) => bindModuleName(name, symbol, inner));
1760
+ if (instance.name !== undefined) {
1761
+ bindModuleName(
1762
+ instance.name,
1763
+ { kind: "Instance", arity: instance.params.length, range: instance.location.range },
1764
+ inner,
1765
+ );
1766
+ }
1767
+ },
1768
+ })),
1769
+ ...module.assumptions.map((assumption) => ({
1770
+ location: assumption.location,
1771
+ check: (errors: SanyError[], warnings: SanyError[]) => {
1772
+ const inner = createUnit(
1773
+ assumption.location,
1774
+ undefined,
1775
+ errors,
1776
+ warnings,
1777
+ assumption.name !== undefined,
1778
+ );
1779
+ resolveExpression(assumption.expression, undefined, inner);
1780
+ if (assumption.name !== undefined) {
1781
+ bindModuleName(
1782
+ assumption.name,
1783
+ { kind: "Theorem", arity: 0, range: assumption.location.range },
1784
+ inner,
1785
+ );
1786
+ }
1787
+ },
1788
+ })),
1789
+ ...module.theorems.map((theorem) => ({
1790
+ location: theorem.location,
1791
+ check: (errors: SanyError[], warnings: SanyError[]) =>
1792
+ resolveTheorem(
1793
+ theorem,
1794
+ createUnit(theorem.location, undefined, errors, warnings, theorem.name !== undefined),
1795
+ ),
1796
+ })),
1797
+ ...module.uses.map((use) => ({
1798
+ location: use.location,
1799
+ check: (errors: SanyError[], warnings: SanyError[]) =>
1800
+ checkFacts(
1801
+ use.facts,
1802
+ undefined,
1803
+ createUnit(use.location, undefined, errors, warnings, false),
1804
+ ),
1805
+ })),
1806
+ {
1807
+ location: module.location.range?.end ?? module.location,
1808
+ check: (errors: SanyError[]) =>
1809
+ declarations.forEach((item) => {
1810
+ const range = item.declaration.location.range;
1811
+ if (range && (!item.binding || item.binding.isPending)) {
1812
+ errors.push({
1813
+ location: formatRange(range),
1814
+ message: `Symbol ${item.declaration.name} declared in RECURSIVE statement but not defined.`,
1815
+ });
1816
+ }
1817
+ }),
1818
+ },
1819
+ ],
1820
+ unit.warnings,
793
1821
  );
794
1822
  };