tla-ts 0.0.3-dev.d9ff6f2 → 0.0.3-dev.e8bef80

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 +166 -40
  5. package/dist/index.d.ts +166 -40
  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 -22
  12. package/dist/run-cli.js +1351 -22
  13. package/dist/transfer.cjs +83 -34
  14. package/dist/transfer.js +83 -34
  15. package/package.json +5 -1
  16. package/src/ast.ts +55 -7
  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 +1331 -367
  22. package/src/cli.ts +8 -1
  23. package/src/codegen.ts +68 -21
  24. package/src/config.ts +226 -207
  25. package/src/environment.ts +423 -127
  26. package/src/errors.ts +168 -9
  27. package/src/evaluate.ts +720 -177
  28. package/src/exit-codes.ts +6 -24
  29. package/src/index.ts +1 -0
  30. package/src/instances.ts +3 -1
  31. package/src/java-overrides.ts +104 -25
  32. package/src/levels.ts +149 -31
  33. package/src/lexer.ts +122 -29
  34. package/src/live-check.ts +204 -148
  35. package/src/liveness.ts +191 -122
  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 +428 -141
  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 +1436 -459
  48. package/src/run-cli.ts +1166 -181
  49. package/src/runtime.ts +16 -0
  50. package/src/sany-builtins.ts +147 -0
  51. package/src/sany-generator.ts +3128 -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 +356 -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 +25 -5
  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 +161 -167
  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 +680 -255
