tla-ts 0.0.3-dev.037ac3b → 0.0.3-dev.0ad0249

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/dist/cli.cjs +1 -1
  2. package/dist/cli.js +1 -1
  3. package/dist/index.cjs +1 -1
  4. package/dist/index.d.cts +146 -8
  5. package/dist/index.d.ts +146 -8
  6. package/dist/index.js +1 -1
  7. package/dist/parallel-worker.cjs +1 -1
  8. package/dist/parallel-worker.js +2 -2
  9. package/dist/parallel.cjs +1 -1
  10. package/dist/parallel.js +2 -2
  11. package/dist/run-cli.cjs +1351 -20
  12. package/dist/run-cli.js +1351 -20
  13. package/dist/transfer.cjs +86 -28
  14. package/dist/transfer.js +86 -28
  15. package/package.json +4 -1
  16. package/src/ast.ts +48 -6
  17. package/src/bags.ts +4 -7
  18. package/src/builtins.ts +29 -11
  19. package/src/bundled-modules.ts +3 -3
  20. package/src/canonical.ts +4 -3
  21. package/src/check.ts +1330 -215
  22. package/src/cli.ts +8 -1
  23. package/src/codegen.ts +68 -18
  24. package/src/config.ts +252 -179
  25. package/src/environment.ts +451 -129
  26. package/src/errors.ts +217 -3
  27. package/src/evaluate.ts +724 -117
  28. package/src/exit-codes.ts +5 -4
  29. package/src/index.ts +1 -0
  30. package/src/instances.ts +4 -2
  31. package/src/java-overrides.ts +104 -25
  32. package/src/levels.ts +183 -37
  33. package/src/lexer.ts +14 -1
  34. package/src/live-check.ts +220 -84
  35. package/src/liveness.ts +192 -65
  36. package/src/obligation-expression.ts +2 -2
  37. package/src/obligation-source.ts +2 -0
  38. package/src/parallel-worker.ts +8 -3
  39. package/src/parallel.ts +56 -5
  40. package/src/parser.ts +423 -126
  41. package/src/pcal-ast.ts +770 -0
  42. package/src/pcal-parse.ts +1523 -0
  43. package/src/pcal-tokenize.ts +516 -0
  44. package/src/pcal-translate.ts +1230 -0
  45. package/src/pcal-validate.ts +454 -0
  46. package/src/randomization.ts +24 -7
  47. package/src/resolve.ts +1363 -405
  48. package/src/run-cli.ts +1167 -155
  49. package/src/runtime.ts +16 -0
  50. package/src/sany-builtins.ts +147 -0
  51. package/src/sany-generator.ts +3112 -0
  52. package/src/sany-levels.ts +1208 -0
  53. package/src/sany-lexer.ts +545 -0
  54. package/src/sany-linter.ts +122 -0
  55. package/src/sany-modules.ts +1398 -0
  56. package/src/sany-nodes.ts +463 -0
  57. package/src/sany-parse-error.ts +2161 -0
  58. package/src/sany-report.ts +354 -0
  59. package/src/sany-selectors.ts +738 -0
  60. package/src/sany-source.ts +248 -0
  61. package/src/sany-xml.ts +1017 -0
  62. package/src/spec-description.ts +26 -7
  63. package/src/standard-modules.ts +203 -146
  64. package/src/standard-ranges.ts +116 -0
  65. package/src/state-graph.ts +29 -6
  66. package/src/subexpressions.ts +221 -161
  67. package/src/substitution-levels.ts +38 -17
  68. package/src/successors.ts +162 -114
  69. package/src/symmetry.ts +180 -52
  70. package/src/tableau.ts +4 -2
  71. package/src/tlc-ext.ts +13 -17
  72. package/src/tlc-messages.ts +329 -0
  73. package/src/tlc-module.ts +46 -18
  74. package/src/tlc-order.ts +56 -6
  75. package/src/tlc-random.ts +28 -3
  76. package/src/tlc-replay.ts +655 -0
  77. package/src/tlc-version.ts +18 -0
  78. package/src/transfer.ts +15 -3
  79. package/src/value-sources.ts +29 -0
  80. package/src/values.ts +684 -204
