tla-ts 0.0.3 → 0.0.4-dev.5f6a4bf

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 (86) hide show
  1. package/README.md +32 -12
  2. package/dist/cli.cjs +1 -1
  3. package/dist/cli.js +1 -1
  4. package/dist/index.cjs +1 -1
  5. package/dist/index.d.cts +160 -8
  6. package/dist/index.d.ts +160 -8
  7. package/dist/index.js +1 -1
  8. package/dist/parallel-worker.cjs +2 -2
  9. package/dist/parallel-worker.js +2 -2
  10. package/dist/parallel.cjs +1 -1
  11. package/dist/parallel.js +2 -2
  12. package/dist/run-cli.cjs +45 -18
  13. package/dist/run-cli.js +45 -18
  14. package/dist/transfer.cjs +1393 -18
  15. package/dist/transfer.js +1393 -18
  16. package/package.json +5 -1
  17. package/src/ast.ts +147 -6
  18. package/src/bags.ts +4 -7
  19. package/src/builtins.ts +29 -11
  20. package/src/bundled-modules.ts +3 -3
  21. package/src/canonical.ts +4 -3
  22. package/src/check.ts +1539 -235
  23. package/src/cli-options.ts +11 -5
  24. package/src/cli.ts +8 -1
  25. package/src/codegen.ts +77 -37
  26. package/src/config.ts +254 -181
  27. package/src/dependencies.ts +2 -2
  28. package/src/environment.ts +540 -140
  29. package/src/errors.ts +224 -3
  30. package/src/evaluate.ts +796 -246
  31. package/src/exit-codes.ts +22 -43
  32. package/src/fingerprints.ts +46 -11
  33. package/src/index.ts +1 -0
  34. package/src/instances.ts +19 -16
  35. package/src/java-overrides.ts +104 -25
  36. package/src/levels.ts +191 -45
  37. package/src/lexer.ts +127 -30
  38. package/src/live-check.ts +828 -0
  39. package/src/liveness.ts +218 -572
  40. package/src/obligation-expression.ts +2 -2
  41. package/src/obligation-source.ts +2 -0
  42. package/src/parallel-worker.ts +174 -213
  43. package/src/parallel.ts +131 -39
  44. package/src/parser.ts +456 -147
  45. package/src/pcal-ast.ts +770 -0
  46. package/src/pcal-parse.ts +1523 -0
  47. package/src/pcal-tokenize.ts +516 -0
  48. package/src/pcal-translate.ts +1230 -0
  49. package/src/pcal-validate.ts +454 -0
  50. package/src/randomization.ts +24 -7
  51. package/src/resolve.ts +1481 -426
  52. package/src/run-cli.ts +1212 -143
  53. package/src/runtime.ts +19 -1
  54. package/src/sany-builtins.ts +147 -0
  55. package/src/sany-generator.ts +3128 -0
  56. package/src/sany-levels.ts +1208 -0
  57. package/src/sany-lexer.ts +545 -0
  58. package/src/sany-linter.ts +122 -0
  59. package/src/sany-modules.ts +1398 -0
  60. package/src/sany-nodes.ts +463 -0
  61. package/src/sany-parse-error.ts +2161 -0
  62. package/src/sany-report.ts +356 -0
  63. package/src/sany-selectors.ts +738 -0
  64. package/src/sany-source.ts +248 -0
  65. package/src/sany-xml.ts +1017 -0
  66. package/src/spec-description.ts +42 -11
  67. package/src/standard-modules.ts +200 -148
  68. package/src/standard-ranges.ts +116 -0
  69. package/src/state-graph.ts +180 -0
  70. package/src/subexpressions.ts +231 -171
  71. package/src/substitution-levels.ts +38 -17
  72. package/src/successors.ts +219 -107
  73. package/src/symmetry.ts +194 -54
  74. package/src/tableau.ts +54 -25
  75. package/src/tlc-ext.ts +42 -29
  76. package/src/tlc-messages.ts +329 -0
  77. package/src/tlc-module.ts +52 -43
  78. package/src/tlc-modules.ts +4 -0
  79. package/src/tlc-order.ts +78 -10
  80. package/src/tlc-random.ts +37 -9
  81. package/src/tlc-replay.ts +655 -0
  82. package/src/tlc-summary.ts +20 -5
  83. package/src/tlc-version.ts +18 -0
  84. package/src/transfer.ts +15 -3
  85. package/src/value-sources.ts +29 -0
  86. package/src/values.ts +731 -184
