tla-ts 0.0.3-dev.cf3b82c → 0.0.3-dev.cfd469d

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,33 +4,77 @@ 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;
32
66
  }
33
67
 
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. isGenerated holds in a definition tla-ts generates for a LET INSTANCE.
34
78
  interface Unit {
35
79
  imported: Symbols;
36
80
  definitions: Map<string, Definition>;
@@ -38,8 +82,23 @@ interface Unit {
38
82
  location: SourceLocation;
39
83
  self: Definition | undefined;
40
84
  facts: Set<string>;
85
+ goals: Map<string, Goal>;
86
+ bindings: Map<string, ModuleBinding>;
87
+ errors: SanyError[];
88
+ warnings: SanyError[];
89
+ hasLabelScope: boolean;
90
+ isLabelForbidden: boolean;
91
+ isGenerated: boolean;
92
+ }
93
+
94
+ interface SelectionState {
95
+ node: Expression | NewSymbol | AssumeProve;
96
+ isGoal: boolean;
97
+ isSufficesOpen: boolean;
41
98
  }
42
99
 
100
+ type Reference = Expression & { kind: "Identifier" | "Apply" | "Subexpression" };
101
+
43
102
  export const LOCAL_RESOLUTION = { kind: "Local" } as const;
44
103
 
45
104
  const renamedArities = new WeakMap<Expression, number>();
@@ -53,7 +112,7 @@ const isKey = (name: string) => {
53
112
  };
54
113
 
55
114
  const CORE_SYMBOLS: Symbols = new Map(
56
- ["~>", "-+->", "\\cdot"].map((name) => [name, { key: name, arity: 2 }]),
115
+ ["~>", "-+->", "\\cdot"].map((name) => [name, { key: name, arity: 2, kind: "Builtin" }]),
57
116
  );
58
117
 
59
118
  export const isBefore = (left: SourceLocation, right: SourceLocation) =>
@@ -62,6 +121,9 @@ export const isBefore = (left: SourceLocation, right: SourceLocation) =>
62
121
  export const getArity = (definition: Definition) =>
63
122
  definition.kind === "Operator" ? definition.params.length : 0;
64
123
 
124
+ export const getParamArities = (definition: Definition) =>
125
+ definition.kind === "Operator" ? definition.params.map((param) => param.arity) : [];
126
+
65
127
  const isInstantiated = (definition: Definition) => definition.name.includes("!");
66
128
 
67
129
  const lookupLocal = (scope: LocalName | undefined, name: string) => {
@@ -71,12 +133,99 @@ const lookupLocal = (scope: LocalName | undefined, name: string) => {
71
133
  return undefined;
72
134
  };
73
135
 
74
- const bindNames = (scope: LocalName | undefined, names: string[], arity = 0) =>
75
- names.reduce<LocalName | undefined>((parent, name) => ({ name, arity, parent }), scope);
136
+ // A name the module binds before the unit and before the range, which a copy of a subexpression
137
+ // that a reference selects keeps from its definition.
138
+ const getModuleBinding = (name: string, unit: Unit, range: SourceRange | undefined) => {
139
+ const binding = unit.bindings.get(name);
140
+ return binding &&
141
+ isBefore(binding.position, unit.location) &&
142
+ (!range || isBefore(binding.position, range.start))
143
+ ? binding
144
+ : undefined;
145
+ };
146
+
147
+ const isSameRange = (left: SourceRange | undefined, right: SourceRange | undefined) =>
148
+ left !== undefined && right !== undefined && formatRange(left) === formatRange(right);
149
+
150
+ // SymbolTable.addSymbol binds a name nothing binds yet. It rejects a built-in operator, a parameter
151
+ // or bound name already in use, and a symbol of another kind or arity than the one bound, and warns
152
+ // of any other duplicate. tla-ts binds a symbol SANY never sees, such as one it generates. Tells
153
+ // whether to bind the added symbol.
154
+ const isBindable = (name: string, current: Binding | undefined, added: Binding, unit: Unit) => {
155
+ if (current === undefined) return true;
156
+ if (isSameRange(current.range, added.range)) return false;
157
+ const range = added.range;
158
+ if (range === undefined || unit.isGenerated || (current.kind !== "Builtin" && !current.range)) {
159
+ return true;
160
+ }
161
+ const location = formatRange(range);
162
+ const existing = current.range && formatRange(current.range);
163
+ if (current.kind === "Builtin") {
164
+ unit.errors.push({
165
+ location,
166
+ message: `Symbol ${name} is a built-in operator, and cannot be redefined.`,
167
+ });
168
+ } else if (
169
+ added.kind === "Parameter" ||
170
+ current.kind !== added.kind ||
171
+ current.arity !== added.arity
172
+ ) {
173
+ unit.errors.push({
174
+ location,
175
+ message: `Multiply-defined symbol '${name}': this definition or declaration conflicts \nwith the one at ${existing}.`,
176
+ });
177
+ } else {
178
+ unit.warnings.push({
179
+ location,
180
+ message: `Multiple declarations or definitions for symbol ${name}. \nThis duplicates the one at ${existing}.`,
181
+ });
182
+ }
183
+ return false;
184
+ };
185
+
186
+ const bindName = (
187
+ scope: LocalName | undefined,
188
+ name: string,
189
+ added: Binding,
190
+ unit: Unit,
191
+ ): LocalName | undefined =>
192
+ isBindable(
193
+ name,
194
+ lookupLocal(scope, name) ?? getModuleBinding(name, unit, added.range),
195
+ added,
196
+ unit,
197
+ )
198
+ ? { ...added, name, parent: scope }
199
+ : scope;
200
+
201
+ // Binds the names of a module from the unit on.
202
+ const bindModuleName = (name: string, added: Binding, unit: Unit) => {
203
+ if (isBindable(name, unit.bindings.get(name), added, unit)) {
204
+ unit.bindings.set(name, { ...added, position: unit.location });
205
+ }
206
+ };
207
+
208
+ const bindNames = (
209
+ scope: LocalName | undefined,
210
+ names: string[],
211
+ ranges: SourceRange[] | undefined,
212
+ unit: Unit,
213
+ ) =>
214
+ names.reduce(
215
+ (parent, name, index) =>
216
+ bindName(parent, name, { kind: "Parameter", arity: 0, range: ranges?.[index] }, unit),
217
+ scope,
218
+ );
76
219
 
77
- const bindParams = (scope: LocalName | undefined, params: OperatorParam[]) =>
78
- params.reduce<LocalName | undefined>(
79
- (parent, param) => ({ name: param.name, arity: param.arity, parent }),
220
+ const bindParams = (scope: LocalName | undefined, params: OperatorParam[], unit: Unit) =>
221
+ params.reduce(
222
+ (parent, param) =>
223
+ bindName(
224
+ parent,
225
+ param.name,
226
+ { kind: "Parameter", arity: param.arity, range: param.location?.range },
227
+ unit,
228
+ ),
80
229
  scope,
81
230
  );
82
231
 
@@ -99,10 +248,33 @@ const getVisibleDefinition = (name: string, unit: Unit) => {
99
248
  const findSymbol = (name: string, unit: Unit): ModuleSymbol | undefined => {
100
249
  const definition = getVisibleDefinition(name, unit);
101
250
  return definition
102
- ? { key: unit.getKey(definition), arity: getArity(definition) }
251
+ ? {
252
+ key: unit.getKey(definition),
253
+ arity: getArity(definition),
254
+ params: getParamArities(definition),
255
+ kind: "Definition",
256
+ }
103
257
  : unit.imported.get(name);
104
258
  };
105
259
 
260
+ const findBinding = (name: string, scope: LocalName | undefined, unit: Unit): Binding | undefined =>
261
+ lookupLocal(scope, name) ?? findSymbol(name, unit);
262
+
263
+ // SANY reports a name at the range of its text.
264
+ const getNameRange = (location: SourceLocation, name: string): SourceRange => ({
265
+ module: location.range?.module ?? "",
266
+ start: location,
267
+ end: { line: location.line, column: location.column + name.length - 1 },
268
+ });
269
+
270
+ // SANY reports an operator symbol applied to operands as one it cannot resolve.
271
+ const getFixity = (expression: Expression) => {
272
+ if (expression.kind !== "Apply") return undefined;
273
+ if (expression.args.length === 2) return "infix";
274
+ if (expression.args.length !== 1) return undefined;
275
+ return isBefore(expression.location, expression.args[0].location) ? "prefix" : "postfix";
276
+ };
277
+
106
278
  // SANY names an undefined operator symbol such as + differently from an undefined identifier.
107
279
  const isOperatorSymbol = (name: string) =>
108
280
  name[0].toLowerCase() === name[0].toUpperCase() &&
@@ -112,6 +284,187 @@ const isOperatorSymbol = (name: string) =>
112
284
  const isStepName = (name: string) =>
113
285
  name.startsWith("<") && ((name[1] >= "0" && name[1] <= "9") || name[1] === "*");
114
286
 
287
+ export const getOperandIndex = (operand: number | "<<" | ">>", count: number) => {
288
+ if (typeof operand === "number") return operand >= 1 && operand <= count ? operand - 1 : -1;
289
+ if (operand === "<<") return count > 0 ? 0 : -1;
290
+ return count === 2 ? 1 : -1;
291
+ };
292
+
293
+ const getSelectors = (reference: Reference): Selector[] =>
294
+ reference.kind === "Subexpression"
295
+ ? reference.selectors
296
+ : (reference.kind === "Identifier" ? reference.name : reference.operator)
297
+ .split("!")
298
+ .map((name) => ({ kind: "Name", name, args: [] }));
299
+
300
+ const isReference = (expression: Expression): expression is Reference =>
301
+ expression.kind === "Identifier" ||
302
+ expression.kind === "Apply" ||
303
+ expression.kind === "Subexpression";
304
+
305
+ const isInScopeOfDeclaration = (assumeProve: AssumeProve, clause: number) =>
306
+ assumeProve.assumptions.slice(0, clause).some((assumption) => assumption.kind === "NewSymbol");
307
+
308
+ const findLabel = (expression: Expression, name: string): LabelExpression | undefined => {
309
+ if (expression.kind === "Label") return expression.name === name ? expression : undefined;
310
+ if (expression.kind === "Lambda") return undefined;
311
+ if (expression.kind === "Let") return findLabel(expression.body, name);
312
+ return getChildren(expression).reduce<LabelExpression | undefined>(
313
+ (found, child) => found ?? findLabel(child, name),
314
+ undefined,
315
+ );
316
+ };
317
+
318
+ // SANY drops a label in the scope of a NEW in a nested ASSUME, after it reports the label.
319
+ const findClauseLabel = (
320
+ clause: Expression | NewSymbol | AssumeProve,
321
+ name: string,
322
+ isForbidden: boolean,
323
+ ): LabelExpression | undefined => {
324
+ if (clause.kind === "AssumeProve") {
325
+ return [...clause.assumptions, clause.conclusion].reduce<LabelExpression | undefined>(
326
+ (found, inner, index) =>
327
+ found ?? findClauseLabel(inner, name, isForbidden || isInScopeOfDeclaration(clause, index)),
328
+ undefined,
329
+ );
330
+ }
331
+ if (isForbidden) return undefined;
332
+ if (clause.kind === "NewSymbol") return clause.set && findLabel(clause.set, name);
333
+ return findLabel(clause, name);
334
+ };
335
+
336
+ const getOperandName = (operand: number | "<<" | ">>") =>
337
+ typeof operand === "number" ? `argument selector ${operand}` : operand;
338
+
339
+ const SCOPE_MESSAGE = "within the scope of a declaration\n from outside that declaration's scope.";
340
+
341
+ // Generator.selectorToNode for a name that selects part of a theorem or step. A part in the scope of
342
+ // a NEW in its ASSUME may be selected only within the proof of the theorem, or only after the proof
343
+ // of a SUFFICES step. A fact may select an ASSUME/PROVE or a NEW clause.
344
+ const checkSelection = (
345
+ reference: Reference,
346
+ selectors: Selector[],
347
+ goal: Goal,
348
+ unit: Unit,
349
+ isFact: boolean,
350
+ ) => {
351
+ const report = (index: number | undefined, message: string) => {
352
+ const range =
353
+ (index === undefined ? undefined : reference.selectorRanges?.[index]) ??
354
+ reference.location.range;
355
+ if (range) unit.errors.push({ location: formatRange(range), message });
356
+ };
357
+ const isOutOfScope = goal.isSuffices === goal.isInProof;
358
+ const statement = goal.statement;
359
+ const second = selectors[1];
360
+ if (second.kind === "Name") {
361
+ const clauses =
362
+ statement.kind === "AssumeProve"
363
+ ? [...statement.assumptions, statement.conclusion]
364
+ : [statement];
365
+ const found = clauses
366
+ .map((clause, index) => ({ index, label: findClauseLabel(clause, second.name, false) }))
367
+ .find((item) => item.label !== undefined);
368
+ if (!found) return report(1, `Cannot find label \`${second.name}'.`);
369
+ if (
370
+ statement.kind === "AssumeProve" &&
371
+ isInScopeOfDeclaration(statement, found.index) &&
372
+ isOutOfScope
373
+ ) {
374
+ return report(
375
+ 1,
376
+ `Accessing subexpression labeled \`${second.name}' of ASSUME/PROVE clause ${SCOPE_MESSAGE}`,
377
+ );
378
+ }
379
+ selectors.slice(2).reduce((label, selector, offset) => {
380
+ if (!label || selector.kind !== "Name") return undefined;
381
+ const inner = findLabel(label.body, selector.name);
382
+ if (!inner) report(offset + 2, `Cannot find label \`${selector.name}'.`);
383
+ return inner;
384
+ }, found.label);
385
+ return;
386
+ }
387
+ const state: SelectionState = {
388
+ node: statement,
389
+ isGoal: true,
390
+ isSufficesOpen: goal.isSuffices,
391
+ };
392
+ for (const [offset, selector] of selectors.slice(1).entries()) {
393
+ const index = offset + 1;
394
+ const node = state.node;
395
+ if (selector.kind !== "Operand") return;
396
+ if (state.isSufficesOpen) {
397
+ if (getOperandIndex(selector.operand, 1) !== 0) {
398
+ return report(
399
+ index,
400
+ node.kind === "AssumeProve"
401
+ ? "Accessing non-existent subexpression of a SUFFICES"
402
+ : `Nonexistent operand specified by \`${getOperandName(selector.operand)}'.`,
403
+ );
404
+ }
405
+ state.isSufficesOpen = false;
406
+ continue;
407
+ }
408
+ if (node.kind !== "AssumeProve") return;
409
+ const clauses = [...node.assumptions, node.conclusion];
410
+ const position = getOperandIndex(selector.operand, clauses.length);
411
+ if (position === -1) {
412
+ return report(
413
+ index,
414
+ `Nonexistent operand specified by \`${getOperandName(selector.operand)}'.`,
415
+ );
416
+ }
417
+ if (isInScopeOfDeclaration(node, position) && (!state.isGoal || isOutOfScope)) {
418
+ return report(index, `Accessing ASSUME/PROVE clause ${SCOPE_MESSAGE}`);
419
+ }
420
+ const clause = clauses[position];
421
+ if (clause.kind === "NewSymbol" && index !== selectors.length - 1) {
422
+ return report(index, "Selected a subexpression of a NEW clause of an ASSUME.");
423
+ }
424
+ state.node = clause;
425
+ state.isGoal = false;
426
+ }
427
+ if (isFact) return;
428
+ if (state.node.kind === "AssumeProve") {
429
+ report(undefined, "Selected ASSUME/PROVE instead of expression.");
430
+ }
431
+ if (state.node.kind === "NewSymbol") {
432
+ report(undefined, "Selected a NEW declaration as an expression or operator.");
433
+ }
434
+ };
435
+
436
+ // Generator.generateLabel reports a label where it may not appear, and skips the label's body.
437
+ const isLabelReported = (label: LabelExpression, unit: Unit) => {
438
+ const message = !unit.hasLabelScope
439
+ ? "Label not in definition or proof step."
440
+ : unit.isLabelForbidden
441
+ ? "Label not allowed within scope of declaration in nested ASSUME/PROVE."
442
+ : undefined;
443
+ if (message === undefined || !label.location.range) return false;
444
+ unit.errors.push({ location: formatRange(label.location.range), message });
445
+ return true;
446
+ };
447
+
448
+ // Checks a name that selects part of a theorem or step, and tells whether it is one.
449
+ const checkReference = (
450
+ expression: Expression,
451
+ scope: LocalName | undefined,
452
+ unit: Unit,
453
+ isFact: boolean,
454
+ ) => {
455
+ if (!isReference(expression)) return false;
456
+ const selectors = getSelectors(expression);
457
+ const first = selectors[0];
458
+ const goal =
459
+ selectors.length > 1 && first.kind === "Name"
460
+ ? (lookupLocal(scope, first.name)?.goal ?? unit.goals.get(first.name))
461
+ : undefined;
462
+ if (goal) checkSelection(expression, selectors, goal, unit, isFact);
463
+ return goal !== undefined;
464
+ };
465
+
466
+ // Generator.selectorToNode reports an unknown operator and goes on without analyzing its arguments,
467
+ // so its arity is undefined. It does the same for an operator given the wrong number of arguments.
115
468
  const getSymbolArity = (
116
469
  expression: Expression & { kind: "Identifier" | "Apply" | "OperatorReference" },
117
470
  name: string,
@@ -122,7 +475,9 @@ const getSymbolArity = (
122
475
  const renamed = renamedArities.get(expression);
123
476
  if (renamed !== undefined) return renamed;
124
477
  if (isKey(name)) return expression.kind === "Apply" ? expression.args.length : 0;
125
- if (isStepName(name)) return 0;
478
+ if (checkReference(expression, scope, unit, false) || isStepName(name)) {
479
+ return expression.kind === "Apply" ? expression.args.length : 0;
480
+ }
126
481
  const local = lookupLocal(scope, name);
127
482
  if (local && expression.kind !== "OperatorReference") expression.resolution = LOCAL_RESOLUTION;
128
483
  if (local) return local.arity;
@@ -135,7 +490,7 @@ const getSymbolArity = (
135
490
  }
136
491
  // A name such as Inv!P1 selects the label P1 of a definition or theorem, which takes its own
137
492
  // arguments.
138
- const prefix = name.slice(0, name.indexOf("!"));
493
+ const prefix = name.includes("!") ? name.slice(0, name.indexOf("!")) : "";
139
494
  const isSelected =
140
495
  prefix !== "" &&
141
496
  (lookupLocal(scope, prefix) !== undefined ||
@@ -144,18 +499,30 @@ const getSymbolArity = (
144
499
  if (isSelected) {
145
500
  return expression.kind === "Apply" ? expression.args.length : 0;
146
501
  }
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}`,
152
- );
502
+ const range = formatRange(getNameRange(location, name === "-." ? "-" : name));
503
+ if (!isOperatorSymbol(name)) {
504
+ unit.errors.push({ location: range, message: `Unknown operator: \`${name}'.` });
505
+ return undefined;
506
+ }
507
+ unit.errors.push({
508
+ location: range,
509
+ message: `Could not find declaration or definition of symbol '${name}'.`,
510
+ });
511
+ const fixity = getFixity(expression);
512
+ if (fixity && location.range) {
513
+ unit.errors.push({
514
+ location: formatRange(location.range),
515
+ message: `Couldn't resolve ${fixity} operator symbol \`${name}'.`,
516
+ });
517
+ }
518
+ return undefined;
153
519
  };
154
520
 
155
521
  const resolveBounds = (bounds: Bound[], scope: LocalName | undefined, unit: Unit) => {
156
522
  bounds.forEach((bound) => resolveExpression(bound.set, scope, unit));
157
523
  return bounds.reduce(
158
- (current, bound) => bindNames(current, getPatternNames(bound.pattern)),
524
+ (current, bound) =>
525
+ bindNames(current, getPatternNames(bound.pattern), bound.pattern.ranges, unit),
159
526
  scope,
160
527
  );
161
528
  };
@@ -171,14 +538,60 @@ const markRecursiveConstructions = (expression: Expression, name: string): void
171
538
  getChildren(expression).forEach((child) => markRecursiveConstructions(child, name));
172
539
  };
173
540
 
174
- const resolveDefinition = (definition: Definition, scope: LocalName | undefined, unit: Unit) => {
175
- const self = bindNames(scope, definition.kind === "Function" ? [definition.name] : []);
541
+ // Generator.processOperator binds the parameters, reports a name already bound unless a RECURSIVE
542
+ // declaration of this level awaits the definition, analyzes the body, and then binds the name.
543
+ // processFunction binds the bound names before it looks up the name, and binds the name only where
544
+ // nothing else does. recursive holds the declarations of this level. Tells whether to bind the name.
545
+ const resolveDefinition = (
546
+ definition: Definition,
547
+ scope: LocalName | undefined,
548
+ outer: Unit,
549
+ recursive: Set<Binding>,
550
+ ) => {
551
+ const unit = outer.hasLabelScope ? outer : { ...outer, hasLabelScope: true };
552
+ const name = definition.name;
553
+ const range = definition.location.range;
554
+ const report = (message: string) => {
555
+ if (range && !unit.isGenerated) unit.errors.push({ location: formatRange(range), message });
556
+ };
557
+ const inner =
558
+ definition.kind === "Function"
559
+ ? resolveBounds(definition.bounds, scope, unit)
560
+ : bindParams(scope, definition.params, unit);
561
+ const current = lookupLocal(inner, name) ?? getModuleBinding(name, unit, range);
562
+ const isDeclared = current?.isPending === true && recursive.has(current);
563
+ if (current?.isPending && !isDeclared) {
564
+ report(
565
+ `Recursive ${definition.kind === "Function" ? "function" : "operator"} ${name} defined at wrong LET/IN level.`,
566
+ );
567
+ } else if (current && !isDeclared) {
568
+ report(
569
+ definition.kind === "Function"
570
+ ? `Function name \`${name}' already defined or declared.`
571
+ : `Operator ${name} already defined or declared.`,
572
+ );
573
+ }
176
574
  if (definition.kind === "Function") {
177
- resolveExpression(definition.body, resolveBounds(definition.bounds, self, unit), unit);
178
- markRecursiveConstructions(definition.body, definition.name);
179
- return;
575
+ resolveExpression(
576
+ definition.body,
577
+ { name, kind: "Parameter", arity: 0, range, parent: inner },
578
+ unit,
579
+ );
580
+ markRecursiveConstructions(definition.body, name);
581
+ } else resolveExpression(definition.body, inner, unit);
582
+ if (current && isDeclared) {
583
+ current.isPending = false;
584
+ current.range = range;
585
+ return false;
180
586
  }
181
- resolveExpression(definition.body, bindParams(self, definition.params), unit);
587
+ return definition.kind === "Function"
588
+ ? current === undefined
589
+ : isBindable(
590
+ name,
591
+ lookupLocal(scope, name) ?? getModuleBinding(name, unit, range),
592
+ { kind: "Definition", arity: getArity(definition), range },
593
+ unit,
594
+ );
182
595
  };
183
596
 
184
597
  const resolveDefinitions = (
@@ -186,79 +599,138 @@ const resolveDefinitions = (
186
599
  scope: LocalName | undefined,
187
600
  unit: Unit,
188
601
  ) => {
189
- const recursiveScope = definitions
602
+ const recursive = new Set<Binding>();
603
+ const declared = definitions
190
604
  .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);
199
- };
200
-
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,
209
- ) => {
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
- );
223
- }
605
+ .reduce<LocalName | undefined>((parent, definition) => {
606
+ if (lookupLocal(parent, definition.name)?.isPending) return parent;
607
+ const local: LocalName = {
608
+ name: definition.name,
609
+ arity: getArity(definition),
610
+ params: getParamArities(definition),
611
+ kind: "Definition",
612
+ parent,
613
+ isPending: true,
614
+ };
615
+ recursive.add(local);
616
+ return local;
617
+ }, scope);
618
+ return definitions.reduce<LocalName | undefined>((current, definition) => {
619
+ const local: LocalName = {
620
+ name: definition.name,
621
+ arity: getArity(definition),
622
+ kind: "Definition",
623
+ range: definition.location.range,
624
+ parent: current,
625
+ };
626
+ if (isInstantiated(definition)) return local;
627
+ const isGenerated = unit.isGenerated || definition.isLocal || isKey(definition.name);
628
+ return resolveDefinition(
629
+ definition,
630
+ current,
631
+ isGenerated ? { ...unit, isGenerated } : unit,
632
+ recursive,
633
+ )
634
+ ? { ...local, params: getParamArities(definition) }
635
+ : current;
636
+ }, declared);
224
637
  };
