tla-ts 0.0.3-dev.f6f300a → 0.0.3-dev.fac17cc

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/dist/cli.cjs +1 -1
  2. package/dist/cli.js +1 -1
  3. package/dist/index.cjs +1 -1
  4. package/dist/index.d.cts +149 -8
  5. package/dist/index.d.ts +149 -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 +82 -27
  14. package/dist/transfer.js +82 -27
  15. package/package.json +5 -1
  16. package/src/ast.ts +56 -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 +1335 -236
  22. package/src/cli.ts +8 -1
  23. package/src/codegen.ts +68 -21
  24. package/src/config.ts +252 -179
  25. package/src/environment.ts +431 -120
  26. package/src/errors.ts +207 -9
  27. package/src/evaluate.ts +716 -141
  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 +32 -4
  34. package/src/live-check.ts +204 -146
  35. package/src/liveness.ts +192 -63
  36. package/src/obligation-expression.ts +2 -2
  37. package/src/obligation-source.ts +2 -0
  38. package/src/parallel-worker.ts +6 -1
  39. package/src/parallel.ts +57 -6
  40. package/src/parser.ts +425 -144
  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 +1408 -400
  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 +168 -50
  70. package/src/tableau.ts +3 -1
  71. package/src/tlc-ext.ts +13 -17
  72. package/src/tlc-messages.ts +329 -0
  73. package/src/tlc-module.ts +49 -21
  74. package/src/tlc-modules.ts +0 -4
  75. package/src/tlc-order.ts +55 -9
  76. package/src/tlc-random.ts +28 -3
  77. package/src/tlc-replay.ts +655 -0
  78. package/src/tlc-version.ts +18 -0
  79. package/src/transfer.ts +15 -3
  80. package/src/value-sources.ts +29 -0
  81. package/src/values.ts +683 -256