@@ -0,0 +1,770 @@
1
+ import { PcalBugError, PcalError, PcalRuntimeError } from "./errors";
2
+ import type { TlcVersion } from "./tlc-version";
3
+
4
+ // TLAToken's types.
5
+ export const PCAL_TOKEN = { builtin: 1, number: 2, string: 3, ident: 4, added: 5 } as const;
6
+
7
+ export interface PcalToken {
8
+ string: string;
9
+ column: number;
10
+ type: number;
11
+ }
12
+
13
+ // TLAExpr: the tokens of an expression, line by line, and for each line the token of an earlier
14
+ // line it is aligned under, with that token's column when the expression was normalized.
15
+ export interface PcalExpr {
16
+ tokens: PcalToken[][];
17
+ anchorTokens: (PcalToken | undefined)[] | undefined;
18
+ anchorTokCol: number[] | undefined;
19
+ }
20
+
21
+ // IntPair, as the "Java coordinates" of a token in an expression.
22
+ interface PcalCoord {
23
+ line: number;
24
+ item: number;
25
+ }
26
+
27
+ // PcalParams: the translator's options, which the Java keeps in static fields that SANY never
28
+ // resets, so options one module sets carry over to the modules SANY validates after it.
29
+ export interface PcalParams {
30
+ labelFlag: boolean;
31
+ reportLabelsFlag: boolean;
32
+ labelRoot: string;
33
+ fairnessOption: string;
34
+ fairAlgorithm: boolean;
35
+ checkTermination: boolean;
36
+ noOld: boolean;
37
+ nocfg: boolean;
38
+ noDoneDisjunct: boolean;
39
+ specOption: boolean;
40
+ myspecOption: boolean;
41
+ specFile: string;
42
+ optionsInFile: boolean;
43
+ inputVersionNumber: number;
44
+ }
45
+
46
+ // PcalParams.versionWeight.
47
+ export const PCAL_VERSION_WEIGHT = 1903;
48
+
49
+ export const createPcalParams = (): PcalParams => ({
50
+ labelFlag: false,
51
+ reportLabelsFlag: false,
52
+ labelRoot: "Lbl_",
53
+ fairnessOption: "",
54
+ fairAlgorithm: false,
55
+ checkTermination: false,
56
+ noOld: false,
57
+ nocfg: false,
58
+ noDoneDisjunct: false,
59
+ specOption: false,
60
+ myspecOption: false,
61
+ specFile: "",
62
+ optionsInFile: false,
63
+ inputVersionNumber: PCAL_VERSION_WEIGHT,
64
+ });
65
+
66
+ // PcalParams.VersionToNumber: "1.5" is 1500, and -1 means a malformed version.
67
+ export const getPcalVersionNumber = (text: string) => {
68
+ const state = { result: 0, digitsAfterDecimal: 0, isAfterDecimal: false };
69
+ for (const char of text) {
70
+ if (char === ".") {
71
+ state.isAfterDecimal = true;
72
+ continue;
73
+ }
74
+ if (char < "0" || char > "9") return -1;
75
+ state.result = 10 * state.result + Number(char);
76
+ if (state.isAfterDecimal) state.digitsAfterDecimal += 1;
77
+ if (state.digitsAfterDecimal > 3) return -1;
78
+ }
79
+ return state.result * 10 ** Math.max(0, 3 - state.digitsAfterDecimal);
80
+ };
81
+
82
+ interface PcalBase {
83
+ col: number;
84
+ line: number;
85
+ macroCol: number;
86
+ macroLine: number;
87
+ lbl: string;
88
+ }
89
+
90
+ interface PcalUniprocess extends PcalBase {
91
+ kind: "Uniprocess";
92
+ name: string;
93
+ decls: PcalVarDecl[];
94
+ defs: PcalExpr;
95
+ macros: PcalMacro[];
96
+ prcds: PcalProcedure[];
97
+ body: PcalStmt[];
98
+ }
99
+
100
+ interface PcalMultiprocess extends PcalBase {
101
+ kind: "Multiprocess";
102
+ name: string;
103
+ decls: PcalVarDecl[];
104
+ defs: PcalExpr;
105
+ macros: PcalMacro[];
106
+ prcds: PcalProcedure[];
107
+ procs: PcalProcess[];
108
+ }
109
+
110
+ export interface PcalProcedure extends PcalBase {
111
+ kind: "Procedure";
112
+ name: string;
113
+ minusLabels: string[];
114
+ plusLabels: string[];
115
+ proceduresCalled: string[];
116
+ params: PcalPVarDecl[];
117
+ decls: PcalPVarDecl[];
118
+ body: PcalStmt[];
119
+ }
120
+
121
+ // AST.UNFAIR_PROC, WF_PROC and SF_PROC index FairnessString.
122
+ const PCAL_FAIRNESS = ["unfair", "wf", "sf"];
123
+
124
+ export interface PcalProcess extends PcalBase {
125
+ kind: "Process";
126
+ name: string;
127
+ fairness: number;
128
+ minusLabels: string[];
129
+ plusLabels: string[];
130
+ proceduresCalled: string[];
131
+ isEq: boolean;
132
+ id: PcalExpr;
133
+ decls: PcalVarDecl[];
134
+ body: PcalStmt[];
135
+ }
136
+
137
+ export interface PcalVarDecl extends PcalBase {
138
+ kind: "VarDecl";
139
+ var: string;
140
+ isEq: boolean;
141
+ val: PcalExpr;
142
+ }
143
+
144
+ export interface PcalPVarDecl extends PcalBase {
145
+ kind: "PVarDecl";
146
+ var: string;
147
+ val: PcalExpr;
148
+ }
149
+
150
+ export interface PcalLabeledStmt extends PcalBase {
151
+ kind: "LabeledStmt";
152
+ label: string;
153
+ stmts: PcalStmt[];
154
+ }
155
+
156
+ export interface PcalWhile extends PcalBase {
157
+ kind: "While";
158
+ test: PcalExpr;
159
+ unlabDo: PcalStmt[];
160
+ labDo: PcalLabeledStmt[];
161
+ }
162
+
163
+ export interface PcalAssign extends PcalBase {
164
+ kind: "Assign";
165
+ ass: PcalSingleAssign[];
166
+ }
167
+
168
+ export interface PcalSingleAssign extends PcalBase {
169
+ kind: "SingleAssign";
170
+ lhs: PcalLhs;
171
+ rhs: PcalExpr;
172
+ }
173
+
174
+ export interface PcalLhs extends PcalBase {
175
+ kind: "Lhs";
176
+ var: string;
177
+ sub: PcalExpr;
178
+ }
179
+
180
+ interface PcalIf extends PcalBase {
181
+ kind: "If";
182
+ test: PcalExpr;
183
+ Then: PcalStmt[];
184
+ Else: PcalStmt[];
185
+ }
186
+
187
+ interface PcalEither extends PcalBase {
188
+ kind: "Either";
189
+ ors: PcalStmt[][];
190
+ }
191
+
192
+ export interface PcalWith extends PcalBase {
193
+ kind: "With";
194
+ var: string;
195
+ isEq: boolean;
196
+ exp: PcalExpr;
197
+ Do: PcalStmt[];
198
+ }
199
+
200
+ export interface PcalWhen extends PcalBase {
201
+ kind: "When";
202
+ exp: PcalExpr;
203
+ }
204
+
205
+ interface PcalPrintS extends PcalBase {
206
+ kind: "PrintS";
207
+ exp: PcalExpr;
208
+ }
209
+
210
+ interface PcalAssert extends PcalBase {
211
+ kind: "Assert";
212
+ exp: PcalExpr;
213
+ }
214
+
215
+ interface PcalSkip extends PcalBase {
216
+ kind: "Skip";
217
+ }
218
+
219
+ export interface PcalLabelIf extends PcalBase {
220
+ kind: "LabelIf";
221
+ test: PcalExpr;
222
+ unlabThen: PcalStmt[];
223
+ labThen: PcalLabeledStmt[];
224
+ unlabElse: PcalStmt[];
225
+ labElse: PcalLabeledStmt[];
226
+ }
227
+
228
+ export interface PcalLabelEither extends PcalBase {
229
+ kind: "LabelEither";
230
+ clauses: PcalClause[];
231
+ }
232
+
233
+ export interface PcalClause extends PcalBase {
234
+ kind: "Clause";
235
+ unlabOr: PcalStmt[];
236
+ labOr: PcalLabeledStmt[];
237
+ }
238
+
239
+ export interface PcalCall extends PcalBase {
240
+ kind: "Call";
241
+ returnTo: string;
242
+ to: string;
243
+ args: PcalExpr[];
244
+ }
245
+
246
+ // A Return or CallReturn outside a procedure has a null from, which Java prints as "null".
247
+ export interface PcalReturn extends PcalBase {
248
+ kind: "Return";
249
+ from: string | undefined;
250
+ }
251
+
252
+ export interface PcalCallReturn extends PcalBase {
253
+ kind: "CallReturn";
254
+ from: string | undefined;
255
+ to: string;
256
+ args: PcalExpr[];
257
+ }
258
+
259
+ interface PcalCallGoto extends PcalBase {
260
+ kind: "CallGoto";
261
+ after: string;
262
+ to: string;
263
+ args: PcalExpr[];
264
+ }
265
+
266
+ interface PcalGoto extends PcalBase {
267
+ kind: "Goto";
268
+ to: string;
269
+ }
270
+
271
+ export interface PcalMacro extends PcalBase {
272
+ kind: "Macro";
273
+ name: string;
274
+ params: string[];
275
+ body: PcalStmt[];
276
+ }
277
+
278
+ export interface PcalMacroCall extends PcalBase {
279
+ kind: "MacroCall";
280
+ name: string;
281
+ args: PcalExpr[];
282
+ }
283
+
284
+ export type PcalStmt =
285
+ | PcalLabeledStmt
286
+ | PcalWhile
287
+ | PcalAssign
288
+ | PcalIf
289
+ | PcalEither
290
+ | PcalWith
291
+ | PcalWhen
292
+ | PcalPrintS
293
+ | PcalAssert
294
+ | PcalSkip
295
+ | PcalLabelIf
296
+ | PcalLabelEither
297
+ | PcalCall
298
+ | PcalReturn
299
+ | PcalCallReturn
300
+ | PcalCallGoto
301
+ | PcalGoto
302
+ | PcalMacroCall;
303
+
304
+ export type PcalAlgorithm = PcalUniprocess | PcalMultiprocess;
305
+
306
+ export type PcalNode =
307
+ | PcalStmt
308
+ | PcalAlgorithm
309
+ | PcalProcedure
310
+ | PcalProcess
311
+ | PcalVarDecl
312
+ | PcalPVarDecl
313
+ | PcalSingleAssign
314
+ | PcalLhs
315
+ | PcalClause
316
+ | PcalMacro;
317
+
318
+ // The fields every AST object starts with.
319
+ export const createPcalBase = (): PcalBase => ({
320
+ col: 0,
321
+ line: 0,
322
+ macroCol: 0,
323
+ macroLine: -1,
324
+ lbl: "",
325
+ });
326
+
327
+ // AST.location.
328
+ export const getPcalLocation = (node: PcalBase) =>
329
+ node.macroLine < 0
330
+ ? `line ${node.line}, column ${node.col}`
331
+ : `line ${node.line}, column ${node.col} of macro called at line ${node.macroLine}, column ${node.macroCol}`;
332
+
333
+ // A Java cast of a statement to AST.LabeledStmt.
334
+ export const toLabeledStmt = (node: PcalStmt) => {
335
+ if (node.kind !== "LabeledStmt") throw new PcalRuntimeError(`ClassCastException: ${node.kind}`);
336
+ return node;
337
+ };
338
+
339
+ // Vector.elementAt, which throws for an index out of bounds.
340
+ export const getElement = <T>(vector: T[], index: number) => {
341
+ if (index < 0 || index >= vector.length) {
342
+ throw new PcalRuntimeError(`ArrayIndexOutOfBoundsException: ${index}`);
343
+ }
344
+ return vector[index];
345
+ };
346
+
347
+ export const createPcalToken = (string: string, column: number, type: number): PcalToken => ({
348
+ string,
349
+ column,
350
+ type,
351
+ });
352
+
353
+ // TLAToken.getWidth: a string token's width counts its quotes.
354
+ export const getPcalTokenWidth = (token: PcalToken) =>
355
+ token.type === PCAL_TOKEN.string ? token.string.length + 2 : token.string.length;
356
+
357
+ export const createPcalExpr = (tokens: PcalToken[][] = []): PcalExpr => ({
358
+ tokens,
359
+ anchorTokens: undefined,
360
+ anchorTokCol: undefined,
361
+ });
362
+
363
+ // TLAExpr.normalize: drops empty first and last lines, shifts the tokens left as far as they go,
364
+ // and records the token each line is aligned under.
365
+ export const normalizePcalExpr = (expr: PcalExpr) => {
366
+ while (expr.tokens.length > 0 && expr.tokens[0].length === 0) expr.tokens.shift();
367
+ while (expr.tokens.length > 0 && expr.tokens[expr.tokens.length - 1].length === 0) {
368
+ expr.tokens.pop();
369
+ }
370
+ const minColumn = Math.min(
371
+ 999999,
372
+ ...expr.tokens.filter((line) => line.length > 0).map((line) => line[0].column),
373
+ );
374
+ expr.tokens.forEach((line) =>
375
+ line.forEach((token) => {
376
+ token.column -= minColumn;
377
+ }),
378
+ );
379
+ const anchorTokens: (PcalToken | undefined)[] = [];
380
+ const anchorTokCol: number[] = [];
381
+ expr.tokens.forEach((line, index) => {
382
+ anchorTokCol.push(0);
383
+ anchorTokens.push(undefined);
384
+ if (line.length === 0) return;
385
+ const firstColumn = line[0].column;
386
+ const anchorLine = expr.tokens
387
+ .slice(0, index)
388
+ .findLast((candidate) => candidate.length > 0 && candidate[0].column <= firstColumn);
389
+ if (anchorLine === undefined) return;
390
+ const stop = anchorLine.findIndex((token, item) => item > 0 && token.column > firstColumn);
391
+ const anchor = anchorLine[(stop === -1 ? anchorLine.length : stop) - 1];
392
+ anchorTokens[index] = anchor;
393
+ anchorTokCol[index] = anchor.column;
394
+ });
395
+ expr.anchorTokens = anchorTokens;
396
+ expr.anchorTokCol = anchorTokCol;
397
+ };
398
+
399
+ export const createNormalizedPcalExpr = (tokens: PcalToken[][]) => {
400
+ const expr = createPcalExpr(tokens);
401
+ normalizePcalExpr(expr);
402
+ return expr;
403
+ };
404
+
405
+ // TLAExpr.renormalize: shifts each line right by as much as its anchor token has moved.
406
+ const renormalizePcalExpr = (expr: PcalExpr) => {
407
+ const anchorTokens = expr.anchorTokens;
408
+ const anchorTokCol = expr.anchorTokCol;
409
+ if (anchorTokens === undefined || anchorTokCol === undefined) {
410
+ throw new PcalRuntimeError("NullPointerException: TLAExpr.renormalize");
411
+ }
412
+ expr.tokens.forEach((line, index) => {
413
+ const anchor = anchorTokens[index];
414
+ if (anchor === undefined) return;
415
+ const shift = anchor.column - anchorTokCol[index];
416
+ anchorTokCol[index] = anchor.column;
417
+ if (shift < 0) throw new PcalError("TLAExpr.renormalize() found anchor has moved to left.");
418
+ line.forEach((token) => {
419
+ token.column += shift;
420
+ });
421
+ });
422
+ };
423
+
424
+ export const clonePcalExpr = (expr: PcalExpr) =>
425
+ createNormalizedPcalExpr(expr.tokens.map((line) => line.map((token) => ({ ...token }))));
426
+
427
+ // TLAExpr.prepend: puts prefix in front of the expression, spaces columns before its first token.
428
+ export const prependPcalExpr = (expr: PcalExpr, prefix: PcalExpr, spaces: number) => {
429
+ const prefixLines = prefix.tokens.length;
430
+ expr.tokens.splice(0, 0, ...prefix.tokens.slice(0, prefixLines - 1));
431
+ const prefixLine = prefix.tokens[prefixLines - 1];
432
+ const exprLine = expr.tokens[prefixLines - 1];
433
+ const last = prefixLine[prefixLine.length - 1];
434
+ const shift = last.column + getPcalTokenWidth(last) + spaces;
435
+ exprLine.forEach((token) => {
436
+ token.column += shift;
437
+ });
438
+ exprLine.splice(0, 0, ...prefixLine);
439
+ const anchorTokens = [...(prefix.anchorTokens ?? [])];
440
+ const anchorTokCol = [...(prefix.anchorTokCol ?? [])];
441
+ for (let index = prefixLines; index < expr.tokens.length; index++) {
442
+ anchorTokens.push(expr.anchorTokens?.[index - prefixLines + 1]);
443
+ anchorTokCol.push(expr.anchorTokCol?.[index - prefixLines + 1] ?? 0);
444
+ }
445
+ expr.anchorTokens = anchorTokens;
446
+ expr.anchorTokCol = anchorTokCol;
447
+ renormalizePcalExpr(expr);
448
+ };
449
+
450
+ export const isOneTokenPcalExpr = (expr: PcalExpr) =>
451
+ expr.tokens.length === 1 && expr.tokens[0].length === 1;
452
+
453
+ export const getPcalTokenAt = (expr: PcalExpr, coord: PcalCoord) =>
454
+ getElement(getElement(expr.tokens, coord.line), coord.item);
455
+
456
+ // TLAExpr.stepCoord: the coordinates steps tokens after coord, or undefined past the end.
457
+ export const stepPcalCoord = (expr: PcalExpr, coord: PcalCoord, steps: number) => {
458
+ if (expr.tokens.length <= coord.line) {
459
+ throw new PcalBugError("TLAExpr.StepCoord called with line too big");
460
+ }
461
+ if (expr.tokens[coord.line].length <= coord.item) {
462
+ throw new PcalBugError("TLAExpr.StepCoord called with col too big");
463
+ }
464
+ const result = { line: coord.line, item: coord.item };
465
+ for (let step = 0; step < steps; step++) {
466
+ result.item += 1;
467
+ if (expr.tokens[result.line].length === result.item) {
468
+ result.item = 0;
469
+ result.line += 1;
470
+ while (result.line < expr.tokens.length && expr.tokens[result.line].length === 0) {
471
+ result.line += 1;
472
+ }
473
+ if (result.line === expr.tokens.length) return undefined;
474
+ }
475
+ }
476
+ return result;
477
+ };
478
+
479
+ // TLAExpr.findNextInstanceIn: the next token id at or after start that is not a record field
480
+ // name, such as the a in r.a, [a |-> 1] or [a : S].
481
+ const findNextInstance = (expr: PcalExpr, id: string, start: PcalCoord) => {
482
+ for (let coord = expr.tokens.length === 0 ? undefined : { ...start }; coord !== undefined;) {
483
+ const token = getPcalTokenAt(expr, coord);
484
+ const isString = token.type === PCAL_TOKEN.string;
485
+ // The id is an identifier, so a token that is the id is none of the tokens skipped below.
486
+ if (!isString && token.string === id) return coord;
487
+ const afterNext =
488
+ !isString && (token.string === "[" || token.string === ",")
489
+ ? stepPcalCoord(expr, coord, 2)
490
+ : undefined;
491
+ const fieldEnd = afterNext === undefined ? undefined : getPcalTokenAt(expr, afterNext);
492
+ const isFieldName =
493
+ fieldEnd !== undefined &&
494
+ fieldEnd.type !== PCAL_TOKEN.string &&
495
+ [":", "|->", "↦"].includes(fieldEnd.string);
496
+ const steps = isString ? 1 : token.string === "." ? 2 : isFieldName ? 3 : 1;
497
+ coord = stepPcalCoord(expr, coord, steps);
498
+ }
499
+ return undefined;
500
+ };
501
+
502
+ // TLAExpr.substituteAt: replaces the token at coord with a copy of replacement, parenthesized when
503
+ // isParenthesized and replacement has more than one token, and returns the coordinates of the
504
+ // token after it.
505
+ const substituteAt = (
506
+ expr: PcalExpr,
507
+ replacement: PcalExpr,
508
+ coord: PcalCoord,
509
+ isParenthesized: boolean,
510
+ ) => {
511
+ const token = getPcalTokenAt(expr, coord);
512
+ if (isOneTokenPcalExpr(expr)) {
513
+ const cloned = clonePcalExpr(replacement);
514
+ expr.tokens = cloned.tokens;
515
+ expr.anchorTokens = cloned.anchorTokens;
516
+ expr.anchorTokCol = cloned.anchorTokCol;
517
+ return undefined;
518
+ }
519
+ const tokenLine = expr.tokens[coord.line];
520
+ const spaces =
521
+ coord.item + 1 < tokenLine.length
522
+ ? tokenLine[coord.item + 1].column - (token.column + getPcalTokenWidth(token))
523
+ : 0;
524
+ const restOfLine = tokenLine.splice(coord.item + 1);
525
+ // The line the replacement's tokens go on, and how far right they move.
526
+ const cursor = {
527
+ lineIndex: coord.line,
528
+ indent: (isParenthesized ? 1 : 0) + token.column,
529
+ isInserting: !isParenthesized,
530
+ };
531
+ const getLine = () => expr.tokens[cursor.lineIndex];
532
+ if (isOneTokenPcalExpr(replacement)) {
533
+ const replacementToken = replacement.tokens[0][0];
534
+ token.string = replacementToken.string;
535
+ token.type = replacementToken.type;
536
+ } else {
537
+ if (isParenthesized) {
538
+ token.string = "(";
539
+ token.type = PCAL_TOKEN.builtin;
540
+ }
541
+ const newExpr = clonePcalExpr(replacement);
542
+ newExpr.tokens.forEach((replacementLine, index) => {
543
+ replacementLine.forEach((nextToken) => {
544
+ nextToken.column += cursor.indent;
545
+ if (!cursor.isInserting) {
546
+ getLine().push(nextToken);
547
+ return;
548
+ }
549
+ token.string = nextToken.string;
550
+ token.type = nextToken.type;
551
+ cursor.isInserting = false;
552
+ });
553
+ if (index + 1 >= newExpr.tokens.length) return;
554
+ cursor.indent = 0;
555
+ cursor.lineIndex += 1;
556
+ const currentLine = cursor.lineIndex;
557
+ expr.tokens.splice(currentLine, 0, []);
558
+ const oldAnchors = expr.anchorTokens ?? [];
559
+ const oldColumns = expr.anchorTokCol ?? [];
560
+ expr.anchorTokens = expr.tokens.map((_, item) =>
561
+ item < currentLine
562
+ ? oldAnchors[item]
563
+ : item === currentLine
564
+ ? newExpr.anchorTokens?.[index + 1]
565
+ : oldAnchors[item - 1],
566
+ );
567
+ expr.anchorTokCol = expr.tokens.map((_, item) =>
568
+ item < currentLine
569
+ ? oldColumns[item]
570
+ : item === currentLine
571
+ ? (newExpr.anchorTokCol?.[index + 1] ?? 0)
572
+ : oldColumns[item - 1],
573
+ );
574
+ });
575
+ if (isParenthesized) {
576
+ const last = getLine()[getLine().length - 1];
577
+ getLine().push(
578
+ createPcalToken(")", last.column + getPcalTokenWidth(last), PCAL_TOKEN.builtin),
579
+ );
580
+ }
581
+ }
582
+ const line = getLine();
583
+ const result = { line: cursor.lineIndex, item: line.length - 1 };
584
+ if (restOfLine.length > 0) {
585
+ const previous = line[line.length - 1];
586
+ const shift = previous.column + getPcalTokenWidth(previous) + spaces - restOfLine[0].column;
587
+ restOfLine.forEach((oldToken) => {
588
+ oldToken.column += shift;
589
+ line.push(oldToken);
590
+ });
591
+ }
592
+ renormalizePcalExpr(expr);
593
+ return stepPcalCoord(expr, result, 1);
594
+ };
595
+
596
+ // TLAExpr.substituteForAll: replaces each instance of names[i] with exprs[i], in the order the
597
+ // instances appear.
598
+ export const substitutePcalExpr = (
599
+ expr: PcalExpr,
600
+ exprs: PcalExpr[],
601
+ names: string[],
602
+ isParenthesized = true,
603
+ ) => {
604
+ const next = names.map((name) => findNextInstance(expr, name, { line: 0, item: 0 }));
605
+ for (;;) {
606
+ const nearest = next.reduce<{ index: number; position: PcalCoord } | undefined>(
607
+ (best, position, index) =>
608
+ position !== undefined &&
609
+ (best === undefined ||
610
+ position.line < best.position.line ||
611
+ (position.line === best.position.line && position.item < best.position.item))
612
+ ? { index, position }
613
+ : best,
614
+ undefined,
615
+ );
616
+ if (nearest === undefined) return;
617
+ const afterNext = stepPcalCoord(expr, nearest.position, 1);
618
+ const newPosition = substituteAt(expr, exprs[nearest.index], nearest.position, isParenthesized);
619
+ next[nearest.index] =
620
+ newPosition === undefined
621
+ ? undefined
622
+ : findNextInstance(expr, names[nearest.index], newPosition);
623
+ next.forEach((position, index) => {
624
+ if (index === nearest.index || position === undefined || newPosition === undefined) return;
625
+ // HACK: TLAExpr.substituteForAll dereferences afterNextPos without checking for null, which
626
+ // throws a NullPointerException when the substituted token ends the expression.
627
+ if (afterNext === undefined) {
628
+ throw new PcalRuntimeError("NullPointerException: TLAExpr.substituteForAll");
629
+ }
630
+ if (position.line === nearest.position.line)
631
+ position.item += newPosition.item - afterNext.item;
632
+ position.line += newPosition.line - afterNext.line;
633
+ });
634
+ }
635
+ };
636
+
637
+ export const getSubstitutedPcalExpr = (expr: PcalExpr, args: PcalExpr[], params: string[]) => {
638
+ const result = clonePcalExpr(expr);
639
+ substitutePcalExpr(result, args, params);
640
+ return result;
641
+ };
642
+
643
+ // TLAExpr.SeqSubstituteForAll.
644
+ export const substitutePcalExprs = (exprs: PcalExpr[], args: PcalExpr[], params: string[]) =>
645
+ exprs.map((expr) => getSubstitutedPcalExpr(expr, args, params));
646
+
647
+ // TLAExpr.toString, which names the column of a junction except in TLC 1.7.4.
648
+ const formatPcalExpr = (expr: PcalExpr, version?: TlcVersion) => {
649
+ const getColumn = (token: PcalToken) => (version === "1.7.4" ? "" : `(col${token.column}) `);
650
+ const tokens = expr.tokens.map((line) =>
651
+ line.map((token) => {
652
+ if (token.type === PCAL_TOKEN.string) return `"\\"", "${token.string}", "\\""`;
653
+ if (token.string === "\\/") return `"${getColumn(token)}\\\\/"`;
654
+ if (token.string.startsWith("\\")) return `"\\${token.string}"`;
655
+ if (token.string === "/\\") return `"${getColumn(token)}/\\\\"`;
656
+ return `"${token.string}"`;
657
+ }),
658
+ );
659
+ const firstTokenLine = tokens.findIndex((line) => line.length > 0);
660
+ const text = tokens
661
+ .map((line, index) => {
662
+ const isAfterToken = firstTokenLine !== -1 && index > firstTokenLine;
663
+ return line.map((token, item) => (isAfterToken || item > 0 ? `, ${token}` : token)).join("");
664
+ })
665
+ .join("\n");
666
+ return `<< ${text} >>`;
667
+ };
668
+
669
+ // AST.toString: the TLA+ record that PlusCal.tla uses for the node. Indent, EndIndent and NewLine
670
+ // keep a stack of indentation columns as the Java concatenates the record's text left to right.
671
+ export const formatPcalNode = (
672
+ node: PcalNode,
673
+ inputVersionNumber: number,
674
+ version?: TlcVersion,
675
+ ) => {
676
+ const formatExpr = (expr: PcalExpr) => formatPcalExpr(expr, version);
677
+ const columns = [0];
678
+ const depth = { value: 0 };
679
+ const indent = (text: string) => {
680
+ columns[depth.value + 1] = columns[depth.value] + text.length;
681
+ depth.value += 1;
682
+ return text;
683
+ };
684
+ const endIndent = () => {
685
+ depth.value -= 1;
686
+ return "";
687
+ };
688
+ const newLine = () => `\n${" ".repeat(columns[depth.value])}`;
689
+ const isOldVersion = inputVersionNumber < 1500;
690
+ // The separators' new lines take the indentation the elements before them leave.
691
+ const formatSeq = (vector: (PcalNode | PcalExpr)[]) =>
692
+ `${indent("<<")}${vector
693
+ .map(
694
+ (element, index) =>
695
+ `${index > 0 ? `, ${newLine()}` : ""}${"kind" in element ? format(element) : formatExpr(element)}`,
696
+ )
697
+ .join("")}>>${endIndent()}`;
698
+ const formatQuotedSeq = (vector: string[]) =>
699
+ `${indent("<<")}${vector.map((element) => `"${element}"`).join(", ")}>>${endIndent()}`;
700
+ const formatSeqOfSeqs = (vectors: PcalStmt[][]) =>
701
+ `${indent("<< ")}${vectors
702
+ .map((vector, index) => `${index > 0 ? `, ${newLine()}` : ""}${formatSeq(vector)}`)
703
+ .join("")} >>${endIndent()}`;
704
+ const formatEqOrIn = (isEq: boolean) => (isEq ? '"="' : '"\\\\in"');
705
+ const format = (node: PcalNode): string => {
706
+ switch (node.kind) {
707
+ case "Uniprocess":
708
+ return `${indent("")}[type |-> "uniprocess", ${newLine()} name |-> "${node.name}", ${newLine()}${indent(" decls |-> ")}${formatSeq(node.decls)},${endIndent()}${newLine()}${indent(" defs |-> ")}${formatExpr(node.defs)},${endIndent()}${newLine()}${indent(" prcds |-> ")}${formatSeq(node.prcds)},${endIndent()}${newLine()}${indent(" body |-> ")}${formatSeq(node.body)}]${endIndent()}${endIndent()}`;
709
+ case "Multiprocess":
710
+ return `${indent("")}[type |-> "multiprocess", ${newLine()} name |-> "${node.name}", ${newLine()}${indent(" decls |-> ")}${formatSeq(node.decls)},${endIndent()}${newLine()}${indent(" defs |-> ")}${formatExpr(node.defs)},${endIndent()}${newLine()}${indent(" prcds |-> ")}${formatSeq(node.prcds)},${endIndent()}${newLine()}${indent(" procs |-> ")}${formatSeq(node.procs)}]${endIndent()}${endIndent()}`;
711
+ case "Procedure":
712
+ return isOldVersion
713
+ ? `${indent("")}[name |-> "${node.name}", ${newLine()}${indent(" params |-> ")}${formatSeq(node.params)},${endIndent()}${newLine()}${indent(" decls |-> ")}${formatSeq(node.decls)},${endIndent()}${newLine()}${indent(" body |-> ")}${formatSeq(node.body)}]${endIndent()}${endIndent()}`
714
+ : `${indent("")}[name |-> "${node.name}", ${newLine()}minusLabels |-> ${formatQuotedSeq(node.minusLabels)}, plusLabels |->${formatQuotedSeq(node.plusLabels)}, proceduresCalled |->${formatQuotedSeq(node.proceduresCalled)},${newLine()}${indent(" params |-> ")}${formatSeq(node.params)},${endIndent()}${newLine()}${indent(" decls |-> ")}${formatSeq(node.decls)},${endIndent()}${newLine()}${indent(" body |-> ")}${formatSeq(node.body)}]${endIndent()}${endIndent()}`;
715
+ case "Process":
716
+ return isOldVersion
717
+ ? `${indent("")}[name |-> "${node.name}", ${newLine()} eqOrIn |-> ${formatEqOrIn(node.isEq)},${newLine()} id |-> ${formatExpr(node.id)},${newLine()}${indent(" decls |-> ")}${formatSeq(node.decls)},${endIndent()}${newLine()}${indent(" body |-> ")}${formatSeq(node.body)}]${endIndent()}${endIndent()}`
718
+ : `${indent("")}[name |-> "${node.name}",${newLine()} fairness |-> "${PCAL_FAIRNESS[node.fairness]}", minusLabels |-> ${formatQuotedSeq(node.minusLabels)}, plusLabels |->${formatQuotedSeq(node.plusLabels)}, proceduresCalled |->${formatQuotedSeq(node.proceduresCalled)},${newLine()} eqOrIn |-> ${formatEqOrIn(node.isEq)},${newLine()} id |-> ${formatExpr(node.id)},${newLine()}${indent(" decls |-> ")}${formatSeq(node.decls)},${endIndent()}${newLine()}${indent(" body |-> ")}${formatSeq(node.body)}]${endIndent()}${endIndent()}`;
719
+ case "VarDecl":
720
+ return `${indent("")}[var |-> "${node.var}", eqOrIn |-> ${formatEqOrIn(node.isEq)}, val |-> ${formatExpr(node.val)}]${endIndent()}`;
721
+ case "PVarDecl":
722
+ return `${indent("")}[var |-> "${node.var}", eqOrIn |-> "=", val |-> ${formatExpr(node.val)}]${endIndent()}`;
723
+ case "LabeledStmt":
724
+ return `${indent("")}[label |-> "${node.label}",${newLine()}${indent(" stmts |-> ")}${formatSeq(node.stmts)}]${endIndent()}${endIndent()}`;
725
+ case "While":
726
+ return `${indent("")}[type |-> "while", ${newLine()} test |-> ${formatExpr(node.test)},${newLine()}${indent(" labDo |-> ")}${formatSeq(node.labDo)},${endIndent()}${newLine()}${indent(" unlabDo |-> ")}${formatSeq(node.unlabDo)}]${endIndent()}${endIndent()}`;
727
+ case "Assign":
728
+ return `${indent("")}[type |-> "assignment",${newLine()}${indent(" ass |-> ")}${formatSeq(node.ass)}]${endIndent()}${endIndent()}`;
729
+ case "SingleAssign":
730
+ return `${indent("")}[lhs |-> ${format(node.lhs)},${newLine()} rhs |-> ${formatExpr(node.rhs)}]${endIndent()}`;
731
+ case "Lhs":
732
+ return `[var |-> "${node.var}", sub |-> ${formatExpr(node.sub)}]`;
733
+ case "If":
734
+ return `${indent("")}[type |-> "if", ${newLine()} test |-> ${formatExpr(node.test)},${newLine()}${indent(" then |-> ")}${formatSeq(node.Then)},${endIndent()}${newLine()}${indent(" else |-> ")}${formatSeq(node.Else)}]${endIndent()}${endIndent()}`;
735
+ case "Either":
736
+ return `${indent("")}[type |-> "either", ${newLine()}${indent(" ors |-> ")}${formatSeqOfSeqs(node.ors)}]${endIndent()}${endIndent()}`;
737
+ case "With":
738
+ return `${indent("")}[type |-> "with", ${newLine()} var |-> "${node.var}",${newLine()} eqOrIn |-> ${formatEqOrIn(node.isEq)},${newLine()} exp |-> ${formatExpr(node.exp)},${newLine()}${indent(" do |-> ")}${formatSeq(node.Do)}]${endIndent()}${endIndent()}`;
739
+ case "When":
740
+ return `${indent("")}[type |-> "when", ${newLine()} exp |-> ${formatExpr(node.exp)}]${endIndent()}`;
741
+ case "PrintS":
742
+ return `${indent("")}[type |-> "print", ${newLine()} exp |-> ${formatExpr(node.exp)}]${endIndent()}`;
743
+ case "Assert":
744
+ return `${indent("")}[type |-> "assert", ${newLine()} exp |-> ${formatExpr(node.exp)}]${endIndent()}`;
745
+ case "Skip":
746
+ return '[type |-> "skip"]';
747
+ case "LabelIf":
748
+ return `${indent("")}[type |-> "labelIf",${newLine()} test |-> ${formatExpr(node.test)},${newLine()}${indent(" unlabThen |-> ")}${formatSeq(node.unlabThen)},${endIndent()}${newLine()}${indent(" labThen |-> ")}${formatSeq(node.labThen)},${endIndent()}${newLine()}${indent(" unlabElse |-> ")}${formatSeq(node.unlabElse)},${endIndent()}${newLine()}${indent(" labElse |-> ")}${formatSeq(node.labElse)}]${endIndent()}${newLine()}${endIndent()}`;
749
+ case "LabelEither":
750
+ return `${indent("")}[type |-> "labelEither",${newLine()}${indent(" clauses |-> ")}${formatSeq(node.clauses)}]${endIndent()}${newLine()}${endIndent()}`;
751
+ case "Clause":
752
+ return `${indent("")}${indent("[unlabOr |-> ")}${formatSeq(node.unlabOr)},${endIndent()}${newLine()}${indent(" labOr |-> ")}${formatSeq(node.labOr)}]${endIndent()}${newLine()}${endIndent()}`;
753
+ case "Call":
754
+ return `${indent("")}[type |-> "call",${newLine()} returnTo |-> "${node.returnTo}",${newLine()} to |-> "${node.to}",${newLine()}${indent(" args |-> ")}${formatSeq(node.args)}]${endIndent()}${endIndent()}`;
755
+ case "Return":
756
+ return `[type |-> "return", from |-> "${node.from ?? "null"}"]`;
757
+ case "CallReturn":
758
+ return `${indent("")}[type |-> "callReturn",${newLine()} from |-> "${node.from ?? "null"}",${newLine()} to |-> "${node.to}",${newLine()}${indent("args |-> ")}${formatSeq(node.args)}]${newLine()}${endIndent()}${endIndent()}`;
759
+ case "CallGoto":
760
+ return `${indent("")}[type |-> "callGoto",${newLine()} after |-> "${node.after}",${newLine()} to |-> "${node.to}",${newLine()}${indent("args |-> ")}${formatSeq(node.args)}]${newLine()}${endIndent()}${endIndent()}`;
761
+ case "Goto":
762
+ return `[type |-> "goto", to |-> "${node.to}"]`;
763
+ case "Macro":
764
+ return `${indent("")}[name |-> "${node.name}", ${newLine()}${indent(" params |-> ")}${indent("<<")}${node.params.join(`, ${newLine()}`)}>>${endIndent()},${endIndent()}${newLine()}${indent(" body |-> ")}${formatSeq(node.body)}]${endIndent()}${endIndent()}`;
765
+ case "MacroCall":
766
+ return `${indent("")}[type |-> "macrocall",${newLine()} name |-> "${node.name}",${newLine()}${indent(" args |-> ")}${formatSeq(node.args)}]${endIndent()}${endIndent()}`;
767
+ }
768
+ };
769
+ return format(node);
770
+ };