225
638
 
226
- const getArgumentName = (arg: Expression) =>
227
- arg.kind === "Identifier"
228
- ? arg.name
229
- : arg.kind === "OperatorReference"
230
- ? arg.operator
231
- : undefined;
232
-
639
+ // Generator.generateExprOrOpArg analyzes an argument as an expression, unless a defined operator
640
+ // takes an operator in its place, which a name, a built-in operator, or a LAMBDA of the parameter's
641
+ // arity must give. OpDefNode#match then reports each argument that gives no such operator, or one
642
+ // whose own parameters take operators. tla-ts lets an operator whose parameters it does not know
643
+ // take any argument.
233
644
  const resolveApply = (
234
645
  expression: Expression & { kind: "Apply" },
235
646
  scope: LocalName | undefined,
236
647
  unit: Unit,
237
648
  ) => {
238
- const callee = lookupLocal(scope, expression.operator)
239
- ? undefined
240
- : getVisibleDefinition(expression.operator, unit);
241
- const arity = getSymbolArity(expression, expression.operator, scope, unit);
649
+ const operator = expression.operator;
650
+ const callee = findBinding(operator, scope, unit);
651
+ const arity = getSymbolArity(expression, operator, scope, unit);
652
+ if (arity === undefined) return;
242
653
  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
- );
654
+ unit.errors.push({
655
+ location: formatRange(
656
+ expression.argumentsRange ?? getNameRange(expression.location, operator),
657
+ ),
658
+ message: `The operator ${operator} requires ${arity} arguments.`,
659
+ });
660
+ return;
246
661
  }
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
- });
662
+ const params = callee && (callee.kind === "Definition" ? callee.params : []);
663
+ if (params === undefined) {
664
+ expression.args.forEach((arg) => resolveArgument(arg, scope, unit));
665
+ return;
666
+ }
667
+ const report = (range: SourceRange | undefined, message: string) => {
668
+ if (range) unit.errors.push({ location: formatRange(range), message });
669
+ };
670
+ expression.args
671
+ .map((arg, index) => {
672
+ const expected = params[index] ?? 0;
673
+ // A prefix operator argument such as SUBSET, which tla-ts reads as a LAMBDA, has no range.
674
+ const range = arg.location.range;
675
+ if (expected === 0) {
676
+ if (arg.kind === "Lambda" && range) {
677
+ report(range, "LAMBDA expression used where an expression is required.");
678
+ } else if (arg.kind === "OperatorReference") {
679
+ // SANY fails here with an internal error, so tla-ts words it as it does for a name.
680
+ const argArity = getSymbolArity(arg, arg.operator, scope, unit);
681
+ if (argArity !== undefined) {
682
+ report(range, `The operator ${arg.operator} requires ${argArity} arguments.`);
683
+ }
684
+ } else resolveExpression(arg, scope, unit);
685
+ return true;
686
+ }
687
+ if (arg.kind === "Lambda") {
688
+ resolveExpression(arg, scope, unit);
689
+ const isMatched = arg.params.length === expected;
690
+ if (!isMatched && range) {
691
+ report(
692
+ expression.selectorRanges?.at(-1) ?? getNameRange(expression.location, operator),
693
+ `Lambda expression with arity ${arg.params.length} used as argument ${index + 1} of operator \`${operator}', \nbut an operator of arity ${expected} is required.`,
694
+ );
695
+ }
696
+ return isMatched;
697
+ }
698
+ if (arg.kind === "Subexpression") {
699
+ resolveExpression(arg, scope, unit);
700
+ return true;
701
+ }
702
+ if (arg.kind !== "Identifier" && arg.kind !== "OperatorReference") {
703
+ report(
704
+ range,
705
+ `An expression appears as argument number ${index + 1} (counting from 1) to operator '${operator}', in a position an operator is required.`,
706
+ );
707
+ return false;
708
+ }
709
+ const name = arg.kind === "Identifier" ? arg.name : arg.operator;
710
+ const argParams = findBinding(name, scope, unit)?.params ?? [];
711
+ const argArity = getSymbolArity(arg, name, scope, unit);
712
+ if (arg.kind === "Identifier" && argArity !== undefined && argArity !== expected) {
713
+ report(
714
+ getNameRange(arg.location, name),
715
+ `Expected arity ${expected} but found operator of arity ${argArity}.`,
716
+ );
717
+ }
718
+ return argArity === expected && argParams.every((param) => param === 0);
719
+ })
720
+ .forEach((isMatched, index) => {
721
+ if (!isMatched) {
722
+ report(
723
+ expression.location.range,
724
+ `Argument number ${index + 1} to operator '${operator}' \nshould be a ${params[index]}-parameter operator.`,
725
+ );
726
+ }
727
+ });
254
728
  };