@@ -1,17 +1,31 @@
1
1
  import {
2
2
  getChildren,
3
+ type AssumeProve,
3
4
  type Bound,
4
5
  type Definition,
5
6
  type Expression,
7
+ type Fact,
6
8
  type Instance,
7
9
  type Module,
8
10
  type OperatorParam,
11
+ type Proof,
9
12
  type Selector,
10
13
  type SourceLocation,
14
+ type SourceRange,
15
+ type StepBody,
11
16
  } from "./ast";
12
- import { TlaSyntaxError } from "./errors";
17
+ import { formatRange, TlaSyntaxError } from "./errors";
13
18
  import { getSourceName, mapChildren, mapDefinition } from "./instances";
14
- import { getArity, getBoundNames, getPatternNames, LOCAL_RESOLUTION } from "./resolve";
19
+ import {
20
+ getArity,
21
+ getBinder,
22
+ getNameSelectors,
23
+ getOperandIndex,
24
+ getOperands,
25
+ LOCAL_RESOLUTION,
26
+ selectionErrors,
27
+ selections,
28
+ } from "./resolve";
15
29
 
16
30
  type Lookup = (name: string) => Definition | undefined;
17
31
 
@@ -27,114 +41,19 @@ interface Selection {
27
41
  location: SourceLocation;
28
42
  }
29
43
 
44
+ // A name that selects a subexpression, with the range of each part and of the arguments of each
45
+ // part, where SANY reports an error in selecting that part.
46
+ interface SelectingName {
47
+ location: SourceLocation;
48
+ selectorRanges?: SourceRange[];
49
+ argumentRanges?: (SourceRange | undefined)[];
50
+ }
51
+
30
52
  const SELECTION_NAME = "$subexpression";
31
53
 
32
54
  const createError = (message: string, location: SourceLocation) =>
33
55
  new TlaSyntaxError(`${message} at line ${location.line}, column ${location.column}`);
34
56
 