@@ -0,0 +1,1523 @@
1
+ import { PcalError, PcalRuntimeError, PcalBugError } from "./errors";
2
+ import {
3
+ clonePcalExpr,
4
+ createNormalizedPcalExpr,
5
+ createPcalBase,
6
+ getElement,
7
+ getPcalLocation,
8
+ getPcalTokenAt,
9
+ getSubstitutedPcalExpr,
10
+ isOneTokenPcalExpr,
11
+ normalizePcalExpr,
12
+ PCAL_TOKEN,
13
+ prependPcalExpr,
14
+ stepPcalCoord,
15
+ substitutePcalExprs,
16
+ type PcalAlgorithm,
17
+ type PcalAssign,
18
+ type PcalCall,
19
+ type PcalClause,
20
+ type PcalExpr,
21
+ type PcalLabeledStmt,
22
+ type PcalLabelEither,
23
+ type PcalLabelIf,
24
+ type PcalLhs,
25
+ type PcalMacro,
26
+ type PcalMacroCall,
27
+ type PcalParams,
28
+ type PcalProcedure,
29
+ type PcalProcess,
30
+ type PcalPVarDecl,
31
+ type PcalSingleAssign,
32
+ type PcalStmt,
33
+ type PcalVarDecl,
34
+ type PcalWith,
35
+ createPcalExpr,
36
+ createPcalToken,
37
+ } from "./pcal-ast";
38
+ import {
39
+ createPcalTokenizerState,
40
+ getPcalAlgorithmToken,
41
+ peekPcalReader,
42
+ tokenizePcalExpr,
43
+ type PcalCharReader,
44
+ type PcalTokenizerState,
45
+ } from "./pcal-tokenize";
46
+
47
+ // The translator's state that its Java code keeps in static fields, which SANY never resets
48
+ // between the modules it validates: the options, the tokenizer's state, ParseAlgorithm's
49
+ // lookahead buffer and last token, and whether a macro's parsing was cut short by an error.
50
+ export interface PcalSession {
51
+ params: PcalParams;
52
+ tokenizer: PcalTokenizerState;
53
+ lookahead: { tokens: string[]; columns: number[]; lines: number[] };
54
+ lastToken: { column: number; line: number; text: string };
55
+ isInMacro: boolean;
56
+ // ToolIO.out.println, which PcalDebug's reports go to.
57
+ log: (line: string) => void;
58
+ }
59
+
60
+ export const createPcalSession = (
61
+ params: PcalParams,
62
+ log: (line: string) => void,
63
+ ): PcalSession => ({
64
+ params,
65
+ tokenizer: createPcalTokenizerState(),
66
+ lookahead: {
67
+ tokens: Array.from({ length: 10 }, () => ""),
68
+ columns: Array.from({ length: 10 }, () => 0),
69
+ lines: Array.from({ length: 10 }, () => 0),
70
+ },
71
+ lastToken: { column: 0, line: 0, text: "" },
72
+ isInMacro: false,
73
+ log,
74
+ });
75
+
76
+ // ParseAlgorithm's static fields that Init resets for each algorithm.
77
+ interface PcalParserState {
78
+ lookaheadSize: number;
79
+ addedLabels: string[];
80
+ addedLabelsLocs: string[];
81
+ nextLabelNum: number;
82
+ allLabels: Set<string>;
83
+ hasLabel: boolean;
84
+ hasDefaultInitialization: boolean;
85
+ currentProcedure: string | undefined;
86
+ procedures: PcalProcedure[];
87
+ pSyntax: boolean;
88
+ cSyntax: boolean;
89
+ plusLabels: string[];
90
+ minusLabels: string[];
91
+ proceduresCalled: string[];
92
+ gotoUsed: boolean;
93
+ gotoDoneUsed: boolean;
94
+ omitPC: boolean;
95
+ omitStutteringWhenDone: boolean;
96
+ }
97
+
98
+ interface PcalParseResult {
99
+ ast: PcalAlgorithm;
100
+ omitPC: boolean;
101
+ omitStutteringWhenDone: boolean;
102
+ hasDefaultInitialization: boolean;
103
+ }
104
+
105
+ // PcalParams.DefaultVarInit: the value of a variable declared without one.
106
+ const createDefaultVarInit = () =>
107
+ createNormalizedPcalExpr([[createPcalToken("defaultInitValue", 0, 0)]]);
108
+
109
+ // ParseAlgorithm.Union.
110
+ const getUnion = (first: string[], second: string[]) => [
111
+ ...first,
112
+ ...second.filter((name, index) => !first.includes(name) && second.indexOf(name) === index),
113
+ ];
114
+
115
+ // ParseAlgorithm.HasEmptyIntersection.
116
+ const isDisjoint = (first: string[], second: string[]) =>
117
+ !second.some((name) => first.includes(name));
118
+
119
+ // ParseAlgorithm.Copy: replaces the contents of target, which callers share.
120
+ const copyInto = (source: string[], target: string[]) => {
121
+ target.splice(0, target.length, ...source);
122
+ };
123
+
124
+ // ParseAlgorithm.getAlgorithm: parses the algorithm the reader is at, just after "--algorithm" or
125
+ // "--fair", adds the labels it needs, and expands its macros.
126
+ export const parsePcalAlgorithm = (
127
+ session: PcalSession,
128
+ reader: PcalCharReader,
129
+ isFairAlgorithm: boolean,
130
+ ): PcalParseResult => {
131
+ const params = session.params;
132
+ const lookahead = session.lookahead;
133
+ const lastToken = session.lastToken;
134
+ // ParseAlgorithm.Init.
135
+ const state: PcalParserState = {
136
+ lookaheadSize: 0,
137
+ addedLabels: [],
138
+ addedLabelsLocs: [],
139
+ nextLabelNum: 1,
140
+ allLabels: new Set(),
141
+ hasLabel: false,
142
+ hasDefaultInitialization: false,
143
+ currentProcedure: undefined,
144
+ procedures: [],
145
+ pSyntax: false,
146
+ cSyntax: false,
147
+ plusLabels: [],
148
+ minusLabels: [],
149
+ proceduresCalled: [],
150
+ gotoUsed: false,
151
+ gotoDoneUsed: false,
152
+ omitPC: params.inputVersionNumber >= 1500,
153
+ omitStutteringWhenDone: params.inputVersionNumber >= 1500,
154
+ };
155
+
156
+ // ParseAlgorithm.ParsingError.
157
+ const throwParsingError = (message: string): never => {
158
+ throw new PcalError(`${message}\n line ${lastToken.line}, column ${lastToken.column}`);
159
+ };
160
+
161
+ const getAlgToken = () => {
162
+ if (state.lookaheadSize === 0) {
163
+ peekPcalReader(reader);
164
+ lastToken.column = reader.vcolumn + 1;
165
+ lastToken.line = reader.line + 1;
166
+ lastToken.text = getPcalAlgorithmToken(session.tokenizer, reader);
167
+ return lastToken.text;
168
+ }
169
+ lastToken.column = lookahead.columns[0] + 1;
170
+ lastToken.line = lookahead.lines[0] + 1;
171
+ const result = lookahead.tokens[0];
172
+ for (let index = 1; index < state.lookaheadSize; index++) {
173
+ lookahead.tokens[index - 1] = lookahead.tokens[index];
174
+ lookahead.columns[index - 1] = lookahead.columns[index];
175
+ lookahead.lines[index - 1] = lookahead.lines[index];
176
+ }
177
+ state.lookaheadSize -= 1;
178
+ lastToken.text = result;
179
+ return result;
180
+ };
181
+
182
+ const peekAtAlgToken = (tokenNumber: number) => {
183
+ while (state.lookaheadSize < tokenNumber) {
184
+ const size = state.lookaheadSize;
185
+ if (peekPcalReader(reader) === "\t") {
186
+ throw new PcalError(
187
+ `Premature end of file, perhaps because of unclosed comment, near\n line ${lookahead.lines[size] + 1}, column ${lookahead.columns[size] + 1}`,
188
+ );
189
+ }
190
+ lookahead.columns[size] = reader.vcolumn;
191
+ lookahead.lines[size] = reader.line;
192
+ lookahead.tokens[size] = getPcalAlgorithmToken(session.tokenizer, reader);
193
+ state.lookaheadSize += 1;
194
+ }
195
+ return lookahead.tokens[tokenNumber - 1];
196
+ };
197
+
198
+ // ParseAlgorithm.PeekPastAlgToken: the rest of the line after the next tokenNumber tokens.
199
+ const peekPastAlgToken = (tokenNumber: number) => {
200
+ if (tokenNumber < state.lookaheadSize) {
201
+ throw new PcalBugError(
202
+ "ParseAlgorithm.PeekPastAlgToken called to peek after a token\n it has already peeked at",
203
+ );
204
+ }
205
+ while (tokenNumber > state.lookaheadSize) {
206
+ lookahead.tokens[state.lookaheadSize] = getPcalAlgorithmToken(session.tokenizer, reader);
207
+ state.lookaheadSize += 1;
208
+ }
209
+ return peekPcalReader(reader);
210
+ };
211
+
212
+ // ParseAlgorithm.getExprInternal: an expression's delimiter becomes the next token.
213
+ const getExpr = (isDefineBlock = false) => {
214
+ if (state.lookaheadSize !== 0) {
215
+ throw new PcalBugError("ParseAlgorithm: GetExpr called after lookahead");
216
+ }
217
+ const result = tokenizePcalExpr(session.tokenizer, reader, isDefineBlock);
218
+ lookahead.tokens[0] = session.tokenizer.delimiter;
219
+ lookahead.columns[0] = session.tokenizer.delimiterCol;
220
+ lookahead.lines[0] = session.tokenizer.delimiterLine;
221
+ state.lookaheadSize = 1;
222
+ return result;
223
+ };
224
+
225
+ // ParseAlgorithm.GobbleThis: a missing ";" is fine before a token that can't start a statement.
226
+ const gobbleThis = (expected: string, alternate?: string) => {
227
+ if (expected === ";") {
228
+ const next = peekAtAlgToken(1);
229
+ const endings = "end begin else elsif or do macro procedure process fair define } {";
230
+ if (endings.split(" ").includes(next)) return;
231
+ const statements = "if either while with call return goto print assert skip";
232
+ if (statements.split(" ").includes(next)) {
233
+ throw new PcalError(
234
+ `Missing \`;' before line ${lookahead.lines[0] + 1}, column ${lookahead.columns[0] + 1}`,
235
+ );
236
+ }
237
+ }
238
+ const token = getAlgToken();
239
+ if (token !== expected && token !== alternate) {
240
+ throwParsingError(`Expected "${expected}" but found "${token}"`);
241
+ }
242
+ };
243
+
244
+ const mustGobbleThis = (expected: string) => {
245
+ const token = getAlgToken();
246
+ if (token !== expected) throwParsingError(`Expected "${expected}" but found "${token}"`);
247
+ };
248
+
249
+ const gobbleEqualOrIf = () => {
250
+ const token = getAlgToken();
251
+ if (token === "=") return true;
252
+ if (token === "\\in" || token === "∈") return false;
253
+ return throwParsingError(`Expected "=" or "\\in" but found "${token}"`);
254
+ };
255
+
256
+ const gobbleCommaOrSemicolon = () => gobbleThis(peekAtAlgToken(1) === "," ? "," : ";");
257
+
258
+ const gobbleBeginOrLeftBrace = () => gobbleThis(state.pSyntax ? "begin" : "{");
259
+
260
+ const gobbleEndOrRightBrace = (name: string) => {
261
+ if (state.cSyntax) {
262
+ gobbleThis("}");
263
+ return;
264
+ }
265
+ gobbleThis("end");
266
+ gobbleThis(name);
267
+ };
268
+
269
+ const gobbleVariables = () => {
270
+ if (peekAtAlgToken(1) === "variables") mustGobbleThis("variables");
271
+ else gobbleThis("variable");
272
+ };
273
+
274
+ const getVarDecl = () => {
275
+ const decl: PcalVarDecl = {
276
+ ...createPcalBase(),
277
+ kind: "VarDecl",
278
+ var: getAlgToken(),
279
+ col: lastToken.column,
280
+ line: lastToken.line,
281
+ isEq: true,
282
+ val: createDefaultVarInit(),
283
+ };
284
+ if (!["=", "\\in", "∈"].includes(peekAtAlgToken(1))) {
285
+ state.hasDefaultInitialization = true;
286
+ return decl;
287
+ }
288
+ decl.isEq = gobbleEqualOrIf();
289
+ decl.val = getExpr();
290
+ // ParseAlgorithm.GetVarDecl takes the end of the value's origin, which an empty value lacks,
291
+ // before checking for one.
292
+ if (decl.val.tokens.length === 0) throw new PcalRuntimeError("NullPointerException");
293
+ return decl;
294
+ };
295
+
296
+ const getVarDecls = () => {
297
+ gobbleVariables();
298
+ const result: PcalVarDecl[] = [];
299
+ const ends = ["begin", "{", "procedure", "process", "fair", "define", "macro"];
300
+ while (!ends.includes(peekAtAlgToken(1))) {
301
+ result.push(getVarDecl());
302
+ gobbleCommaOrSemicolon();
303
+ }
304
+ return result;
305
+ };
306
+
307
+ const getPVarDecl = () => {
308
+ const decl: PcalPVarDecl = {
309
+ ...createPcalBase(),
310
+ kind: "PVarDecl",
311
+ var: getAlgToken(),
312
+ col: lastToken.column,
313
+ line: lastToken.line,
314
+ val: createDefaultVarInit(),
315
+ };
316
+ if (peekAtAlgToken(1) !== "=") {
317
+ state.hasDefaultInitialization = true;
318
+ return decl;
319
+ }
320
+ gobbleThis("=");
321
+ decl.val = getExpr();
322
+ if (decl.val.tokens.length === 0) throw new PcalRuntimeError("NullPointerException");
323
+ return decl;
324
+ };
325
+
326
+ const getPVarDecls = () => {
327
+ gobbleVariables();
328
+ const result: PcalPVarDecl[] = [];
329
+ while (!(peekAtAlgToken(1) === "begin" || peekAtAlgToken(1) === "{")) {
330
+ result.push(getPVarDecl());
331
+ gobbleCommaOrSemicolon();
332
+ }
333
+ return result;
334
+ };
335
+
336
+ // ParseAlgorithm.IsLabelNext: an identifier followed by ":" but not ":=".
337
+ const isLabelNext = () => {
338
+ const keywords =
339
+ "while if assert print else elsif either or end with when await skip call return goto";
340
+ if (keywords.split(" ").includes(peekAtAlgToken(1))) return false;
341
+ const rest = peekPcalReader(reader);
342
+ return rest.length > 0 && rest[0] === ":" && !(rest.length > 1 && rest[1] === "=");
343
+ };
344
+
345
+ const getLabel = () => {
346
+ if (!isLabelNext()) return "";
347
+ const label = getAlgToken();
348
+ if (session.isInMacro) throwParsingError("A label may not appear in a macro.");
349
+ if (label === "Done") throwParsingError("Cannot use `Done' as a label.");
350
+ if (label === "Error") throwParsingError("Cannot use `Error' as a label.");
351
+ gobbleThis(":");
352
+ state.hasLabel = true;
353
+ state.allLabels.add(label);
354
+ const modifier = peekAtAlgToken(1);
355
+ if (modifier !== "+" && modifier !== "-") return label;
356
+ gobbleThis(modifier);
357
+ (modifier === "+" ? state.plusLabels : state.minusLabels).push(label);
358
+ state.omitPC = false;
359
+ return label;
360
+ };
361
+
362
+ const getStmtSeq = (): PcalStmt[] => {
363
+ const result: PcalStmt[] = [];
364
+ const isEnd = (token: string) =>
365
+ (state.pSyntax && ["end", "else", "elsif", "or"].includes(token)) ||
366
+ (state.cSyntax && token === "}");
367
+ while (!isEnd(peekAtAlgToken(1))) result.push(...getCStmt());
368
+ if (state.cSyntax && result.length === 0) throwParsingError("Empty statement list");
369
+ return result;
370
+ };
371
+
372
+ const getCStmtSeq = (label: string) => {
373
+ mustGobbleThis("{");
374
+ const result = getStmtSeq();
375
+ gobbleThis("}");
376
+ gobbleThis(";");
377
+ if (label !== "") {
378
+ if (result[0].lbl !== "") throw new PcalError("Duplicate labeling of statement", result[0]);
379
+ result[0].lbl = label;
380
+ }
381
+ return result;
382
+ };
383
+
384
+ const getCStmt = () => {
385
+ const label = getLabel();
386
+ if (state.cSyntax && peekAtAlgToken(1) === "{") return getCStmtSeq(label);
387
+ const stmt = getStmt();
388
+ stmt.lbl = label;
389
+ return [stmt];
390
+ };
391
+
392
+ const getStmt = (): PcalStmt => {
393
+ const next = peekAtAlgToken(1);
394
+ if (next === "if") return getIf(0);
395
+ if (next === "either") return getEither();
396
+ if (next === "with") return getWith(0);
397
+ if (next === "when" || next === "await") {
398
+ mustGobbleThis(next);
399
+ const col = lastToken.column;
400
+ const line = lastToken.line;
401
+ const exp = getExpr();
402
+ // ParseAlgorithm.GetWhen takes the end of the expression's origin, which an empty
403
+ // expression lacks, before checking for one.
404
+ if (exp.tokens.length === 0) throw new PcalRuntimeError("NullPointerException");
405
+ gobbleThis(";");
406
+ return { ...createPcalBase(), kind: "When", col, line, exp };
407
+ }
408
+ if (next === "print" || next === "assert") {
409
+ mustGobbleThis(next);
410
+ const col = lastToken.column;
411
+ const line = lastToken.line;
412
+ const exp = getExpr();
413
+ if (exp.tokens.length === 0) throwParsingError(`Empty expression in ${next} statement at `);
414
+ gobbleThis(";");
415
+ return {
416
+ ...createPcalBase(),
417
+ kind: next === "print" ? "PrintS" : "Assert",
418
+ col,
419
+ line,
420
+ exp,
421
+ };
422
+ }
423
+ if (next === "skip") {
424
+ mustGobbleThis("skip");
425
+ const skip: PcalStmt = {
426
+ ...createPcalBase(),
427
+ kind: "Skip",
428
+ col: lastToken.column,
429
+ line: lastToken.line,
430
+ };
431
+ gobbleThis(";");
432
+ return skip;
433
+ }
434
+ if (next === "call") return getCallOrCallReturnOrCallGoto();
435
+ if (next === "return") {
436
+ mustGobbleThis("return");
437
+ const result: PcalStmt = {
438
+ ...createPcalBase(),
439
+ kind: "Return",
440
+ col: lastToken.column,
441
+ line: lastToken.line,
442
+ from: state.currentProcedure,
443
+ };
444
+ gobbleThis(";");
445
+ return result;
446
+ }
447
+ if (next === "goto") {
448
+ mustGobbleThis("goto");
449
+ const col = lastToken.column;
450
+ const line = lastToken.line;
451
+ const to = getAlgToken();
452
+ state.gotoUsed = true;
453
+ if (to === "Done" || to === '"Done"') state.gotoDoneUsed = true;
454
+ gobbleThis(";");
455
+ return { ...createPcalBase(), kind: "Goto", col, line, to };
456
+ }
457
+ if (next === "while") return getWhile();
458
+ if (peekPastAlgToken(1)[0] === "(") return getMacroCall();
459
+ return getAssign();
460
+ };
461
+
462
+ const getWhile = (): PcalStmt => {
463
+ mustGobbleThis("while");
464
+ const col = lastToken.column;
465
+ const line = lastToken.line;
466
+ if (state.cSyntax) gobbleThis("(");
467
+ const test = getExpr();
468
+ if (state.cSyntax) gobbleThis(")");
469
+ if (test.tokens.length === 0) throwParsingError("Empty while test at ");
470
+ if (state.pSyntax) gobbleThis("do");
471
+ const unlabDo = state.pSyntax ? getStmtSeq() : getCStmt();
472
+ if (state.pSyntax) {
473
+ gobbleThis("end");
474
+ gobbleThis("while");
475
+ gobbleThis(";");
476
+ }
477
+ if (unlabDo.length === 0) throwParsingError("Missing body of while statement at");
478
+ return { ...createPcalBase(), kind: "While", col, line, test, unlabDo, labDo: [] };
479
+ };
480
+
481
+ const getIf = (depth: number): PcalLabelIf => {
482
+ mustGobbleThis(depth === 0 ? "if" : "elsif");
483
+ const result: PcalLabelIf = {
484
+ ...createPcalBase(),
485
+ kind: "LabelIf",
486
+ col: lastToken.column,
487
+ line: lastToken.line,
488
+ test: createPcalExpr(),
489
+ unlabThen: [],
490
+ labThen: [],
491
+ unlabElse: [],
492
+ labElse: [],
493
+ };
494
+ if (state.cSyntax) gobbleThis("(");
495
+ result.test = getExpr();
496
+ if (state.cSyntax) gobbleThis(")");
497
+ if (result.test.tokens.length === 0) throwParsingError("Empty if test at ");
498
+ if (state.pSyntax) gobbleThis("then");
499
+ result.unlabThen = state.pSyntax ? getStmtSeq() : getCStmt();
500
+ const next = peekAtAlgToken(1);
501
+ if (next === "else") {
502
+ mustGobbleThis("else");
503
+ result.unlabElse = state.pSyntax ? getStmtSeq() : getCStmt();
504
+ }
505
+ if (state.pSyntax && next === "elsif") result.unlabElse = [getIf(depth + 1)];
506
+ if (state.pSyntax && !["else", "elsif", "end"].includes(next)) {
507
+ throwParsingError('Expecting "else", "elsif", or "end"');
508
+ }
509
+ if (state.pSyntax && depth === 0) {
510
+ gobbleThis("end");
511
+ gobbleThis("if");
512
+ gobbleThis(";");
513
+ }
514
+ // ParseAlgorithm.GetIf takes the origin of the last statement, which an empty then clause
515
+ // with no else clause doesn't have.
516
+ if (result.unlabElse.length === 0) {
517
+ getElement(result.unlabThen, result.unlabThen.length - 1);
518
+ }
519
+ return result;
520
+ };
521
+
522
+ const getEither = () => {
523
+ mustGobbleThis("either");
524
+ const result: PcalLabelEither = {
525
+ ...createPcalBase(),
526
+ kind: "LabelEither",
527
+ col: lastToken.column,
528
+ line: lastToken.line,
529
+ clauses: [],
530
+ };
531
+ for (;;) {
532
+ const clause: PcalClause = {
533
+ ...createPcalBase(),
534
+ kind: "Clause",
535
+ unlabOr: state.pSyntax ? getStmtSeq() : getCStmt(),
536
+ labOr: [],
537
+ };
538
+ if (clause.unlabOr.length === 0) {
539
+ throw new PcalError("`either' statement with empty `or' clause", result);
540
+ }
541
+ result.clauses.push(clause);
542
+ if (peekAtAlgToken(1) !== "or") break;
543
+ mustGobbleThis("or");
544
+ }
545
+ if (state.pSyntax) {
546
+ mustGobbleThis("end");
547
+ gobbleThis("either");
548
+ gobbleThis(";");
549
+ }
550
+ if (result.clauses.length === 1) throw new PcalError("`either' statement has no `or'", result);
551
+ return result;
552
+ };
553
+
554
+ // ParseAlgorithm.InnerGetWith: "with x = e, y \in f" nests a with for each variable.
555
+ const getWith = (depth: number): PcalWith => {
556
+ if (depth === 0) {
557
+ gobbleThis("with");
558
+ if (state.cSyntax) gobbleThis("(");
559
+ }
560
+ const result: PcalWith = {
561
+ ...createPcalBase(),
562
+ kind: "With",
563
+ col: lastToken.column,
564
+ line: lastToken.line,
565
+ var: getAlgToken(),
566
+ isEq: true,
567
+ exp: createPcalExpr(),
568
+ Do: [],
569
+ };
570
+ result.isEq = gobbleEqualOrIf();
571
+ result.exp = getExpr();
572
+ if (state.pSyntax || peekAtAlgToken(1) !== ")") gobbleCommaOrSemicolon();
573
+ if (result.exp.tokens.length === 0) throwParsingError("Empty with expression at ");
574
+ const isBlockBody = state.pSyntax && peekAtAlgToken(1) === "do";
575
+ const isBraceBody = state.cSyntax && peekAtAlgToken(1) === ")";
576
+ if (isBlockBody) gobbleThis("do");
577
+ if (isBraceBody) mustGobbleThis(")");
578
+ result.Do = isBlockBody ? getStmtSeq() : isBraceBody ? getCStmt() : [getWith(depth + 1)];
579
+ if (isBlockBody) {
580
+ gobbleThis("end");
581
+ gobbleThis("with");
582
+ gobbleThis(";");
583
+ }
584
+ if (result.Do.length === 0) throw new PcalError("Missing body of with statement", result);
585
+ return result;
586
+ };
587
+
588
+ const getSingleAssign = (): PcalSingleAssign => {
589
+ const col = lookahead.columns[0] + 1;
590
+ const line = lookahead.lines[0] + 1;
591
+ const lhs: PcalLhs = {
592
+ ...createPcalBase(),
593
+ kind: "Lhs",
594
+ col,
595
+ line,
596
+ var: getAlgToken(),
597
+ sub: getExpr(),
598
+ };
599
+ gobbleThis(":=", "≔");
600
+ const rhs = getExpr();
601
+ if (rhs.tokens.length === 0) throwParsingError("Empty right-hand side of assignment at ");
602
+ return { ...createPcalBase(), kind: "SingleAssign", col, line, lhs, rhs };
603
+ };
604
+
605
+ const getAssign = () => {
606
+ const result: PcalAssign = {
607
+ ...createPcalBase(),
608
+ kind: "Assign",
609
+ col: lookahead.columns[0] + 1,
610
+ line: lookahead.lines[0] + 1,
611
+ ass: [getSingleAssign()],
612
+ };
613
+ while (peekAtAlgToken(1) === "||" || peekAtAlgToken(1) === "‖") {
614
+ getAlgToken();
615
+ // HACK: ParseAlgorithm.GetAssign replaces the error of an assignment after the first with
616
+ // its own.
617
+ try {
618
+ result.ass.push(getSingleAssign());
619
+ } catch (error) {
620
+ if (!(error instanceof PcalError)) throw error;
621
+ throwParsingError("Bad assignment statement at ");
622
+ }
623
+ }
624
+ gobbleThis(";");
625
+ return result;
626
+ };
627
+
628
+ // The arguments of a call or macro call, through its ")" and ";".
629
+ const getCallArgs = () => {
630
+ const args: PcalExpr[] = [];
631
+ if (peekPastAlgToken(0)[0] !== ")") {
632
+ for (;;) {
633
+ const arg = getExpr();
634
+ args.push(arg);
635
+ if (arg.tokens.length === 0) throwParsingError("Empty argument in call statement at ");
636
+ if (peekAtAlgToken(1) === ")") break;
637
+ gobbleThis(",");
638
+ }
639
+ }
640
+ gobbleThis(")");
641
+ gobbleThis(";");
642
+ return args;
643
+ };
644
+
645
+ const getCall = () => {
646
+ mustGobbleThis("call");
647
+ const result: PcalCall = {
648
+ ...createPcalBase(),
649
+ kind: "Call",
650
+ col: lastToken.column,
651
+ line: lastToken.line,
652
+ returnTo: "",
653
+ to: getAlgToken(),
654
+ args: [],
655
+ };
656
+ gobbleThis("(");
657
+ result.args = getCallArgs();
658
+ if (!state.proceduresCalled.includes(result.to)) state.proceduresCalled.push(result.to);
659
+ return result;
660
+ };
661
+
662
+ const getCallOrCallReturnOrCallGoto = (): PcalStmt => {
663
+ const call = getCall();
664
+ if (peekAtAlgToken(1) === "return") {
665
+ mustGobbleThis("return");
666
+ gobbleThis(";");
667
+ return {
668
+ ...createPcalBase(),
669
+ kind: "CallReturn",
670
+ col: call.col,
671
+ line: call.line,
672
+ to: call.to,
673
+ from: state.currentProcedure,
674
+ args: call.args,
675
+ };
676
+ }
677
+ if (peekAtAlgToken(1) !== "goto") return call;
678
+ mustGobbleThis("goto");
679
+ const result: PcalStmt = {
680
+ ...createPcalBase(),
681
+ kind: "CallGoto",
682
+ col: call.col,
683
+ line: call.line,
684
+ to: call.to,
685
+ after: getAlgToken(),
686
+ args: call.args,
687
+ };
688
+ state.gotoUsed = true;
689
+ if (result.to === "Done" || result.to === '"Done"') state.gotoDoneUsed = true;
690
+ gobbleThis(";");
691
+ return result;
692
+ };
693
+
694
+ const getMacroCall = () => {
695
+ const result: PcalMacroCall = {
696
+ ...createPcalBase(),
697
+ kind: "MacroCall",
698
+ name: getAlgToken(),
699
+ col: lastToken.column,
700
+ line: lastToken.line,
701
+ args: [],
702
+ };
703
+ mustGobbleThis("(");
704
+ result.args = getCallArgs();
705
+ return result;
706
+ };
707
+
708
+ const getMacro = (macros: PcalMacro[]) => {
709
+ session.isInMacro = true;
710
+ mustGobbleThis("macro");
711
+ const result: PcalMacro = {
712
+ ...createPcalBase(),
713
+ kind: "Macro",
714
+ col: lastToken.column,
715
+ line: lastToken.line,
716
+ name: getAlgToken(),
717
+ params: [],
718
+ body: [],
719
+ };
720
+ gobbleThis("(");
721
+ while (peekAtAlgToken(1) !== ")") {
722
+ if (result.params.length > 0) gobbleThis(",");
723
+ result.params.push(getAlgToken());
724
+ }
725
+ mustGobbleThis(")");
726
+ gobbleBeginOrLeftBrace();
727
+ result.body = getStmtSeq();
728
+ gobbleEndOrRightBrace("macro");
729
+ if (peekAtAlgToken(1) === ";") getAlgToken();
730
+ expandMacrosInStmtSeq(result.body, macros);
731
+ session.isInMacro = false;
732
+ return result;
733
+ };
734
+
735
+ const getProcedure = () => {
736
+ gobbleThis("procedure");
737
+ const result: PcalProcedure = {
738
+ ...createPcalBase(),
739
+ kind: "Procedure",
740
+ col: lastToken.column,
741
+ line: lastToken.line,
742
+ name: getAlgToken(),
743
+ minusLabels: [],
744
+ plusLabels: [],
745
+ proceduresCalled: [],
746
+ params: [],
747
+ decls: [],
748
+ body: [],
749
+ };
750
+ state.currentProcedure = result.name;
751
+ state.plusLabels = [];
752
+ state.minusLabels = [];
753
+ state.proceduresCalled = [];
754
+ gobbleThis("(");
755
+ while (peekAtAlgToken(1) !== ")") {
756
+ if (result.params.length > 0) gobbleThis(",");
757
+ result.params.push(getPVarDecl());
758
+ }
759
+ mustGobbleThis(")");
760
+ if (!(peekAtAlgToken(1) === "begin" || peekAtAlgToken(1) === "{")) {
761
+ result.decls = getPVarDecls();
762
+ }
763
+ gobbleBeginOrLeftBrace();
764
+ result.body = getStmtSeq();
765
+ gobbleEndOrRightBrace("procedure");
766
+ if (peekAtAlgToken(1) === ";") getAlgToken();
767
+ state.currentProcedure = undefined;
768
+ result.plusLabels = state.plusLabels;
769
+ result.minusLabels = state.minusLabels;
770
+ result.proceduresCalled = state.proceduresCalled;
771
+ return result;
772
+ };
773
+
774
+ const getProcess = (): PcalProcess => {
775
+ gobbleThis("process");
776
+ const col = lastToken.column;
777
+ const line = lastToken.line;
778
+ if (state.cSyntax) gobbleThis("(");
779
+ const name = getAlgToken();
780
+ const isEq = gobbleEqualOrIf();
781
+ const id = getExpr();
782
+ state.plusLabels = [];
783
+ state.minusLabels = [];
784
+ state.proceduresCalled = [];
785
+ if (state.cSyntax) gobbleThis(")");
786
+ if (id.tokens.length === 0) throwParsingError("Empty process id at ");
787
+ const decls = peekAtAlgToken(1) === "begin" || peekAtAlgToken(1) === "{" ? [] : getVarDecls();
788
+ gobbleBeginOrLeftBrace();
789
+ const body = getStmtSeq();
790
+ gobbleEndOrRightBrace("process");
791
+ if (peekAtAlgToken(1) === ";") getAlgToken();
792
+ return {
793
+ ...createPcalBase(),
794
+ kind: "Process",
795
+ col,
796
+ line,
797
+ name,
798
+ fairness: 0,
799
+ minusLabels: state.minusLabels,
800
+ plusLabels: state.plusLabels,
801
+ proceduresCalled: state.proceduresCalled,
802
+ isEq,
803
+ id,
804
+ decls,
805
+ body,
806
+ };
807
+ };
808
+
809
+ // ParseAlgorithm.NeedsLabel: the label root and the next number no label of the algorithm has.
810
+ const getUnusedLabel = (): string => {
811
+ const label = `${params.labelRoot}${state.nextLabelNum}`;
812
+ state.nextLabelNum += 1;
813
+ return state.allLabels.has(label) ? getUnusedLabel() : label;
814
+ };
815
+
816
+ const needsLabel = (stmt: PcalStmt) => {
817
+ if (stmt.lbl !== "") return;
818
+ stmt.lbl = getUnusedLabel();
819
+ state.addedLabels.push(stmt.lbl);
820
+ state.addedLabelsLocs.push(getPcalLocation(stmt));
821
+ };
822
+
823
+ // ParseAlgorithm.InnerAddLabels: labels the statements that must start a step, tracking the
824
+ // variables assigned since the last label in outAssigned. True when the statement after the
825
+ // sequence needs a label.
826
+ const addLabels = (
827
+ stmts: PcalStmt[],
828
+ isFirstLabeled: boolean,
829
+ isInWith: boolean,
830
+ inAssigned: string[],
831
+ outAssigned: string[],
832
+ ): boolean => {
833
+ copyInto(inAssigned, outAssigned);
834
+ const progress = { isNextLabeled: isFirstLabeled, hasLabel: false };
835
+ const startStep = (stmt: PcalStmt) => {
836
+ needsLabel(stmt);
837
+ progress.hasLabel = true;
838
+ outAssigned.length = 0;
839
+ };
840
+ stmts.forEach((stmt) => {
841
+ if (stmt.lbl !== "") {
842
+ progress.hasLabel = true;
843
+ outAssigned.length = 0;
844
+ if (isInWith) throw new PcalError("Label in `with' statement", stmt);
845
+ }
846
+ if (progress.isNextLabeled) {
847
+ if (isInWith) {
848
+ throw new PcalError(
849
+ "Statement follows `call' or `return' inside a `with' statement.",
850
+ stmt,
851
+ );
852
+ }
853
+ startStep(stmt);
854
+ progress.isNextLabeled = false;
855
+ }
856
+ switch (stmt.kind) {
857
+ case "LabelIf": {
858
+ const thenAssigned: string[] = [];
859
+ const elseAssigned: string[] = [];
860
+ const isThenLabeled = addLabels(
861
+ stmt.unlabThen,
862
+ false,
863
+ isInWith,
864
+ outAssigned,
865
+ thenAssigned,
866
+ );
867
+ progress.isNextLabeled =
868
+ addLabels(stmt.unlabElse, false, isInWith, outAssigned, elseAssigned) || isThenLabeled;
869
+ copyInto(getUnion(thenAssigned, elseAssigned), outAssigned);
870
+ return;
871
+ }
872
+ case "LabelEither": {
873
+ const eitherAssigned: string[] = [];
874
+ stmt.clauses.forEach((clause) => {
875
+ const orAssigned: string[] = [];
876
+ progress.isNextLabeled =
877
+ addLabels(clause.unlabOr, false, isInWith, outAssigned, orAssigned) ||
878
+ progress.isNextLabeled;
879
+ copyInto(getUnion(orAssigned, eitherAssigned), eitherAssigned);
880
+ });
881
+ copyInto(eitherAssigned, outAssigned);
882
+ return;
883
+ }
884
+ case "While":
885
+ if (isInWith) throw new PcalError("`while' inside a `with' statement", stmt);
886
+ startStep(stmt);
887
+ addLabels(stmt.unlabDo, false, false, outAssigned, []);
888
+ progress.isNextLabeled = false;
889
+ return;
890
+ case "With": {
891
+ const withAssigned: string[] = [];
892
+ progress.isNextLabeled = addLabels(
893
+ stmt.Do,
894
+ false,
895
+ true,
896
+ isInWith ? [...inAssigned] : [],
897
+ withAssigned,
898
+ );
899
+ copyInto(withAssigned, outAssigned);
900
+ if (!isInWith && !isDisjoint(inAssigned, outAssigned)) startStep(stmt);
901
+ return;
902
+ }
903
+ }
904
+ // A call or return assigns the stack, and a return or a recursive call the parameters and
905
+ // variables of every procedure. A statement that assigns a variable assigned since the
906
+ // last label starts a new step.
907
+ const isCall = stmt.kind === "Call" || stmt.kind === "CallGoto";
908
+ const isReturn = stmt.kind === "Return" || stmt.kind === "CallReturn";
909
+ const assigned =
910
+ stmt.kind === "Assign"
911
+ ? getUnion(
912
+ [],
913
+ stmt.ass.map((assign) => assign.lhs.var),
914
+ )
915
+ : isCall || isReturn
916
+ ? [
917
+ "stack",
918
+ ...(isReturn || stmt.to === state.currentProcedure
919
+ ? state.procedures.flatMap((procedure) =>
920
+ [...procedure.params, ...procedure.decls].map((decl) => decl.var),
921
+ )
922
+ : []),
923
+ ]
924
+ : [];
925
+ progress.isNextLabeled = isCall || isReturn || stmt.kind === "Goto";
926
+ if (isDisjoint(outAssigned, assigned)) {
927
+ copyInto(getUnion(outAssigned, assigned), outAssigned);
928
+ return;
929
+ }
930
+ if (isInWith) {
931
+ throw new PcalError(
932
+ stmt.kind === "Assign"
933
+ ? "Second assignment to same variable inside a `with' statement"
934
+ : "Call or return makes second assignment to a variable inside a `with' statement",
935
+ stmt,
936
+ );
937
+ }
938
+ startStep(stmt);
939
+ copyInto(assigned, outAssigned);
940
+ });
941
+ return progress.hasLabel || progress.isNextLabeled;
942
+ };
943
+
944
+ // ParseAlgorithm.FixStmtSeq: splits each compound statement's sequences into the statements
945
+ // before their first label and the labeled statements from it on.
946
+ const fixStmtSeq = (stmts: PcalStmt[]) => {
947
+ const split = (sequence: PcalStmt[]) => {
948
+ const index = sequence.findIndex((stmt) => stmt.lbl !== "");
949
+ const unlabeled = index === -1 ? sequence : sequence.slice(0, index);
950
+ fixStmtSeq(unlabeled);
951
+ return { unlabeled, labeled: makeLabeledStmts(index === -1 ? [] : sequence.slice(index)) };
952
+ };
953
+ stmts.forEach((stmt) => {
954
+ switch (stmt.kind) {
955
+ case "LabelIf": {
956
+ const thenParts = split(stmt.unlabThen);
957
+ stmt.unlabThen = thenParts.unlabeled;
958
+ stmt.labThen = thenParts.labeled;
959
+ const elseParts = split(stmt.unlabElse);
960
+ stmt.unlabElse = elseParts.unlabeled;
961
+ stmt.labElse = elseParts.labeled;
962
+ return;
963
+ }
964
+ case "LabelEither":
965
+ stmt.clauses.forEach((clause) => {
966
+ const parts = split(clause.unlabOr);
967
+ clause.unlabOr = parts.unlabeled;
968
+ clause.labOr = parts.labeled;
969
+ });
970
+ return;
971
+ case "While": {
972
+ const parts = split(stmt.unlabDo);
973
+ stmt.unlabDo = parts.unlabeled;
974
+ stmt.labDo = parts.labeled;
975
+ }
976
+ }
977
+ });
978
+ };
979
+
980
+ // ParseAlgorithm.InnerMakeLabeledStmtSeq: groups the statements into labeled statements.
981
+ const makeLabeledStmts = (stmts: PcalStmt[]) => {
982
+ const result: PcalLabeledStmt[] = [];
983
+ stmts.forEach((stmt) => {
984
+ if (stmt.lbl === "" && result.length > 0) {
985
+ result[result.length - 1].stmts.push(stmt);
986
+ return;
987
+ }
988
+ if (stmt.lbl === "") {
989
+ throw new PcalBugError("Failure of assertion: Missing Label in MakeLabeledStmtSeq");
990
+ }
991
+ result.push({
992
+ ...createPcalBase(),
993
+ kind: "LabeledStmt",
994
+ col: stmt.col,
995
+ line: stmt.line,
996
+ macroCol: stmt.macroCol,
997
+ macroLine: stmt.macroLine,
998
+ label: stmt.lbl,
999
+ stmts: [stmt],
1000
+ });
1001
+ });
1002
+ result.forEach((labeled) => fixStmtSeq(labeled.stmts));
1003
+ return result;
1004
+ };
1005
+
1006
+ // ParseAlgorithm.ClassifyStmtSeq for one statement: 0 for one that may have a statement after
1007
+ // it in the step, 1 for a call, return or goto, which ends a step, and 2 for one with a labeled
1008
+ // statement inside. An if or either without labels inside becomes an If or Either.
1009
+ const classifyStmt = (stmts: PcalStmt[], index: number): number => {
1010
+ const node = stmts[index];
1011
+ switch (node.kind) {
1012
+ case "LabelIf": {
1013
+ const thenClass = classifyStmtSeq(node.unlabThen);
1014
+ node.labThen.forEach((stmt) => classifyStmtSeq(stmt.stmts));
1015
+ const elseClass = classifyStmtSeq(node.unlabElse);
1016
+ node.labElse.forEach((stmt) => classifyStmtSeq(stmt.stmts));
1017
+ const isLabeled = node.labThen.length > 0 || node.labElse.length > 0;
1018
+ if (isLabeled || thenClass === 2 || elseClass === 2) return 2;
1019
+ stmts[index] = {
1020
+ ...createPcalBase(),
1021
+ kind: "If",
1022
+ test: node.test,
1023
+ Then: node.unlabThen,
1024
+ Else: node.unlabElse,
1025
+ };
1026
+ return thenClass + elseClass > 0 ? 1 : 0;
1027
+ }
1028
+ case "LabelEither": {
1029
+ const eitherClass = node.clauses.reduce((result, clause) => {
1030
+ const unlabeledClass = Math.max(result, classifyStmtSeq(clause.unlabOr));
1031
+ clause.labOr.forEach((stmt) => classifyStmtSeq(stmt.stmts));
1032
+ return clause.labOr.length > 0 ? 2 : unlabeledClass;
1033
+ }, 0);
1034
+ if (eitherClass === 2) return 2;
1035
+ stmts[index] = {
1036
+ ...createPcalBase(),
1037
+ kind: "Either",
1038
+ ors: node.clauses.map((clause) => clause.unlabOr),
1039
+ };
1040
+ return eitherClass;
1041
+ }
1042
+ case "With": {
1043
+ const withClass = classifyStmtSeq(node.Do);
1044
+ if (withClass === 2) {
1045
+ throw new PcalError(
1046
+ `with statement at ${getPcalLocation(node)} contains a labeled statement`,
1047
+ );
1048
+ }
1049
+ return withClass;
1050
+ }
1051
+ case "While":
1052
+ if (index !== 0) {
1053
+ throw new PcalBugError(
1054
+ "ParseAlgorithm.ClassifyStmtSeq encountered `while' not at beginning of StmtSeq.",
1055
+ );
1056
+ }
1057
+ classifyStmtSeq(node.unlabDo);
1058
+ node.labDo.forEach((stmt) => classifyStmtSeq(stmt.stmts));
1059
+ return 0;
1060
+ case "Call":
1061
+ return stmts[index + 1]?.kind === "Return" ? 0 : 1;
1062
+ case "Return":
1063
+ case "CallReturn":
1064
+ if (state.currentProcedure === undefined) {
1065
+ throw new PcalError(`return statement not in a procedure at ${getPcalLocation(node)}`);
1066
+ }
1067
+ return 1;
1068
+ case "Goto":
1069
+ case "CallGoto":
1070
+ return 1;
1071
+ case "Assign":
1072
+ case "When":
1073
+ case "PrintS":
1074
+ case "Assert":
1075
+ case "Skip":
1076
+ case "MacroCall":
1077
+ return 0;
1078
+ default:
1079
+ throw new PcalBugError(
1080
+ `ParseAlgorithm.ClassifyStmtSeq encountered the unexpected statement type ${node.kind}`,
1081
+ );
1082
+ }
1083
+ };
1084
+
1085
+ // ParseAlgorithm.ClassifyStmtSeq: a statement that ends a step can only end its sequence.
1086
+ const classifyStmtSeq = (stmts: PcalStmt[]): number => {
1087
+ for (let index = 0; index < stmts.length; index++) {
1088
+ const stmtClass = classifyStmt(stmts, index);
1089
+ if (stmtClass === 0) continue;
1090
+ if (index === stmts.length - 1) return stmtClass;
1091
+ throw new PcalBugError(
1092
+ `Translator discovered later than it should have that\n Statement at ${getPcalLocation(stmts[index + 1])} must have a label`,
1093
+ );
1094
+ }
1095
+ return 0;
1096
+ };
1097
+
1098
+ // ParseAlgorithm.AddLabelsToStmtSeq followed by MakeLabeledStmtSeq.
1099
+ const makeLabeledStmtSeq = (stmts: PcalStmt[]) => {
1100
+ addLabels(stmts, true, false, [], []);
1101
+ const result = makeLabeledStmts(stmts);
1102
+ result.forEach((stmt) => classifyStmtSeq(stmt.stmts));
1103
+ return result;
1104
+ };
1105
+
1106
+ // ParseAlgorithm.SubstituteInStmt: a copy of a macro's statement with the macro's arguments
1107
+ // for its parameters, which records the position of the macro call.
1108
+ const substituteInStmt = (
1109
+ stmt: PcalStmt,
1110
+ args: PcalExpr[],
1111
+ names: string[],
1112
+ macroLine: number,
1113
+ macroCol: number,
1114
+ ): PcalStmt => {
1115
+ const substitute = (expr: PcalExpr) => getSubstitutedPcalExpr(expr, args, names);
1116
+ const substituteAll = (stmts: PcalStmt[]) =>
1117
+ stmts.map((inner) => substituteInStmt(inner, args, names, macroLine, macroCol));
1118
+ const substituteLabeled = (stmts: PcalLabeledStmt[]) =>
1119
+ stmts.map((inner): PcalLabeledStmt => ({
1120
+ ...createPcalBase(),
1121
+ kind: "LabeledStmt",
1122
+ label: inner.label,
1123
+ stmts: inner.stmts.map((labeled) => substituteInStmt(labeled, args, names, -1, 0)),
1124
+ }));
1125
+ const base = {
1126
+ ...createPcalBase(),
1127
+ col: stmt.col,
1128
+ line: stmt.line,
1129
+ macroCol: macroLine > 0 ? macroCol : stmt.macroCol,
1130
+ macroLine: macroLine > 0 ? macroLine : stmt.macroLine,
1131
+ };
1132
+ switch (stmt.kind) {
1133
+ case "Assign":
1134
+ return {
1135
+ ...base,
1136
+ kind: "Assign",
1137
+ ass: stmt.ass.map((assign) =>
1138
+ substituteInSingleAssign(assign, args, names, macroLine, macroCol),
1139
+ ),
1140
+ };
1141
+ case "If":
1142
+ return {
1143
+ ...base,
1144
+ kind: "If",
1145
+ test: substitute(stmt.test),
1146
+ Then: substituteAll(stmt.Then),
1147
+ Else: substituteAll(stmt.Else),
1148
+ };
1149
+ case "Either":
1150
+ return { ...base, kind: "Either", ors: stmt.ors.map(substituteAll) };
1151
+ case "With":
1152
+ return {
1153
+ ...base,
1154
+ kind: "With",
1155
+ var: stmt.var,
1156
+ isEq: stmt.isEq,
1157
+ exp: substitute(stmt.exp),
1158
+ Do: substituteAll(stmt.Do),
1159
+ };
1160
+ case "When":
1161
+ case "Assert":
1162
+ case "PrintS":
1163
+ return { ...base, kind: stmt.kind, exp: substitute(stmt.exp) };
1164
+ // SubstituteInStmt doesn't copy a skip's macro position.
1165
+ case "Skip":
1166
+ return {
1167
+ ...base,
1168
+ kind: "Skip",
1169
+ macroCol: macroLine > 0 ? macroCol : 0,
1170
+ macroLine: macroLine > 0 ? macroLine : -1,
1171
+ };
1172
+ case "While":
1173
+ return {
1174
+ ...base,
1175
+ kind: "While",
1176
+ test: substitute(stmt.test),
1177
+ unlabDo: substituteAll(stmt.unlabDo),
1178
+ labDo: substituteLabeled(stmt.labDo),
1179
+ };
1180
+ case "LabelIf":
1181
+ return {
1182
+ ...base,
1183
+ kind: "LabelIf",
1184
+ test: substitute(stmt.test),
1185
+ unlabThen: substituteAll(stmt.unlabThen),
1186
+ labThen: substituteLabeled(stmt.labThen),
1187
+ unlabElse: substituteAll(stmt.unlabElse),
1188
+ labElse: substituteLabeled(stmt.labElse),
1189
+ };
1190
+ case "LabelEither":
1191
+ return {
1192
+ ...base,
1193
+ kind: "LabelEither",
1194
+ clauses: stmt.clauses.map((clause): PcalClause => ({
1195
+ ...createPcalBase(),
1196
+ kind: "Clause",
1197
+ labOr: substituteLabeled(clause.labOr),
1198
+ unlabOr: substituteAll(clause.unlabOr),
1199
+ })),
1200
+ };
1201
+ case "Call":
1202
+ return {
1203
+ ...base,
1204
+ kind: "Call",
1205
+ to: stmt.to,
1206
+ returnTo: stmt.returnTo,
1207
+ args: substitutePcalExprs(stmt.args, args, names),
1208
+ };
1209
+ case "Return":
1210
+ return { ...base, kind: "Return", from: stmt.from };
1211
+ case "CallReturn":
1212
+ return {
1213
+ ...base,
1214
+ kind: "CallReturn",
1215
+ to: stmt.to,
1216
+ from: stmt.from,
1217
+ args: substitutePcalExprs(stmt.args, args, names),
1218
+ };
1219
+ case "CallGoto":
1220
+ return {
1221
+ ...base,
1222
+ kind: "CallGoto",
1223
+ to: stmt.to,
1224
+ after: stmt.after,
1225
+ args: substitutePcalExprs(stmt.args, args, names),
1226
+ };
1227
+ case "Goto":
1228
+ return { ...base, kind: "Goto", to: stmt.to };
1229
+ default:
1230
+ throw new PcalBugError(
1231
+ `Found unexpected statement type in macro at${getPcalLocation(stmt)}`,
1232
+ );
1233
+ }
1234
+ };
1235
+
1236
+ // ParseAlgorithm.SubstituteInSingleAssign: a parameter assigned to becomes the variable its
1237
+ // argument starts with, and the rest of the argument goes before the subscript.
1238
+ const substituteInSingleAssign = (
1239
+ assign: PcalSingleAssign,
1240
+ args: PcalExpr[],
1241
+ names: string[],
1242
+ macroLine: number,
1243
+ macroCol: number,
1244
+ ) => {
1245
+ const rhs = getSubstitutedPcalExpr(assign.rhs, args, names);
1246
+ const lhs: PcalLhs = {
1247
+ ...createPcalBase(),
1248
+ kind: "Lhs",
1249
+ var: assign.lhs.var,
1250
+ sub:
1251
+ assign.lhs.sub.tokens.length === 0
1252
+ ? assign.lhs.sub
1253
+ : getSubstitutedPcalExpr(assign.lhs.sub, args, names),
1254
+ };
1255
+ const result: PcalSingleAssign = {
1256
+ ...createPcalBase(),
1257
+ kind: "SingleAssign",
1258
+ col: assign.col,
1259
+ line: assign.line,
1260
+ macroCol: macroLine > 0 ? macroCol : assign.macroCol,
1261
+ macroLine: macroLine > 0 ? macroLine : assign.macroLine,
1262
+ lhs,
1263
+ rhs,
1264
+ };
1265
+ const index = names.indexOf(lhs.var);
1266
+ if (index === -1) return result;
1267
+ const argument = args[index];
1268
+ const varToken = getPcalTokenAt(argument, { line: 0, item: 0 });
1269
+ if (varToken.type !== PCAL_TOKEN.ident) {
1270
+ throw new PcalError(
1271
+ `Macro expansion substitutes \`${varToken.string}' for assignment variable\n at ${getPcalLocation(result)}`,
1272
+ );
1273
+ }
1274
+ lhs.var = varToken.string;
1275
+ if (stepPcalCoord(argument, { line: 0, item: 0 }, 1) === undefined) return result;
1276
+ const copy = clonePcalExpr(argument);
1277
+ copy.tokens[0].splice(0, 1);
1278
+ normalizePcalExpr(copy);
1279
+ if (lhs.sub.tokens.length === 0) lhs.sub = copy;
1280
+ else prependPcalExpr(lhs.sub, copy, 0);
1281
+ return result;
1282
+ };
1283
+
1284
+ // ParseAlgorithm.ExpandMacrosInStmtSeq: replaces each macro call with the macro's body.
1285
+ const expandMacrosInStmtSeq = (stmts: PcalStmt[], macros: PcalMacro[]) => {
1286
+ const expanded = stmts.flatMap((node) => {
1287
+ switch (node.kind) {
1288
+ case "LabelIf":
1289
+ expandMacrosInStmtSeq(node.unlabThen, macros);
1290
+ expandMacrosInStmtSeq(node.unlabElse, macros);
1291
+ return [node];
1292
+ case "LabelEither":
1293
+ node.clauses.forEach((clause) => expandMacrosInStmtSeq(clause.unlabOr, macros));
1294
+ return [node];
1295
+ case "With":
1296
+ expandMacrosInStmtSeq(node.Do, macros);
1297
+ return [node];
1298
+ case "While":
1299
+ expandMacrosInStmtSeq(node.unlabDo, macros);
1300
+ return [node];
1301
+ case "MacroCall":
1302
+ return expandMacroCall(node, macros);
1303
+ default:
1304
+ return [node];
1305
+ }
1306
+ });
1307
+ stmts.splice(0, stmts.length, ...expanded);
1308
+ };
1309
+
1310
+ // ParseAlgorithm.ExpandMacroCall: the last macro of the name wins.
1311
+ const expandMacroCall = (call: PcalMacroCall, macros: PcalMacro[]) => {
1312
+ const definition = macros.findLast((macro) => macro.name === call.name);
1313
+ if (definition === undefined) {
1314
+ throw new PcalError(`Macro ${call.name} undefined,\n at ${getPcalLocation(call)}`);
1315
+ }
1316
+ if (definition.params.length !== call.args.length) {
1317
+ throw new PcalError(
1318
+ `Macro ${call.name} called with wrong number of arguments at \n ${getPcalLocation(call)}`,
1319
+ );
1320
+ }
1321
+ const result = definition.body.map((stmt) =>
1322
+ substituteInStmt(stmt, call.args, definition.params, call.line, call.col),
1323
+ );
1324
+ if (result.length > 0) result[0].lbl = call.lbl;
1325
+ return result;
1326
+ };
1327
+
1328
+ const checkForDuplicateMacros = (macros: PcalMacro[]) => {
1329
+ macros.forEach((macro, index) => {
1330
+ if (macros.slice(index + 1).some((other) => other.name === macro.name)) {
1331
+ throw new PcalError(`Multiple definitions of macro name \`${macro.name}'`);
1332
+ }
1333
+ });
1334
+ };
1335
+
1336
+ // ParseAlgorithm.checkBody: a body that is a single labeled "while TRUE" without labels inside
1337
+ // lets the translation omit pc.
1338
+ const checkBody = (body: PcalStmt[]) => {
1339
+ if (body.length === 0) return;
1340
+ const clear = () => {
1341
+ state.omitPC = false;
1342
+ state.omitStutteringWhenDone = false;
1343
+ };
1344
+ const labeled = body[0];
1345
+ if (body.length > 1 || labeled.kind !== "LabeledStmt") return clear();
1346
+ if (labeled.stmts.length === 0) return;
1347
+ const whileStmt = labeled.stmts[0];
1348
+ if (labeled.stmts.length > 1 || whileStmt.kind !== "While") return clear();
1349
+ if (!isOneTokenPcalExpr(whileStmt.test) || whileStmt.test.tokens[0][0].string !== "TRUE") {
1350
+ return clear();
1351
+ }
1352
+ if (whileStmt.labDo.length > 0) state.omitPC = false;
1353
+ const hasLabeled = whileStmt.unlabDo.some((stmt) =>
1354
+ ["LabelIf", "LabelEither", "LabeledStmt"].includes(stmt.kind),
1355
+ );
1356
+ if (hasLabeled) state.omitPC = false;
1357
+ };
1358
+
1359
+ // ParseAlgorithm.AddedMessagesError.
1360
+ const throwAddedLabels = (): never => {
1361
+ const header =
1362
+ state.addedLabels.length > 1
1363
+ ? "Missing labels at the following locations:"
1364
+ : "Missing label at the following location:";
1365
+ throw new PcalError([header, ...state.addedLabelsLocs].join("\n "));
1366
+ };
1367
+
1368
+ // ParseAlgorithm.ReportLabels.
1369
+ const reportLabels = () => {
1370
+ if (!params.reportLabelsFlag) {
1371
+ session.log("Labels added.");
1372
+ return;
1373
+ }
1374
+ session.log(
1375
+ state.addedLabels.length > 1
1376
+ ? "The following labels were added:"
1377
+ : "The following label was added:",
1378
+ );
1379
+ state.addedLabels.forEach((label, index) =>
1380
+ session.log(` ${label} at ${state.addedLabelsLocs[index]}`),
1381
+ );
1382
+ };
1383
+
1384
+ const fixProcedures = (macros: PcalMacro[]) =>
1385
+ state.procedures.forEach((procedure) => {
1386
+ state.currentProcedure = procedure.name;
1387
+ expandMacrosInStmtSeq(procedure.body, macros);
1388
+ procedure.body = makeLabeledStmtSeq(procedure.body);
1389
+ });
1390
+
1391
+ const parse = (): PcalAlgorithm => {
1392
+ if (isFairAlgorithm) {
1393
+ if (getAlgToken() !== "algorithm") throwParsingError("`--fair' not followed by `algorithm'");
1394
+ params.fairAlgorithm = true;
1395
+ }
1396
+ const name = getAlgToken();
1397
+ state.cSyntax = peekAtAlgToken(1) === "{";
1398
+ state.pSyntax = !state.cSyntax;
1399
+ if (state.cSyntax) mustGobbleThis("{");
1400
+ const decls =
1401
+ peekAtAlgToken(1) === "variable" || peekAtAlgToken(1) === "variables" ? getVarDecls() : [];
1402
+ const defs = { value: createPcalExpr() };
1403
+ if (peekAtAlgToken(1) === "define") {
1404
+ mustGobbleThis("define");
1405
+ if (state.cSyntax) gobbleThis("{");
1406
+ defs.value = getExpr(true);
1407
+ gobbleEndOrRightBrace("define");
1408
+ gobbleThis(";");
1409
+ }
1410
+ const macros: PcalMacro[] = [];
1411
+ while (peekAtAlgToken(1) === "macro") macros.push(getMacro(macros));
1412
+ while (peekAtAlgToken(1) === "procedure") {
1413
+ state.procedures.push(getProcedure());
1414
+ state.omitPC = false;
1415
+ }
1416
+ const isMultiprocess =
1417
+ (peekAtAlgToken(1) === "fair" &&
1418
+ (peekAtAlgToken(2) === "process" ||
1419
+ (peekAtAlgToken(2) === "+" && peekAtAlgToken(3) === "process"))) ||
1420
+ peekAtAlgToken(1) === "process";
1421
+ if (isMultiprocess) {
1422
+ const procs: PcalProcess[] = [];
1423
+ while (peekAtAlgToken(1) === "fair" || peekAtAlgToken(1) === "process") {
1424
+ const isFair = peekAtAlgToken(1) === "fair";
1425
+ if (isFair) mustGobbleThis("fair");
1426
+ const isStronglyFair = isFair && peekAtAlgToken(1) === "+";
1427
+ if (isStronglyFair) mustGobbleThis("+");
1428
+ const fairness =
1429
+ isStronglyFair || (!isFair && params.fairnessOption === "sf")
1430
+ ? 2
1431
+ : isFair || params.fairnessOption === "wf"
1432
+ ? 1
1433
+ : 0;
1434
+ procs.push({ ...getProcess(), fairness });
1435
+ }
1436
+ gobbleEndOrRightBrace("algorithm");
1437
+ checkForDuplicateMacros(macros);
1438
+ const omitsStutteringWhenDone = procs.map((proc) => {
1439
+ expandMacrosInStmtSeq(proc.body, macros);
1440
+ proc.body = makeLabeledStmtSeq(proc.body);
1441
+ state.omitStutteringWhenDone = true;
1442
+ checkBody(proc.body);
1443
+ return state.omitStutteringWhenDone;
1444
+ });
1445
+ state.omitStutteringWhenDone = omitsStutteringWhenDone.includes(true);
1446
+ fixProcedures(macros);
1447
+ if (state.addedLabels.length > 0) {
1448
+ if (!params.labelFlag) throwAddedLabels();
1449
+ reportLabels();
1450
+ }
1451
+ if (state.gotoDoneUsed) {
1452
+ state.omitPC = false;
1453
+ state.omitStutteringWhenDone = false;
1454
+ }
1455
+ if (state.gotoUsed) state.omitPC = false;
1456
+ return {
1457
+ ...createPcalBase(),
1458
+ kind: "Multiprocess",
1459
+ name,
1460
+ decls,
1461
+ defs: defs.value,
1462
+ macros,
1463
+ prcds: state.procedures,
1464
+ procs,
1465
+ };
1466
+ }
1467
+ if (params.inputVersionNumber === 1500 && peekAtAlgToken(1) === "fair") {
1468
+ gobbleThis("fair");
1469
+ if (peekAtAlgToken(1) === "+") gobbleThis("+");
1470
+ params.fairnessOption = "wf";
1471
+ }
1472
+ if (isFairAlgorithm) {
1473
+ if (!["", "wf", "wfNext"].includes(params.fairnessOption)) {
1474
+ session.log(`Warning: Option \`${params.fairnessOption}' specified for --fair algorithm.`);
1475
+ }
1476
+ params.fairnessOption = "wf";
1477
+ }
1478
+ gobbleBeginOrLeftBrace();
1479
+ const body = getStmtSeq();
1480
+ checkForDuplicateMacros(macros);
1481
+ expandMacrosInStmtSeq(body, macros);
1482
+ fixProcedures(macros);
1483
+ // The first brace ends the body that gobbleBeginOrLeftBrace began.
1484
+ if (state.cSyntax) gobbleThis("}");
1485
+ gobbleEndOrRightBrace("algorithm");
1486
+ const labeledBody = makeLabeledStmtSeq(body);
1487
+ if (state.addedLabels.length > 0) {
1488
+ if (state.hasLabel && !params.labelFlag) throwAddedLabels();
1489
+ reportLabels();
1490
+ }
1491
+ if (state.gotoUsed) state.omitPC = false;
1492
+ if (!state.gotoDoneUsed) checkBody(labeledBody);
1493
+ if (state.gotoDoneUsed) {
1494
+ state.omitPC = false;
1495
+ state.omitStutteringWhenDone = false;
1496
+ }
1497
+ return {
1498
+ ...createPcalBase(),
1499
+ kind: "Uniprocess",
1500
+ name,
1501
+ decls,
1502
+ defs: defs.value,
1503
+ macros,
1504
+ prcds: state.procedures,
1505
+ body: labeledBody,
1506
+ };
1507
+ };
1508
+
1509
+ // HACK: ParseAlgorithm.getAlgorithm turns any RuntimeException, such as an index out of bounds
1510
+ // on input it doesn't expect, into a parsing error at the last token.
1511
+ try {
1512
+ const ast = parse();
1513
+ return {
1514
+ ast,
1515
+ omitPC: state.omitPC,
1516
+ omitStutteringWhenDone: state.omitStutteringWhenDone,
1517
+ hasDefaultInitialization: state.hasDefaultInitialization,
1518
+ };
1519
+ } catch (error) {
1520
+ if (!(error instanceof PcalRuntimeError)) throw error;
1521
+ return throwParsingError("Unknown error at or before");
1522
+ }
1523
+ };