255
729
 
256
730
  // An argument may name an operator that takes arguments of its own.
257
731
  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;
732
+ if (arg.kind === "Identifier") getSymbolArity(arg, arg.name, scope, unit);
733
+ else resolveExpression(arg, scope, unit);
262
734
  };
263
735
 
264
736
  const resolveExpression = (
@@ -275,11 +747,13 @@ const resolveExpression = (
275
747
  case "ExceptAt":
276
748
  return;
277
749
  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
- );
750
+ const name = expression.name;
751
+ const arity = getSymbolArity(expression, name, scope, unit);
752
+ if (arity !== undefined && arity > 0) {
753
+ unit.errors.push({
754
+ location: formatRange(getNameRange(expression.location, name)),
755
+ message: `The operator ${name} requires ${arity} arguments.`,
756
+ });
283
757
  }
284
758
  return;
285
759
  }
@@ -290,7 +764,11 @@ const resolveExpression = (
290
764
  resolveApply(expression, scope, unit);
291
765
  return;
292
766
  case "Lambda":
293
- resolveExpression(expression.body, bindNames(scope, expression.params), unit);
767
+ resolveExpression(
768
+ expression.body,
769
+ bindNames(scope, expression.params, expression.paramRanges, unit),
770
+ unit,
771
+ );
294
772
  return;
295
773
  case "And":
296
774
  case "Or":
@@ -323,13 +801,17 @@ const resolveExpression = (
323
801
  resolveExpression(expression.body, resolveBounds(expression.bounds, scope, unit), unit);
324
802
  return;
325
803
  case "UnboundedQuantifier":
326
- resolveExpression(expression.body, bindNames(scope, expression.names), unit);
804
+ resolveExpression(
805
+ expression.body,
806
+ bindNames(scope, expression.names, expression.nameRanges, unit),
807
+ unit,
808
+ );
327
809
  return;
328
810
  case "Choose":
329
811
  if (expression.set) resolveExpression(expression.set, scope, unit);
330
812
  resolveExpression(
331
813
  expression.body,
332
- bindNames(scope, getPatternNames(expression.pattern)),
814
+ bindNames(scope, getPatternNames(expression.pattern), expression.pattern.ranges, unit),
333
815
  unit,
334
816
  );
335
817
  return;
@@ -348,12 +830,15 @@ const resolveExpression = (
348
830
  return;
349
831
  case "Record":
350
832
  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));
833
+ expression.fields.forEach((field, index) => {
834
+ if (expression.fields.slice(0, index).some((earlier) => earlier.name === field.name)) {
835
+ unit.errors.push({
836
+ location: formatRange(field.location.range ?? getNameRange(field.location, field.name)),
837
+ message: "Non-unique fields in constructor.",
838
+ });
839
+ }
840
+ resolveExpression(field.value, scope, unit);
841
+ });
357
842
  return;
358
843
  case "Except":
359
844
  resolveAll([
@@ -382,34 +867,72 @@ const resolveExpression = (
382
867
  resolveAll([expression.subscript, expression.action]);
383
868
  return;
384
869
  case "Label":
385
- resolveExpression(expression.body, scope, unit);
870
+ if (!isLabelReported(expression, unit)) resolveExpression(expression.body, scope, unit);
386
871
  return;
387
- case "Subexpression":
872
+ case "Subexpression": {
388
873
  expression.selectors
389
874
  .flatMap((selector) => ("args" in selector ? selector.args : []))
390
875
  .forEach((arg) => resolveArgument(arg, scope, unit));
876
+ checkReference(expression, scope, unit, false);
877
+ }
391
878
  }
392
879
  };
393
880
 
881
+ // SANY analyzes the facts of a proof apart from their names, which may name theorems and modules.
882
+ const checkFacts = (facts: Fact[], scope: LocalName | undefined, unit: Unit) => {
883
+ const check = (expression: Expression, isFact: boolean, inner: Unit): void => {
884
+ if (expression.kind === "Label" && isLabelReported(expression, inner)) return;
885
+ checkReference(expression, scope, inner, isFact);
886
+ getChildren(expression).forEach((child) =>
887
+ check(
888
+ child,
889
+ false,
890
+ expression.kind === "Let" && child !== expression.body
891
+ ? { ...inner, hasLabelScope: true }
892
+ : inner,
893
+ ),
894
+ );
895
+ };
896
+ facts.forEach((fact) => {
897
+ if (fact.kind !== "ModuleFact") check(fact, true, { ...unit, hasLabelScope: false });
898
+ });
899
+ };
900
+
394
901
  const resolveNewSymbol = (symbol: NewSymbol, scope: LocalName | undefined, unit: Unit) => {
395
902
  if (symbol.set) resolveExpression(symbol.set, scope, unit);
396
- return { name: symbol.name, arity: symbol.arity, parent: scope };
903
+ return bindName(
904
+ scope,
905
+ symbol.name,
906
+ { kind: `New${symbol.level}`, arity: symbol.arity, range: symbol.nameRange },
907
+ unit,
908
+ );
397
909
  };
398
910
 
399
- // The NEW symbols of an ASSUME stay in scope for its conclusion and the proof that follows.
911
+ // The NEW symbols of an ASSUME stay in scope for its conclusion and the proof that follows. SANY
912
+ // forbids a label in the scope of a NEW in a nested ASSUME.
400
913
  const resolveAssumeProve = (
401
914
  assumeProve: AssumeProve,
402
915
  scope: LocalName | undefined,
403
916
  unit: Unit,
917
+ isNested = false,
404
918
  ): 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;
919
+ const assumed = assumeProve.assumptions.reduce(
920
+ (current, assumption) => {
921
+ if (assumption.kind === "NewSymbol") {
922
+ return {
923
+ scope: resolveNewSymbol(assumption, current.scope, current.unit),
924
+ unit: isNested ? { ...current.unit, isLabelForbidden: true } : current.unit,
925
+ };
926
+ }
927
+ if (assumption.kind === "AssumeProve") {
928
+ resolveAssumeProve(assumption, current.scope, current.unit, true);
929
+ } else resolveExpression(assumption, current.scope, current.unit);
930
+ return current;
931
+ },
932
+ { scope, unit },
933
+ );
934
+ resolveExpression(assumeProve.conclusion, assumed.scope, assumed.unit);
935
+ return assumed.scope;
413
936
  };
414
937
 
415
938
  const resolveStatement = (
@@ -424,7 +947,9 @@ const resolveStatement = (
424
947
 
425
948
  // SANY resolves the expressions of a proof, while its facts and DEF clauses may also name
426
949
  // theorems, assumptions, and modules.
427
- const resolveProof = (proof: Proof | undefined, scope: LocalName | undefined, unit: Unit) => {
950
+ const resolveProof = (proof: Proof | undefined, scope: LocalName | undefined, outer: Unit) => {
951
+ const unit = outer.hasLabelScope ? { ...outer, hasLabelScope: false } : outer;
952
+ if (proof?.kind === "By") checkFacts(proof.facts, scope, unit);
428
953
  if (proof?.kind !== "Steps") return;
429
954
  proof.steps.reduce((current, step) => resolveStep(step, current, unit), scope);
430
955
  };
@@ -435,12 +960,27 @@ const resolveStep = (
435
960
  unit: Unit,
436
961
  ): LocalName | undefined => {
437
962
  const body = step.body;
963
+ const stepUnit = step.name === undefined ? unit : { ...unit, hasLabelScope: true };
438
964
  switch (body.kind) {
965
+ // The NEW symbols of a SUFFICES ASSUME are in scope after its proof, and those of any other
966
+ // ASSUME in its proof.
439
967
  case "Assert": {
440
- const assumed = resolveStatement(body.statement, scope, unit);
441
- resolveProof(step.proof, assumed, unit);
442
- return body.isSuffices ? assumed : scope;
968
+ const assumed = resolveStatement(body.statement, scope, stepUnit);
969
+ const proofScope = body.isSuffices ? scope : assumed;
970
+ const name = step.name;
971
+ if (name === undefined) {
972
+ resolveProof(step.proof, proofScope, unit);
973
+ return body.isSuffices ? assumed : scope;
974
+ }
975
+ const goal = { statement: body.statement, isSuffices: body.isSuffices, isInProof: true };
976
+ resolveProof(step.proof, { name, arity: 0, kind: "Theorem", parent: proofScope, goal }, unit);
977
+ goal.isInProof = false;
978
+ return { name, arity: 0, kind: "Theorem", parent: body.isSuffices ? assumed : scope, goal };
443
979
  }
980
+ case "Use":
981
+ case "Hide":
982
+ checkFacts(body.facts, scope, unit);
983
+ return scope;
444
984
  case "Define":
445
985
  return resolveDefinitions(
446
986
  body.definitions.flatMap((definition) =>
@@ -451,17 +991,27 @@ const resolveStep = (
451
991
  );
452
992
  case "Have":
453
993
  case "Case":
454
- resolveExpression(body.expression, scope, unit);
994
+ resolveExpression(body.expression, scope, stepUnit);
455
995
  resolveProof(step.proof, scope, unit);
456
996
  return scope;
457
997
  case "Witness":
458
- body.expressions.forEach((expression) => resolveExpression(expression, scope, unit));
998
+ body.expressions.forEach((expression) => resolveExpression(expression, scope, stepUnit));
459
999
  return scope;
460
1000
  case "Take":
461
- return bindNames(resolveBounds(body.bounds, scope, unit), body.names);
1001
+ return bindNames(
1002
+ resolveBounds(body.bounds, scope, stepUnit),
1003
+ body.names,
1004
+ body.nameRanges,
1005
+ stepUnit,
1006
+ );
462
1007
  case "Pick": {
463
- const picked = bindNames(resolveBounds(body.bounds, scope, unit), body.names);
464
- resolveExpression(body.body, picked, unit);
1008
+ const picked = bindNames(
1009
+ resolveBounds(body.bounds, scope, stepUnit),
1010
+ body.names,
1011
+ body.nameRanges,
1012
+ stepUnit,
1013
+ );
1014
+ resolveExpression(body.body, picked, stepUnit);
465
1015
  resolveProof(step.proof, scope, unit);
466
1016
  return picked;
467
1017
  }
@@ -471,324 +1021,375 @@ const resolveStep = (
471
1021
  }
472
1022
  };
473
1023
 
1024
+ // SANY binds the name of a theorem after its statement and before its proof.
474
1025
  const resolveTheorem = (theorem: Theorem, unit: Unit) => {
475
1026
  const isDefinition = theorem.name !== undefined && theorem.statement.kind !== "AssumeProve";
476
1027
  const scope = isDefinition ? undefined : resolveStatement(theorem.statement, undefined, unit);
1028
+ if (theorem.name !== undefined) {
1029
+ bindModuleName(
1030
+ theorem.name,
1031
+ { kind: "Theorem", arity: 0, range: theorem.location.range },
1032
+ unit,
1033
+ );
1034
+ }
1035
+ const goal = unit.goals.get(theorem.name ?? "");
1036
+ if (goal) goal.isInProof = true;
477
1037
  resolveProof(theorem.proof, scope, unit);
1038
+ if (goal) goal.isInProof = false;
478
1039
  };
479
1040
 
480
- interface ModuleUnit {
1041
+ // What SANY reports at a location as it links a module, such as a conflict between the modules it
1042
+ // extends.
1043
+ export interface ModuleReport {
1044
+ location: SourceLocation;
1045
+ errors: SanyError[];
1046
+ warnings: SanyError[];
1047
+ }
1048
+
1049
+ // bound holds the names in scope where the module starts: the built-in operators, the names of the
1050
+ // module that encloses it, and those of the modules it extends. instanced holds the names each
1051
+ // INSTANCE adds, and warnings the warnings SANY reports for the spec.
1052
+ export interface ModuleUnit {
481
1053
  imported: Symbols;
482
- importedAt: Map<string, SourceLocation>;
1054
+ bound: Symbols;
483
1055
  definitions: Map<string, Definition>;
484
1056
  getKey: (definition: Definition) => string;
1057
+ instanced: Map<Instance, Symbols>;
1058
+ reports: ModuleReport[];
1059
+ warnings: SanyError[];
485
1060
  }
486
1061
 
487
- interface ModuleName {
488
- name: string;
489
- kind: "Definition" | "Constant" | "Variable";
490
- location: SourceLocation;
491
- isRecursive: boolean;
492
- }
493
-
494
- type IsDefined = (name: string) => boolean;
495
-
496
- const createRedefinitionError = (name: string, location: SourceLocation) =>
497
- new TlaSyntaxError(
498
- `Multiply-defined symbol '${name}' at line ${location.line}, column ${location.column}`,
499
- );
500
-
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);
1062
+ export const MODULE_START: SourceLocation = { line: 0, column: 0 };
511
1063
 
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,
522
- );
523
- };
524
-
525
- const checkDefinitionNames = (
526
- definition: Definition,
527
- scope: LocalName | undefined,
528
- isDefined: IsDefined,
529
- ) => {
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,
1064
+ // A named theorem or assumption is linked as a definition too.
1065
+ export const isTheoremDefinition = (module: Module, definition: Definition) =>
1066
+ [...module.theorems, ...module.assumptions].some(
1067
+ (item) =>
1068
+ item.name === definition.name &&
1069
+ item.location.line === definition.location.line &&
1070
+ item.location.column === definition.location.column,
541
1071
  );
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
- );
582
- return;
583
- }
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,
620
- );
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);
669
- };
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
- );
709
- });
710
- };
711
1072
 
