tla-ts 0.0.3-dev.3504663 → 0.0.3-dev.3539317

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