35
- const getBoundSets = (bounds: Bound[]) =>
36
- bounds
37
- .filter((bound, index) => index === 0 || bounds[index - 1].set !== bound.set)
38
- .map((bound) => bound.set);
39
-
40
- const getOperandIndex = (operand: number | "<<" | ">>", count: number) => {
41
- if (typeof operand === "number") return operand >= 1 && operand <= count ? operand - 1 : -1;
42
- if (operand === "<<") return count > 0 ? 0 : -1;
43
- return count === 2 ? 1 : -1;
44
- };
45
-
46
- const getOperands = (expression: Expression): Expression[] | undefined => {
47
- switch (expression.kind) {
48
- case "Apply":
49
- return expression.args;
50
- case "And":
51
- case "Or":
52
- return expression.operands;
53
- case "If":
54
- return [expression.condition, expression.consequent, expression.alternative];
55
- case "Tuple":
56
- case "SetEnumeration":
57
- return expression.elements;
58
- case "Record":
59
- case "RecordSet":
60
- return expression.fields.map((field) => field.value);
61
- case "FunctionApplication":
62
- return [
63
- expression.function,
64
- expression.args.length === 1
65
- ? expression.args[0]
66
- : { kind: "Tuple", elements: expression.args, location: expression.location },
67
- ];
68
- case "FieldAccess":
69
- return [
70
- expression.record,
71
- { kind: "String", value: expression.field, location: expression.location },
72
- ];
73
- case "Prime":
74
- case "Unchanged":
75
- case "Enabled":
76
- case "Always":
77
- case "Eventually":
78
- return [expression.expression];
79
- case "BoxAction":
80
- case "AngleAction":
81
- return [expression.action, expression.subscript];
82
- case "WeakFairness":
83
- case "StrongFairness":
84
- return [expression.subscript, expression.action];
85
- case "FunctionSet":
86
- return [expression.domain, expression.range];
87
- case "Product":
88
- return expression.factors;
89
- case "Except":
90
- return [expression.function];
91
- default:
92
- return undefined;
93
- }
94
- };
95
-
96
- const getBinder = (
97
- expression: Expression,
98
- ): { names: string[]; body: Expression; sets: Expression[] } | undefined => {
99
- switch (expression.kind) {
100
- case "Forall":
101
- case "Exists":
102
- case "FunctionConstruction":
103
- return {
104
- names: getBoundNames(expression.bounds),
105
- body: expression.body,
106
- sets: getBoundSets(expression.bounds),
107
- };
108
- case "SetMap":
109
- return {
110
- names: getBoundNames(expression.bounds),
111
- body: expression.expression,
112
- sets: getBoundSets(expression.bounds),
113
- };
114
- case "SetFilter":
115
- return {
116
- names: getPatternNames(expression.bound.pattern),
117
- body: expression.predicate,
118
- sets: [expression.bound.set],
119
- };
120
- case "Choose":
121
- return {
122
- names: getPatternNames(expression.pattern),
123
- body: expression.body,
124
- sets: expression.set ? [expression.set] : [],
125
- };
126
- case "UnboundedQuantifier":
127
- case "Lambda":
128
- return {
129
- names: expression.kind === "Lambda" ? expression.params : expression.names,
130
- body: expression.body,
131
- sets: [],
132
- };
133
- default:
134
- return undefined;
135
- }
136
- };
137
-
138
57
  const findLabel = (
139
58
  expression: Expression,
140
59
  name: string,
@@ -153,9 +72,6 @@ const findLabel = (
153
72
  return undefined;
154
73
  };
155
74
 
156
- const takeArguments = (args: Expression[], count: number, pool: Expression[]) =>
157
- args.length === 0 && pool.length > 0 ? pool.splice(0, count) : args;
158
-
159
75
  const wrapLets = (body: Expression, lets: Definition[][], location: SourceLocation) =>
160
76
  lets.reduceRight<Expression>(
161
77
  (inner, definitions) => ({ kind: "Let", definitions, body: inner, location }),
@@ -235,14 +151,30 @@ const applyDefinition = (definition: Definition, selection: Selection) => {
235
151
  return createApplication({ ...selection, params: [...selection.params, ...params] }, reference);
236
152
  };
237
153
 
154
+ // Generator.selectorToNode reports the first part of a name that selects nothing, after it analyzes
155
+ // the arguments of the parts before, and goes on after the name. An operator or a label must be given
156
+ // all its arguments, except in a name that an operator argument may select whole.
238
157
  const selectSubexpression = (
239
158
  selectors: Selector[],
240
159
  lookup: Lookup,
241
- location: SourceLocation,
242
- pool: Expression[],
160
+ reference: Expression & SelectingName,
161
+ isOperator: boolean,
243
162
  ): Expression => {
163
+ const location = reference.location;
244
164
  const selection: Selection = { params: [], args: [], lets: [], location };
245
- const state = { index: 0, current: undefined as Expression | undefined };
165
+ const state = { index: 0, current: undefined as Expression | undefined, isFailed: false };
166
+
167
+ const report = (range: SourceRange | undefined, message: string) => {
168
+ if (!range) throw createError(message, location);
169
+ selectionErrors.set(reference, {
170
+ args: selectors
171
+ .slice(0, state.index)
172
+ .flatMap((selector) => ("args" in selector ? selector.args : [])),
173
+ error: { location: formatRange(range), message },
174
+ });
175
+ state.isFailed = true;
176
+ return undefined;
177
+ };
246
178
 
247
179
  const findDefinition = (local: Definition[] | undefined) => {
248
180
  const names: string[] = [];
@@ -256,9 +188,8 @@ const selectSubexpression = (
256
188
  const definition = local
257
189
  ? local.find((candidate) => getSourceName(candidate) === name)
258
190
  : lookup(name);
259
- if (definition) {
260
- return { definition, args: takeArguments(args, getArity(definition), pool) };
261
- }
191
+ if (definition)
192
+ return { definition, name, args, earlier: args.length - selector.args.length };
262
193
  state.index++;
263
194
  }
264
195
  throw createError(`Unknown operator ${names.join("!")}`, location);
@@ -269,8 +200,11 @@ const selectSubexpression = (
269
200
  const definition = found.definition;
270
201
  const arity = getArity(definition);
271
202
  const isLast = state.index === selectors.length - 1;
272
- if (found.args.length !== arity && found.args.length !== 0) {
273
- throw createError(`The operator ${definition.name} requires ${arity} arguments`, location);
203
+ if (found.args.length !== arity && (!isOperator || found.args.length !== 0)) {
204
+ return report(
205
+ reference.argumentRanges?.[state.index] ?? location.range,
206
+ `The operator ${found.name} requires ${arity - found.earlier} arguments.`,
207
+ );
274
208
  }
275
209
  if (isLast) return { definition, args: found.args };
276
210
  if (definition.kind !== "Operator") {
@@ -284,14 +218,19 @@ const selectSubexpression = (
284
218
  };
285
219
 
286
220
  const followLabels = () => {
287
- while (state.index < selectors.length) {
221
+ while (state.index < selectors.length && !state.isFailed) {
288
222
  const selector = selectors[state.index];
289
223
  if (selector.kind !== "Name") return;
224
+ const range = reference.selectorRanges?.[state.index];
290
225
  const found = state.current && findLabel(state.current, selector.name, []);
291
- if (!found) throw createError(`Cannot find label ${selector.name}`, location);
226
+ if (!found) return report(range, `Cannot find label \`${selector.name}'.`);
227
+ const params = found.label.params;
228
+ if (!isOperator && selector.args.length !== params.length) {
229
+ return report(range, `Label \`${selector.name}' used with wrong number of arguments.`);
230
+ }
292
231
  selection.lets.push(...found.lets);
293
- selection.params.push(...found.label.params.map((name) => ({ name, arity: 0 })));
294
- selection.args.push(...takeArguments(selector.args, found.label.params.length, pool));
232
+ selection.params.push(...params.map((name) => ({ name, arity: 0 })));
233
+ selection.args.push(...selector.args);
295
234
  state.current = found.label.body;
296
235
  state.index++;
297
236
  }
@@ -317,9 +256,7 @@ const selectSubexpression = (
317
256
  const binder = getBinder(current);
318
257
  if (binder && (selector.kind === "Bound" || selector.kind === "At")) {
319
258
  selection.params.push(...binder.names.map((name) => ({ name, arity: 0 })));
320
- if (selector.kind === "Bound") {
321
- selection.args.push(...takeArguments(selector.args, binder.names.length, pool));
322
- }
259
+ if (selector.kind === "Bound") selection.args.push(...selector.args);
323
260
  state.current = binder.body;
324
261
  return;
325
262
  }
@@ -349,9 +286,10 @@ const selectSubexpression = (
349
286
  };
350
287
 
351
288
  const first = enterDefinition(undefined);
289
+ if (state.isFailed) return reference;
352
290
  if (first) return applyDefinition(first.definition, { ...selection, args: first.args });
353
291
  followLabels();
354
- while (state.index < selectors.length) {
292
+ while (state.index < selectors.length && !state.isFailed) {
355
293
  const selector = selectors[state.index];
356
294
  if (selector.kind === "Name") {
357
295
  while (state.current?.kind === "Label") state.current = state.current.body;
@@ -360,6 +298,7 @@ const selectSubexpression = (
360
298
  }
361
299
  selection.lets.push(state.current.definitions);
362
300
  const last = enterDefinition(state.current.definitions);
301
+ if (state.isFailed) return reference;
363
302
  if (last) {
364
303
  return applyDefinition(last.definition, {
365
304
  ...selection,
@@ -372,19 +311,22 @@ const selectSubexpression = (
372
311
  selectOperand(selector);
373
312
  state.index++;
374
313
  }
314
+ if (state.isFailed) return reference;
375
315
  if (!state.current) throw createError("Subexpression selection failed", location);
376
316
  return createApplication(selection, state.current);
377
317
  };
378
318
 
379
- const getQualifiedSelectors = (name: string, lookup: Lookup): Selector[] | undefined => {
319
+ // A name such as Op(1)!lab(2) whose first parts name a definition selects part of it.
320
+ const getQualifiedSelectors = (
321
+ name: string,
322
+ args: Expression[],
323
+ counts: number[] | undefined,
324
+ lookup: Lookup,
325
+ ) => {
380
326
  if (!name.includes("!") || lookup(name)) return undefined;
381
327
  const parts = name.split("!");
382
- const prefix = parts.findIndex((_, index) => lookup(parts.slice(0, index + 1).join("!")));
383
- if (prefix === -1) return undefined;
384
- return [
385
- { kind: "Name", name: parts.slice(0, prefix + 1).join("!"), args: [] },
386
- ...parts.slice(prefix + 1).map((part): Selector => ({ kind: "Name", name: part, args: [] })),
387
- ];
328
+ if (!parts.some((_, index) => lookup(parts.slice(0, index + 1).join("!")))) return undefined;
329
+ return getNameSelectors(name, args, counts);
388
330
  };
389
331
 
390
332
  const containsReference = (expression: Expression): boolean =>
@@ -393,57 +335,175 @@ const containsReference = (expression: Expression): boolean =>
393
335
  (expression.kind === "Apply" && expression.operator.includes("!")) ||
394
336
  getChildren(expression).some(containsReference);
395
337
 
396
- const resolveSubexpressions = (expression: Expression, lookup: Lookup): Expression => {
338
+ // A reference that starts with a name isGoal holds for, such as a theorem whose statement is an
339
+ // ASSUME/PROVE, stays for name resolution to check. isOperator holds where an operator may be given,
340
+ // as the argument of an operator that may take one.
341
+ const resolveSubexpressions = (
342
+ expression: Expression,
343
+ lookup: Lookup,
344
+ isGoal: (name: string) => boolean,
345
+ isOperator = false,
346
+ ): Expression => {
397
347
  if (!containsReference(expression)) return expression;
398
348
  if (expression.kind === "Let") {
399
349
  const local: Lookup = (name) =>
400
350
  expression.definitions.find((definition) => definition.name === name) ?? lookup(name);
401
- return mapChildren(expression, (child) => resolveSubexpressions(child, local));
351
+ const mapped = mapChildren(expression, (child) => resolveSubexpressions(child, local, isGoal));
352
+ return mapped.kind === "Let" && mapped.instances
353
+ ? {
354
+ ...mapped,
355
+ instances: mapped.instances.map((instance) => resolveInstance(instance, local, isGoal)),
356
+ }
357
+ : mapped;
402
358
  }
403
- const mapped = mapChildren(expression, (child) => resolveSubexpressions(child, lookup));
404
- if (mapped.kind === "Subexpression") {
405
- return selectSubexpression(mapped.selectors, lookup, mapped.location, []);
406
- }
407
- const name =
408
- mapped.kind === "Identifier" ? mapped.name : mapped.kind === "Apply" ? mapped.operator : "";
409
- const selectors = getQualifiedSelectors(name, lookup);
410
- if (!selectors) return mapped;
411
- const pool = mapped.kind === "Apply" ? [...mapped.args] : [];
412
- const resolved = selectSubexpression(selectors, lookup, mapped.location, pool);
413
- if (pool.length > 0) throw createError(`Too many arguments for ${name}`, mapped.location);
414
- return resolved;
359
+ const callee = expression.kind === "Apply" ? lookup(expression.operator) : undefined;
360
+ const mapped =
361
+ expression.kind === "Apply"
362
+ ? {
363
+ ...expression,
364
+ args: expression.args.map((arg, index) =>
365
+ resolveSubexpressions(
366
+ arg,
367
+ lookup,
368
+ isGoal,
369
+ callee?.kind !== "Operator" || callee.params[index]?.arity !== 0,
370
+ ),
371
+ ),
372
+ }
373
+ : mapChildren(expression, (child) => resolveSubexpressions(child, lookup, isGoal));
374
+ const selectors =
375
+ mapped.kind === "Subexpression"
376
+ ? mapped.selectors
377
+ : mapped.kind === "Identifier"
378
+ ? getQualifiedSelectors(mapped.name, [], undefined, lookup)
379
+ : mapped.kind === "Apply"
380
+ ? getQualifiedSelectors(mapped.operator, mapped.args, mapped.argumentCounts, lookup)
381
+ : undefined;
382
+ const first = selectors?.[0];
383
+ if (!selectors || (first?.kind === "Name" && isGoal(first.name))) return mapped;
384
+ const selected = selectSubexpression(selectors, lookup, mapped, isOperator);
385
+ if (selected !== mapped) selections.add(selected);
386
+ return selected;
415
387
  };
416
388
 
389
+ const resolveInstance = (
390
+ instance: Instance,
391
+ lookup: Lookup,
392
+ isGoal: (name: string) => boolean,
393
+ ): Instance => ({
394
+ ...instance,
395
+ substitutions: instance.substitutions.map((substitution) => ({
396
+ ...substitution,
397
+ expression: resolveSubexpressions(substitution.expression, lookup, isGoal, true),
398
+ })),
399
+ });
400
+
417
401
  const createLookup = (definitions: Definition[]): Lookup => {
418
402
  const byName = new Map(definitions.map((definition) => [definition.name, definition]));
419
403
  return (name) => byName.get(name);
420
404
  };
421
405
 
422
- export const resolveInstanceSubexpressions = (instance: Instance, module: Module): Instance => {
423
- const lookup = createLookup(module.definitions);
424
- return {
425
- ...instance,
426
- substitutions: instance.substitutions.map((substitution) => ({
427
- name: substitution.name,
428
- expression: resolveSubexpressions(substitution.expression, lookup),
429
- })),
430
- };
431
- };
406
+ export const resolveInstanceSubexpressions = (instance: Instance, module: Module): Instance =>
407
+ resolveInstance(instance, createLookup(module.definitions), () => false);
432
408
 
409
+ // Generator.selectorToNode resolves a name in a theorem, a proof, or a fact as it does in a definition.
433
410
  export const resolveModuleSubexpressions = (module: Module, available: Definition[]): Module => {
434
411
  const lookup = createLookup([...available, ...module.definitions]);
412
+ const goals = new Set(
413
+ module.theorems.flatMap((theorem) =>
414
+ theorem.name !== undefined && theorem.statement.kind === "AssumeProve" ? [theorem.name] : [],
415
+ ),
416
+ );
417
+ const isGoal = (name: string) => goals.has(name);
418
+ const resolve = (expression: Expression) => resolveSubexpressions(expression, lookup, isGoal);
419
+ // A name in a theorem, a proof, or a fact may also start with a step, a theorem, or a symbol that
420
+ // no definition names.
421
+ const isProofGoal = (name: string) => isGoal(name) || !lookup(name);
422
+ const resolveInProof = (expression: Expression) =>
423
+ resolveSubexpressions(expression, lookup, isProofGoal);
424
+ const resolveFacts = (facts: Fact[]) =>
425
+ facts.map((fact) => (fact.kind === "ModuleFact" ? fact : resolveInProof(fact)));
426
+ const resolveBounds = (bounds: Bound[]) =>
427
+ bounds.map((bound) => ({ ...bound, set: resolveInProof(bound.set) }));
428
+ const resolveStatement = (statement: Expression | AssumeProve): Expression | AssumeProve =>
429
+ statement.kind === "AssumeProve"
430
+ ? {
431
+ ...statement,
432
+ assumptions: statement.assumptions.map((assumption) =>
433
+ assumption.kind === "NewSymbol"
434
+ ? { ...assumption, set: assumption.set && resolveInProof(assumption.set) }
435
+ : resolveStatement(assumption),
436
+ ),
437
+ conclusion: resolveInProof(statement.conclusion),
438
+ }
439
+ : resolveInProof(statement);
440
+ const resolveStep = (body: StepBody): StepBody => {
441
+ switch (body.kind) {
442
+ case "Use":
443
+ case "Hide":
444
+ return { ...body, facts: resolveFacts(body.facts) };
445
+ case "Instance":
446
+ return resolveInstance(body, lookup, isProofGoal);
447
+ case "Define":
448
+ return {
449
+ ...body,
450
+ definitions: body.definitions.map((definition) =>
451
+ definition.kind === "Instance"
452
+ ? resolveInstance(definition, lookup, isProofGoal)
453
+ : mapDefinition(definition, resolveInProof),
454
+ ),
455
+ };
456
+ case "Have":
457
+ case "Case":
458
+ return { ...body, expression: resolveInProof(body.expression) };
459
+ case "Witness":
460
+ return { ...body, expressions: body.expressions.map(resolveInProof) };
461
+ case "Take":
462
+ return { ...body, bounds: resolveBounds(body.bounds) };
463
+ case "Pick":
464
+ return { ...body, bounds: resolveBounds(body.bounds), body: resolveInProof(body.body) };
465
+ case "Assert":
466
+ return { ...body, statement: resolveStatement(body.statement) };
467
+ default:
468
+ return body;
469
+ }
470
+ };
471
+ const resolveProof = (proof: Proof | undefined): Proof | undefined =>
472
+ proof?.kind === "By"
473
+ ? { ...proof, facts: resolveFacts(proof.facts) }
474
+ : proof?.kind === "Steps"
475
+ ? {
476
+ ...proof,
477
+ steps: proof.steps.map((step) => ({
478
+ ...step,
479
+ body: resolveStep(step.body),
480
+ proof: resolveProof(step.proof),
481
+ })),
482
+ }
483
+ : proof;
484
+ const resolved = {
485
+ ...module,
486
+ // A named theorem's statement is resolved as its definition.
487
+ theorems: module.theorems.map((theorem) => ({
488
+ ...theorem,
489
+ statement:
490
+ theorem.name !== undefined && theorem.statement.kind !== "AssumeProve"
491
+ ? theorem.statement
492
+ : resolveStatement(theorem.statement),
493
+ proof: resolveProof(theorem.proof),
494
+ })),
495
+ uses: module.uses.map((use) => ({ ...use, facts: resolveFacts(use.facts) })),
496
+ };
435
497
  const hasReferences =
436
498
  module.definitions.some((definition) => containsReference(definition.body)) ||
437
499
  module.assumptions.some((assumption) => containsReference(assumption.expression));
438
- if (!hasReferences) return module;
500
+ if (!hasReferences) return resolved;
439
501
  return {
440
- ...module,
441
- definitions: module.definitions.map((definition) =>
442
- mapDefinition(definition, (child) => resolveSubexpressions(child, lookup)),
443
- ),
502
+ ...resolved,
503
+ definitions: module.definitions.map((definition) => mapDefinition(definition, resolve)),
444
504
  assumptions: module.assumptions.map((assumption) => ({
445
505
  ...assumption,
446
- expression: resolveSubexpressions(assumption.expression, lookup),
506
+ expression: resolve(assumption.expression),
447
507
  })),
448
508
  };
449
509
  };
@@ -1,6 +1,8 @@
1
- import type { Declaration, Definition, Expression, SourceLocation } from "./ast";
2
- import { TlaSyntaxError } from "./errors";
1
+ import type { Declaration, Definition, Expression, SourceLocation, Theorem } from "./ast";
2
+ import { createSanyError, formatRange } from "./errors";
3
3
  import {
4
+ ACTION_LEVEL,
5
+ analyzeAssumeProve,
4
6
  createLevelAnalyzer,
5
7
  getArgumentKey,
6
8
  MAX_LEVEL,
@@ -24,6 +26,7 @@ interface ModuleContext {
24
26
  variables: string[];
25
27
  definitions: Definition[];
26
28
  assumptions: Expression[];
29
+ theorems: Theorem[];
27
30
  getDefinition: (name: string) => Definition | undefined;
28
31
  }
29
32
 
@@ -46,10 +49,7 @@ interface Substituted {
46
49
  const getMaxLevel = (operator: OperatorLevels, index: number) =>
47
50
  operator.maxLevels[index] ?? MAX_LEVEL;
48
51
 
49
- export const checkInstances = (
50
- checks: InstanceCheck[],
51
- getModule: (name: string) => ModuleContext,
52
- ) => {
52
+ export const createInstanceChecker = (getModule: (name: string) => ModuleContext) => {
53
53
  const analyzers = new Map<string, ReturnType<typeof createLevelAnalyzer>>();
54
54
  const getAnalyzer = (name: string) => {
55
55
  const cached = analyzers.get(name);
@@ -101,17 +101,38 @@ export const checkInstances = (
101
101
  definition.formals.every((formal) => formal.name !== operator && formal.name !== param),
102
102
  ),
103
103
  );
104
+ const addAssumedLevels = (data: ReturnType<typeof analyzeAssumeProve>) => {
105
+ addLevels(data, () => true);
106
+ module.constants.forEach((constant) => {
107
+ if (data.params.has(constant.name)) {
108
+ putConstraint(levels.constraints, constant.name, ACTION_LEVEL);
109
+ }
110
+ });
111
+ };
104
112
  module.assumptions.forEach((assumption) =>
105
- addLevels(analyzer.analyze(assumption, new Map()), () => true),
113
+ addAssumedLevels(analyzer.analyze(assumption, new Map())),
114
+ );
115
+ module.theorems.forEach((theorem) =>
116
+ theorem.statement.kind === "AssumeProve"
117
+ ? addAssumedLevels(analyzeAssumeProve(theorem.statement, new Map(), analyzer))
118
+ : addLevels(analyzer.analyze(theorem.statement, new Map()), () => true),
106
119
  );
107
120
  moduleLevels.set(name, levels);
108
121
  return levels;
109
122
  };
110
123
 
111
- const messages = new Set<string>();
112
- checks.forEach((check) => {
113
- const location = `at line ${check.location.line}, column ${check.location.column}`;
114
- const addMessage = (message: string) => messages.add(`${message} ${location}`);
124
+ return (check: InstanceCheck) => {
125
+ const errors = new Map<string, { location: string; message: string }>();
126
+ // SANY reports each error at the whole instance.
127
+ const location = formatRange(
128
+ check.location.range ?? {
129
+ module: check.instancer,
130
+ start: check.location,
131
+ end: check.location,
132
+ },
133
+ );
134
+ const addMessage = (message: string) =>
135
+ errors.set(`${location}\n${message}`, { location, message });
115
136
  const instancee = getModule(check.module);
116
137
  const levels = getModuleLevels(check.module);
117
138
  const analyzer = getAnalyzer(check.instancer);
@@ -141,14 +162,14 @@ export const checkInstances = (
141
162
  ];
142
163
  });
143
164
  const getLevelMessage = (name: string, level: number) =>
144
- `Level error in instantiating module '${check.module}': the level of the expression or operator substituted for '${name}' must be at most ${level}`;
165
+ `Level error in instantiating module '${check.module}':\nThe level of the expression or operator substituted for '${name}' \nmust be at most ${level}.`;
145
166
  substituted.forEach((item) => {
146
167
  if (!levels.isConstant && item.level > item.maximumLevel) {
147
168
  addMessage(getLevelMessage(item.name, item.maximumLevel));
148
169
  }
149
170
  if (!item.isLeibniz) {
150
171
  addMessage(
151
- `Error in instantiating module '${check.module}': a non-Leibniz operator substituted for '${item.name}'`,
172
+ `Error in instantiating module '${check.module}':\n A non-Leibniz operator substituted for '${item.name}'.`,
152
173
  );
153
174
  }
154
175
  });
@@ -162,7 +183,7 @@ export const checkInstances = (
162
183
  const minimum = levels.argConstraints.get(getArgumentKey(item.name, index));
163
184
  if (minimum !== undefined && getMaxLevel(operator, index) < minimum) {
164
185
  addMessage(
165
- `Level error in instantiating module '${check.module}': the level of the argument ${index + 1} of the operator ${operator.name} must be at least ${minimum}`,
186
+ `Level error in instantiating module '${check.module}':\nThe level of the argument ${index + 1} of the operator ${operator.name} \nmust be at least ${minimum}.`,
166
187
  );
167
188
  }
168
189
  });
@@ -175,10 +196,10 @@ export const checkInstances = (
175
196
  const maximum = getMaxLevel(operator, parameter.index);
176
197
  if (argument.level > maximum) {
177
198
  addMessage(
178
- `Level error when instantiating module '${check.module}': the level of the argument ${parameter.index} of the operator ${parameter.operator}' must be at most ${maximum}`,
199
+ `Level error when instantiating module '${check.module}':\nThe level of the argument ${parameter.index} of the operator ${parameter.operator}' \nmust be at most ${maximum}.`,
179
200
  );
180
201
  }
181
202
  });
182
- });
183
- if (messages.size > 0) throw new TlaSyntaxError([...messages].join("\n"));
203
+ if (errors.size > 0) throw createSanyError([...errors.values()]);
204
+ };
184
205
  };