712
1073
  const createSymbols = (module: Module, imported: Symbols) => {
713
1074
  const symbols = new Map([...CORE_SYMBOLS, ...imported]);
714
1075
  module.constants.forEach((constant) =>
715
- symbols.set(constant.name, { key: constant.name, arity: constant.arity }),
1076
+ symbols.set(constant.name, { key: constant.name, arity: constant.arity, kind: "Constant" }),
716
1077
  );
717
1078
  module.variables.forEach((variable) =>
718
- symbols.set(variable.name, { key: variable.name, arity: 0 }),
1079
+ symbols.set(variable.name, { key: variable.name, arity: 0, kind: "Variable" }),
719
1080
  );
720
1081
  return symbols;
721
1082
  };
722
1083
 
1084
+ // Generator.processSubst analyzes the explicit substitutions in the order they appear, then the
1085
+ // implicit ones, and then reports each declaration left without one. tla-ts reports what SANY goes on
1086
+ // after with the INSTANCE.
723
1087
  export const resolveSubstitutions = (
724
1088
  instance: Instance,
725
- declarations: OperatorParam[],
1089
+ declarations: Declaration[],
726
1090
  module: Module,
727
1091
  unit: ModuleUnit,
728
1092
  ) => {
729
- const scope = bindParams(undefined, instance.params);
1093
+ const scope = instance.params.reduce<LocalName | undefined>(
1094
+ (parent, param) => ({ name: param.name, arity: param.arity, kind: "Parameter", parent }),
1095
+ undefined,
1096
+ );
1097
+ const imported = createSymbols(module, unit.imported);
1098
+ const report: ModuleReport = { location: instance.location, errors: [], warnings: [] };
1099
+ unit.reports.push(report);
730
1100
  const context: Unit = {
731
- imported: createSymbols(module, unit.imported),
1101
+ imported,
732
1102
  definitions: unit.definitions,
733
1103
  getKey: unit.getKey,
734
1104
  location: instance.location,
735
1105
  self: undefined,
736
1106
  facts: new Set(),
1107
+ goals: new Map(),
1108
+ bindings: new Map(
1109
+ [...imported].map(([name, symbol]) => [name, { ...symbol, position: MODULE_START }]),
1110
+ ),
1111
+ errors: report.errors,
1112
+ warnings: report.warnings,
1113
+ hasLabelScope: true,
1114
+ isLabelForbidden: false,
1115
+ isGenerated: false,
737
1116
  };
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)) {
1117
+ const resolveSubstitute = (declaration: Declaration, expression: Expression) => {
1118
+ if (declaration.arity === 0 || expression.kind !== "Identifier") {
1119
+ resolveExpression(expression, scope, context);
1120
+ return;
1121
+ }
1122
+ const arity = getSymbolArity(expression, expression.name, scope, context);
1123
+ if (arity !== undefined && arity !== declaration.arity) {
742
1124
  throw new TlaSyntaxError(
743
- `Identifier '${name}' is not a legal target of a substitution ${position}`,
1125
+ `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}`,
744
1126
  );
745
1127
  }
1128
+ };
1129
+ const substitutions = new Map<string, Expression>();
1130
+ instance.substitutions.forEach((substitution) => {
1131
+ const name = substitution.name;
1132
+ const declaration = declarations.find((item) => item.name === name);
1133
+ if (!declaration) {
1134
+ report.errors.push({
1135
+ location: formatRange(substitution.nameRange),
1136
+ 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.)`,
1137
+ });
1138
+ return;
1139
+ }
1140
+ const expression = substitution.expression;
1141
+ resolveSubstitute(declaration, expression);
1142
+ const range = expression.location.range;
1143
+ if (!substitutions.has(name)) substitutions.set(name, expression);
1144
+ else if (range) {
1145
+ report.errors.push({
1146
+ location: formatRange(range),
1147
+ message: `Multiple substitutions for symbol '${name}' in substitution.`,
1148
+ });
1149
+ }
746
1150
  });
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) ?? {
1151
+ const implicit = declarations.filter((declaration) => !substitutions.has(declaration.name));
1152
+ const isMissing = (declaration: Declaration) =>
1153
+ !lookupLocal(scope, declaration.name) && !findSymbol(declaration.name, context);
1154
+ implicit
1155
+ .filter((declaration) => !isMissing(declaration))
1156
+ .forEach((declaration) => {
1157
+ const expression: Expression = {
754
1158
  kind: "Identifier",
755
- name,
1159
+ name: declaration.name,
756
1160
  location: instance.location,
757
1161
  };
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
- );
1162
+ resolveSubstitute(declaration, expression);
1163
+ substitutions.set(declaration.name, expression);
1164
+ });
1165
+ implicit.filter(isMissing).forEach((declaration) => {
1166
+ const range = instance.location.range;
1167
+ const declared = declaration.location.range;
1168
+ if (range && declared) {
1169
+ report.errors.push({
1170
+ location: formatRange(range),
1171
+ message: `Substitution missing for symbol ${declaration.name} declared at ${formatRange(declared)} \nand instantiated in module ${module.name}.`,
1172
+ });
1173
+ }
1174
+ });
1175
+ return substitutions;
1176
+ };
1177
+
1178
+ // SANY reports the errors of every unit it checks, in the order of the units in the module, after
1179
+ // the warnings it reports for the spec. A unit reports to its lists what SANY goes on after, and
1180
+ // throws the error that stops it. An error tla-ts cannot word as SANY does yields to the errors the
1181
+ // unit reported before it. Returns the errors.
1182
+ export const collectSemanticErrors = (
1183
+ units: {
1184
+ location: SourceLocation;
1185
+ check: (reported: SanyError[], warned: SanyError[]) => void;
1186
+ }[],
1187
+ warnings: SanyError[],
1188
+ ) => {
1189
+ const errors: SanyError[] = [];
1190
+ const add = (list: SanyError[], item: SanyError) => {
1191
+ if (
1192
+ list.every(
1193
+ (existing) => existing.location !== item.location || existing.message !== item.message,
1194
+ )
1195
+ ) {
1196
+ list.push(item);
1197
+ }
1198
+ };
1199
+ units
1200
+ .toSorted((left, right) =>
1201
+ isBefore(left.location, right.location)
1202
+ ? -1
1203
+ : isBefore(right.location, left.location)
1204
+ ? 1
1205
+ : 0,
1206
+ )
1207
+ .forEach((unit) => {
1208
+ const reported: SanyError[] = [];
1209
+ const warned: SanyError[] = [];
1210
+ try {
1211
+ unit.check(reported, warned);
1212
+ } catch (error) {
1213
+ if (!(error instanceof TlaSyntaxError) || (!error.sany && reported.length === 0)) {
1214
+ throw error;
1215
+ }
1216
+ reported.push(...(error.sany?.errors ?? []));
766
1217
  }
767
- return [name, expression];
768
- }),
769
- );
1218
+ reported.forEach((item) => add(errors, item));
1219
+ warned.forEach((item) => add(warnings, item));
1220
+ });
1221
+ return errors;
770
1222
  };
771
1223
 
1224
+ // SANY binds the names of a module in the order of its units, and reports a RECURSIVE declaration
1225
+ // that no definition follows at the end. Returns the errors.
772
1226
  export const resolveModule = (module: Module, unit: ModuleUnit) => {
773
1227
  const symbols = createSymbols(module, unit.imported);
774
1228
  const facts = new Set(
775
1229
  [...module.theorems, ...module.assumptions].flatMap((fact) => fact.name ?? []),
776
1230
  );
777
- const createUnit = (location: SourceLocation, self: Definition | undefined) => ({
1231
+ const goals = new Map(
1232
+ module.theorems.flatMap((theorem): [string, Goal][] =>
1233
+ theorem.name !== undefined && theorem.statement.kind === "AssumeProve"
1234
+ ? [[theorem.name, { statement: theorem.statement, isSuffices: false, isInProof: false }]]
1235
+ : [],
1236
+ ),
1237
+ );
1238
+ const bindings = new Map<string, ModuleBinding>(
1239
+ [...CORE_SYMBOLS, ...unit.bound].map(([name, symbol]) => [
1240
+ name,
1241
+ { ...symbol, position: MODULE_START },
1242
+ ]),
1243
+ );
1244
+ const recursive = new Set<Binding>();
1245
+ const declarations: { declaration: Declaration; binding: ModuleBinding | undefined }[] = [];
1246
+ const createUnit = (
1247
+ location: SourceLocation,
1248
+ self: Definition | undefined,
1249
+ errors: SanyError[],
1250
+ warnings: SanyError[],
1251
+ hasLabelScope: boolean,
1252
+ ): Unit => ({
778
1253
  imported: symbols,
779
1254
  definitions: unit.definitions,
780
1255
  getKey: unit.getKey,
781
1256
  location,
782
1257
  self,
783
1258
  facts,
1259
+ goals,
1260
+ bindings,
1261
+ errors,
1262
+ warnings,
1263
+ hasLabelScope,
1264
+ isLabelForbidden: false,
1265
+ isGenerated: false,
784
1266
  });
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)),
1267
+ const bindDeclarations = (declarations: Declaration[], kind: "Constant" | "Variable") =>
1268
+ declarations.map((declaration) => ({
1269
+ location: declaration.location,
1270
+ check: (errors: SanyError[], warnings: SanyError[]) =>
1271
+ bindModuleName(
1272
+ declaration.name,
1273
+ { kind, arity: declaration.arity, range: declaration.location.range },
1274
+ createUnit(declaration.location, undefined, errors, warnings, false),
1275
+ ),
1276
+ }));
1277
+ return collectSemanticErrors(
1278
+ [
1279
+ ...unit.reports.map((report) => ({
1280
+ location: report.location,
1281
+ check: (errors: SanyError[], warnings: SanyError[]) => {
1282
+ errors.push(...report.errors);
1283
+ warnings.push(...report.warnings);
1284
+ },
1285
+ })),
1286
+ ...bindDeclarations(module.constants, "Constant"),
1287
+ ...bindDeclarations(module.variables, "Variable"),
1288
+ ...module.units
1289
+ .flatMap((item) => (item.kind === "Recursive" ? item.declarations : []))
1290
+ .map((declaration) => ({
1291
+ location: declaration.location,
1292
+ check: (errors: SanyError[], warnings: SanyError[]) => {
1293
+ const binding: ModuleBinding = {
1294
+ kind: "Definition",
1295
+ arity: declaration.arity,
1296
+ range: declaration.location.range,
1297
+ position: declaration.location,
1298
+ isPending: true,
1299
+ };
1300
+ const isBound = isBindable(
1301
+ declaration.name,
1302
+ bindings.get(declaration.name),
1303
+ binding,
1304
+ createUnit(declaration.location, undefined, errors, warnings, false),
1305
+ );
1306
+ if (isBound) {
1307
+ bindings.set(declaration.name, binding);
1308
+ recursive.add(binding);
1309
+ }
1310
+ declarations.push({ declaration, binding: isBound ? binding : undefined });
1311
+ },
1312
+ })),
1313
+ ...module.definitions.map((definition) => ({
1314
+ location: definition.location,
1315
+ check: (errors: SanyError[], warnings: SanyError[]) => {
1316
+ const inner = createUnit(definition.location, definition, errors, warnings, true);
1317
+ if (isTheoremDefinition(module, definition)) {
1318
+ resolveExpression(definition.body, undefined, inner);
1319
+ } else if (resolveDefinition(definition, undefined, inner, recursive)) {
1320
+ bindings.set(definition.name, {
1321
+ kind: "Definition",
1322
+ arity: getArity(definition),
1323
+ range: definition.location.range,
1324
+ position: definition.location,
1325
+ });
1326
+ }
1327
+ },
1328
+ })),
1329
+ ...module.instances.map((instance) => ({
1330
+ location: instance.location,
1331
+ check: (errors: SanyError[], warnings: SanyError[]) => {
1332
+ const inner = createUnit(instance.location, undefined, errors, warnings, false);
1333
+ bindParams(undefined, instance.params, inner);
1334
+ unit.instanced
1335
+ .get(instance)
1336
+ ?.forEach((symbol, name) => bindModuleName(name, symbol, inner));
1337
+ if (instance.name !== undefined) {
1338
+ bindModuleName(
1339
+ instance.name,
1340
+ { kind: "Instance", arity: instance.params.length, range: instance.location.range },
1341
+ inner,
1342
+ );
1343
+ }
1344
+ },
1345
+ })),
1346
+ // An assumption holds the subexpressions its references select, labels and all, so its own
1347
+ // labels go unchecked.
1348
+ ...module.assumptions.map((assumption) => ({
1349
+ location: assumption.location,
1350
+ check: (errors: SanyError[], warnings: SanyError[]) => {
1351
+ const inner = createUnit(assumption.location, undefined, errors, warnings, true);
1352
+ resolveExpression(assumption.expression, undefined, inner);
1353
+ if (assumption.name !== undefined) {
1354
+ bindModuleName(
1355
+ assumption.name,
1356
+ { kind: "Theorem", arity: 0, range: assumption.location.range },
1357
+ inner,
1358
+ );
1359
+ }
1360
+ },
1361
+ })),
1362
+ ...module.theorems.map((theorem) => ({
1363
+ location: theorem.location,
1364
+ check: (errors: SanyError[], warnings: SanyError[]) =>
1365
+ resolveTheorem(
1366
+ theorem,
1367
+ createUnit(theorem.location, undefined, errors, warnings, theorem.name !== undefined),
1368
+ ),
1369
+ })),
1370
+ ...module.uses.map((use) => ({
1371
+ location: use.location,
1372
+ check: (errors: SanyError[], warnings: SanyError[]) =>
1373
+ checkFacts(
1374
+ use.facts,
1375
+ undefined,
1376
+ createUnit(use.location, undefined, errors, warnings, false),
1377
+ ),
1378
+ })),
1379
+ {
1380
+ location: module.location.range?.end ?? module.location,
1381
+ check: (errors: SanyError[]) =>
1382
+ declarations.forEach((item) => {
1383
+ const range = item.declaration.location.range;
1384
+ if (range && (!item.binding || item.binding.isPending)) {
1385
+ errors.push({
1386
+ location: formatRange(range),
1387
+ message: `Symbol ${item.declaration.name} declared in RECURSIVE statement but not defined.`,
1388
+ });
1389
+ }
1390
+ }),
1391
+ },
1392
+ ],
1393
+ unit.warnings,
793
1394
  );
794
1395
  };