@@ -0,0 +1,738 @@
1
+ import type { Expression } from "./ast";
2
+ import type { TlcVersion } from "./tlc-version";
3
+ import {
4
+ CONSTANT_DECL_KIND,
5
+ getContextSymbol,
6
+ getSymbolArity,
7
+ type AssumeProveNode,
8
+ type Context,
9
+ type ExprNode,
10
+ type ExprOrOpArgNode,
11
+ type FactNode,
12
+ type FormalParamNode,
13
+ type LabelNode,
14
+ type LevelNode,
15
+ type OpApplNode,
16
+ type OpArgNode,
17
+ type OpDefNode,
18
+ type SanyLocation,
19
+ type SubstInNode,
20
+ type SymbolNode,
21
+ type ThmOrAssumpDefNode,
22
+ } from "./sany-nodes";
23
+
24
+ // A port of SANY's Generator.selectorToNode, which turns a name such as Op(a)!lab(b)!:!2 into the
25
+ // semantic node it names, following the Subexpression algorithm of SANY's Subexpression.tla.
26
+
27
+ // An operand selector !i is the number i, and the other selectors are named after SANY's NameSel,
28
+ // NullSel, GGSel, LLSel, ColonSel and AtSel.
29
+ type SelectorOp = number | "Name" | "Null" | ">>" | "<<" | ":" | "@";
30
+
31
+ export interface SelectorItem {
32
+ op: SelectorOp;
33
+ name: string;
34
+ args: Expression[] | undefined;
35
+ // Where SANY locates the selector and its parenthesized arguments, when known.
36
+ location?: SanyLocation;
37
+ argsLocation?: SanyLocation;
38
+ }
39
+
40
+ interface SelectorGenerator {
41
+ version: TlcVersion | undefined;
42
+ resolveSymbol: (name: string) => SymbolNode | undefined;
43
+ resolveSynonym: (name: string) => string;
44
+ generateExpression: (expression: Expression) => ExprNode;
45
+ generateArgument: (
46
+ operator: SymbolNode,
47
+ index: number,
48
+ argument: Expression,
49
+ location: SanyLocation,
50
+ ) => ExprOrOpArgNode;
51
+ createOpAppl: (
52
+ operator: SymbolNode,
53
+ operands: ExprOrOpArgNode[],
54
+ location: SanyLocation,
55
+ ) => OpApplNode;
56
+ createOpArg: (operator: SymbolNode, location: SanyLocation) => OpArgNode;
57
+ createFormalParam: (
58
+ name: string,
59
+ arity: number,
60
+ location: SanyLocation | undefined,
61
+ ) => FormalParamNode;
62
+ createLambda: (params: FormalParamNode[], body: ExprNode, location: SanyLocation) => OpDefNode;
63
+ copySubstIn: (prefix: SubstInNode, body: ExprNode) => SubstInNode;
64
+ getBuiltin: (name: string) => OpDefNode;
65
+ // Errors.addMessage for an error SANY recovers from, and the null node SANY returns after one.
66
+ addError: (location: SanyLocation, text: string) => OpApplNode;
67
+ // Generator.illegalLabelRef and illegalAPPosRef: whether the node being generated lies outside
68
+ // the scope of a declaration that a label or a clause of an ASSUME/PROVE lies in.
69
+ isOutOfLabelScope: (label: LabelNode) => boolean;
70
+ isOutOfClauseScope: (assumeProve: AssumeProveNode, position: number) => boolean;
71
+ }
72
+
73
+ const PROOF_STEP_OPERATORS = new Map([
74
+ ["$Qed", "QED step"],
75
+ ["$Pfcase", "CASE"],
76
+ ["$Have", "HAVE"],
77
+ ["$Take", "TAKE"],
78
+ ["$Pick", "PICK"],
79
+ ["$Witness", "WITNESS"],
80
+ ["$Suffices", "SUFFICES"],
81
+ ]);
82
+
83
+ // The parts of a name like I!Op or Op!lab, except for an operator such as !! that contains a "!".
84
+ const getNameParts = (name: string) => {
85
+ const parts = name.split("!");
86
+ return parts.some((part) => part.length === 0) ? [name] : parts;
87
+ };
88
+
89
+ // The selector of a name, an application of a name or a subexpression reference.
90
+ export const getSelectorItems = (expression: Expression): SelectorItem[] | undefined => {
91
+ switch (expression.kind) {
92
+ case "Identifier":
93
+ return getNameParts(expression.name).map((name) => ({ op: "Name", name, args: undefined }));
94
+ case "Apply": {
95
+ const parts = getNameParts(expression.operator);
96
+ const counts =
97
+ expression.argumentCounts ??
98
+ parts.map((_, index) => (index === parts.length - 1 ? expression.args.length : 0));
99
+ const cursor = { value: 0 };
100
+ return parts.map((name, index) => {
101
+ const args = expression.args.slice(cursor.value, cursor.value + counts[index]);
102
+ cursor.value += counts[index];
103
+ return { op: "Name", name, args: args.length > 0 ? args : undefined };
104
+ });
105
+ }
106
+ case "Subexpression":
107
+ return expression.selectors.map((selector): SelectorItem => {
108
+ switch (selector.kind) {
109
+ case "Name":
110
+ return {
111
+ op: "Name",
112
+ name: selector.name,
113
+ args: selector.args.length > 0 ? selector.args : undefined,
114
+ };
115
+ case "Operand":
116
+ return { op: selector.operand, name: String(selector.operand), args: undefined };
117
+ case "Bound":
118
+ return { op: "Null", name: "!(...)", args: selector.args };
119
+ case "At":
120
+ return { op: "@", name: "@", args: undefined };
121
+ case "Colon":
122
+ return { op: ":", name: ":", args: undefined };
123
+ }
124
+ });
125
+ }
126
+ return undefined;
127
+ };
128
+
129
+ // A selector SANY parses as a GeneralId rather than an OpApplication: one whose last part is not a
130
+ // name with arguments.
131
+ export const isGeneralId = (items: SelectorItem[]) => {
132
+ const last = items[items.length - 1];
133
+ return last.op !== "Name" || last.args === undefined;
134
+ };
135
+
136
+ // SANY's selectorItemToString, which names an operand selector after the argument it selects.
137
+ const getSelectorItemName = (item: SelectorItem) =>
138
+ typeof item.op === "number" ? `argument selector ${item.name}` : item.name;
139
+
140
+ // Subexpression.tla's ArgNum: the human number of the operand that a selector picks out of an
141
+ // expression with arity operands, or -1.
142
+ const getArgNumber = (op: SelectorOp, arity: number) => {
143
+ if (typeof op === "number") return op > 0 && op <= arity ? op : -1;
144
+ if (op === "<<") return arity > 0 ? 1 : -1;
145
+ if (op === ">>") return arity === 2 ? 2 : -1;
146
+ return -1;
147
+ };
148
+
149
+ type Mode = "FindingOpName" | "FollowingLabels" | "FindingSubExpr";
150
+
151
+ // The state of Generator.selectorToNode as it walks the items.
152
+ interface SelectorWalk {
153
+ name: string | undefined;
154
+ nameLocation: SanyLocation | undefined;
155
+ node: LevelNode | SymbolNode | undefined;
156
+ index: number;
157
+ mode: Mode;
158
+ previousMode: Mode | undefined;
159
+ letInContext: Context | undefined;
160
+ definitionArityFound: number;
161
+ definitionArgs: ExprOrOpArgNode[];
162
+ isInSuffices: boolean;
163
+ }
164
+
165
+ const isDeclarationLike = (node: SymbolNode) =>
166
+ node.kind === "OpDecl" ||
167
+ node.kind === "FormalParam" ||
168
+ (node.kind === "OpDef" && (node.defKind === "BuiltIn" || node.defKind === "NumberedProofStep"));
169
+
170
+ const isSymbol = (node: LevelNode | SymbolNode): node is SymbolNode =>
171
+ node.kind === "FormalParam" ||
172
+ node.kind === "OpDecl" ||
173
+ node.kind === "OpDef" ||
174
+ node.kind === "ThmOrAssumpDef" ||
175
+ node.kind === "Module";
176
+
177
+ // The symbols a quantifier binds: its bounded ones if it has any, else its unbounded ones.
178
+ const getQuantifierSymbols = (node: OpApplNode) =>
179
+ (node.bounded?.length ?? 0) > 0 ? (node.bounded ?? []).flat() : (node.unbounded ?? []);
180
+
181
+ // Generator.extendedBy: a name's location grown to the end of its next part.
182
+ const extendLocation = (name: SanyLocation | undefined, part: SanyLocation): SanyLocation =>
183
+ name === undefined ? part : { ...name, endLine: part.endLine, endColumn: part.endColumn };
184
+
185
+ // selectorToNode: with expectedArity 0 the expression a selector names, with a positive one the
186
+ // operator argument, and with -1 the definition a DEF clause names. A fact can also be an
187
+ // ASSUME/PROVE, a NEW clause or a module instance.
188
+ export const createSelectorResolver =
189
+ (generator: SelectorGenerator) =>
190
+ (
191
+ items: SelectorItem[],
192
+ expectedArity: number,
193
+ isFact: boolean,
194
+ isDef: boolean,
195
+ location: SanyLocation,
196
+ ): FactNode | ThmOrAssumpDefNode => {
197
+ const substInPrefix: SubstInNode[] = [];
198
+ const params: FormalParamNode[] = [];
199
+ const allArgs: ExprOrOpArgNode[] = [];
200
+ const getItemLocation = (itemIndex: number) => items[itemIndex].location ?? location;
201
+ const walk: SelectorWalk = {
202
+ name: undefined,
203
+ nameLocation: undefined,
204
+ node: undefined,
205
+ index: 0,
206
+ mode: "FindingOpName",
207
+ previousMode: undefined,
208
+ letInContext: undefined,
209
+ definitionArityFound: 0,
210
+ definitionArgs: [],
211
+ isInSuffices: false,
212
+ };
213
+ const getArgs = (item: SelectorItem) => item.args ?? [];
214
+
215
+ while (walk.index < items.length) {
216
+ const item = items[walk.index];
217
+ if (
218
+ ((item.op !== "Name" && item.op !== "Null") || expectedArity !== 0) &&
219
+ item.args !== undefined
220
+ ) {
221
+ return generator.addError(
222
+ getItemLocation(walk.index),
223
+ `Selector \`${item.name}' should not have argument(s).`,
224
+ );
225
+ }
226
+ switch (walk.mode) {
227
+ case "FindingOpName": {
228
+ let symbol: SymbolNode | undefined;
229
+ let newName: string | undefined;
230
+ const collectedArgs: Expression[] = [];
231
+ while (symbol === undefined && walk.index < items.length) {
232
+ const current = items[walk.index];
233
+ newName =
234
+ current.op === "Name"
235
+ ? walk.name === undefined
236
+ ? generator.resolveSynonym(current.name)
237
+ : `${walk.name}!${generator.resolveSynonym(current.name)}`
238
+ : undefined;
239
+ if (walk.name === undefined && current.op !== "Name") {
240
+ return generator.addError(
241
+ getItemLocation(walk.index),
242
+ `Need name or step number here, not \`${current.name}'.`,
243
+ );
244
+ }
245
+ if (newName !== undefined) {
246
+ symbol =
247
+ walk.letInContext === undefined
248
+ ? generator.resolveSymbol(newName)
249
+ : getContextSymbol(walk.letInContext, newName);
250
+ }
251
+ if (symbol === undefined) {
252
+ if (newName !== undefined) {
253
+ walk.name = newName;
254
+ walk.nameLocation = extendLocation(walk.nameLocation, getItemLocation(walk.index));
255
+ }
256
+ collectedArgs.push(...getArgs(current));
257
+ walk.index++;
258
+ }
259
+ }
260
+ // TLC 1.7.4's SANY names only the last item of a selector it can't resolve, as
261
+ // selectorItemToString does, which fails on an argument selector that isn't a number.
262
+ if (symbol === undefined && generator.version === "1.7.4") {
263
+ const last = items.length - 1;
264
+ return generator.addError(
265
+ getItemLocation(last),
266
+ `Unknown operator: \`${getSelectorItemName(items[last])}'.`,
267
+ );
268
+ }
269
+ if (symbol === undefined) {
270
+ return generator.addError(
271
+ walk.nameLocation ?? location,
272
+ `Unknown operator: \`${walk.name}'.`,
273
+ );
274
+ }
275
+ if (symbol.kind === "Module") {
276
+ return generator.addError(
277
+ getItemLocation(walk.index),
278
+ `Module name (${items[walk.index].name}) not allowed here.`,
279
+ );
280
+ }
281
+ walk.node = symbol;
282
+ walk.nameLocation = extendLocation(walk.nameLocation, getItemLocation(walk.index));
283
+ walk.name = newName;
284
+ if (isDeclarationLike(symbol) && items.length !== 1) {
285
+ return generator.addError(
286
+ getItemLocation(walk.index),
287
+ `Cannot take subexpression of \`${walk.name}'.`,
288
+ );
289
+ }
290
+ const nodeArity = getSymbolArity(symbol);
291
+ if (expectedArity === 0) {
292
+ collectedArgs.push(...getArgs(items[walk.index]));
293
+ if (walk.definitionArityFound + collectedArgs.length !== nodeArity) {
294
+ return generator.addError(
295
+ items[walk.index].argsLocation ?? location,
296
+ `The operator ${walk.name} requires ${nodeArity - walk.definitionArityFound} arguments.`,
297
+ );
298
+ }
299
+ collectedArgs.forEach((argument, argumentIndex) =>
300
+ walk.definitionArgs.push(
301
+ generator.generateArgument(
302
+ symbol,
303
+ argumentIndex + walk.definitionArityFound,
304
+ argument,
305
+ getItemLocation(walk.index),
306
+ ),
307
+ ),
308
+ );
309
+ }
310
+ walk.definitionArityFound = nodeArity;
311
+ if (symbol.kind === "OpDef" && symbol.defKind === "ModuleInstance") {
312
+ if (walk.index === items.length - 1 && !(isDef || isFact)) {
313
+ return generator.addError(
314
+ getItemLocation(walk.index),
315
+ `Operator name ${walk.name} is incomplete.`,
316
+ );
317
+ }
318
+ } else {
319
+ const definition =
320
+ (symbol.kind === "OpDef" && symbol.defKind === "UserDefined") ||
321
+ symbol.kind === "ThmOrAssumpDef"
322
+ ? symbol
323
+ : undefined;
324
+ if (
325
+ symbol.kind === "OpDef" &&
326
+ symbol.defKind === "UserDefined" &&
327
+ !symbol.isDefined &&
328
+ items.length !== 1
329
+ ) {
330
+ return generator.addError(
331
+ getItemLocation(walk.index),
332
+ `Subexpression of \`${walk.name}' used inside the operator's definition.`,
333
+ );
334
+ }
335
+ if (walk.index !== items.length - 1 && definition !== undefined) {
336
+ params.push(...(definition.params ?? []));
337
+ walk.name = undefined;
338
+ walk.nameLocation = undefined;
339
+ walk.mode =
340
+ items[walk.index + 1].op === "Name" ? "FollowingLabels" : "FindingSubExpr";
341
+ allArgs.push(...walk.definitionArgs);
342
+ walk.definitionArityFound = 0;
343
+ walk.definitionArgs = [];
344
+ let body: LevelNode | undefined = definition.body;
345
+ while (body?.kind === "SubstIn") {
346
+ substInPrefix.push(body);
347
+ body = body.body;
348
+ }
349
+ while (body?.kind === "APSubstIn") {
350
+ substInPrefix.push(body);
351
+ body = body.body;
352
+ }
353
+ if (walk.mode === "FindingSubExpr") walk.node = body;
354
+ }
355
+ }
356
+ walk.previousMode = "FindingOpName";
357
+ break;
358
+ }
359
+ case "FollowingLabels": {
360
+ const owner = walk.node;
361
+ const label =
362
+ owner?.kind === "OpDef" || owner?.kind === "ThmOrAssumpDef" || owner?.kind === "Label"
363
+ ? owner.labels.get(item.name)
364
+ : undefined;
365
+ if (label === undefined)
366
+ return generator.addError(
367
+ getItemLocation(walk.index),
368
+ `Cannot find label \`${item.name}'.`,
369
+ );
370
+ walk.node = label;
371
+ if (generator.isOutOfLabelScope(label)) {
372
+ return generator.addError(
373
+ getItemLocation(walk.index),
374
+ `Accessing subexpression labeled \`${item.name}' of ASSUME/PROVE clause within the scope of a declaration\n from outside that declaration's scope.`,
375
+ );
376
+ }
377
+ if (expectedArity === 0) {
378
+ if (label.params.length !== getArgs(item).length) {
379
+ return generator.addError(
380
+ getItemLocation(walk.index),
381
+ `Label \`${item.name}' used with wrong number of arguments.`,
382
+ );
383
+ }
384
+ allArgs.push(...getArgs(item).map(generator.generateExpression));
385
+ }
386
+ params.push(...label.params);
387
+ if (walk.index < items.length - 1 && items[walk.index + 1].op !== "Name")
388
+ walk.mode = "FindingSubExpr";
389
+ if (walk.mode === "FindingSubExpr") walk.node = label.body;
390
+ walk.previousMode = "FollowingLabels";
391
+ break;
392
+ }
393
+ case "FindingSubExpr": {
394
+ const node = walk.node;
395
+ const addNonexistentError = () =>
396
+ generator.addError(
397
+ getItemLocation(walk.index),
398
+ `Nonexistent operand specified by \`${getSelectorItemName(item)}'.`,
399
+ );
400
+ if (item.op === ":") {
401
+ const isAllowed =
402
+ walk.previousMode !== "FindingSubExpr" &&
403
+ ((walk.index === items.length - 1 && walk.previousMode === "FindingOpName") ||
404
+ (walk.index < items.length - 1 && items[walk.index + 1].op === "Name"));
405
+ if (!isAllowed) {
406
+ return generator.addError(
407
+ getItemLocation(walk.index),
408
+ "`!:' can be used only after a name and either at the end after an\noperator name or before an operator name.",
409
+ );
410
+ }
411
+ } else if (node === undefined) {
412
+ return generator.addError(
413
+ getItemLocation(walk.index),
414
+ "Subexpression selection failed, probably due to an error in the selected expression.",
415
+ );
416
+ } else if (node.kind === "LetIn") {
417
+ if (getArgNumber(item.op, 1) !== 1)
418
+ return generator.addError(
419
+ getItemLocation(walk.index),
420
+ "A LET/IN expression has only one operand.",
421
+ );
422
+ walk.node = node.body;
423
+ } else if (node.kind === "OpAppl") {
424
+ const operator = node.operator;
425
+ const operands = node.operands;
426
+ const isUserOperator =
427
+ operator.kind === "FormalParam" ||
428
+ (operator.kind === "OpDecl" && operator.declKind === CONSTANT_DECL_KIND) ||
429
+ (operator.kind === "OpDef" && operator.defKind === "UserDefined");
430
+ const addNotPairError = () =>
431
+ generator.addError(
432
+ getItemLocation(walk.index),
433
+ "Internal error: Expecting $Pair and didn't find it.",
434
+ );
435
+ const isPair = (pair: ExprOrOpArgNode | undefined): pair is OpApplNode =>
436
+ pair?.kind === "OpAppl" && pair.operator.name === "$Pair";
437
+ const operandNumber = getArgNumber(item.op, operands.length);
438
+ if (isUserOperator) {
439
+ const number = getArgNumber(item.op, operator.arity);
440
+ if (number === -1) return addNonexistentError();
441
+ walk.node = operands[number - 1];
442
+ } else if (operator.kind === "OpDef" && operator.defKind === "BuiltIn") {
443
+ if (operator.name === "$RcdConstructor" || operator.name === "$SetOfRcds") {
444
+ if (operandNumber === -1) return addNonexistentError();
445
+ const pair = operands[operandNumber - 1];
446
+ if (!isPair(pair)) return addNotPairError();
447
+ walk.node = pair.operands[1];
448
+ } else if (operator.name === "$Case") {
449
+ if (walk.index === items.length - 1) {
450
+ return generator.addError(
451
+ getItemLocation(walk.index),
452
+ "Subexpression of CASE must have form !i!j.",
453
+ );
454
+ }
455
+ if (operandNumber === -1) return addNonexistentError();
456
+ const pair = operands[operandNumber - 1];
457
+ if (!isPair(pair)) return addNotPairError();
458
+ walk.index++;
459
+ const number = getArgNumber(items[walk.index].op, 2);
460
+ if (number === -1) {
461
+ return generator.addError(
462
+ getItemLocation(walk.index),
463
+ "Second selector for CASE subexpression must specify one of two operands.",
464
+ );
465
+ }
466
+ walk.node = pair.operands[number - 1];
467
+ if (walk.node === undefined)
468
+ return generator.addError(
469
+ getItemLocation(walk.index),
470
+ "Selecting OTHER in a CASE statement.",
471
+ );
472
+ } else if (operator.name === "$Except") {
473
+ if (operandNumber > 1) {
474
+ return generator.addError(
475
+ getItemLocation(walk.index),
476
+ "Selecting subexpression of an EXCEPT not yet implemented.",
477
+ );
478
+ }
479
+ if (operandNumber === -1) return addNonexistentError();
480
+ walk.node = operands[operandNumber - 1];
481
+ } else if ((node.bounded?.length ?? 0) === 0 && (node.unbounded?.length ?? 0) === 0) {
482
+ if (operandNumber === -1) return addNonexistentError();
483
+ walk.node = operands[operandNumber - 1];
484
+ } else if (item.op === "Null" || item.op === "@") {
485
+ const symbols = getQuantifierSymbols(node);
486
+ params.push(...symbols);
487
+ if (item.op === "Null") {
488
+ if (getArgs(item).length !== symbols.length) {
489
+ return generator.addError(
490
+ getItemLocation(walk.index),
491
+ `Selector with ${getArgs(item).length} argument(s) used for quantifier with ${symbols.length} bound identifier(s).`,
492
+ );
493
+ }
494
+ allArgs.push(...getArgs(item).map(generator.generateExpression));
495
+ }
496
+ walk.node = operands[0];
497
+ } else {
498
+ const number = getArgNumber(item.op, node.ranges.length);
499
+ if (number === -1) return addNonexistentError();
500
+ walk.node = node.ranges[number - 1];
501
+ }
502
+ } else {
503
+ return generator.addError(
504
+ getItemLocation(walk.index),
505
+ `Choosing operand \`${item.name}' of subexpression with no operands.`,
506
+ );
507
+ }
508
+ } else if (node.kind === "AssumeProve") {
509
+ if (node.isSuffices && !walk.isInSuffices) {
510
+ if (getArgNumber(item.op, 1) !== 1) {
511
+ return generator.addError(
512
+ getItemLocation(walk.index),
513
+ "Accessing non-existent subexpression of a SUFFICES",
514
+ );
515
+ }
516
+ walk.isInSuffices = true;
517
+ } else {
518
+ walk.isInSuffices = false;
519
+ const number = getArgNumber(item.op, 1 + node.assumptions.length);
520
+ if (number === -1) return addNonexistentError();
521
+ if (generator.isOutOfClauseScope(node, number)) {
522
+ return generator.addError(
523
+ getItemLocation(walk.index),
524
+ "Accessing ASSUME/PROVE clause within the scope of a declaration\n from outside that declaration's scope.",
525
+ );
526
+ }
527
+ if (number <= node.assumptions.length) {
528
+ walk.node = node.assumptions[number - 1];
529
+ if (walk.node.kind === "NewSymb" && walk.index !== items.length - 1) {
530
+ return generator.addError(
531
+ getItemLocation(walk.index),
532
+ "Selected a subexpression of a NEW clause of an ASSUME.",
533
+ );
534
+ }
535
+ } else walk.node = node.goal;
536
+ }
537
+ } else if (node.kind === "OpArg") {
538
+ const lambda = node.op;
539
+ if (lambda.kind !== "OpDef" || lambda.name !== "LAMBDA") {
540
+ return generator.addError(
541
+ getItemLocation(walk.index),
542
+ "Trying to select subexpression of an operator argument.",
543
+ );
544
+ }
545
+ if (item.op !== "Null" && item.op !== "@") {
546
+ return generator.addError(
547
+ getItemLocation(walk.index),
548
+ `Cannot use !${item.name} to select subexpression of a LAMBDA.`,
549
+ );
550
+ }
551
+ if (item.op === "Null") {
552
+ if (lambda.arity !== getArgs(item).length) {
553
+ return generator.addError(
554
+ getItemLocation(walk.index),
555
+ `Selector with ${getArgs(item).length} arguments used for LAMBDA expression taking ${lambda.arity} arguments.`,
556
+ );
557
+ }
558
+ allArgs.push(...getArgs(item).map(generator.generateExpression));
559
+ }
560
+ params.push(...(lambda.params ?? []));
561
+ walk.node = lambda.body;
562
+ } else if (node.kind === "Label") {
563
+ walk.node = node.body;
564
+ walk.index--;
565
+ } else {
566
+ return generator.addError(
567
+ getItemLocation(walk.index),
568
+ "Selecting subexpression of expression that has none.",
569
+ );
570
+ }
571
+ if (walk.node === undefined)
572
+ return generator.addError(
573
+ getItemLocation(walk.index),
574
+ `An unexpected null node specified by '${item.name}'.\nThis is probably due to a previous error.`,
575
+ );
576
+ if (walk.index !== items.length - 1) {
577
+ const next = items[walk.index + 1];
578
+ if (next.op === "Name") {
579
+ while (walk.node?.kind === "Label") walk.node = walk.node.body;
580
+ if (walk.node?.kind !== "LetIn") {
581
+ return generator.addError(
582
+ getItemLocation(walk.index),
583
+ "A name selector here must be from a LET clause.",
584
+ );
585
+ }
586
+ walk.letInContext = walk.node.context;
587
+ walk.mode = "FindingOpName";
588
+ } else if (next.op === ":") {
589
+ return generator.addError(
590
+ getItemLocation(walk.index),
591
+ "!: should not follow an operand selector.",
592
+ );
593
+ }
594
+ }
595
+ walk.previousMode = "FindingSubExpr";
596
+ break;
597
+ }
598
+ }
599
+ walk.index++;
600
+ }
601
+
602
+ const node = walk.node;
603
+ if (node === undefined)
604
+ return generator.addError(
605
+ location,
606
+ "Subexpression selection failed, probably due to an error in the selected expression.",
607
+ );
608
+ if (node.kind === "AssumeProve" || node.kind === "NewSymb") {
609
+ if (isFact) return node;
610
+ return generator.addError(
611
+ location,
612
+ node.kind === "AssumeProve"
613
+ ? "Selected ASSUME/PROVE instead of expression."
614
+ : "Selected a NEW declaration as an expression or operator.",
615
+ );
616
+ }
617
+ if (expectedArity < 0) {
618
+ const isDefinition =
619
+ (node.kind === "OpDef" &&
620
+ (node.defKind === "UserDefined" ||
621
+ node.defKind === "NumberedProofStep" ||
622
+ (node.defKind === "ModuleInstance" && isDef))) ||
623
+ node.kind === "ThmOrAssumpDef";
624
+ if (walk.previousMode !== "FindingOpName" || !isDefinition) {
625
+ return generator.addError(location, "DEF clause entry should describe a defined operator.");
626
+ }
627
+ if (node.kind === "OpDef" && node.step !== undefined && node.step.kind !== "DefStep") {
628
+ return generator.addError(location, "DEF clause entry refers to a non-definition step.");
629
+ }
630
+ return node;
631
+ }
632
+ if (node.kind === "OpDef" && node.defKind === "NumberedProofStep") {
633
+ return generator.addError(
634
+ location,
635
+ isFact
636
+ ? "Step number of non-fact used as a fact"
637
+ : "Step number of non-expression step used as an expression.",
638
+ );
639
+ }
640
+ if (expectedArity > 0) {
641
+ const found =
642
+ params.length +
643
+ (node.kind === "OpArg"
644
+ ? getSymbolArity(node.op)
645
+ : walk.previousMode === "FindingOpName" && isSymbol(node)
646
+ ? getSymbolArity(node)
647
+ : 0);
648
+ if (expectedArity !== found) {
649
+ return generator.addError(
650
+ location,
651
+ `Expected arity ${expectedArity} but found operator of arity ${found}.`,
652
+ );
653
+ }
654
+ }
655
+ let current: LevelNode | SymbolNode = node;
656
+ if (walk.previousMode === "FindingOpName" && params.length + substInPrefix.length > 0) {
657
+ if (current.kind !== "OpDef" && current.kind !== "ThmOrAssumpDef") {
658
+ return generator.addError(
659
+ items[items.length - 1].location ?? location,
660
+ "Internal Error: Found unexpected node kind after FindingOpName",
661
+ );
662
+ }
663
+ allArgs.push(...walk.definitionArgs);
664
+ const operands = (current.params ?? []).map((param) => {
665
+ const copy = generator.createFormalParam(param.name, param.arity, param.location);
666
+ params.push(copy);
667
+ return param.arity === 0
668
+ ? generator.createOpAppl(copy, [], location)
669
+ : generator.createOpArg(copy, location);
670
+ });
671
+ current = generator.createOpAppl(current, operands, location);
672
+ }
673
+ if (current.kind === "OpArg") {
674
+ if (expectedArity === 0)
675
+ return generator.addError(location, "Selected operator argument when expression expected.");
676
+ if (params.length + substInPrefix.length > 0) {
677
+ const operator = current.op;
678
+ params.push(
679
+ ...Array.from({ length: getSymbolArity(operator) }, (_, paramIndex) =>
680
+ generator.createFormalParam(`NewParam${paramIndex}`, 0, undefined),
681
+ ),
682
+ );
683
+ current = generator.createOpAppl(operator, walk.definitionArgs, location);
684
+ }
685
+ }
686
+ if (!isFact) {
687
+ const isAssumeProve =
688
+ (current.kind === "ThmOrAssumpDef" && current.body.kind === "AssumeProve") ||
689
+ (current.kind === "Label" && current.isAssumeProve);
690
+ if (isAssumeProve)
691
+ return generator.addError(location, "ASSUME/PROVE used where an expression is required.");
692
+ if (current.kind === "ThmOrAssumpDef" && current.body.kind === "OpAppl") {
693
+ const step = PROOF_STEP_OPERATORS.get(current.body.operator.name);
694
+ if (step !== undefined)
695
+ return generator.addError(location, `${step} proof step selected instead of expression.`);
696
+ }
697
+ }
698
+ if (
699
+ current.kind === "FormalParam" ||
700
+ current.kind === "OpDecl" ||
701
+ current.kind === "ThmOrAssumpDef" ||
702
+ (current.kind === "OpDef" &&
703
+ (current.defKind === "UserDefined" || current.defKind === "BuiltIn"))
704
+ ) {
705
+ return expectedArity > 0
706
+ ? generator.createOpArg(current, location)
707
+ : generator.createOpAppl(current, walk.definitionArgs, location);
708
+ }
709
+ if (current.kind === "OpArg") return current;
710
+ if (current.kind === "OpDef" || current.kind === "Module") {
711
+ if ((isFact || isDef) && current.kind === "OpDef") return current;
712
+ return generator.addError(location, "Module instantiation selected instead of expression.");
713
+ }
714
+ const expression = substInPrefix.reduceRight<ExprNode>(
715
+ (body, prefix) => generator.copySubstIn(prefix, body),
716
+ current,
717
+ );
718
+ const lambda =
719
+ params.length > 0 ? generator.createLambda(params, expression, location) : undefined;
720
+ if (expectedArity > 0) {
721
+ if (lambda === undefined || params.length !== expectedArity) {
722
+ return generator.addError(
723
+ location,
724
+ `Expected operator argument with arity ${expectedArity} but found one of arity ${params.length}.`,
725
+ );
726
+ }
727
+ return generator.createOpArg(lambda, location);
728
+ }
729
+ if (params.length !== allArgs.length) {
730
+ return generator.addError(
731
+ location,
732
+ `Expected ${params.length} arguments but found ${allArgs.length}.`,
733
+ );
734
+ }
735
+ return lambda === undefined
736
+ ? generator.createOpAppl(generator.getBuiltin("$Nop"), [expression], location)
737
+ : generator.createOpAppl(lambda, allArgs, location);
738
+ };