tla-ts 0.0.3-dev.07eab97 → 0.0.3-dev.0e500e5

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